From 5229e42d6602b380ac3430bac2221660957f9490 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:59:14 +0100 Subject: [PATCH 1/8] test(pi): reproduce legacy forks after a session handoff Co-authored-by: GPT 6.2 Sol --- .../provider-pi/src/server/rollback.test.ts | 157 +++++++++++------- 1 file changed, 98 insertions(+), 59 deletions(-) diff --git a/packages/provider-pi/src/server/rollback.test.ts b/packages/provider-pi/src/server/rollback.test.ts index a742af314d50..0d7942285101 100644 --- a/packages/provider-pi/src/server/rollback.test.ts +++ b/packages/provider-pi/src/server/rollback.test.ts @@ -24,7 +24,9 @@ import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { expect } from "vite-plus/test"; import { makePiAdapterV2, PI_PROVIDER } from "./adapter.ts"; const layerTest = Layer.mergeAll( @@ -64,6 +66,7 @@ const decodeRequest = Schema.decodeUnknownSync( ); it.effect.each([ + "fork across a legacy session switch", "earlier checkpoint", "last checkpoint", "uncaptured handoff", @@ -112,65 +115,76 @@ it.effect.each([ ); } - const output = yield* Queue.unbounded(); const switchApplied = yield* Deferred.make(); const sessionRequests: { readonly type: string; readonly file: string }[] = []; - let liveFile = currentFile; - let pending = ""; - const encoder = new TextEncoder(); - const decoder = new TextDecoder(); - const stdin = Sink.forEach((chunk: Uint8Array) => + let attachedFile = currentFile; + const spawner = ChildProcessSpawner.make((command) => Effect.gen(function* () { - const lines = (pending + decoder.decode(chunk, { stream: true })).split("\n"); - pending = lines.pop() ?? ""; - for (const line of lines) { - const request = decodeRequest(line); - const entries = sessions.get(liveFile) ?? []; - let data: unknown = {}; - let error: string | undefined; - if (request.type === "get_state") data = { sessionFile: liveFile }; - if (request.type === "get_entries") - data = { entries, leafId: entries.at(-1)?.id ?? null }; - if (request.type === "switch_session") { - if (request.sessionPath !== undefined && sessions.has(request.sessionPath)) { - liveFile = request.sessionPath; - sessionRequests.push({ type: "switch_session", file: liveFile }); - if (scenario === "switch timed out after attaching") { - yield* Deferred.succeed(switchApplied, undefined); - continue; + const output = yield* Queue.unbounded(); + const args = ChildProcess.isStandardCommand(command) ? command.args.map(String) : []; + const sourceFile = args.includes("--fork") ? args[args.indexOf("--fork") + 1] : undefined; + const cloneFile = `${dir}/clone.jsonl`; + let liveFile = currentFile; + if (sourceFile !== undefined) { + sessions.set(cloneFile, [...(sessions.get(sourceFile) ?? [])]); + liveFile = cloneFile; + } + let pending = ""; + const encoder = new TextEncoder(); + const decoder = new TextDecoder(); + const stdin = Sink.forEach((chunk: Uint8Array) => + Effect.gen(function* () { + const lines = (pending + decoder.decode(chunk, { stream: true })).split("\n"); + pending = lines.pop() ?? ""; + for (const line of lines) { + const request = decodeRequest(line); + const entries = sessions.get(liveFile) ?? []; + let data: unknown = {}; + let error: string | undefined; + if (request.type === "get_state") data = { sessionFile: liveFile }; + if (request.type === "get_entries") + data = { entries, leafId: entries.at(-1)?.id ?? null }; + if (request.type === "switch_session") { + if (request.sessionPath !== undefined && sessions.has(request.sessionPath)) { + liveFile = request.sessionPath; + sessionRequests.push({ type: "switch_session", file: liveFile }); + if (scenario === "switch timed out after attaching") { + attachedFile = liveFile; + yield* Deferred.succeed(switchApplied, undefined); + continue; + } + data = { cancelled: false }; + } else error = "Session not found"; + } + if (request.type === "fork") { + const index = entries.findIndex(({ id }) => id === request.entryId); + if (index === -1) error = "Invalid entry ID for forking"; + else { + sessionRequests.push({ type: "fork", file: liveFile }); + const branchFile = + sourceFile === undefined ? forkedFile : `${dir}/clone-branch.jsonl`; + sessions.set(branchFile, entries.slice(0, index)); + liveFile = branchFile; + data = { cancelled: false }; + } } - data = { cancelled: false }; - } else error = "Session not found"; - } - if (request.type === "fork") { - const index = entries.findIndex(({ id }) => id === request.entryId); - if (index === -1) error = "Invalid entry ID for forking"; - else { - sessionRequests.push({ type: "fork", file: liveFile }); - sessions.set(forkedFile, entries.slice(0, index)); - liveFile = forkedFile; - data = { cancelled: false }; + yield* Queue.offer( + output, + encoder.encode( + JSON.stringify({ + type: "response", + id: request.id, + command: request.type, + success: error === undefined, + data, + error, + }) + "\n", + ), + ); } - } - yield* Queue.offer( - output, - encoder.encode( - JSON.stringify({ - type: "response", - id: request.id, - command: request.type, - success: error === undefined, - data, - error, - }) + "\n", - ), - ); - } - }), - ); - const spawner = ChildProcessSpawner.make(() => - Effect.succeed( - ChildProcessSpawner.makeHandle({ + }), + ); + return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(999_999_999), exitCode: Effect.never, isRunning: Effect.succeed(true), @@ -182,8 +196,8 @@ it.effect.each([ all: Stream.empty, getInputFd: () => Sink.drain, getOutputFd: () => Stream.empty, - }), - ), + }); + }), ); const instanceId = ProviderInstanceId.make("pi"); const adapter = yield* makePiAdapterV2({ @@ -218,7 +232,8 @@ it.effect.each([ : ordinal === 3 && scenario === "uncaptured handoff" ? ref("uncaptured", "weak") : ref(`u${ordinal}`), - ...(scenario === "legacy turns" + ...(scenario === "legacy turns" || + (scenario === "fork across a legacy session switch" && ordinal < 3) ? {} : { nativeThreadRef: ref( @@ -233,6 +248,30 @@ it.effect.each([ ); const shouldFork = scenario === "earlier checkpoint" || scenario === "legacy turns"; const target = turns[shouldFork ? 0 : 1]!; + if (scenario === "fork across a legacy session switch") { + const targetThreadId = ThreadId.make("pi-fork"); + const targetRuntime = yield* adapter.openSession({ + threadId: targetThreadId, + providerSessionId: ProviderSessionId.make("pi-fork"), + modelSelection, + runtimePolicy, + }); + yield* targetRuntime.events.pipe(Stream.runDrain, Effect.forkScoped); + const forked = yield* targetRuntime.forkThread({ + sourceProviderThread: providerThread, + sourceProviderTurns: turns, + providerTurnId: target.id, + targetThreadId, + }); + expect(sessions.get(forked.nativeThreadRef?.nativeId ?? "")?.map(({ id }) => id)).toEqual([ + "u1", + "a1", + "u2", + "steer", + "a2", + ]); + return; + } const rollback = runtime.rollbackThread({ providerThread, target: { @@ -246,7 +285,7 @@ it.effect.each([ if (scenario === "switch timed out after attaching") { const attempt = yield* rollback.pipe(Effect.result, Effect.forkChild); yield* Deferred.await(switchApplied); - assert.equal(liveFile, oldFile); + assert.equal(attachedFile, oldFile); yield* TestClock.adjust("61 seconds"); assert.equal((yield* Fiber.join(attempt))._tag, "Failure"); yield* Fiber.join(events); @@ -264,7 +303,7 @@ it.effect.each([ shouldFork ? "a1" : "a2", ); assert.deepEqual( - sessions.get(liveFile)?.map(({ id }) => id), + sessions.get(restored.providerThread.nativeThreadRef?.nativeId ?? "")?.map(({ id }) => id), shouldFork ? ["u1", "a1"] : ["u1", "a1", "u2", "steer", "a2"], ); assert.deepEqual( From 21357300549a6b6951722182646eba8c231148db Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:02:11 +0100 Subject: [PATCH 2/8] fix(pi): preserve legacy fork history after a handoff Co-authored-by: GPT 6.2 Sol --- packages/provider-pi/src/server/adapter.ts | 61 +++++++++++++++++++--- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 920acee2e200..c2c2b18392e6 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3042,11 +3042,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return readable ? { entries, leafId } : null; }); - // 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. + // Old records hold entry IDs without a session file. Use timestamped user entries + // to distinguish the original branch from unrelated sessions with matching IDs. const findHistoricalForkSession = Effect.fnUntraced(function* ( currentFile: string, boundary: Extract, + acrossHandoff = false, ) { const targetId = piTurnEntryId(boundary.target); const startedAt = boundary.target?.startedAt; @@ -3072,12 +3073,30 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( .map((entry) => path.join(dir, entry.name)) .sort() .reverse(); + let historicalFile: string | undefined; for (const file of files) { if (file === currentFile) continue; const listing = yield* readSessionFile(file); if ( - listing !== null && - piUserEntryInWindow(listing.entries.get(targetId), from, between) && + listing === null || + !piUserEntryInWindow(listing.entries.get(targetId), from, between) + ) + continue; + if (acrossHandoff) { + // The discard boundary is in the new session. Clone only a unique old branch + // whose saved history already ends within the selected turn. + const leafTime = + listing.leafId === null ? null : listing.entries.get(listing.leafId)?.timestamp; + if ( + leafTime == null || + leafTime < from || + leafTime > between || + walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== true + ) + continue; + if (historicalFile !== undefined) return undefined; + historicalFile = file; + } else if ( piUserEntryInWindow(listing.entries.get(boundary.entryId), between, to) && walkPiBranch(listing.entries, listing.leafId, boundary.entryId)?.reachedStop === true && walkPiBranch(listing.entries, boundary.entryId, targetId)?.reachedStop === true @@ -3085,7 +3104,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return file; } } - return undefined; + return historicalFile; }); const sessionFileInCwd = Effect.fnUntraced(function* ( @@ -4224,11 +4243,41 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const boundaryFile = boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; const sourceFile = targetFile ?? boundaryFile ?? currentFile; - const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt).pipe( + let historicalFile: string | undefined; + // Pi can successfully fork before the first entry in the new session, + // even though that session never contained the selected turn. + if (targetFile === undefined && boundaryFile != null && boundary.type === "entry") { + const targetId = piTurnEntryId(boundary.target); + const completedAt = boundary.target?.completedAt; + const boundaryEnd = boundary.turn.completedAt; + if (targetId !== undefined && completedAt != null && boundaryEnd !== null) { + const file = path.resolve(cwd, boundaryFile); + const listing = yield* readSessionFile(file); + if ( + listing !== null && + !listing.entries.has(targetId) && + piUserEntryInWindow( + listing.entries.get(boundary.entryId), + DateTime.toEpochMillis(completedAt), + DateTime.toEpochMillis(boundaryEnd), + ) + ) { + historicalFile = yield* findHistoricalForkSession(file, boundary, true); + if (historicalFile === undefined) + return yield* protocolError("Pi fork target was not found in a session"); + } + } + } + const nativeId = yield* forkSessionIntoCwd( + historicalFile ?? sourceFile, + historicalFile === undefined ? boundary : { type: "nothing" }, + source.createdAt, + ).pipe( Effect.catchTags({ PiRpcError: (error) => { if ( boundary.type !== "entry" || + targetFile !== undefined || boundaryFile != null || error.operation !== "fork" || error.detail !== "Invalid entry ID for forking" From ddd735c0d360568f5ccd0ce23bf30a48c74498c8 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:04:50 +0100 Subject: [PATCH 3/8] refactor(pi): drop the fork retry guard the fix does not need The legacy retry already requires boundaryFile to be unset; the extra targetFile check changed a path the fix never reaches. Co-authored-by: Claude Opus 5.5 --- packages/provider-pi/src/server/adapter.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index c2c2b18392e6..1cded39a0944 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -4277,7 +4277,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( PiRpcError: (error) => { if ( boundary.type !== "entry" || - targetFile !== undefined || boundaryFile != null || error.operation !== "fork" || error.detail !== "Invalid entry ID for forking" From ff6879939f1e3429e6b1abb84330527051ad5c87 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:20:22 +0100 Subject: [PATCH 4/8] fix(pi): recover legacy handoffs for forks and rollback Co-authored-by: GPT 6.2 Sol --- .../provider-pi/src/server/adapter.test.ts | 118 +++++++++++ packages/provider-pi/src/server/adapter.ts | 185 +++++++++++------- 2 files changed, 231 insertions(+), 72 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 5565f456677f..7aa90da48c01 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -3254,6 +3254,124 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect.each([ + "equivalent copies with a discarded prompt", + "running legacy boundary with a colliding entry ID", + "rollback across a handoff", + "conflicting retained branches", + ] as const)("recovers Pi history across a handoff for %s", (scenario) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const oldFile = `${dir}/original.jsonl`; + const copyFile = `${dir}/a-copy.jsonl`; + const currentFile = `${dir}/current.jsonl`; + const forkFile = `${dir}/result.jsonl`; + const writeSession = (file: string, entries: ReadonlyArray) => + fs.writeFileString( + file, + [{ type: "session", version: 3 }, ...entries].map(encodeJsonLine).join("\n") + "\n", + ); + const legacyBoundary = scenario === "running legacy boundary with a colliding entry ID"; + const trailingPrompt = scenario === "equivalent copies with a discarded prompt"; + const ambiguous = scenario === "conflicting retained branches"; + const newerEntries = legacyBoundary + ? [ + sessionMessage("u1", null, "user", 90), + { ...sessionMessage("u2", "u1", "user", 110), timestamp: undefined }, + ] + : [sessionMessage("u2", null, "user", 110)]; + yield* writeSession(currentFile, newerEntries); + yield* writeSession( + oldFile, + trailingPrompt + ? [...TURN_ONE_ENTRIES, sessionMessage("discarded", "a1b", "user", 60)] + : TURN_ONE_ENTRIES, + ); + if (trailingPrompt) yield* writeSession(copyFile, TURN_ONE_ENTRIES); + if (ambiguous) + yield* writeSession(copyFile, [ + ...TURN_ONE_ENTRIES, + sessionMessage("other-reply", "a1b", "assistant", 45), + ]); + + const fake = yield* makeFakePi; + const forkFake = yield* makeFakePi; + const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake); + fake.queueState({ sessionFile: currentFile }); + const source = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const [target, boundary] = uncapturedTurns(source.id, { startedAt: 100, completedAt: 150 }); + if (target === undefined || boundary === undefined) throw new Error("missing turns"); + const turns = [ + target, + { + ...boundary, + nativeTurnRef: { driver: PI_PROVIDER, nativeId: "u2", strength: "strong" as const }, + ...(legacyBoundary + ? { status: "running" as const, completedAt: null } + : { + nativeThreadRef: { + driver: PI_PROVIDER, + nativeId: currentFile, + strength: "strong" as const, + }, + }), + }, + ]; + if (scenario === "rollback across a handoff") { + fake.queueState({ sessionFile: oldFile }); + fake.queueState({ sessionFile: oldFile }); + const retained = { entries: TURN_ONE_ENTRIES, leafId: "a1b" }; + fake.queueEntries(retained); + fake.queueEntries(retained); + const result = yield* runtime.rollbackThread({ + providerThread: source, + providerThreadTurns: turns, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint"), + appRunOrdinal: target.ordinal, + providerTurn: target, + }, + }); + assert.equal(result.providerThread.nativeThreadRef?.nativeId, oldFile); + assert.equal(result.providerThread.nativeConversationHeadRef?.nativeId, "a1b"); + return; + } + + forkFake.queueState({ sessionFile: forkFile }); + fake.queueState({ sessionFile: forkFile }); + const result = yield* runtime + .forkThread({ + sourceProviderThread: source, + sourceProviderTurns: turns, + providerTurnId: target.id, + targetThreadId: ThreadId.make("fork-target"), + }) + .pipe(Effect.result); + if (ambiguous) { + assert.equal(result._tag, "Failure"); + assert.isFalse(forkFake.allRequests().some((request) => request.type === "fork")); + return; + } + if (result._tag === "Failure") return yield* Effect.fail(result.failure); + const args = forkFake.lastSpawn().args; + assert.equal(args[args.indexOf("--fork") + 1], oldFile); + assert.deepEqual( + forkFake + .allRequests() + .filter((request) => request.type === "fork") + .map((request) => request.entryId), + trailingPrompt ? ["discarded"] : [], + ); + assert.equal(result.success.nativeThreadRef?.nativeId, forkFile); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("natively forks before 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 1cded39a0944..b5c3b9ecf895 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3042,12 +3042,24 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return readable ? { entries, leafId } : null; }); - // Old records hold entry IDs without a session file. Use timestamped user entries - // to distinguish the original branch from unrelated sessions with matching IDs. + const siblingSessionFiles = Effect.fnUntraced(function* (currentFile: string) { + const dir = path.dirname(currentFile); + 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)) + .filter((file) => file !== currentFile) + .sort() + .reverse(); + }); + + // Old records hold entry IDs without a session file. Corroborate them with the + // saved prompt timestamps and ancestry before using a sibling session. const findHistoricalForkSession = Effect.fnUntraced(function* ( currentFile: string, boundary: Extract, - acrossHandoff = false, ) { const targetId = piTurnEntryId(boundary.target); const startedAt = boundary.target?.startedAt; @@ -3064,39 +3076,11 @@ 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(); - let historicalFile: string | undefined; - for (const file of files) { - if (file === currentFile) continue; + for (const file of yield* siblingSessionFiles(currentFile)) { const listing = yield* readSessionFile(file); if ( - listing === null || - !piUserEntryInWindow(listing.entries.get(targetId), from, between) - ) - continue; - if (acrossHandoff) { - // The discard boundary is in the new session. Clone only a unique old branch - // whose saved history already ends within the selected turn. - const leafTime = - listing.leafId === null ? null : listing.entries.get(listing.leafId)?.timestamp; - if ( - leafTime == null || - leafTime < from || - leafTime > between || - walkPiBranch(listing.entries, listing.leafId, targetId)?.reachedStop !== true - ) - continue; - if (historicalFile !== undefined) return undefined; - historicalFile = file; - } else if ( + listing !== null && + piUserEntryInWindow(listing.entries.get(targetId), from, between) && piUserEntryInWindow(listing.entries.get(boundary.entryId), between, to) && walkPiBranch(listing.entries, listing.leafId, boundary.entryId)?.reachedStop === true && walkPiBranch(listing.entries, boundary.entryId, targetId)?.reachedStop === true @@ -3104,7 +3088,63 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return file; } } - return historicalFile; + return undefined; + }); + + const recoverLegacyHandoff = Effect.fnUntraced(function* ( + sourceFile: string, + boundary: Extract, + source: PiSessionListing | null, + ) { + const targetId = piTurnEntryId(boundary.target); + const startedAt = boundary.target?.startedAt; + const completedAt = boundary.target?.completedAt; + if (targetId === undefined || source === null || !source.entries.has(boundary.entryId)) + return undefined; + + const unresolved = () => protocolError("Pi fork target was not found in a session"); + if (startedAt == null || completedAt == null) return yield* unresolved(); + const from = DateTime.toEpochMillis(startedAt); + const to = DateTime.toEpochMillis(completedAt); + if ( + piUserEntryInWindow(source.entries.get(targetId), from, to) && + walkPiBranch(source.entries, boundary.entryId, targetId)?.reachedStop === true + ) + return undefined; + + // Pi accepts a fork before the first prompt in a new session even when the + // selected turn is absent. Find its retained branch before asking Pi to fork. + let recovered: { file: string; boundary: PiForkBoundary; history: string } | undefined; + for (const file of yield* siblingSessionFiles(sourceFile)) { + const listing = yield* readSessionFile(file); + if (listing === null || !piUserEntryInWindow(listing.entries.get(targetId), from, to)) + continue; + const afterTarget = walkPiBranch(listing.entries, listing.leafId, targetId); + if (afterTarget?.reachedStop !== true) continue; + let entryId: string | undefined; + for (const id of [...afterTarget.userEntryIds].reverse()) { + const timestamp = listing.entries.get(id)?.timestamp; + if (timestamp == null) return yield* unresolved(); + if (timestamp >= to) { + entryId = id; + break; + } + } + const retainedLeaf = + entryId === undefined + ? listing.leafId + : (listing.entries.get(entryId)?.parentId ?? null); + const retained = walkPiBranch(listing.entries, retainedLeaf, null); + if (retained?.reachedStop !== true) continue; + const history = JSON.stringify([...retained.entryIds]); + if (recovered !== undefined && history !== recovered.history) return yield* unresolved(); + recovered ??= { + file, + boundary: entryId === undefined ? { type: "nothing" } : { ...boundary, entryId }, + history, + }; + } + return recovered ?? (yield* unresolved()); }); const sessionFileInCwd = Effect.fnUntraced(function* ( @@ -4050,19 +4090,29 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( boundary = piForkBoundary({ ...rollbackInput, sessionFile: targetFile }); } } + const candidateFile = sourceFile ?? currentFile; if ( - sourceFile == null && - currentFile != null && - boundary.type === "entry" && - piTurnEntryId(boundary.target) !== undefined && - boundary.target?.startedAt != null && - boundary.target.completedAt !== null && - boundary.turn.completedAt !== null + targetFile === undefined && + candidateFile != null && + boundary.type === "entry" ) { // The persisted file avoids sending the whole tree over RPC before forking. - const live = yield* readSessionFile(path.resolve(cwd, currentFile)); - if (live !== null && !live.entries.has(boundary.entryId)) { - sourceFile = yield* findHistoricalForkSession(currentFile, boundary); + const file = path.resolve(cwd, candidateFile); + const listing = yield* readSessionFile(file); + const recovered = yield* recoverLegacyHandoff(file, boundary, listing); + if (recovered !== undefined) { + sourceFile = recovered.file; + boundary = recovered.boundary; + } else if ( + sourceFile == null && + listing !== null && + !listing.entries.has(boundary.entryId) && + targetId !== undefined && + target?.startedAt != null && + target.completedAt !== null && + boundary.turn.completedAt !== null + ) { + sourceFile = yield* findHistoricalForkSession(file, boundary); if (sourceFile === undefined) return yield* protocolError("Pi rollback entry was not found in a session"); } @@ -4243,39 +4293,24 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const boundaryFile = boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; const sourceFile = targetFile ?? boundaryFile ?? currentFile; - let historicalFile: string | undefined; - // Pi can successfully fork before the first entry in the new session, - // even though that session never contained the selected turn. - if (targetFile === undefined && boundaryFile != null && boundary.type === "entry") { - const targetId = piTurnEntryId(boundary.target); - const completedAt = boundary.target?.completedAt; - const boundaryEnd = boundary.turn.completedAt; - if (targetId !== undefined && completedAt != null && boundaryEnd !== null) { - const file = path.resolve(cwd, boundaryFile); - const listing = yield* readSessionFile(file); - if ( - listing !== null && - !listing.entries.has(targetId) && - piUserEntryInWindow( - listing.entries.get(boundary.entryId), - DateTime.toEpochMillis(completedAt), - DateTime.toEpochMillis(boundaryEnd), + const resolvedSourceFile = path.resolve(cwd, sourceFile); + const recovered = + targetFile === undefined && boundary.type === "entry" + ? yield* readSessionFile(resolvedSourceFile).pipe( + Effect.flatMap((listing) => + recoverLegacyHandoff(resolvedSourceFile, boundary, listing), + ), ) - ) { - historicalFile = yield* findHistoricalForkSession(file, boundary, true); - if (historicalFile === undefined) - return yield* protocolError("Pi fork target was not found in a session"); - } - } - } + : undefined; const nativeId = yield* forkSessionIntoCwd( - historicalFile ?? sourceFile, - historicalFile === undefined ? boundary : { type: "nothing" }, + recovered?.file ?? sourceFile, + recovered?.boundary ?? boundary, source.createdAt, ).pipe( Effect.catchTags({ PiRpcError: (error) => { if ( + recovered !== undefined || boundary.type !== "entry" || boundaryFile != null || error.operation !== "fork" || @@ -4419,6 +4454,7 @@ function walkPiBranch( stopAt: string | null, ): { readonly entryCount: number; + readonly entryIds: ReadonlySet; readonly userEntryIds: ReadonlyArray; readonly reachedStop: boolean; } | null { @@ -4433,7 +4469,12 @@ function walkPiBranch( if (entry.isUserMessage) userEntryIds.push(current); current = entry.parentId; } - return { entryCount: visited.size, userEntryIds, reachedStop: current === stopAt }; + return { + entryCount: visited.size, + entryIds: visited, + userEntryIds, + reachedStop: current === stopAt, + }; } type PiForkBoundary = From 22c630d0761c0e9cdd4d8e62a4291f4777a7c271 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:22:03 +0100 Subject: [PATCH 5/8] fix(pi): compare retained entry IDs directly Co-authored-by: GPT 6.2 Sol --- packages/provider-pi/src/server/adapter.test.ts | 6 ++++-- packages/provider-pi/src/server/adapter.ts | 13 ++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 7aa90da48c01..169fddfb058d 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -3270,7 +3270,9 @@ describe("PiAdapterV2", () => { const writeSession = (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 legacyBoundary = scenario === "running legacy boundary with a colliding entry ID"; const trailingPrompt = scenario === "equivalent copies with a discarded prompt"; @@ -3358,7 +3360,7 @@ describe("PiAdapterV2", () => { assert.isFalse(forkFake.allRequests().some((request) => request.type === "fork")); return; } - if (result._tag === "Failure") return yield* Effect.fail(result.failure); + if (result._tag === "Failure") return yield* result.failure; const args = forkFake.lastSpawn().args; assert.equal(args[args.indexOf("--fork") + 1], oldFile); assert.deepEqual( diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index b5c3b9ecf895..f549662ade95 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3114,7 +3114,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( // Pi accepts a fork before the first prompt in a new session even when the // selected turn is absent. Find its retained branch before asking Pi to fork. - let recovered: { file: string; boundary: PiForkBoundary; history: string } | undefined; + let recovered: + | { file: string; boundary: PiForkBoundary; history: ReadonlyArray } + | undefined; for (const file of yield* siblingSessionFiles(sourceFile)) { const listing = yield* readSessionFile(file); if (listing === null || !piUserEntryInWindow(listing.entries.get(targetId), from, to)) @@ -3136,8 +3138,13 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( : (listing.entries.get(entryId)?.parentId ?? null); const retained = walkPiBranch(listing.entries, retainedLeaf, null); if (retained?.reachedStop !== true) continue; - const history = JSON.stringify([...retained.entryIds]); - if (recovered !== undefined && history !== recovered.history) return yield* unresolved(); + const history = [...retained.entryIds]; + if ( + recovered !== undefined && + (history.length !== recovered.history.length || + recovered.history.some((id, index) => id !== history[index])) + ) + return yield* unresolved(); recovered ??= { file, boundary: entryId === undefined ? { type: "nothing" } : { ...boundary, entryId }, From 2af778f009d4930f4cb9230c112f617bd30662fd Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:24:04 +0100 Subject: [PATCH 6/8] refactor(pi): restore the unchanged historical lookup's comment findHistoricalForkSession keeps main's behaviour, so its comment stays as main wrote it. Co-authored-by: Claude Opus 5.5 --- packages/provider-pi/src/server/adapter.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index f549662ade95..a7560efa758b 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3055,8 +3055,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( .reverse(); }); - // Old records hold entry IDs without a session file. Corroborate them with the - // saved prompt timestamps and ancestry before using a sibling session. + // 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* ( currentFile: string, boundary: Extract, From c6871753081dcfbf377005e369f4bf396c40e3bb Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:33:59 +0100 Subject: [PATCH 7/8] fix(pi): bound legacy recovery to the selected reply Co-authored-by: GPT 6.2 Sol --- .../provider-pi/src/server/adapter.test.ts | 68 +++++++++++++++---- packages/provider-pi/src/server/adapter.ts | 64 ++++++++++------- 2 files changed, 95 insertions(+), 37 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 169fddfb058d..2e4fe429ce2d 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -3259,6 +3259,9 @@ describe("PiAdapterV2", () => { "running legacy boundary with a colliding entry ID", "rollback across a handoff", "conflicting retained branches", + "adopted wake in the same session", + "missing timing in the same session", + "assistant continuation after the selected turn", ] as const)("recovers Pi history across a handoff for %s", (scenario) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -3277,20 +3280,43 @@ describe("PiAdapterV2", () => { const legacyBoundary = scenario === "running legacy boundary with a colliding entry ID"; const trailingPrompt = scenario === "equivalent copies with a discarded prompt"; const ambiguous = scenario === "conflicting retained branches"; - const newerEntries = legacyBoundary + const adoptedWake = scenario === "adopted wake in the same session"; + const missingTiming = scenario === "missing timing in the same session"; + const sameSession = adoptedWake || missingTiming; + const lateOutput = scenario === "assistant continuation after the selected turn"; + const newerEntries = sameSession ? [ - sessionMessage("u1", null, "user", 90), - { ...sessionMessage("u2", "u1", "user", 110), timestamp: undefined }, + ...TURN_ONE_ENTRIES.map((entry) => + missingTiming && entry.id === "u1" ? { ...entry, timestamp: undefined } : entry, + ), + sessionMessage("u2", "a1b", "user", 110), ] - : [sessionMessage("u2", null, "user", 110)]; + : legacyBoundary + ? [ + sessionMessage("u1", null, "user", 90), + { ...sessionMessage("u2", "u1", "user", 110), timestamp: undefined }, + ] + : [sessionMessage("u2", null, "user", 110)]; yield* writeSession(currentFile, newerEntries); yield* writeSession( oldFile, - trailingPrompt - ? [...TURN_ONE_ENTRIES, sessionMessage("discarded", "a1b", "user", 60)] - : TURN_ONE_ENTRIES, + lateOutput + ? [...TURN_ONE_ENTRIES, sessionMessage("late-reply", "a1b", "assistant", 60)] + : trailingPrompt + ? [...TURN_ONE_ENTRIES, sessionMessage("discarded", "a1b", "user", 60)] + : TURN_ONE_ENTRIES, ); - if (trailingPrompt) yield* writeSession(copyFile, TURN_ONE_ENTRIES); + if (trailingPrompt) + yield* writeSession(copyFile, [ + ...TURN_ONE_ENTRIES, + { + type: "model_change", + id: "changed-model", + parentId: "a1b", + timestamp: DateTime.formatIso(at(55)), + }, + sessionMessage("copy-prompt", "changed-model", "user", 60), + ]); if (ambiguous) yield* writeSession(copyFile, [ ...TURN_ONE_ENTRIES, @@ -3306,8 +3332,16 @@ describe("PiAdapterV2", () => { modelSelection: modelSelection("default"), runtimePolicy, }); - const [target, boundary] = uncapturedTurns(source.id, { startedAt: 100, completedAt: 150 }); - if (target === undefined || boundary === undefined) throw new Error("missing turns"); + const [firstTurn, boundary] = uncapturedTurns(source.id, { + startedAt: 100, + completedAt: 150, + }); + if (firstTurn === undefined || boundary === undefined) throw new Error("missing turns"); + const target = { + ...firstTurn, + startedAt: adoptedWake ? at(15) : firstTurn.startedAt, + completedAt: missingTiming ? null : firstTurn.completedAt, + }; const turns = [ target, { @@ -3342,6 +3376,14 @@ describe("PiAdapterV2", () => { }); assert.equal(result.providerThread.nativeThreadRef?.nativeId, oldFile); assert.equal(result.providerThread.nativeConversationHeadRef?.nativeId, "a1b"); + assert.deepEqual( + fake + .allRequests() + .filter((request) => request.type === "switch_session") + .map((request) => request.sessionPath), + [oldFile], + ); + assert.isFalse(fake.allRequests().some((request) => request.type === "fork")); return; } @@ -3355,20 +3397,20 @@ describe("PiAdapterV2", () => { targetThreadId: ThreadId.make("fork-target"), }) .pipe(Effect.result); - if (ambiguous) { + if (ambiguous || lateOutput) { assert.equal(result._tag, "Failure"); assert.isFalse(forkFake.allRequests().some((request) => request.type === "fork")); return; } if (result._tag === "Failure") return yield* result.failure; const args = forkFake.lastSpawn().args; - assert.equal(args[args.indexOf("--fork") + 1], oldFile); + assert.equal(args[args.indexOf("--fork") + 1], sameSession ? currentFile : oldFile); assert.deepEqual( forkFake .allRequests() .filter((request) => request.type === "fork") .map((request) => request.entryId), - trailingPrompt ? ["discarded"] : [], + sameSession ? ["u2"] : trailingPrompt ? ["discarded"] : [], ); assert.equal(result.success.nativeThreadRef?.nativeId, forkFile); }).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 a7560efa758b..67591bc9eb7b 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3103,15 +3103,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return undefined; const unresolved = () => protocolError("Pi fork target was not found in a session"); - if (startedAt == null || completedAt == null) return yield* unresolved(); - const from = DateTime.toEpochMillis(startedAt); - const to = DateTime.toEpochMillis(completedAt); + const sourcePrompt = source.entries.get(targetId); if ( - piUserEntryInWindow(source.entries.get(targetId), from, to) && + sourcePrompt?.isUserMessage === true && + (completedAt == null || + sourcePrompt.timestamp === null || + sourcePrompt.timestamp <= DateTime.toEpochMillis(completedAt)) && walkPiBranch(source.entries, boundary.entryId, targetId)?.reachedStop === true ) return undefined; + if (startedAt == null || completedAt == null) return yield* unresolved(); + const from = DateTime.toEpochMillis(startedAt); + const to = DateTime.toEpochMillis(completedAt); // Pi accepts a fork before the first prompt in a new session even when the // selected turn is absent. Find its retained branch before asking Pi to fork. let recovered: @@ -3121,24 +3125,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const listing = yield* readSessionFile(file); if (listing === null || !piUserEntryInWindow(listing.entries.get(targetId), from, to)) continue; - const afterTarget = walkPiBranch(listing.entries, listing.leafId, targetId); - if (afterTarget?.reachedStop !== true) continue; - let entryId: string | undefined; - for (const id of [...afterTarget.userEntryIds].reverse()) { - const timestamp = listing.entries.get(id)?.timestamp; - if (timestamp == null) return yield* unresolved(); - if (timestamp >= to) { - entryId = id; - break; - } - } - const retainedLeaf = - entryId === undefined - ? listing.leafId - : (listing.entries.get(entryId)?.parentId ?? null); - const retained = walkPiBranch(listing.entries, retainedLeaf, null); - if (retained?.reachedStop !== true) continue; - const history = [...retained.entryIds]; + const retained = piLegacyRetainedBranch(listing, targetId, to); + if (retained === undefined) continue; + const { history, entryId } = retained; if ( recovered !== undefined && (history.length !== recovered.history.length || @@ -4393,6 +4382,7 @@ const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schem interface PiSessionEntry { readonly parentId: string | null; readonly isUserMessage: boolean; + readonly isSessionMetadata: boolean; /** Pi's `timestamp` as epoch milliseconds; null when missing or unparsable. */ readonly timestamp: number | null; } @@ -4426,13 +4416,18 @@ function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { const parentId = recordField(entry, "parentId"); if (id === undefined || (parentId !== null && typeof parentId !== "string")) return null; const timestamp = recordString(entry, "timestamp"); + const type = recordString(entry, "type"); return [ id, { parentId, isUserMessage: - recordField(entry, "type") === "message" && - recordString(recordField(entry, "message"), "role") === "user", + type === "message" && recordString(recordField(entry, "message"), "role") === "user", + isSessionMetadata: + type === "model_change" || + type === "thinking_level_change" || + type === "label" || + type === "session_info", timestamp: timestamp === undefined ? null @@ -4484,6 +4479,27 @@ function walkPiBranch( }; } +function piLegacyRetainedBranch(listing: PiSessionListing, targetId: string, completedAt: number) { + const afterTarget = walkPiBranch(listing.entries, listing.leafId, targetId); + if (afterTarget?.reachedStop !== true) return undefined; + const throughTarget = walkPiBranch(listing.entries, targetId, null); + if (throughTarget?.reachedStop !== true) return undefined; + const history = [...throughTarget.entryIds].reverse(); + for (const id of [...afterTarget.entryIds].reverse()) { + const entry = listing.entries.get(id); + if (entry?.timestamp == null) return undefined; + if (entry.isUserMessage && entry.timestamp >= completedAt) return { history, entryId: id }; + if (entry.timestamp > completedAt) { + // Pi only forks before user messages. Later settings can stay in the file, + // but later conversation entries make this branch unsafe to recover. + if (!entry.isSessionMetadata) return undefined; + } else { + history.push(id); + } + } + return { history, entryId: undefined }; +} + type PiForkBoundary = | { readonly type: "entry"; From 56c01cce2ebda01fd2d8e0569430cc8f38d0e658 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:35:33 +0100 Subject: [PATCH 8/8] refactor(pi): flatten the retained-branch timestamp check One if/else-if says the same as the nested branch. Co-authored-by: Claude Opus 5.5 --- packages/provider-pi/src/server/adapter.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 67591bc9eb7b..be22df147fe2 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -4489,13 +4489,10 @@ function piLegacyRetainedBranch(listing: PiSessionListing, targetId: string, com const entry = listing.entries.get(id); if (entry?.timestamp == null) return undefined; if (entry.isUserMessage && entry.timestamp >= completedAt) return { history, entryId: id }; - if (entry.timestamp > completedAt) { - // Pi only forks before user messages. Later settings can stay in the file, - // but later conversation entries make this branch unsafe to recover. - if (!entry.isSessionMetadata) return undefined; - } else { - history.push(id); - } + if (entry.timestamp <= completedAt) history.push(id); + // Pi only forks before user messages. Later settings can stay in the file, + // but later conversation entries make this branch unsafe to recover. + else if (!entry.isSessionMetadata) return undefined; } return { history, entryId: undefined }; }