From a668b17c9e09b6e1d983c49860fd9403c7527d63 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:05:38 +0100 Subject: [PATCH 1/9] test(pi): reproduce rewind after a legacy checkpoint and session switch Co-authored-by: GPT 6.2 Sol --- packages/provider-pi/src/server/rollback.test.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/rollback.test.ts b/packages/provider-pi/src/server/rollback.test.ts index a742af314d50..1943eea0afca 100644 --- a/packages/provider-pi/src/server/rollback.test.ts +++ b/packages/provider-pi/src/server/rollback.test.ts @@ -72,9 +72,12 @@ it.effect.each([ "checkpoint inherited by a prior fork", "repeated rollback after a handoff", "handoff prompt left in the source", + "a checkpoint recorded before upgrading, followed by a session switch", "switch timed out after attaching", ] as const)("restores exactly the retained Pi history for %s", (scenario) => Effect.gen(function* () { + const repro = + scenario === "a checkpoint recorded before upgrading, followed by a session switch"; const fs = yield* FileSystem.FileSystem; const dir = yield* fs.makeTempDirectoryScoped(); const oldFile = `${dir}/old.jsonl`; @@ -215,10 +218,10 @@ it.effect.each([ nativeTurnRef: ordinal === 3 && scenario === "command-only handoff" ? null - : ordinal === 3 && scenario === "uncaptured handoff" + : ordinal === 3 && (scenario === "uncaptured handoff" || repro) ? ref("uncaptured", "weak") : ref(`u${ordinal}`), - ...(scenario === "legacy turns" + ...(scenario === "legacy turns" || (repro && ordinal < 3) ? {} : { nativeThreadRef: ref( @@ -254,6 +257,15 @@ it.effect.each([ assert.deepEqual(sessionRequests, [{ type: "switch_session", file: oldFile }]); return; } + if (repro) { + const restored = yield* rollback.pipe(Effect.result); + assert.equal(restored._tag, "Success"); + assert.deepEqual( + sessions.get(liveFile)?.map(({ id }) => id), + ["u1", "a1", "u2", "steer", "a2"], + ); + return; + } const restored = yield* rollback; assert.equal( restored.providerThread.nativeThreadRef?.nativeId, From be8e0b50ea883d5c1be15e49602e755cda694566 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:07:23 +0100 Subject: [PATCH 2/9] fix(pi): rewind legacy checkpoints after a session switch Co-authored-by: GPT 6.2 Sol --- packages/provider-pi/src/server/adapter.ts | 75 +++++++++++++++++++--- 1 file changed, 65 insertions(+), 10 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 920acee2e200..9053fdaa6780 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3042,6 +3042,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return readable ? { entries, leafId } : null; }); + const historicalSessionFiles = Effect.fnUntraced(function* (sessionFile: string) { + const dir = path.dirname(sessionFile); + const siblings = yield* fileSystem + .readDirectoryEntries(dir) + .pipe(Effect.orElseSucceed(() => [])); + return siblings + .filter((entry) => entry.type === "File" && entry.name.endsWith(".jsonl")) + .map((entry) => path.join(dir, entry.name)) + .sort() + .reverse(); + }); + // Old records hold entry IDs without a session file. Recover only when both // timestamped user entries are on the same branch in a sibling session. const findHistoricalForkSession = Effect.fnUntraced(function* ( @@ -3063,15 +3075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const from = DateTime.toEpochMillis(startedAt); const between = DateTime.toEpochMillis(completedAt); const to = DateTime.toEpochMillis(boundaryEnd); - const dir = path.dirname(currentFile); - const siblings = yield* fileSystem - .readDirectoryEntries(dir) - .pipe(Effect.orElseSucceed(() => [])); - const files = siblings - .filter((entry) => entry.type === "File" && entry.name.endsWith(".jsonl")) - .map((entry) => path.join(dir, entry.name)) - .sort() - .reverse(); + const files = yield* historicalSessionFiles(currentFile); for (const file of files) { if (file === currentFile) continue; const listing = yield* readSessionFile(file); @@ -3088,6 +3092,31 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return undefined; }); + const findHistoricalCheckpointSession = Effect.fnUntraced(function* ( + boundaryFile: string, + targetId: string, + startedAt: DateTime.Utc, + completedAt: DateTime.Utc, + ) { + const from = DateTime.toEpochMillis(startedAt); + const to = DateTime.toEpochMillis(completedAt); + let match: string | undefined; + for (const file of yield* historicalSessionFiles(boundaryFile)) { + if (file === boundaryFile) continue; + const listing = yield* readSessionFile(file); + if ( + listing !== null && + piUserEntryInWindow(listing.entries.get(targetId), from, to) && + walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop === true + ) { + // Forks may inherit the same checkpoint, so the first match need not be its source. + if (match !== undefined) return undefined; + match = file; + } + } + return match; + }); + const sessionFileInCwd = Effect.fnUntraced(function* ( sessionFile: string, providerThreadCreatedAt: DateTime.Utc, @@ -4000,6 +4029,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( : firstBoundary.turn.nativeThreadRef?.nativeId; let boundary = firstBoundary; let sourceFile = targetFile ?? boundaryFile; + let recoveredLegacySource = false; const targetId = piTurnEntryId(target); if ( targetFile !== undefined && @@ -4031,6 +4061,31 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( boundary = piForkBoundary({ ...rollbackInput, sessionFile: targetFile }); } } + if ( + targetFile === undefined && + boundaryFile != null && + boundary.type === "uncaptured" && + targetId !== undefined && + target?.startedAt != null && + target.completedAt !== null + ) { + const resolvedBoundaryFile = path.resolve(cwd, boundaryFile); + const listing = isCurrentFile(boundaryFile) + ? piSessionListing(yield* request({ type: "get_entries" })) + : yield* readSessionFile(resolvedBoundaryFile); + if (listing !== null && !listing.entries.has(targetId)) { + sourceFile = yield* findHistoricalCheckpointSession( + resolvedBoundaryFile, + targetId, + target.startedAt, + target.completedAt, + ); + if (sourceFile === undefined) + return yield* protocolError("Pi rollback entry was not found in a session"); + boundary = { type: "nothing" }; + recoveredLegacySource = true; + } + } if ( sourceFile == null && currentFile != null && @@ -4084,7 +4139,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( rollbackInput.providerThread.createdAt, request({ type: "get_entries" }), ); - } else if (switchedTo === undefined) { + } else if (switchedTo === undefined && !recoveredLegacySource) { return piThreadSnapshot(state.providerThread); } else { const listing = piSessionListing(yield* request({ type: "get_entries" })); From 1a1656ff6476572d35601115ad4aebfa3f854d1a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:24:43 +0100 Subject: [PATCH 3/9] fix(pi): verify legacy rewind history across handoff types Co-authored-by: GPT 6.2 Sol --- .../provider-pi/src/server/adapter.test.ts | 98 ++++++++++ packages/provider-pi/src/server/adapter.ts | 175 ++++++++++++------ 2 files changed, 219 insertions(+), 54 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 5565f456677f..3205595bb24f 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4534,6 +4534,104 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + "captured handoff", + "uncaptured handoff", + "command-only handoff", + "legacy uncaptured boundary", + "adopted prompt", + "equivalent prior rollback fork", + "conflicting prior fork", + ] as const)("restores a legacy checkpoint after a %s", (scenario) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const original = `${dir}/z-original.jsonl`; + const switched = `${dir}/current.jsonl`; + const priorFork = `${dir}/fork.jsonl`; + const retained = TURN_ONE_ENTRIES; + const unrelated = [sessionMessage("u3", null, "user", 180)]; + const write = (file: string, entries: ReadonlyArray) => + fs.writeFileString( + file, + [{ type: "session", version: 3 }, ...entries].map(encodeJsonLine).join("\n") + "\n", + ); + const equivalent = scenario === "equivalent prior rollback fork"; + const conflicting = scenario === "conflicting prior fork"; + yield* write( + original, + equivalent ? [...retained, sessionMessage("discarded", "a1b", "user", 160)] : retained, + ); + yield* write(switched, unrelated); + if (equivalent || conflicting) + yield* write( + priorFork, + conflicting ? [...retained, sessionMessage("other", "a1b", "assistant", 40)] : retained, + ); + + const fake = yield* makeFakePi; + fake.reloadExtensions(switched); + const { runtime } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const [first, next] = uncapturedTurns(providerThread.id); + assert.isDefined(first); + assert.isDefined(next); + const target = { ...first, startedAt: at(scenario === "adopted prompt" ? 20 : 0) }; + const boundary: OrchestrationV2ProviderTurn = { + ...next, + nativeTurnRef: + scenario === "command-only handoff" + ? null + : scenario === "uncaptured handoff" || scenario === "legacy uncaptured boundary" + ? next.nativeTurnRef + : { driver: PI_PROVIDER, strength: "strong", nativeId: "u3" }, + ...(scenario === "legacy uncaptured boundary" + ? {} + : { + nativeThreadRef: { driver: PI_PROVIDER, strength: "strong", nativeId: switched }, + }), + }; + const expected = equivalent ? priorFork : original; + fake.queueEntries({ entries: unrelated, leafId: "u3" }); + fake.queueState({ sessionFile: expected }); + fake.queueState({ sessionFile: expected }); + fake.queueEntries({ entries: retained, leafId: "a1b" }); + fake.queueEntries({ entries: retained, leafId: "a1b" }); + const result = yield* runtime + .rollbackThread({ + providerThread: { ...providerThread, createdAt: at(0) }, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("legacy-checkpoint"), + appRunOrdinal: target.ordinal, + providerTurn: target, + }, + providerThreadTurns: [target, boundary], + }) + .pipe(Effect.result); + const requests = fake + .allRequests() + .filter(({ type }) => type === "switch_session" || type === "fork"); + if (conflicting) { + assert.equal(result._tag, "Failure"); + assert.deepEqual(requests, []); + return; + } + assert.equal(result._tag, "Success"); + if (result._tag !== "Success") return; + assert.equal(result.success.providerThread.nativeThreadRef?.nativeId, expected); + assert.equal(result.success.providerThread.nativeConversationHeadRef?.nativeId, "a1b"); + assert.deepEqual( + requests.map(({ type, sessionPath }) => ({ type, sessionPath })), + [{ type: "switch_session", sessionPath: expected }], + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("rolls back past a turn whose start entry was never captured", () => Effect.gen(function* () { const fake = yield* makeFakePi; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 9053fdaa6780..6cede690bd76 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3095,26 +3095,38 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const findHistoricalCheckpointSession = Effect.fnUntraced(function* ( boundaryFile: string, targetId: string, - startedAt: DateTime.Utc, + earliestPromptAt: DateTime.Utc, completedAt: DateTime.Utc, ) { - const from = DateTime.toEpochMillis(startedAt); + const from = DateTime.toEpochMillis(earliestPromptAt); const to = DateTime.toEpochMillis(completedAt); - let match: string | undefined; + let match: + | { file: string; listing: PiSessionListing; retained: PiRetainedCheckpoint } + | undefined; for (const file of yield* historicalSessionFiles(boundaryFile)) { if (file === boundaryFile) continue; const listing = yield* readSessionFile(file); + if (listing === null || !piUserEntryInWindow(listing.entries.get(targetId), from, to)) + continue; + const retained = piRetainedCheckpoint(listing, targetId, to); + if (retained === undefined) continue; if ( - listing !== null && - piUserEntryInWindow(listing.entries.get(targetId), from, to) && - walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop === true + match !== undefined && + (retained.headId !== match.retained.headId || + !piSameAncestry(listing, match.listing, retained.headId)) + ) { + return yield* protocolError( + "Pi rollback found conflicting histories for the checkpoint", + ); + } + if ( + match === undefined || + (match.retained.forkEntryId !== undefined && retained.forkEntryId === undefined) ) { - // Forks may inherit the same checkpoint, so the first match need not be its source. - if (match !== undefined) return undefined; - match = file; + match = { file, listing, retained }; } } - return match; + return match?.file; }); const sessionFileInCwd = Effect.fnUntraced(function* ( @@ -4030,6 +4042,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( let boundary = firstBoundary; let sourceFile = targetFile ?? boundaryFile; let recoveredLegacySource = false; + const readEntries = request({ type: "get_entries" }); + const readCurrentEntries = yield* Effect.cached(readEntries); const targetId = piTurnEntryId(target); if ( targetFile !== undefined && @@ -4061,31 +4075,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( boundary = piForkBoundary({ ...rollbackInput, sessionFile: targetFile }); } } - if ( - targetFile === undefined && - boundaryFile != null && - boundary.type === "uncaptured" && - targetId !== undefined && - target?.startedAt != null && - target.completedAt !== null - ) { - const resolvedBoundaryFile = path.resolve(cwd, boundaryFile); - const listing = isCurrentFile(boundaryFile) - ? piSessionListing(yield* request({ type: "get_entries" })) - : yield* readSessionFile(resolvedBoundaryFile); - if (listing !== null && !listing.entries.has(targetId)) { - sourceFile = yield* findHistoricalCheckpointSession( - resolvedBoundaryFile, - targetId, - target.startedAt, - target.completedAt, - ); - if (sourceFile === undefined) - return yield* protocolError("Pi rollback entry was not found in a session"); - boundary = { type: "nothing" }; - recoveredLegacySource = true; - } - } if ( sourceFile == null && currentFile != null && @@ -4099,8 +4088,60 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const live = yield* readSessionFile(path.resolve(cwd, currentFile)); if (live !== null && !live.entries.has(boundary.entryId)) { sourceFile = yield* findHistoricalForkSession(currentFile, boundary); + } + } + const candidateFile = sourceFile ?? currentFile; + if ( + targetFile === undefined && + candidateFile != null && + targetId !== undefined && + target?.startedAt != null && + target.completedAt !== null + ) { + const resolvedCandidate = path.resolve(cwd, candidateFile); + const listing = isCurrentFile(candidateFile) + ? piSessionListing(yield* readCurrentEntries) + : yield* readSessionFile(resolvedCandidate); + if (listing === null) + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); + if ( + walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== true + ) { + const previousTurn = rollbackInput.providerThreadTurns.reduce< + OrchestrationV2ProviderTurn | undefined + >( + (previous, turn) => + turn.ordinal < target.ordinal && + (previous === undefined || turn.ordinal > previous.ordinal) + ? turn + : previous, + undefined, + ); + const earliestPromptAt = + previousTurn?.completedAt ?? rollbackInput.providerThread.createdAt; + sourceFile = yield* findHistoricalCheckpointSession( + resolvedCandidate, + targetId, + DateTime.min(earliestPromptAt, target.startedAt), + target.completedAt, + ); if (sourceFile === undefined) return yield* protocolError("Pi rollback entry was not found in a session"); + boundary = { type: "nothing" }; + recoveredLegacySource = true; + } else if ( + boundary.type === "entry" && + (boundary.entryId === targetId || + walkPiBranch(listing.entries, listing.leafId, boundary.entryId) + ?.reachedStop !== true || + walkPiBranch(listing.entries, boundary.entryId, targetId)?.reachedStop !== + true) + ) { + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); } } let switchedTo: string | undefined; @@ -4137,33 +4178,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( forkEntryId = yield* piForkEntry( boundary, rollbackInput.providerThread.createdAt, - request({ type: "get_entries" }), + switchedTo === undefined ? readCurrentEntries : readEntries, ); } else if (switchedTo === undefined && !recoveredLegacySource) { return piThreadSnapshot(state.providerThread); } else { const listing = piSessionListing(yield* request({ type: "get_entries" })); - const walk = - listing !== null && targetId !== undefined && listing.entries.has(targetId) - ? walkPiBranch(listing.entries, listing.leafId, targetId) - : null; - if (listing === null || walk?.reachedStop !== true) + const retained = + listing !== null && targetId !== undefined && target?.completedAt != null + ? piRetainedCheckpoint( + listing, + targetId, + DateTime.toEpochMillis(target.completedAt), + ) + : undefined; + if (retained === undefined) return yield* protocolError( "Pi rollback could not verify the retained session head", ); - // A move can leave prompts behind in the source file, even when no later - // app turn points at that file. Keep steers sent during the retained turn. - for (const id of [...walk.userEntryIds].reverse()) { - const timestamp = listing.entries.get(id)?.timestamp; - if (timestamp == null || target?.completedAt == null) - return yield* protocolError( - "Pi rollback could not verify the retained session head", - ); - if (timestamp >= DateTime.toEpochMillis(target.completedAt)) { - forkEntryId = id; - break; - } - } + forkEntryId = retained.forkEntryId; } if (forkEntryId !== undefined) { const forkData = yield* lifecycleRequest({ @@ -4443,6 +4476,40 @@ function walkPiBranch( return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt }; } +interface PiRetainedCheckpoint { + readonly headId: string; + readonly forkEntryId?: string; +} + +function piRetainedCheckpoint( + listing: PiSessionListing, + targetId: string, + completedAt: number, +): PiRetainedCheckpoint | undefined { + const walk = walkPiBranch(listing.entries, listing.leafId, targetId); + if (listing.leafId === null || walk?.reachedStop !== true || !listing.entries.has(targetId)) + return undefined; + // An extension can leave later prompts in the source. Keep steers within the retained turn. + for (const id of [...walk.userEntryIds].reverse()) { + const entry = listing.entries.get(id); + if (entry?.timestamp == null) return undefined; + if (entry.timestamp >= completedAt) + return entry.parentId === null ? undefined : { headId: entry.parentId, forkEntryId: id }; + } + return { headId: listing.leafId }; +} + +function piSameAncestry(a: PiSessionListing, b: PiSessionListing, headId: string): boolean { + if (walkPiBranch(a.entries, headId, null)?.reachedStop !== true) return false; + let id: string | null = headId; + while (id !== null) { + const entry: PiSessionEntry | undefined = a.entries.get(id); + if (entry === undefined || entry.parentId !== b.entries.get(id)?.parentId) return false; + id = entry.parentId; + } + return true; +} + type PiForkBoundary = | { readonly type: "entry"; From 9d5374a3f7a9ebe365da7377a0171424873a4fa6 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:25:18 +0100 Subject: [PATCH 4/9] fix(pi): preserve rewind when no prompt needs trimming Co-authored-by: GPT 6.2 Sol --- packages/provider-pi/src/server/adapter.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 6cede690bd76..786615a81c22 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -4184,12 +4184,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return piThreadSnapshot(state.providerThread); } else { const listing = piSessionListing(yield* request({ type: "get_entries" })); + const completedAt = target?.completedAt; const retained = - listing !== null && targetId !== undefined && target?.completedAt != null + listing !== null && targetId !== undefined ? piRetainedCheckpoint( listing, targetId, - DateTime.toEpochMillis(target.completedAt), + completedAt == null ? undefined : DateTime.toEpochMillis(completedAt), ) : undefined; if (retained === undefined) @@ -4484,7 +4485,7 @@ interface PiRetainedCheckpoint { function piRetainedCheckpoint( listing: PiSessionListing, targetId: string, - completedAt: number, + completedAt: number | undefined, ): PiRetainedCheckpoint | undefined { const walk = walkPiBranch(listing.entries, listing.leafId, targetId); if (listing.leafId === null || walk?.reachedStop !== true || !listing.entries.has(targetId)) @@ -4492,7 +4493,7 @@ function piRetainedCheckpoint( // An extension can leave later prompts in the source. Keep steers within the retained turn. for (const id of [...walk.userEntryIds].reverse()) { const entry = listing.entries.get(id); - if (entry?.timestamp == null) return undefined; + if (entry?.timestamp == null || completedAt === undefined) return undefined; if (entry.timestamp >= completedAt) return entry.parentId === null ? undefined : { headId: entry.parentId, forkEntryId: id }; } From 0ad4cc999c98ae2dc3a21001030427810705b86a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:26:23 +0100 Subject: [PATCH 5/9] test(pi): serialize session entries with the typed encoder Co-authored-by: GPT 6.2 Sol --- packages/provider-pi/src/server/adapter.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 3205595bb24f..fcaa4040aeef 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4554,7 +4554,9 @@ describe("PiAdapterV2", () => { const write = (file: string, entries: ReadonlyArray) => fs.writeFileString( file, - [{ type: "session", version: 3 }, ...entries].map(encodeJsonLine).join("\n") + "\n", + [{ type: "session", version: 3 }, ...entries] + .map((entry) => encodeJsonLine(entry)) + .join("\n") + "\n", ); const equivalent = scenario === "equivalent prior rollback fork"; const conflicting = scenario === "conflicting prior fork"; From 04d18c0280e49ae6ed7e1530ffd21bcb68cb5cf7 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:29:44 +0100 Subject: [PATCH 6/9] refactor(pi): find the previous turn the way piForkBoundary does Replace the typed reduce with the filter and sort used beside it. Co-authored-by: Claude Opus 5.5 --- packages/provider-pi/src/server/adapter.ts | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 786615a81c22..b7ef2b1469a4 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -4109,16 +4109,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if ( walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== true ) { - const previousTurn = rollbackInput.providerThreadTurns.reduce< - OrchestrationV2ProviderTurn | undefined - >( - (previous, turn) => - turn.ordinal < target.ordinal && - (previous === undefined || turn.ordinal > previous.ordinal) - ? turn - : previous, - undefined, - ); + const previousTurn = rollbackInput.providerThreadTurns + .filter((turn) => turn.ordinal < target.ordinal) + .sort((a, b) => b.ordinal - a.ordinal)[0]; const earliestPromptAt = previousTurn?.completedAt ?? rollbackInput.providerThread.createdAt; sourceFile = yield* findHistoricalCheckpointSession( From 472428f905e412e3231bb61e117358f8b5e566e3 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:38:05 +0100 Subject: [PATCH 7/9] fix(pi): verify rewind ancestry across session attachment Co-authored-by: GPT 6.2 Sol --- .../provider-pi/src/server/adapter.test.ts | 181 +++++++++++++----- packages/provider-pi/src/server/adapter.ts | 59 ++++-- 2 files changed, 170 insertions(+), 70 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index fcaa4040aeef..5db63453ece9 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -225,7 +225,9 @@ const recordedIdleState = (sessionFile: string) => ({ const PI_COMPACTING_PROMPT_ERROR = "Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry."; -const makeFakePi: Effect.Effect = Effect.gen(function* () { +const makeFakePiWithResponses = Effect.fnUntraced(function* ( + override?: (request: PiRpcRecord, response: PiRpcRecord) => Effect.Effect, +) { const stdout = yield* Queue.unbounded(); const requests = yield* Queue.unbounded(); const entriesQueue: Array = []; @@ -406,7 +408,8 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { continue; } const response = respondTo(record); - if (response !== null) yield* emit(response); + if (response !== null) + yield* emit(override === undefined ? response : yield* override(record, response)); } }); @@ -524,6 +527,8 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { } satisfies FakePi; }); +const makeFakePi: Effect.Effect = makeFakePiWithResponses(); + const makeAdapter = Effect.fnUntraced(function* ( fake: FakePi, launchArgs = "", @@ -4540,8 +4545,11 @@ describe("PiAdapterV2", () => { "command-only handoff", "legacy uncaptured boundary", "adopted prompt", - "equivalent prior rollback fork", + "retry after creating a recovery fork", "conflicting prior fork", + "captured boundary on a sibling branch", + "dangling checkpoint parent", + "different branch attached after recovery", ] as const)("restores a legacy checkpoint after a %s", (scenario) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -4550,29 +4558,88 @@ describe("PiAdapterV2", () => { const switched = `${dir}/current.jsonl`; const priorFork = `${dir}/fork.jsonl`; const retained = TURN_ONE_ENTRIES; - const unrelated = [sessionMessage("u3", null, "user", 180)]; - const write = (file: string, entries: ReadonlyArray) => - fs.writeFileString( - file, - [{ type: "session", version: 3 }, ...entries] - .map((entry) => encodeJsonLine(entry)) - .join("\n") + "\n", - ); - const equivalent = scenario === "equivalent prior rollback fork"; + const retry = scenario === "retry after creating a recovery fork"; const conflicting = scenario === "conflicting prior fork"; + const sibling = scenario === "captured boundary on a sibling branch"; + const changedBranch = scenario === "different branch attached after recovery"; + const handoff = sessionMessage( + "u3", + sibling || scenario === "dangling checkpoint parent" ? "a1b" : null, + "user", + 180, + ); + const sessions = new Map>>(); + const write = (file: string, entries: ReadonlyArray>) => + fs + .writeFileString( + file, + [{ type: "session", version: 3 }, ...entries] + .map((entry) => encodeJsonLine(entry)) + .join("\n") + "\n", + ) + .pipe(Effect.tap(() => Effect.sync(() => sessions.set(file, entries)))); + const extra = sessionMessage("other", "a1b", "assistant", 45); + const discarded = sessionMessage("discarded", "a1b", "user", 160); yield* write( original, - equivalent ? [...retained, sessionMessage("discarded", "a1b", "user", 160)] : retained, + changedBranch + ? [...retained, extra, discarded] + : retry + ? [...retained, discarded] + : retained, ); - yield* write(switched, unrelated); - if (equivalent || conflicting) - yield* write( - priorFork, - conflicting ? [...retained, sessionMessage("other", "a1b", "assistant", 40)] : retained, - ); + yield* write( + switched, + sibling + ? [...retained, handoff, sessionMessage("sibling", null, "assistant", 28)] + : scenario === "dangling checkpoint parent" + ? [...retained.slice(1), handoff] + : [handoff], + ); + if (conflicting) yield* write(priorFork, [...retained, extra]); - const fake = yield* makeFakePi; - fake.reloadExtensions(switched); + let liveFile = switched; + const fake = yield* makeFakePiWithResponses((request, response) => + Effect.gen(function* () { + const entries = sessions.get(liveFile) ?? []; + switch (request.type) { + case "get_state": + return { ...response, data: recordedIdleState(liveFile) }; + case "get_entries": + return { + ...response, + data: { + entries, + leafId: + changedBranch && liveFile === original ? "other" : (entries.at(-1)?.id ?? null), + }, + }; + case "switch_session": { + const file = request.sessionPath; + if (typeof file !== "string" || !sessions.has(file)) + throw new Error("Pi switch requested an unknown fixture session"); + liveFile = file; + return response; + } + case "fork": { + let parentId = entries.find(({ id }) => id === request.entryId)?.parentId; + assert.isDefined(parentId); + const branch: Array> = []; + while (parentId !== null) { + const entry = entries.find(({ id }) => id === parentId); + assert.isDefined(entry); + branch.unshift(entry); + parentId = entry.parentId; + } + yield* write(priorFork, branch).pipe(Effect.orDie); + liveFile = priorFork; + return response; + } + default: + return response; + } + }), + ); const { runtime } = yield* openRuntime(fake); const providerThread = yield* runtime.ensureThread({ threadId: THREAD_ID, @@ -4597,40 +4664,48 @@ describe("PiAdapterV2", () => { nativeThreadRef: { driver: PI_PROVIDER, strength: "strong", nativeId: switched }, }), }; - const expected = equivalent ? priorFork : original; - fake.queueEntries({ entries: unrelated, leafId: "u3" }); - fake.queueState({ sessionFile: expected }); - fake.queueState({ sessionFile: expected }); - fake.queueEntries({ entries: retained, leafId: "a1b" }); - fake.queueEntries({ entries: retained, leafId: "a1b" }); - const result = yield* runtime - .rollbackThread({ - providerThread: { ...providerThread, createdAt: at(0) }, - target: { - type: "provider_turn", - checkpointId: CheckpointId.make("legacy-checkpoint"), - appRunOrdinal: target.ordinal, - providerTurn: target, - }, - providerThreadTurns: [target, boundary], - }) - .pipe(Effect.result); - const requests = fake - .allRequests() - .filter(({ type }) => type === "switch_session" || type === "fork"); - if (conflicting) { - assert.equal(result._tag, "Failure"); - assert.deepEqual(requests, []); + const rewind = runtime.rollbackThread({ + providerThread: { ...providerThread, createdAt: at(0) }, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("legacy-checkpoint"), + appRunOrdinal: target.ordinal, + providerTurn: target, + }, + providerThreadTurns: [target, boundary], + }); + const requests = () => + fake.allRequests().flatMap((request) => { + if (request.type === "switch_session") + return [{ type: request.type, value: request.sessionPath }]; + if (request.type === "fork") return [{ type: request.type, value: request.entryId }]; + return []; + }); + if (conflicting || changedBranch) { + assert.equal((yield* rewind.pipe(Effect.result))._tag, "Failure"); + assert.deepEqual( + requests(), + changedBranch ? [{ type: "switch_session", value: original }] : [], + ); return; } - assert.equal(result._tag, "Success"); - if (result._tag !== "Success") return; - assert.equal(result.success.providerThread.nativeThreadRef?.nativeId, expected); - assert.equal(result.success.providerThread.nativeConversationHeadRef?.nativeId, "a1b"); - assert.deepEqual( - requests.map(({ type, sessionPath }) => ({ type, sessionPath })), - [{ type: "switch_session", sessionPath: expected }], - ); + const expected = retry || sibling ? priorFork : original; + const assertRestored = ({ providerThread: restored }: Effect.Success) => { + assert.equal(restored.nativeThreadRef?.nativeId, expected); + assert.equal(restored.nativeConversationHeadRef?.nativeId, "a1b"); + assert.equal(liveFile, expected); + assert.deepEqual(sessions.get(liveFile), retained); + }; + const expectedRequests = [ + ...(sibling ? [] : [{ type: "switch_session", value: original }]), + ...(retry || sibling ? [{ type: "fork", value: sibling ? "u3" : "discarded" }] : []), + ]; + assertRestored(yield* rewind); + assert.deepEqual(requests(), expectedRequests); + if (retry) { + assertRestored(yield* rewind); + assert.deepEqual(requests(), expectedRequests); + } }).pipe(Effect.scoped, Effect.provide(layerTest)), ); diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index b7ef2b1469a4..53089ca051a4 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3100,9 +3100,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const from = DateTime.toEpochMillis(earliestPromptAt); const to = DateTime.toEpochMillis(completedAt); - let match: - | { file: string; listing: PiSessionListing; retained: PiRetainedCheckpoint } - | undefined; + let match: PiHistoricalCheckpoint | undefined; for (const file of yield* historicalSessionFiles(boundaryFile)) { if (file === boundaryFile) continue; const listing = yield* readSessionFile(file); @@ -3126,7 +3124,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( match = { file, listing, retained }; } } - return match?.file; + return match; }); const sessionFileInCwd = Effect.fnUntraced(function* ( @@ -4041,7 +4039,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( : firstBoundary.turn.nativeThreadRef?.nativeId; let boundary = firstBoundary; let sourceFile = targetFile ?? boundaryFile; - let recoveredLegacySource = false; + let recoveredLegacySource: PiHistoricalCheckpoint | undefined; const readEntries = request({ type: "get_entries" }); const readCurrentEntries = yield* Effect.cached(readEntries); const targetId = piTurnEntryId(target); @@ -4106,31 +4104,33 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return yield* protocolError( "Pi rollback could not verify the retained session head", ); + const boundaryId = boundary.type === "entry" ? boundary.entryId : undefined; if ( - walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== true + !listing.entries.has(targetId) || + (boundaryId === undefined + ? walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== + true + : !listing.entries.has(boundaryId)) ) { const previousTurn = rollbackInput.providerThreadTurns .filter((turn) => turn.ordinal < target.ordinal) .sort((a, b) => b.ordinal - a.ordinal)[0]; const earliestPromptAt = previousTurn?.completedAt ?? rollbackInput.providerThread.createdAt; - sourceFile = yield* findHistoricalCheckpointSession( + recoveredLegacySource = yield* findHistoricalCheckpointSession( resolvedCandidate, targetId, DateTime.min(earliestPromptAt, target.startedAt), target.completedAt, ); - if (sourceFile === undefined) + if (recoveredLegacySource === undefined) return yield* protocolError("Pi rollback entry was not found in a session"); + sourceFile = recoveredLegacySource.file; boundary = { type: "nothing" }; - recoveredLegacySource = true; } else if ( - boundary.type === "entry" && - (boundary.entryId === targetId || - walkPiBranch(listing.entries, listing.leafId, boundary.entryId) - ?.reachedStop !== true || - walkPiBranch(listing.entries, boundary.entryId, targetId)?.reachedStop !== - true) + boundaryId !== undefined && + (boundaryId === targetId || + walkPiBranch(listing.entries, boundaryId, targetId)?.reachedStop !== true) ) { return yield* protocolError( "Pi rollback could not verify the retained session head", @@ -4173,7 +4173,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( rollbackInput.providerThread.createdAt, switchedTo === undefined ? readCurrentEntries : readEntries, ); - } else if (switchedTo === undefined && !recoveredLegacySource) { + } else if (switchedTo === undefined && recoveredLegacySource === undefined) { return piThreadSnapshot(state.providerThread); } else { const listing = piSessionListing(yield* request({ type: "get_entries" })); @@ -4186,7 +4186,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( completedAt == null ? undefined : DateTime.toEpochMillis(completedAt), ) : undefined; - if (retained === undefined) + if ( + listing === null || + retained === undefined || + (recoveredLegacySource !== undefined && + (retained.headId !== recoveredLegacySource.retained.headId || + !piSameAncestry(listing, recoveredLegacySource.listing, retained.headId))) + ) return yield* protocolError( "Pi rollback could not verify the retained session head", ); @@ -4216,6 +4222,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.orElseSucceed(() => undefined), ); const leafId = recordString(entriesData, "leafId") ?? null; + if (recoveredLegacySource !== undefined) { + const listing = piSessionListing(entriesData); + if ( + listing === null || + leafId !== recoveredLegacySource.retained.headId || + !piSameAncestry(listing, recoveredLegacySource.listing, leafId) + ) { + threadState = null; + return yield* protocolError( + "Pi rollback could not verify the retained session head", + ); + } + } // RPC responses bypass the pump; drain prior native events before replacing their binding. const queued = yield* Queue.offer(connection.events, { type: "t3.rollback_barrier", @@ -4475,6 +4494,12 @@ interface PiRetainedCheckpoint { readonly forkEntryId?: string; } +interface PiHistoricalCheckpoint { + readonly file: string; + readonly listing: PiSessionListing; + readonly retained: PiRetainedCheckpoint; +} + function piRetainedCheckpoint( listing: PiSessionListing, targetId: string, From ed7218a1b59a825772cd4b6d10c7ea8db7f13b67 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:03:51 +0000 Subject: [PATCH 8/9] test(pi): drop the adapter row that repeats the rollback repro Co-Authored-By: Claude Opus 5.5 --- packages/provider-pi/src/server/adapter.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 5db63453ece9..f754532afdac 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4541,7 +4541,6 @@ describe("PiAdapterV2", () => { it.effect.each([ "captured handoff", - "uncaptured handoff", "command-only handoff", "legacy uncaptured boundary", "adopted prompt", @@ -4655,7 +4654,7 @@ describe("PiAdapterV2", () => { nativeTurnRef: scenario === "command-only handoff" ? null - : scenario === "uncaptured handoff" || scenario === "legacy uncaptured boundary" + : scenario === "legacy uncaptured boundary" ? next.nativeTurnRef : { driver: PI_PROVIDER, strength: "strong", nativeId: "u3" }, ...(scenario === "legacy uncaptured boundary" From 382981afe6b4901522e509902c421d37866f8c10 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 25 Nov 2026 07:14:56 +0000 Subject: [PATCH 9/9] fix(pi): compare recovered history around Pi's rewritten labels Pi's fork drops label entries from the copied path and re-adds them with new ids at the leaf, so exact head and parent comparisons rejected a valid recovery fork whenever the retained history held a label. Co-Authored-By: Claude Opus 5.5 --- .../provider-pi/src/server/adapter.test.ts | 35 ++++++++---- packages/provider-pi/src/server/adapter.ts | 54 ++++++++++++++----- 2 files changed, 67 insertions(+), 22 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index f754532afdac..99adf0393e53 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4545,6 +4545,7 @@ describe("PiAdapterV2", () => { "legacy uncaptured boundary", "adopted prompt", "retry after creating a recovery fork", + "label before the discarded prompt", "conflicting prior fork", "captured boundary on a sibling branch", "dangling checkpoint parent", @@ -4557,7 +4558,8 @@ describe("PiAdapterV2", () => { const switched = `${dir}/current.jsonl`; const priorFork = `${dir}/fork.jsonl`; const retained = TURN_ONE_ENTRIES; - const retry = scenario === "retry after creating a recovery fork"; + const labelled = scenario === "label before the discarded prompt"; + const retry = labelled || scenario === "retry after creating a recovery fork"; const conflicting = scenario === "conflicting prior fork"; const sibling = scenario === "captured boundary on a sibling branch"; const changedBranch = scenario === "different branch attached after recovery"; @@ -4567,8 +4569,9 @@ describe("PiAdapterV2", () => { "user", 180, ); - const sessions = new Map>>(); - const write = (file: string, entries: ReadonlyArray>) => + type Entry = { readonly id: string; readonly parentId: string | null; readonly type: string }; + const sessions = new Map>(); + const write = (file: string, entries: ReadonlyArray) => fs .writeFileString( file, @@ -4578,13 +4581,14 @@ describe("PiAdapterV2", () => { ) .pipe(Effect.tap(() => Effect.sync(() => sessions.set(file, entries)))); const extra = sessionMessage("other", "a1b", "assistant", 45); - const discarded = sessionMessage("discarded", "a1b", "user", 160); + const discarded = sessionMessage("discarded", labelled ? "label" : "a1b", "user", 160); + const label = { type: "label", id: "label", parentId: "a1b", targetId: "a1", label: "keep" }; yield* write( original, changedBranch ? [...retained, extra, discarded] : retry - ? [...retained, discarded] + ? [...retained, ...(labelled ? [label] : []), discarded] : retained, ); yield* write( @@ -4623,13 +4627,23 @@ describe("PiAdapterV2", () => { case "fork": { let parentId = entries.find(({ id }) => id === request.entryId)?.parentId; assert.isDefined(parentId); - const branch: Array> = []; + const path: Array = []; while (parentId !== null) { const entry = entries.find(({ id }) => id === parentId); assert.isDefined(entry); - branch.unshift(entry); + path.unshift(entry); parentId = entry.parentId; } + // Like Pi, drop labels from the path and re-add them with new ids at the leaf. + const branch: Array = []; + for (const entry of path.filter(({ type }) => type !== "label")) + branch.push({ ...entry, parentId: branch.at(-1)?.id ?? null }); + for (const entry of path.filter(({ type }) => type === "label")) + branch.push({ + ...entry, + id: `${entry.id}-copy`, + parentId: branch.at(-1)?.id ?? null, + }); yield* write(priorFork, branch).pipe(Effect.orDie); liveFile = priorFork; return response; @@ -4691,9 +4705,12 @@ describe("PiAdapterV2", () => { const expected = retry || sibling ? priorFork : original; const assertRestored = ({ providerThread: restored }: Effect.Success) => { assert.equal(restored.nativeThreadRef?.nativeId, expected); - assert.equal(restored.nativeConversationHeadRef?.nativeId, "a1b"); + assert.equal(restored.nativeConversationHeadRef?.nativeId, labelled ? "label-copy" : "a1b"); assert.equal(liveFile, expected); - assert.deepEqual(sessions.get(liveFile), retained); + assert.deepEqual( + sessions.get(liveFile)?.filter(({ type }) => type !== "label"), + retained, + ); }; const expectedRequests = [ ...(sibling ? [] : [{ type: "switch_session", value: original }]), diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 53089ca051a4..3195b6c62d2a 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3110,8 +3110,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (retained === undefined) continue; if ( match !== undefined && - (retained.headId !== match.retained.headId || - !piSameAncestry(listing, match.listing, retained.headId)) + !piSameHistory(listing, retained.headId, match.listing, match.retained.headId) ) { return yield* protocolError( "Pi rollback found conflicting histories for the checkpoint", @@ -4190,8 +4189,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( listing === null || retained === undefined || (recoveredLegacySource !== undefined && - (retained.headId !== recoveredLegacySource.retained.headId || - !piSameAncestry(listing, recoveredLegacySource.listing, retained.headId))) + !piSameHistory( + listing, + retained.headId, + recoveredLegacySource.listing, + recoveredLegacySource.retained.headId, + )) ) return yield* protocolError( "Pi rollback could not verify the retained session head", @@ -4226,8 +4229,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const listing = piSessionListing(entriesData); if ( listing === null || - leafId !== recoveredLegacySource.retained.headId || - !piSameAncestry(listing, recoveredLegacySource.listing, leafId) + !piSameHistory( + listing, + leafId, + recoveredLegacySource.listing, + recoveredLegacySource.retained.headId, + ) ) { threadState = null; return yield* protocolError( @@ -4404,6 +4411,7 @@ const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schem interface PiSessionEntry { readonly parentId: string | null; readonly isUserMessage: boolean; + readonly isLabel: boolean; /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */ readonly timestamp: number | null; } @@ -4444,6 +4452,7 @@ function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { isUserMessage: recordField(entry, "type") === "message" && recordString(recordField(entry, "message"), "role") === "user", + isLabel: recordField(entry, "type") === "label", timestamp: timestamp === undefined ? null @@ -4518,15 +4527,34 @@ function piRetainedCheckpoint( return { headId: listing.leafId }; } -function piSameAncestry(a: PiSessionListing, b: PiSessionListing, headId: string): boolean { - if (walkPiBranch(a.entries, headId, null)?.reachedStop !== true) return false; - let id: string | null = headId; - while (id !== null) { - const entry: PiSessionEntry | undefined = a.entries.get(id); - if (entry === undefined || entry.parentId !== b.entries.get(id)?.parentId) return false; +// Pi's fork drops label entries from the copied path and re-adds them with new ids at the leaf. +function piSameHistory( + a: PiSessionListing, + aHead: string | null, + b: PiSessionListing, + bHead: string | null, +): boolean { + const aPath = piContentPath(a, aHead); + const bPath = piContentPath(b, bHead); + return ( + aPath !== null && + bPath !== null && + aPath.length === bPath.length && + aPath.every((id, index) => id === bPath[index]) + ); +} + +function piContentPath(listing: PiSessionListing, headId: string | null): Array | null { + const path: Array = []; + const visited = new Set(); + for (let id = headId; id !== null;) { + const entry = listing.entries.get(id); + if (entry === undefined || visited.has(id)) return null; + visited.add(id); + if (!entry.isLabel) path.push(id); id = entry.parentId; } - return true; + return path; } type PiForkBoundary =