From 7ef242ede688d83002040aacc8786d1dd9b67692 Mon Sep 17 00:00:00 2001 From: Bean Date: Tue, 17 Nov 2026 14:00:55 -0600 Subject: [PATCH 1/2] fix(pi): fork historical turns from their original session --- packages/contracts/src/orchestrationV2.ts | 2 + .../provider-pi/src/server/adapter.test.ts | 98 +++++++++- packages/provider-pi/src/server/adapter.ts | 180 ++++++++++++++++-- 3 files changed, 258 insertions(+), 22 deletions(-) diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 39543e9a5f26..a297d92a444d 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1232,6 +1232,8 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ nodeId: NodeId, runAttemptId: Schema.NullOr(RunAttemptId), nativeTurnRef: Schema.NullOr(OrchestrationV2ProviderRef), + /** The native session that held this turn, when a provider can move a thread between sessions. */ + nativeThreadRef: Schema.optional(OrchestrationV2ProviderRef), ordinal: PositiveInt, status: Schema.Literals([ "pending", diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index a1dd152e662e..74ed8b73622d 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -164,6 +164,7 @@ interface FakePi { readonly queueEntries: (data: unknown) => void; readonly queueMessages: (data: unknown) => void; readonly vetoNextSwitch: () => void; + readonly failNextFork: () => void; readonly queueState: (data: Record) => void; readonly setStreaming: (streaming: boolean) => void; readonly setCompacting: (compacting: boolean) => void; @@ -237,6 +238,7 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { let failStateAfter: number | null = null; let failThinking = false; let vetoSwitch = false; + let failFork = false; let vetoNewSession = false; let deferredLifecycle: string | undefined; let sessionFile = FAKE_SESSION_FILE; @@ -354,6 +356,10 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { case "get_session_stats": return { ...base, data: statsQueue.shift() ?? {} }; case "fork": + if (failFork) { + failFork = false; + return { ...base, success: false, error: "Invalid entry ID for forking" }; + } serviceTier = null; return { ...base, data: { text: "Hello pi", cancelled: false } }; case "clear_queue": @@ -498,6 +504,9 @@ const makeFakePi: Effect.Effect = Effect.gen(function* () { vetoNextSwitch: () => { vetoSwitch = true; }, + failNextFork: () => { + failFork = true; + }, queueState: (data) => stateQueue.push(data), setStreaming: (streaming) => { isStreaming = streaming; @@ -2806,6 +2815,16 @@ describe("PiAdapterV2", () => { yield* fake.emit({ type: "agent_start" }); yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.equal( + completed.type === "provider_turn.updated" + ? completed.providerTurn.nativeThreadRef?.nativeId + : undefined, + childFile, + ); const idle = yield* takeEvent( (event) => event.type === "provider_thread.updated" && event.providerThread.status === "idle", @@ -2965,9 +2984,10 @@ describe("PiAdapterV2", () => { ); it.effect.each([ - { historical: false, label: "the latest turn" }, - { historical: true, label: "a historical turn" }, - ])("natively forks $label into an independent session", ({ historical }) => + { historical: false, moved: false, label: "the latest turn" }, + { historical: true, moved: false, label: "a historical turn" }, + { historical: true, moved: true, label: "a historical turn after a session switch" }, + ])("natively forks $label into an independent session", ({ historical, moved }) => Effect.gen(function* () { const fake = yield* makeFakePi; const forkFake = yield* makeFakePi; @@ -2990,6 +3010,9 @@ describe("PiAdapterV2", () => { nodeId: NodeId.make(`node-${ordinal}`), runAttemptId: null, nativeTurnRef: { driver: PI_PROVIDER, nativeId: `u${ordinal}`, strength: "strong" }, + ...(moved && source.nativeThreadRef !== null + ? { nativeThreadRef: source.nativeThreadRef } + : {}), ordinal, status: "completed", startedAt: null, @@ -3005,7 +3028,16 @@ describe("PiAdapterV2", () => { fake.queueState({ sessionFile: forkFile }); const target = ThreadId.make("fork-target"); const forked = yield* runtime.forkThread({ - sourceProviderThread: source, + sourceProviderThread: moved + ? { + ...source, + nativeThreadRef: { + driver: PI_PROVIDER, + nativeId: "/fake/new-session.jsonl", + strength: "strong", + }, + } + : source, sourceProviderTurns: historical ? [turn(1), turn(2)] : [turn(1)], providerTurnId: turn(1).id, targetThreadId: target, @@ -3061,6 +3093,64 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("recovers a historical Pi fork recorded before turns stored the session file", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped(); + const oldFile = `${dir}/original.jsonl`; + const unrelatedFile = `${dir}/unrelated.jsonl`; + const currentFile = `${dir}/current.jsonl`; + const header = { type: "session", version: 3 }; + const writeSession = (file: string, entries: ReadonlyArray) => + fs.writeFileString( + file, + [header, ...entries].map((entry) => encodeJsonLine(entry)).join("\n") + "\n", + ); + yield* writeSession(oldFile, UNCAPTURED_TURN_TREE.entries); + yield* writeSession(unrelatedFile, [ + sessionMessage("u1", null, "user", 10), + sessionMessage("u2", null, "user", 110), + ]); + yield* writeSession(currentFile, [sessionMessage("new", null, "user", 120)]); + + const fake = yield* makeFakePi; + const forkFake = yield* makeFakePi; + const { runtime } = yield* openRuntime(fake, "default", THREAD_ID, SESSION_ID, forkFake); + const source = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const forkFile = `${dir}/forked.jsonl`; + forkFake.failNextFork(); + forkFake.queueState({ sessionFile: forkFile }); + fake.queueState({ sessionFile: forkFile }); + const [target, boundary] = uncapturedTurns(source.id, { + startedAt: 100, + completedAt: 145, + }); + if (target === undefined || boundary === undefined) throw new Error("missing fork turns"); + const forked = yield* runtime.forkThread({ + sourceProviderThread: { + ...source, + nativeThreadRef: { driver: PI_PROVIDER, nativeId: currentFile, strength: "strong" }, + }, + sourceProviderTurns: [ + target, + { + ...boundary, + nativeTurnRef: { driver: PI_PROVIDER, nativeId: "u2", strength: "strong" }, + }, + ], + providerTurnId: target.id, + targetThreadId: ThreadId.make("fork-target"), + }); + const args = forkFake.lastSpawn().args; + assert.equal(args[args.indexOf("--fork") + 1], oldFile); + assert.equal(forked.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 1e80b48d7fb9..72b3146f0420 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -520,7 +520,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.orElseSucceed(() => undefined), ); if (header === undefined) return true; - const sessionCwd = recordString(Option.getOrUndefined(decodeSessionHeader(header)), "cwd"); + const sessionCwd = recordString(Option.getOrUndefined(decodeSessionLine(header)), "cwd"); if (sessionCwd === undefined || sessionCwd === cwd) return true; const realCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return sessionCwd === realCwd; @@ -2067,6 +2067,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ...(treeRefs === null || treeRefs.nativeTurnRef === undefined ? {} : { nativeTurnRef: treeRefs.nativeTurnRef }), + ...(state.providerThread.nativeThreadRef === null + ? {} + : { nativeThreadRef: state.providerThread.nativeThreadRef }), status: interrupted ? "interrupted" : failure !== null ? "failed" : "completed", completedAt, ...(tokenUsage === undefined ? {} : { tokenUsage }), @@ -2886,6 +2889,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( sourceFile: string, boundary: PiForkBoundary, providerThreadCreatedAt: DateTime.Utc, + expectedAncestor?: string, ) { const forkLaunch = buildPiRpcLaunch({ launchArgs: resolvedLaunchArgs.args, @@ -2917,6 +2921,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( providerThreadCreatedAt, forkConnection.request({ type: "get_entries" }), ); + if (expectedAncestor !== undefined && boundary.type !== "uncaptured") { + const listing = piSessionListing( + yield* forkConnection.request({ type: "get_entries" }), + ); + const end = beforeEntry ?? listing?.leafId ?? null; + if ( + listing === null || + listing.entries.get(expectedAncestor)?.isUserMessage !== true || + beforeEntry === expectedAncestor || + walkPiBranch(listing.entries, end, expectedAncestor)?.reachedStop !== true + ) { + return yield* protocolError("Pi fork boundary does not follow the requested turn"); + } + } if (beforeEntry !== null) { const result = yield* forkConnection.request({ type: "fork", @@ -2936,6 +2954,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); }); + // 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, + ) { + const targetId = piTurnEntryId(boundary.target); + const startedAt = boundary.target?.startedAt; + const completedAt = boundary.target?.completedAt; + const boundaryEnd = boundary.turn.completedAt; + if ( + targetId === undefined || + startedAt == null || + completedAt == null || + boundaryEnd === null + ) { + return undefined; + } + 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(); + for (const file of files) { + if (file === currentFile) continue; + const entries = new Map(); + let leafId: string | null = null; + const readable = yield* fileSystem.stream(file).pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.runForEach((line) => + Effect.sync(() => { + const entry = readPiSessionEntry(Option.getOrUndefined(decodeSessionLine(line))); + if (entry === null) return; + const [id, value] = entry; + entries.set(id, value); + leafId = id; + }), + ), + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if ( + readable && + piUserEntryInWindow(entries.get(targetId), from, between) && + piUserEntryInWindow(entries.get(boundary.entryId), between, to) && + walkPiBranch(entries, leafId, boundary.entryId)?.reachedStop === true && + walkPiBranch(entries, boundary.entryId, targetId)?.reachedStop === true + ) { + return file; + } + } + return undefined; + }); + const sessionFileInCwd = Effect.fnUntraced(function* ( sessionFile: string, providerThreadCreatedAt: DateTime.Utc, @@ -3354,6 +3434,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nodeId: turnInput.rootNodeId, runAttemptId: turnInput.attemptId, nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"), + ...(state.providerThread.nativeThreadRef === null + ? {} + : { nativeThreadRef: state.providerThread.nativeThreadRef }), ordinal: turnInput.providerTurnOrdinal, status: "running", startedAt, @@ -3912,8 +3995,8 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return yield* protocolError("Cannot fork while a Pi turn is active"); } const source = forkInput.sourceProviderThread; - const sourceFile = source.nativeThreadRef?.nativeId; - if (sourceFile == null) + const currentFile = source.nativeThreadRef?.nativeId; + if (currentFile == null) return yield* protocolError("Pi fork source has no session file"); const sourceTurns = (forkInput.sourceProviderTurns ?? []).filter( (turn) => turn.providerThreadId === source.id, @@ -3929,7 +4012,41 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( target: { type: "provider_turn", providerTurn: target }, providerThreadTurns: sourceTurns, }); - const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt); + const targetFile = target?.nativeThreadRef?.nativeId; + const boundaryFile = + boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; + const sourceFile = boundaryFile ?? currentFile; + const differentSessions = targetFile != null && sourceFile !== targetFile; + const expectedAncestor = differentSessions ? piTurnEntryId(target) : undefined; + if (differentSessions && expectedAncestor === undefined) { + return yield* protocolError("Pi cannot verify the fork point across session files"); + } + const nativeId = yield* forkSessionIntoCwd( + sourceFile, + boundary, + source.createdAt, + expectedAncestor, + ).pipe( + Effect.catchTags({ + PiRpcError: (error) => { + if ( + boundary.type !== "entry" || + boundaryFile != null || + error.operation !== "fork" || + error.detail !== "Invalid entry ID for forking" + ) { + return Effect.fail(error); + } + return findHistoricalForkSession(currentFile, boundary).pipe( + Effect.flatMap((file) => + file === undefined + ? Effect.fail(error) + : forkSessionIntoCwd(file, boundary, source.createdAt), + ), + ); + }, + }), + ); const now = yield* DateTime.now; return yield* registerThread( { @@ -3983,7 +4100,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( }); }); -const decodeSessionHeader = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); +const decodeSessionLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); interface PiSessionEntry { readonly parentId: string | null; @@ -4006,15 +4123,24 @@ function piSessionListing(data: unknown): PiSessionListing | null { } function piSessionEntries(entries: unknown): ReadonlyMap | null { - const byId = new Map(); if (!Array.isArray(entries)) return null; - for (const entry of entries) { - const id = recordString(entry, "id"); - const parentId = recordField(entry, "parentId"); - if (id === undefined || byId.has(id) || (parentId !== null && typeof parentId !== "string")) - return null; - const timestamp = recordString(entry, "timestamp"); - byId.set(id, { + const byId = new Map(); + for (const raw of entries) { + const entry = readPiSessionEntry(raw); + if (entry === null || byId.has(entry[0])) return null; + byId.set(...entry); + } + return byId; +} + +function readPiSessionEntry(entry: unknown): [string, PiSessionEntry] | null { + const id = recordString(entry, "id"); + const parentId = recordField(entry, "parentId"); + if (id === undefined || (parentId !== null && typeof parentId !== "string")) return null; + const timestamp = recordString(entry, "timestamp"); + return [ + id, + { parentId, isUserMessage: recordField(entry, "type") === "message" && @@ -4023,9 +4149,22 @@ function piSessionEntries(entries: unknown): ReadonlyMap timestamp === undefined ? null : Option.getOrNull(Option.map(DateTime.make(timestamp), DateTime.toEpochMillis)), - }); - } - return byId; + }, + ]; +} + +function piUserEntryInWindow(entry: PiSessionEntry | undefined, from: number, to: number): boolean { + return ( + entry?.isUserMessage === true && + entry.timestamp !== null && + entry.timestamp >= from && + entry.timestamp <= to + ); +} + +function piTurnEntryId(turn: OrchestrationV2ProviderTurn | null | undefined): string | undefined { + const ref = turn?.nativeTurnRef; + return ref?.strength === "strong" ? (ref.nativeId ?? undefined) : undefined; } function walkPiBranch( @@ -4052,7 +4191,12 @@ function walkPiBranch( } type PiForkBoundary = - | { readonly type: "entry"; readonly entryId: string } + | { + readonly type: "entry"; + readonly entryId: string; + readonly turn: OrchestrationV2ProviderTurn; + readonly target: OrchestrationV2ProviderTurn | null; + } | { readonly type: "nothing" } | { readonly type: "uncaptured"; @@ -4078,7 +4222,7 @@ function piForkBoundary(input: { const ref = boundary?.nativeTurnRef; if (boundary === undefined || ref == null) return { type: "nothing" }; return ref.strength === "strong" && ref.nativeId !== null - ? { type: "entry", entryId: ref.nativeId } + ? { type: "entry", entryId: ref.nativeId, turn: boundary, target } : { type: "uncaptured", turn: boundary, target }; } From d94bccc0a0908048c4dec431c82570c3d77efc0e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 21:22:50 +0000 Subject: [PATCH 2/2] fix(pi): fork a historical turn from the session that recorded it Pick the fork boundary only from later turns recorded in the target turn's session file, and fork from that file's end when none follows. A switch to a fresh session (/new, /handoff) no longer makes the fork fail, and the cross-session ancestor check that refused it is gone. Co-Authored-By: Claude Opus 5.5 --- .../provider-pi/src/server/adapter.test.ts | 45 +++++++++++-------- packages/provider-pi/src/server/adapter.ts | 41 +++++------------ 2 files changed, 39 insertions(+), 47 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 74ed8b73622d..1a50c56cce69 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2984,10 +2984,21 @@ describe("PiAdapterV2", () => { ); it.effect.each([ - { historical: false, moved: false, label: "the latest turn" }, - { historical: true, moved: false, label: "a historical turn" }, - { historical: true, moved: true, label: "a historical turn after a session switch" }, - ])("natively forks $label into an independent session", ({ historical, moved }) => + { historical: false, moved: false, split: false, label: "the latest turn" }, + { historical: true, moved: false, split: false, label: "a historical turn" }, + { + historical: true, + moved: true, + split: false, + label: "a historical turn after a session switch", + }, + { + historical: true, + moved: true, + split: true, + label: "the last turn before a switch to a fresh session", + }, + ])("natively forks $label into an independent session", ({ historical, moved, split }) => Effect.gen(function* () { const fake = yield* makeFakePi; const forkFake = yield* makeFakePi; @@ -3004,15 +3015,22 @@ describe("PiAdapterV2", () => { modelSelection: modelSelection("default"), runtimePolicy, }); + const freshSession = { + driver: PI_PROVIDER, + nativeId: "/fake/new-session.jsonl", + strength: "strong", + } as const; const turn = (ordinal: number): OrchestrationV2ProviderTurn => ({ id: ProviderTurnId.make(`turn-${ordinal}`), providerThreadId: source.id, nodeId: NodeId.make(`node-${ordinal}`), runAttemptId: null, nativeTurnRef: { driver: PI_PROVIDER, nativeId: `u${ordinal}`, strength: "strong" }, - ...(moved && source.nativeThreadRef !== null - ? { nativeThreadRef: source.nativeThreadRef } - : {}), + ...(split && ordinal === 2 + ? { nativeThreadRef: freshSession } + : moved && source.nativeThreadRef !== null + ? { nativeThreadRef: source.nativeThreadRef } + : {}), ordinal, status: "completed", startedAt: null, @@ -3028,16 +3046,7 @@ describe("PiAdapterV2", () => { fake.queueState({ sessionFile: forkFile }); const target = ThreadId.make("fork-target"); const forked = yield* runtime.forkThread({ - sourceProviderThread: moved - ? { - ...source, - nativeThreadRef: { - driver: PI_PROVIDER, - nativeId: "/fake/new-session.jsonl", - strength: "strong", - }, - } - : source, + sourceProviderThread: moved ? { ...source, nativeThreadRef: freshSession } : source, sourceProviderTurns: historical ? [turn(1), turn(2)] : [turn(1)], providerTurnId: turn(1).id, targetThreadId: target, @@ -3057,7 +3066,7 @@ describe("PiAdapterV2", () => { .allRequests() .filter((request) => request.type === "fork") .map((request) => request.entryId), - historical ? ["u2"] : [], + historical && !split ? ["u2"] : [], ); assert.isFalse( fake.allRequests().some((request) => request.type === "fork" || request.type === "clone"), diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 72b3146f0420..9374419556bf 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -2889,7 +2889,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( sourceFile: string, boundary: PiForkBoundary, providerThreadCreatedAt: DateTime.Utc, - expectedAncestor?: string, ) { const forkLaunch = buildPiRpcLaunch({ launchArgs: resolvedLaunchArgs.args, @@ -2921,20 +2920,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( providerThreadCreatedAt, forkConnection.request({ type: "get_entries" }), ); - if (expectedAncestor !== undefined && boundary.type !== "uncaptured") { - const listing = piSessionListing( - yield* forkConnection.request({ type: "get_entries" }), - ); - const end = beforeEntry ?? listing?.leafId ?? null; - if ( - listing === null || - listing.entries.get(expectedAncestor)?.isUserMessage !== true || - beforeEntry === expectedAncestor || - walkPiBranch(listing.entries, end, expectedAncestor)?.reachedStop !== true - ) { - return yield* protocolError("Pi fork boundary does not follow the requested turn"); - } - } if (beforeEntry !== null) { const result = yield* forkConnection.request({ type: "fork", @@ -4005,28 +3990,19 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (forkInput.providerTurnId !== undefined && target === undefined) { return yield* protocolError("Pi fork target turn is missing"); } + const targetFile = target?.nativeThreadRef?.nativeId ?? undefined; const boundary: PiForkBoundary = target === undefined ? { type: "nothing" } : piForkBoundary({ target: { type: "provider_turn", providerTurn: target }, providerThreadTurns: sourceTurns, + sessionFile: targetFile, }); - const targetFile = target?.nativeThreadRef?.nativeId; const boundaryFile = boundary.type === "nothing" ? undefined : boundary.turn.nativeThreadRef?.nativeId; - const sourceFile = boundaryFile ?? currentFile; - const differentSessions = targetFile != null && sourceFile !== targetFile; - const expectedAncestor = differentSessions ? piTurnEntryId(target) : undefined; - if (differentSessions && expectedAncestor === undefined) { - return yield* protocolError("Pi cannot verify the fork point across session files"); - } - const nativeId = yield* forkSessionIntoCwd( - sourceFile, - boundary, - source.createdAt, - expectedAncestor, - ).pipe( + const sourceFile = targetFile ?? boundaryFile ?? currentFile; + const nativeId = yield* forkSessionIntoCwd(sourceFile, boundary, source.createdAt).pipe( Effect.catchTags({ PiRpcError: (error) => { if ( @@ -4214,10 +4190,17 @@ function piForkBoundary(input: { | { readonly type: "thread_start" } | { readonly type: "provider_turn"; readonly providerTurn: OrchestrationV2ProviderTurn }; readonly providerThreadTurns: ReadonlyArray; + /** Only turns recorded in this session can bound a fork from it. */ + readonly sessionFile?: string | undefined; }): PiForkBoundary { const target = input.target.type === "thread_start" ? null : input.target.providerTurn; const boundary = input.providerThreadTurns - .filter((turn) => turn.ordinal > (target?.ordinal ?? 0) && turn.nativeTurnRef !== null) + .filter( + (turn) => + turn.ordinal > (target?.ordinal ?? 0) && + turn.nativeTurnRef !== null && + (input.sessionFile === undefined || turn.nativeThreadRef?.nativeId === input.sessionFile), + ) .sort((a, b) => a.ordinal - b.ordinal)[0]; const ref = boundary?.nativeTurnRef; if (boundary === undefined || ref == null) return { type: "nothing" };