diff --git a/src/resumed-session.ts b/src/resumed-session.ts index efc89e58..6d25f5f4 100644 --- a/src/resumed-session.ts +++ b/src/resumed-session.ts @@ -110,8 +110,10 @@ export async function readHistoryAcrossCompactions( ): Promise { if (!isCompactSummaryMessage(messages[0])) return messages; try { - const entries = (snapshot ?? (await loadFullSessionHistory(sessionId, dir))).map( - linkCompactBoundary, + const records = snapshot ?? (await loadFullSessionHistory(sessionId, dir)); + const positions = recordPositions(records); + const entries = records.map((entry) => + linkCompactBoundary(entry, positions, sessionId, logger), ); const read = (records: SessionStoreEntry[]) => getSessionMessages(sessionId, { @@ -161,8 +163,59 @@ export async function loadFullSessionHistory( return entries; } -/** The record unchanged, or a compaction boundary linked to the message before it. */ -function linkCompactBoundary(entry: SessionStoreEntry): SessionStoreEntry { +/** The position of each record of a transcript, by its uuid. */ +export function recordPositions(entries: readonly SessionStoreEntry[]): Map { + return new Map( + entries.flatMap((entry, index) => + typeof entry.uuid === "string" ? [[entry.uuid, index]] : [], + ), + ); +} + +/** + * The uuid of the record that `entry` follows, given the `positions` of the + * records of its transcript: its `parentUuid`, or for a compaction boundary, + * the message before the compaction. + * + * Claude Code can write a boundary whose `logicalParentUuid` is not in the + * transcript: it lists the message in `compactMetadata.preservedMessages`, but + * does not write it. Such a boundary follows + * `compactMetadata.preservedSegment.tailUuid`, the `logicalParentUuid` of the + * other boundaries, when that message comes before the boundary in the file. + * In a fork, the boundary is the first record and the preserved messages come + * after it: the boundary then keeps its `logicalParentUuid`. + */ +export function recordParentUuid( + entry: SessionStoreEntry, + positions: ReadonlyMap, +): string | undefined { + if (typeof entry.parentUuid === "string" && entry.parentUuid) return entry.parentUuid; + const logical = entry.logicalParentUuid; + if (typeof logical !== "string") return undefined; + if (positions.has(logical) || entry.type !== "system" || entry.subtype !== "compact_boundary") { + return logical; + } + const tail = preservedTail(entry); + const tailAt = tail === undefined ? undefined : positions.get(tail); + const at = positions.get(entry.uuid); + return tailAt !== undefined && at !== undefined && tailAt < at ? tail : logical; +} + +function preservedTail(entry: SessionStoreEntry): string | undefined { + const segment = (entry.compactMetadata as { preservedSegment?: unknown } | undefined) + ?.preservedSegment; + const tail = (segment as { tailUuid?: unknown } | null | undefined)?.tailUuid; + return typeof tail === "string" ? tail : undefined; +} + +/** The record unchanged, or a compaction boundary linked to the message + * before it (see {@link recordParentUuid}). */ +function linkCompactBoundary( + entry: SessionStoreEntry, + positions: ReadonlyMap, + sessionId: string, + logger?: ResumeLogger, +): SessionStoreEntry { if ( entry.type !== "system" || entry.subtype !== "compact_boundary" || @@ -170,13 +223,24 @@ function linkCompactBoundary(entry: SessionStoreEntry): SessionStoreEntry { ) { return entry; } + const logical = entry.logicalParentUuid; + const parentUuid = recordParentUuid({ ...entry, parentUuid: null }, positions) ?? logical; + if (parentUuid !== logical) { + logger?.log( + `The compaction ${entry.uuid} of session ${sessionId} follows message ${logical}, which is not in the transcript: linking it to the last preserved message ${parentUuid}`, + ); + } else if (!positions.has(logical) && !positions.has(preservedTail(entry))) { + logger?.error( + `The compaction ${entry.uuid} of session ${sessionId} follows message ${logical}, which is not in the transcript: leaving out the history before it`, + ); + } const compactMetadata: Record = typeof entry.compactMetadata === "object" && entry.compactMetadata !== null ? { ...entry.compactMetadata } : {}; delete compactMetadata.preservedSegment; delete compactMetadata.preservedMessages; - return { ...entry, parentUuid: entry.logicalParentUuid, compactMetadata }; + return { ...entry, parentUuid, compactMetadata }; } /** What a resume restores from the end of the local transcript. */ diff --git a/src/session-rewind.ts b/src/session-rewind.ts index a5af0841..06761772 100644 --- a/src/session-rewind.ts +++ b/src/session-rewind.ts @@ -34,6 +34,8 @@ import { findTranscript, loadFullSessionHistory, readHistoryAcrossCompactions, + recordParentUuid, + recordPositions, } from "./resumed-session.js"; import { cursorMessageId, forkPointOf } from "./session-cursors.js"; @@ -328,9 +330,10 @@ export async function withoutRewoundBranch( const point = await readRewindPoint(sessionId, logger); if (!point) return entries; const dropped = new Set([point.droppedPromptUuid]); + const positions = recordPositions(entries); return entries.filter((entry) => { if (typeof entry.uuid !== "string") return true; - const parent = entry.parentUuid || entry.logicalParentUuid; + const parent = recordParentUuid(entry, positions); const inDropped = entry.uuid === point.droppedPromptUuid || (typeof parent === "string" && dropped.has(parent)); if (inDropped) dropped.add(entry.uuid); @@ -461,7 +464,7 @@ export async function prepareRewoundResume( const byUuid = entriesByUuid(history); const newest = newestMainChainUuid(history); if (!newest) return undefined; - const active = chainUuids(newest, byUuid); + const active = chainUuids(newest, history, byUuid); const pending = isPending(point, history, active); const leaf = pending ? point.resumeSessionAt : newest; await markResumedLeaf(sessionId, history, byUuid, leaf, pending); @@ -519,7 +522,7 @@ async function markResumedLeaf( continue; } } - const branch = chainUuids(leaf, byUuid); + const branch = chainUuids(leaf, history, byUuid); const lastPrompt = history .filter((entry) => branch.has(entry.uuid as string) && entry.type === "user") .map(promptText) @@ -580,20 +583,22 @@ function newestMainChainUuid(entries: SessionStoreEntry[]): string | undefined { )?.uuid; } -/** The uuids of `leaf` and of every entry it descends from. A compaction - * boundary has no `parentUuid`; its `logicalParentUuid` carries the chain on. */ +/** The uuids of `leaf` and of every entry of `history` it descends from. A + * compaction boundary has no `parentUuid`; the message before the compaction + * carries the chain on (see `recordParentUuid`). */ function chainUuids( leaf: string | undefined, + history: SessionStoreEntry[], byUuid: ReadonlyMap, ): Set { + const positions = recordPositions(history); const chain = new Set(); let cursor = leaf; while (cursor && !chain.has(cursor)) { const entry = byUuid.get(cursor); if (!entry) break; chain.add(cursor); - const parent = entry.parentUuid || entry.logicalParentUuid; - cursor = typeof parent === "string" ? parent : undefined; + cursor = recordParentUuid(entry, positions); } return chain; } diff --git a/src/tests/resumed-session.test.ts b/src/tests/resumed-session.test.ts index d2c56602..b7f4b3ea 100644 --- a/src/tests/resumed-session.test.ts +++ b/src/tests/resumed-session.test.ts @@ -344,6 +344,88 @@ describe("readHistoryAcrossCompactions", () => { ]); }); + it("links a boundary whose parent is not in the transcript to the last preserved message", async () => { + // Claude Code lists "missing" in `allUuids`, but does not write it. + await transcript([ + user("u1", "hi"), + assistant("a1", "Hello"), + boundary("b1", "missing", { + preservedSegment: { headUuid: "a1", anchorUuid: "s1", tailUuid: "a1" }, + preservedMessages: { anchorUuid: "s1", uuids: ["a1"], allUuids: ["a1", "missing"] }, + }), + summary("s1"), + user("u2", "identify yourself"), + assistant("a2", "Claude"), + ]); + const chain = await getSessionMessages(sessionId); + const log = vi.fn(); + const error = vi.fn(); + + expect(texts(await readHistoryAcrossCompactions(sessionId, chain, { log, error }))).toEqual([ + "hi", + "Hello", + "Summary s1", + "identify yourself", + "Claude", + ]); + expect(log).toHaveBeenCalledWith(expect.stringContaining("linking it to the last preserved")); + expect(error).not.toHaveBeenCalled(); + }); + + it("keeps the link and logs when neither the parent nor the last preserved message is in the transcript", async () => { + await transcript([ + user("u1", "hi"), + assistant("a1", "Hello"), + boundary("b1", "missing"), + summary("s1"), + user("u2", "identify yourself"), + ]); + const chain = await getSessionMessages(sessionId); + const error = vi.fn(); + + expect( + texts(await readHistoryAcrossCompactions(sessionId, chain, { log: () => {}, error })), + ).toEqual(["Summary s1", "identify yourself"]); + expect(error).toHaveBeenCalledWith(expect.stringContaining("leaving out the history")); + }); + + it("keeps the link of a fork's first boundary, whose preserved messages come after it", async () => { + // A fork starts at the boundary; the kept messages follow the summary. + await transcript([ + boundary("b1", "missing", { + preservedSegment: { headUuid: "h1", anchorUuid: "s1", tailUuid: "t1" }, + preservedMessages: { + anchorUuid: "s1", + uuids: ["h1", "t1"], + allUuids: ["h1", "t1", "missing"], + }, + }), + { ...summary("s1"), parentUuid: "b1" }, + { ...assistant("h1", "Kept head"), parentUuid: "s1" }, + { ...assistant("t1", "Kept tail"), parentUuid: "h1" }, + { ...user("u2", "next"), parentUuid: "t1" }, + { ...assistant("a2", "Next"), parentUuid: "u2" }, + boundary("b2", "a2"), + { ...summary("s2"), parentUuid: "b2" }, + { ...user("u3", "identify yourself"), parentUuid: "s2" }, + ]); + const chain = await getSessionMessages(sessionId); + const log = vi.fn(); + const error = vi.fn(); + + expect(texts(await readHistoryAcrossCompactions(sessionId, chain, { log, error }))).toEqual([ + "Summary s1", + "Kept head", + "Kept tail", + "next", + "Next", + "Summary s2", + "identify yourself", + ]); + expect(log).not.toHaveBeenCalled(); + expect(error).not.toHaveBeenCalled(); + }); + it("returns the chain of a session without a compaction as it is", async () => { await transcript([user("u1", "hi"), assistant("a1", "Hello")]); diff --git a/src/tests/session-read.test.ts b/src/tests/session-read.test.ts index e4f36548..0275467e 100644 --- a/src/tests/session-read.test.ts +++ b/src/tests/session-read.test.ts @@ -10,6 +10,8 @@ import { writeRewindPoint } from "../session-rewind.js"; import { parallelToolCallRecords, transcriptAssistant, + transcriptCompactBoundary, + transcriptCompactSummary, transcriptUser, writeTranscript, } from "./helpers.js"; @@ -175,6 +177,34 @@ describe("session read cursors", () => { }, ); + it("reads the messages before a compaction whose parent is not in the transcript", async () => { + const sessionId = randomUUID(); + const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-missing-parent-")); + const project = path.join(dir, "projects", "-project"); + vi.stubEnv("CLAUDE_CONFIG_DIR", dir); + try { + // Claude Code lists "missing" in `allUuids`, but does not write it. + await writeTranscript(project, sessionId, [ + { cwd: dir, ...transcriptUser("u1", "hi") }, + { cwd: dir, ...transcriptAssistant("a1", "Hello") }, + { + cwd: dir, + ...transcriptCompactBoundary("b1", "missing", { + preservedSegment: { headUuid: "a1", anchorUuid: "s1", tailUuid: "a1" }, + preservedMessages: { anchorUuid: "s1", uuids: ["a1"], allUuids: ["a1", "missing"] }, + }), + }, + { cwd: dir, ...transcriptCompactSummary("s1") }, + { cwd: dir, ...transcriptUser("u2", "identify yourself") }, + ]); + const { messages } = await readSessionTranscript(sessionId); + expect(messages.map((message) => message.uuid)).toEqual(["u1", "a1", "s1", "u2"]); + } finally { + vi.unstubAllEnvs(); + await rm(dir, { recursive: true, force: true }); + } + }); + it.each(["results", "third call", "streamed call", "skill text"] as const)( "reads each record of parallel tool calls of the root in file order: %s", async (variant) => { diff --git a/src/tests/session-rewind.test.ts b/src/tests/session-rewind.test.ts index 9dc1523d..b9f42642 100644 --- a/src/tests/session-rewind.test.ts +++ b/src/tests/session-rewind.test.ts @@ -576,6 +576,56 @@ describe("prepareRewoundResume", () => { }); }); +describe("a rewind into the messages that a compaction kept", () => { + it("keeps the point when the boundary follows a message that is not in the transcript", async () => { + // Claude Code lists "missing" in `allUuids`, but does not write it. + await writeTranscript(projectDir(), SESSION_ID, [ + transcriptUser("u0", "first"), + transcriptAssistant("a0", "zero"), + transcriptUser("p1", "kept prompt"), + transcriptAssistant("p2", "kept answer"), + transcriptUser("p3", "second kept prompt"), + transcriptAssistant("p4", "second kept answer"), + transcriptCompactBoundary("b1", "missing", { + preservedSegment: { headUuid: "p1", anchorUuid: "s1", tailUuid: "p4" }, + preservedMessages: { + anchorUuid: "s1", + uuids: ["p1", "p2", "p3", "p4"], + allUuids: ["p1", "p2", "p3", "p4", "missing"], + }, + }), + transcriptCompactSummary("s1"), + transcriptUser("u2", "after"), + transcriptAssistant("a2", "two"), + ]); + const uuids = (entries: readonly { uuid?: unknown }[]) => + entries.flatMap((entry) => (typeof entry.uuid === "string" ? [entry.uuid] : [])); + expect(uuids((await loadRewindableHistory(SESSION_ID)).visible)).toEqual([ + "u0", + "a0", + "p1", + "p2", + "p3", + "p4", + "s1", + "u2", + "a2", + ]); + + await writeRewindPoint(SESSION_ID, { resumeSessionAt: "p2", droppedPromptUuid: "p3" }); + expect(await prepareRewoundResume(SESSION_ID)).toBe("p2"); + expect(await readRewindPoint(SESSION_ID)).toBeDefined(); + const full = await loadFullSessionHistory(SESSION_ID); + expect(uuids(await withoutRewoundBranch(SESSION_ID, full))).toEqual(["u0", "a0", "p1", "p2"]); + expect(uuids((await loadRewindableHistory(SESSION_ID)).visible)).toEqual([ + "u0", + "a0", + "p1", + "p2", + ]); + }); +}); + describe("prepareRewoundResume with trailing metadata and failures", () => { const transcript = () => path.join(projectDir(), `${SESSION_ID}.jsonl`); diff --git a/src/tests/v1/acp-agent.test.ts b/src/tests/v1/acp-agent.test.ts index 6e7d3a38..0732f8ac 100644 --- a/src/tests/v1/acp-agent.test.ts +++ b/src/tests/v1/acp-agent.test.ts @@ -3665,7 +3665,17 @@ describe("usage-limit failure replay", () => { }); describe("compacted session replay", () => { - it("replays the messages before the compaction, then the compaction", async () => { + it.each([ + ["", transcriptCompactBoundary("b1", "a1")], + [ + " (a parent that is not in the transcript)", + // Claude Code lists "missing" in `allUuids`, but does not write it. + transcriptCompactBoundary("b1", "missing", { + preservedSegment: { headUuid: "a1", anchorUuid: "s1", tailUuid: "a1" }, + preservedMessages: { anchorUuid: "s1", uuids: ["a1"], allUuids: ["a1", "missing"] }, + }), + ], + ])("replays the messages before the compaction, then the compaction%s", async (_, boundary) => { const configDir = await mkdtemp(path.join(os.tmpdir(), "claude-acp-compacted-replay-")); const originalConfigDir = process.env.CLAUDE_CONFIG_DIR; process.env.CLAUDE_CONFIG_DIR = configDir; @@ -3676,7 +3686,7 @@ describe("compacted session replay", () => { await writeTranscript(path.join(configDir, "projects", "-tmp-proj"), sessionId, [ transcriptUser("u1", "hi"), transcriptAssistant("a1", "Hello"), - transcriptCompactBoundary("b1", "a1"), + boundary, transcriptCompactSummary("s1"), transcriptUser("u2", "identify yourself"), transcriptAssistant("a2", "Claude"),