From 2ae6f39211cbf7afafa555da28b22ba1b496ee8a Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Wed, 4 Nov 2026 10:53:13 +0000 Subject: [PATCH 1/8] fix(server): a stopped run is checkpointed in its own worktree A stopped run's checkpoint is captured after it ends, in the thread scope's current cwd, which the next run may already have moved to another worktree. Runs now record the workspace they started in, and capture and baselines use it; runs recorded without it keep today's behaviour. Co-authored-by: Claude Opus 5.5 --- .../CheckpointCaptureService.test.ts | 182 ++++++++++++++++++ .../CheckpointCaptureService.ts | 9 +- .../src/orchestration-v2/Orchestrator.ts | 7 +- .../orchestration-v2/ProjectionStore.test.ts | 38 ++-- .../src/orchestration-v2/ProjectionStore.ts | 10 +- .../ProviderTurnStartService.ts | 2 + .../SteeringCompletion.integration.test.ts | 181 +++++++++++++++++ packages/contracts/src/orchestrationV2.ts | 2 + 8 files changed, 414 insertions(+), 17 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index 17fe7224773d5..a73a3b53d989e 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -905,4 +905,186 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { assert.equal(checkpoint?.status, "missing"); }), ); + + // A stopped run is captured after it ends; the next root run may have re-created the thread's one + // root scope in another worktree by then. + it.effect("captures a stopped run in its own workspace after the next run re-scoped", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const stoppedThreadId = ThreadId.make("thread:checkpoint-capture-own-workspace"); + const stoppedRunId = RunId.make("run:checkpoint-capture-own-workspace"); + const stoppedRootNodeId = NodeId.make("node:checkpoint-capture-own-workspace-root"); + const stoppedScopeId = CheckpointScopeId.make("scope:checkpoint-capture-own-workspace"); + const stoppedProviderThreadId = ProviderThreadId.make( + "provider-thread:checkpoint-capture-own-workspace", + ); + const event = { threadId: stoppedThreadId, occurredAt: now }; + const events: ReadonlyArray = [ + { + ...event, + id: EventId.make("event:checkpoint-capture-own-workspace:thread"), + type: "thread.created", + payload: { + createdBy: "user", + creationSource: "web", + id: stoppedThreadId, + projectId, + title: "Checkpoint capture after a worktree switch", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: "/repo-next", + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: stoppedThreadId, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }, + { + ...event, + id: EventId.make("event:checkpoint-capture-own-workspace:provider-thread"), + type: "provider-thread.updated", + driver, + providerInstanceId, + payload: { + id: stoppedProviderThreadId, + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: stoppedThreadId, + ownerNodeId: stoppedRootNodeId, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 2, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + }, + { + ...event, + id: EventId.make("event:checkpoint-capture-own-workspace:run"), + type: "run.updated", + runId: stoppedRunId, + payload: { + id: stoppedRunId, + threadId: stoppedThreadId, + ordinal: 2, + providerInstanceId, + modelSelection, + providerThreadId: stoppedProviderThreadId, + userMessageId: MessageId.make("message:checkpoint-capture-own-workspace"), + rootNodeId: stoppedRootNodeId, + activeAttemptId: null, + status: "interrupted", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + workspaceCwd: "/repo", + }, + }, + { + ...event, + id: EventId.make("event:checkpoint-capture-own-workspace:node"), + type: "node.updated", + runId: stoppedRunId, + nodeId: stoppedRootNodeId, + payload: { + id: stoppedRootNodeId, + threadId: stoppedThreadId, + runId: stoppedRunId, + parentNodeId: null, + rootNodeId: stoppedRootNodeId, + kind: "root_turn", + status: "interrupted", + countsForRun: true, + providerThreadId: stoppedProviderThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: stoppedScopeId, + startedAt: now, + completedAt: now, + }, + }, + { + ...event, + id: EventId.make("event:checkpoint-capture-own-workspace:scope-of-next-run"), + type: "checkpoint-scope.created", + runId: RunId.make("run:checkpoint-capture-own-workspace-next"), + nodeId: NodeId.make("node:checkpoint-capture-own-workspace-next-root"), + payload: { + id: stoppedScopeId, + threadId: stoppedThreadId, + runId: RunId.make("run:checkpoint-capture-own-workspace-next"), + nodeId: NodeId.make("node:checkpoint-capture-own-workspace-next-root"), + parentScopeId: null, + providerThreadId: stoppedProviderThreadId, + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo-next", + createdAt: now, + }, + }, + ]; + yield* Effect.forEach(events, (candidate) => projectionStore.apply(candidate)); + const workspaces = new Set(); + const inWorkspace = (cwd: string) => Effect.sync(() => workspaces.add(cwd)); + const layerCapture = CheckpointCaptureService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + NodeCrypto.layer, + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: (cwd) => inWorkspace(cwd).pipe(Effect.as(true)), + hasCheckpointRef: ({ cwd }) => inWorkspace(cwd).pipe(Effect.as(true)), + captureCheckpoint: ({ cwd }) => inWorkspace(cwd).pipe(Effect.asVoid), + diffCheckpoints: ({ cwd }) => inWorkspace(cwd).pipe(Effect.as("")), + listAuthoredPaths: ({ cwd }) => inWorkspace(cwd).pipe(Effect.as(null)), + }), + ), + ), + ), + Layer.mock(EventSink.EventSinkV2)({ + commitCommand: () => Effect.succeed({ committed: true } as never), + }), + ), + ), + ); + + yield* CheckpointCaptureService.CheckpointCaptureServiceV2.use((service) => + service.execute({ + threadId: stoppedThreadId, + runId: stoppedRunId, + scopeId: stoppedScopeId, + }), + ).pipe(Effect.provide(layerCapture)); + + // Its checkpoint and both baselines are taken where it ran, not in the thread's latest worktree. + assert.deepEqual([...workspaces], ["/repo"]); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 9d7d3cfd4ae2a..c8932f469b426 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -100,6 +100,9 @@ export const layer: Layer.Layer< } const capturedAt = yield* DateTime.now; + // The run's checkpoints are taken where it ran: the thread's scope follows its latest root run + // and may name another worktree by now. Runs recorded without a workspace use the scope's. + const runScope = run.workspaceCwd === undefined ? scope : { ...scope, cwd: run.workspaceCwd }; const baselineOrdinalWithinScope = Math.max(0, run.ordinal - 1); const hasReadyCheckpoint = (ordinalWithinScope: number) => readyCheckpointOrdinals.includes(ordinalWithinScope); @@ -107,19 +110,19 @@ export const layer: Layer.Layer< baselineOrdinalWithinScope === 0 || hasReadyCheckpoint(0) ? null : yield* checkpoints.materializeBaselineCheckpoint({ - scope, + scope: runScope, ordinalWithinScope: 0, forceMissing: sideChat, }); const baselineCheckpoint = hasReadyCheckpoint(baselineOrdinalWithinScope) ? null : yield* checkpoints.materializeBaselineCheckpoint({ - scope, + scope: runScope, ordinalWithinScope: baselineOrdinalWithinScope, forceMissing: sideChat, }); const checkpoint = yield* checkpoints.capture({ - scope, + scope: runScope, runId: run.id, nodeId: rootNode.id, ordinalWithinScope: run.ordinal, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b4bdbd705c290..d82634089e318 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2106,6 +2106,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerThreadId: queuedProviderThread.id, ordinal, status: "starting", + workspaceCwd: checkpointScope.cwd, queuePosition: null, startedAt: null, contextHandoffId: activeHandoff?.id ?? null, @@ -5290,6 +5291,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio userMessageId: input.messageId, status: "starting", contextHandoffId: restartHandoff?.id ?? targetRun.contextHandoffId, + workspaceCwd: checkpointScope.cwd, }; const nextAttempt: OrchestrationV2RunAttempt = { id: nextAttemptId, @@ -6124,6 +6126,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { restartContinuationOfRunId: command.restartContinuationOfRunId }), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), + ...(checkpointScope === null ? {} : { workspaceCwd: checkpointScope.cwd }), }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -6490,6 +6493,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : {}), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), ...wakeWorkStartedAt(projection.runs, command), + ...(checkpointScope === null ? {} : { workspaceCwd: checkpointScope.cwd }), }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -7242,6 +7246,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : { restartContinuationOfRunId: command.restartContinuationOfRunId }), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), ...wakeWorkStartedAt(projection.runs, command), + workspaceCwd: checkpointScope.cwd, }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -10160,7 +10165,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio nodeId: state.rootNode.id, providerInstanceId: state.run.providerInstanceId, occurredAt: now, - payload: { ...state.run, status: "starting" }, + payload: { ...state.run, status: "starting", workspaceCwd: checkpointScope.cwd }, }); yield* Ref.update(effects, (existing) => [ ...existing, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index c6187a97ea8db..b28675af4e007 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -4703,6 +4703,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { nextGeneration: 2, delivery: null, }, + workspaceCwd: "/repo/worktree-a", }; const task = { id: taskId, @@ -4731,23 +4732,25 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { updatedAt: now, }; - yield* projectionStore.apply({ + const threadCreated = { id: EventId.make("event:projection-delegated-completion:thread"), - type: "thread.created", + type: "thread.created" as const, threadId, occurredAt: now, payload: thread, - }); - yield* projectionStore.apply({ + }; + const runUpdated = { id: EventId.make("event:projection-delegated-completion:run"), - type: "run.updated", + type: "run.updated" as const, threadId, runId, nodeId: rootNodeId, providerInstanceId, occurredAt: now, payload: run, - }); + }; + yield* projectionStore.apply(threadCreated); + yield* projectionStore.apply(runUpdated); yield* projectionStore.apply({ id: EventId.make("event:projection-delegated-completion:task"), type: "subagent.updated", @@ -4760,18 +4763,23 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { payload: task, }); - const { delegatedCompletion: _delegatedCompletion, ...staleRun } = run; + const { + delegatedCompletion: _delegatedCompletion, + workspaceCwd: _workspaceCwd, + ...staleRun + } = run; const { completionDelivery: _completionDelivery, ...staleTask } = task; - yield* projectionStore.apply({ + const staleRunUpdated = { id: EventId.make("event:projection-delegated-completion:stale-run"), - type: "run.updated", + type: "run.updated" as const, threadId, runId, nodeId: rootNodeId, providerInstanceId, occurredAt: later, - payload: { ...staleRun, status: "interrupted", completedAt: later }, - }); + payload: { ...staleRun, status: "interrupted" as const, completedAt: later }, + }; + yield* projectionStore.apply(staleRunUpdated); yield* projectionStore.apply({ id: EventId.make("event:projection-delegated-completion:stale-task"), type: "subagent.updated", @@ -4791,6 +4799,14 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { const projection = yield* projectionStore.getThreadProjection(threadId); assert.deepEqual(projection.runs[0]?.delegatedCompletion, run.delegatedCompletion); + // The run keeps the workspace it ran in, in the store and in a command's in-memory projection. + const inMemory = [runUpdated, staleRunUpdated].reduce( + ProjectionStore.applyToProjection, + ProjectionStore.emptyProjection(threadCreated), + ); + for (const kept of [projection.runs[0], inMemory.runs[0]]) { + assert.equal(kept?.workspaceCwd, run.workspaceCwd); + } assert.deepEqual(projection.subagents[0]?.completionDelivery, task.completionDelivery); assert.deepEqual( (yield* projectionStore.getThreadRecords(threadId, ["subagents"], { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index b5a0f2cfb5556..1c6f6638a39ce 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -759,6 +759,9 @@ function preserveRunRecordedFields( current.restartCancelledBackgroundWork !== undefined ? { restartCancelledBackgroundWork: current.restartCancelledBackgroundWork } : {}), + ...(next.workspaceCwd === undefined && current.workspaceCwd !== undefined + ? { workspaceCwd: current.workspaceCwd } + : {}), }; } @@ -2101,8 +2104,11 @@ export const layer: Layer.Layer = requested_at = excluded.requested_at, completed_at = excluded.completed_at, payload_json = ${keepRecordedRunField( - keepRecordedRunField(sql`excluded.payload_json`, "$.delegatedCompletion"), - "$.restartCancelledBackgroundWork", + keepRecordedRunField( + keepRecordedRunField(sql`excluded.payload_json`, "$.delegatedCompletion"), + "$.restartCancelledBackgroundWork", + ), + "$.workspaceCwd", )} `; break; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e0797e784ba00..e1c21ea10eb08 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1453,6 +1453,8 @@ export const layer: Layer.Layer< ...run, status: "running", startedAt: now, + // The thread's scope follows its latest root run; this run's checkpoints stay here. + workspaceCwd: checkpointScope.cwd, }; const runningAttempt: OrchestrationV2RunAttempt = { ...attempt, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index bd3f4e5b2e7d8..2b2e02e25156a 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -19,8 +19,13 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; @@ -28,6 +33,7 @@ import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; const driver = ProviderDriverKind.make("codex"); @@ -1441,6 +1447,181 @@ it.effect("keeps a queued message queued when promoted into a run that Stop reac ), ); +// A worktree of the workspace's repo on a branch of its own: it shares the repo's refs. +const repoWorktree = (cwd: string, branch: string) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const parent = yield* fs.makeTempDirectoryScoped({ prefix: `t3-orchestrator-v2-${branch}-` }); + const worktree = path.join(parent, "worktree"); + const added = yield* spawner.exitCode( + ChildProcess.make("git", ["worktree", "add", "-b", branch, worktree], { cwd }), + ); + assert.equal(Number(added), 0); + return worktree; + }); + +// The next root run re-creates the thread's scope in the switched-to worktree before the stopped +// run's capture: sent after Stop, or queued while the run ends (branch selector). Without the run's +// own workspace, another repo loses its thread-start baseline; a worktree of the same repo gives it +// the other worktree's tree. +it.effect.each( + (["sent after Stop", "queued while it ends"] as const).flatMap((flow) => + (["another repo", "a worktree of the same repo"] as const).map((switchedTo) => ({ + flow, + switchedTo, + })), + ), +)( + "a stopped run's checkpoint is its own after a worktree switch ($flow, $switchedTo)", + ({ flow, switchedTo }) => + Effect.scoped( + Effect.gen(function* () { + const name = `own-workspace-${flow}-${switchedTo}`.replaceAll(" ", "-"); + const { cwd, events, started, layer, startFirstTurn } = + yield* nextTurnSelectionHarness(name); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const other = + switchedTo === "another repo" + ? yield* checkpointWorkspace(`${name}-other`) + : yield* repoWorktree(cwd, "switched"); + const threadId = yield* startFirstTurn; + const first = started[0]!; + yield* fs.writeFileString(path.join(cwd, "edited-by-first.txt"), "first\n"); + const switchWorktree = orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("switch"), + threadId, + worktreePath: other, + }); + const sendNext = orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("next"), + threadId, + messageId: MessageId.make("message:next"), + text: "next", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + if (flow === "sent after Stop") { + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + }); + // Delivering the interrupt stops the run and queues its checkpoint capture behind it. + assert.isTrue(yield* worker.runOnce); + yield* switchWorktree; + yield* sendNext; + yield* worker.drain(); + } else { + yield* switchWorktree; + yield* sendNext; + // The session the selector stopped ends the turn. + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + const stopped = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "interrupted", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "interrupted", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "interrupted", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(stopped); + yield* worker.drain(); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + } + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.checkpointScopes[0]?.cwd, other); + const threadStart = projection.checkpoints.find( + (checkpoint) => checkpoint.ordinalWithinScope === 0, + ); + const stopped = projection.checkpoints.find( + (checkpoint) => checkpoint.runId === first.runId, + ); + // Revert to thread start stays available, and the stopped run's checkpoint is its own. + assert.equal(threadStart?.status, "ready"); + assert.equal(stopped?.status, "ready"); + assert.deepEqual( + stopped?.files.map((file) => file.path), + ["edited-by-first.txt"], + ); + }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer))); + }), + ), +); + +it.effect("a run records its workspace when it is scoped, before its turn starts", () => + Effect.scoped( + Effect.gen(function* () { + const { cwd, layer } = yield* nextTurnSelectionHarness("workspace-when-scoped"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("thread:workspace-when-scoped"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:workspace-when-scoped"), + title: "Workspace when scoped", + modelSelection: runSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("first"), + threadId, + messageId: MessageId.make("message:first"), + text: "first", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + // Its turn has not started (the effect worker has not run), so Stop could still end it. + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs[0]?.status, "starting"); + assert.equal(projection.runs[0]?.workspaceCwd, cwd); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("queues a plain send behind the stopped queue and releases its hold", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 785f41e3aa0fb..f4cc04145fd03 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -705,6 +705,8 @@ export const OrchestrationV2Run = Schema.Struct({ ), delegatedCompletion: Schema.optional(OrchestrationV2DelegatedCompletionCohort), workspacePreparation: Schema.optional(OrchestrationV2ThreadLaunchWorkspaceStrategy), + /** The workspace the run started in; its checkpoints are taken there. Absent on older runs. */ + workspaceCwd: Schema.optional(TrimmedNonEmptyString), }); export type OrchestrationV2Run = typeof OrchestrationV2Run.Type; From bfef847ebfd31483b60493f7221a97db93d51106 Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Wed, 4 Nov 2026 14:34:25 +0000 Subject: [PATCH 2/8] fix(server): a run is checkpointed where its turn started Turn start recorded the run's workspace from the thread's shared scope, which follows the latest root run. A worktree switch before the turn starts, or a message queued behind the run, could leave that scope naming another worktree than the one the turn runs in. The run now records the workspace its turn is started in, and the baseline taken as it starts uses the same one. Co-Authored-By: Claude Opus 5.5 --- .../ProviderTurnStartService.ts | 9 +- .../SteeringCompletion.integration.test.ts | 85 +++++++++++++++++++ 2 files changed, 91 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e1c21ea10eb08..ea580253c5925 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1449,12 +1449,14 @@ export const layer: Layer.Layer< createdAt: providerThread.createdAt, updatedAt: now, }; + // The turn runs where the thread is now. The thread's scope follows its latest root run, which + // may be queued behind this one or predate a worktree switch; this run's checkpoints stay here. + const workspaceCwd = resolvedRuntimePolicy.cwd ?? checkpointScope.cwd; const runningRun: OrchestrationV2Run = { ...run, status: "running", startedAt: now, - // The thread's scope follows its latest root run; this run's checkpoints stay here. - workspaceCwd: checkpointScope.cwd, + workspaceCwd, }; const runningAttempt: OrchestrationV2RunAttempt = { ...attempt, @@ -1687,7 +1689,8 @@ export const layer: Layer.Layer< session: deliverySession, run: runningRun, rootNode: runningRootNode, - checkpointScope, + // The baseline taken as the turn starts belongs in the same workspace. + checkpointScope: { ...checkpointScope, cwd: workspaceCwd }, providerThread: runningProviderThread, attempt: runningAttempt, attemptId: attempt.id, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 2b2e02e25156a..19fa05c32df70 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1622,6 +1622,91 @@ it.effect("a run records its workspace when it is scoped, before its turn starts ), ); +// A run's turn starts in the thread's workspace of that moment. A worktree switch before it starts, +// or a message queued behind it, can leave the thread's shared scope naming another one. +it.effect.each([ + { flow: "switched before its turn starts", queueNext: false, switchBack: false }, + { flow: "switched, with a message queued behind it", queueNext: true, switchBack: false }, + { flow: "switched and back, with a message queued behind it", queueNext: true, switchBack: true }, +])("a run's checkpoint is taken where its turn ran ($flow)", ({ flow, queueNext, switchBack }) => + Effect.scoped( + Effect.gen(function* () { + const name = `turn-workspace-${flow}`.replaceAll(" ", "-").replaceAll(",", ""); + const { cwd, started, layer } = yield* nextTurnSelectionHarness(name); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const other = yield* repoWorktree(cwd, "switched"); + const threadId = ThreadId.make(`thread:${name}`); + const send = (id: string) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId, + messageId: MessageId.make(`message:${id}`), + text: id, + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const switchTo = (worktreePath: string, id: string) => + orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(id), + threadId, + worktreePath, + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make(`project:${name}`), + title: "Turn workspace", + modelSelection: runSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + yield* send("first"); + yield* switchTo(other, "switch"); + if (queueNext) yield* send("next"); + if (switchBack) yield* switchTo(cwd, "switch-back"); + yield* worker.drain(); + const first = started[0]!; + const ranIn = switchBack ? cwd : other; + assert.equal(first.runtimePolicy.cwd, ranIn); + yield* fs.writeFileString(path.join(ranIn, "edited-by-first.txt"), "first\n"); + + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + }); + yield* worker.drain(); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs.find((run) => run.id === first.runId)?.workspaceCwd, ranIn); + const checkpoint = projection.checkpoints.find( + (candidate) => candidate.runId === first.runId, + ); + assert.equal(checkpoint?.status, "ready"); + assert.deepEqual( + checkpoint?.files.map((file) => file.path), + ["edited-by-first.txt"], + ); + }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer))); + }), + ), +); + it.effect("queues a plain send behind the stopped queue and releases its hold", () => Effect.scoped( Effect.gen(function* () { From 5aecfc28788b6c14410fb9ca54451edbca36dd98 Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Wed, 4 Nov 2026 14:54:46 +0000 Subject: [PATCH 3/8] test(server): turn-workspace checks wait for the run's own events The new checks stopped the run right after draining the effect worker, before the provider turn's running event and the run's interruption had been projected, so on a slower host the capture was not queued yet when they read the checkpoint. They now wait for those events, as the other worktree-switch checks do. Co-Authored-By: Claude Opus 5.5 --- .../SteeringCompletion.integration.test.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 19fa05c32df70..7cd289e9cf239 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1674,16 +1674,36 @@ it.effect.each([ createdBy: "user", creationSource: "web", }); + const running = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); yield* send("first"); yield* switchTo(other, "switch"); if (queueNext) yield* send("next"); if (switchBack) yield* switchTo(cwd, "switch-back"); yield* worker.drain(); + yield* Fiber.join(running); const first = started[0]!; const ranIn = switchBack ? cwd : other; assert.equal(first.runtimePolicy.cwd, ranIn); yield* fs.writeFileString(path.join(ranIn, "edited-by-first.txt"), "first\n"); + const stopped = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "interrupted", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); yield* orchestrator.dispatch({ type: "run.interrupt", commandId: CommandId.make("stop"), @@ -1691,6 +1711,9 @@ it.effect.each([ runId: first.runId, }); yield* worker.drain(); + yield* Fiber.join(stopped); + // The stopped run's capture is queued behind its interrupt. + yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); assert.equal(projection.runs.find((run) => run.id === first.runId)?.workspaceCwd, ranIn); From 4c213e634a1fe379ecac7a302ef5e955bd57fffd Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Wed, 4 Nov 2026 15:38:48 +0000 Subject: [PATCH 4/8] test(server): turn-workspace checks wait on replayed events The checks forked watchers that follow domain events from the sequence that is current when the watcher fiber first runs. An event stored before then was skipped, and the join waited until the test timed out. They now wait after each step on the stored event stream, which replays from the first event, so the wait no longer depends on when it starts. Co-Authored-By: Claude Opus 5.5 --- .../SteeringCompletion.integration.test.ts | 35 ++++++++----------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 7cd289e9cf239..338918092c81a 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1660,6 +1660,11 @@ it.effect.each([ threadId, worktreePath, }); + const stored = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamStoredEvents.pipe( + Stream.filter(({ event }) => predicate(event)), + Stream.runHead, + ); yield* orchestrator.dispatch({ type: "thread.create", commandId: CommandId.make("create"), @@ -1674,36 +1679,19 @@ it.effect.each([ createdBy: "user", creationSource: "web", }); - const running = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => event.type === "provider-turn.updated" && event.payload.status === "running", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); yield* send("first"); yield* switchTo(other, "switch"); if (queueNext) yield* send("next"); if (switchBack) yield* switchTo(cwd, "switch-back"); yield* worker.drain(); - yield* Fiber.join(running); + yield* stored( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); const first = started[0]!; const ranIn = switchBack ? cwd : other; assert.equal(first.runtimePolicy.cwd, ranIn); yield* fs.writeFileString(path.join(ranIn, "edited-by-first.txt"), "first\n"); - const stopped = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === first.runId && - event.payload.status === "interrupted", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); yield* orchestrator.dispatch({ type: "run.interrupt", commandId: CommandId.make("stop"), @@ -1711,7 +1699,12 @@ it.effect.each([ runId: first.runId, }); yield* worker.drain(); - yield* Fiber.join(stopped); + yield* stored( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "interrupted", + ); // The stopped run's capture is queued behind its interrupt. yield* worker.drain(); From b82776c91ac15eadb510aac044c2bd4bf30f4883 Mon Sep 17 00:00:00 2001 From: T3 Code Test Date: Sun, 15 Nov 2026 15:41:16 +0000 Subject: [PATCH 5/8] test(server): call the effect worker's runOnce as a function Main made the effect worker's runOnce a function that takes claim limits; the stopped-run check still yielded it as an effect. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/SteeringCompletion.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 4cef20a0f3800..74761e5b17514 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2836,7 +2836,7 @@ it.effect.each( runId: first.runId, }); // Delivering the interrupt stops the run and queues its checkpoint capture behind it. - assert.isTrue(yield* worker.runOnce); + assert.isTrue(yield* worker.runOnce()); yield* switchWorktree; yield* sendNext; yield* worker.drain(); From 73ff1d3cb6fa304fb20680f866df35f8d73e6dd4 Mon Sep 17 00:00:00 2001 From: T3 Code Test Date: Sun, 15 Nov 2026 15:41:29 +0000 Subject: [PATCH 6/8] test(server): a run a worktree switch hands off is awaited from stored events Main now completes a run whose turn a worktree switch ends (a workspace handoff), through waiting for its checkpoint, instead of interrupting it. The check waited on live events for an interrupted run, which never came. It now waits on the replayed stored events for the run to leave running, as the turn-workspace checks do. Co-Authored-By: Claude Opus 5.5 --- .../SteeringCompletion.integration.test.ts | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 74761e5b17514..bcaa2cf75eeea 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2843,19 +2843,8 @@ it.effect.each( } else { yield* switchWorktree; yield* sendNext; - // The session the selector stopped ends the turn. + // The session the selector stopped ends the turn; the switch hands the run off to complete. const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; - const stopped = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === first.runId && - event.payload.status === "interrupted", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); yield* Queue.offer(events, { type: "provider_turn.updated", driver, @@ -2871,7 +2860,17 @@ it.effect.each( failure: null, threadDisposition: "reusable", }); - yield* Fiber.join(stopped); + yield* orchestrator.streamStoredEvents.pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status !== "running" && + event.payload.status !== "queued" && + event.payload.status !== "starting", + ), + Stream.runHead, + ); yield* worker.drain(); yield* orchestrator.resumeQueuedRuns; yield* worker.drain(); From e34e942d0fa1ef39767db54847172a19e32e1e7e Mon Sep 17 00:00:00 2001 From: T3 Code Test Date: Sun, 15 Nov 2026 15:49:28 +0000 Subject: [PATCH 7/8] test(server): a run switched to another repo before its turn starts The pre-start switch checks moved the thread to a worktree of the same repository, which shares its refs, so a turn-start baseline taken in the old checkout went unnoticed. This row moves it to another repository; the run's checkpoint comes back without its edit. Co-Authored-By: Claude Opus 5.5 --- .../SteeringCompletion.integration.test.ts | 199 ++++++++++-------- 1 file changed, 112 insertions(+), 87 deletions(-) diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index bcaa2cf75eeea..7e100c52fb217 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2941,102 +2941,127 @@ it.effect("a run records its workspace when it is scoped, before its turn starts // A run's turn starts in the thread's workspace of that moment. A worktree switch before it starts, // or a message queued behind it, can leave the thread's shared scope naming another one. it.effect.each([ - { flow: "switched before its turn starts", queueNext: false, switchBack: false }, - { flow: "switched, with a message queued behind it", queueNext: true, switchBack: false }, - { flow: "switched and back, with a message queued behind it", queueNext: true, switchBack: true }, -])("a run's checkpoint is taken where its turn ran ($flow)", ({ flow, queueNext, switchBack }) => - Effect.scoped( - Effect.gen(function* () { - const name = `turn-workspace-${flow}`.replaceAll(" ", "-").replaceAll(",", ""); - const { cwd, started, layer } = yield* nextTurnSelectionHarness(name); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const other = yield* repoWorktree(cwd, "switched"); - const threadId = ThreadId.make(`thread:${name}`); - const send = (id: string) => - orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(id), + { + flow: "switched before its turn starts", + queueNext: false, + switchBack: false, + otherRepo: false, + }, + { + flow: "switched to another repo before its turn starts", + queueNext: false, + switchBack: false, + otherRepo: true, + }, + { + flow: "switched, with a message queued behind it", + queueNext: true, + switchBack: false, + otherRepo: false, + }, + { + flow: "switched and back, with a message queued behind it", + queueNext: true, + switchBack: true, + otherRepo: false, + }, +])( + "a run's checkpoint is taken where its turn ran ($flow)", + ({ flow, queueNext, switchBack, otherRepo }) => + Effect.scoped( + Effect.gen(function* () { + const name = `turn-workspace-${flow}`.replaceAll(" ", "-").replaceAll(",", ""); + const { cwd, started, layer } = yield* nextTurnSelectionHarness(name); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const other = otherRepo + ? yield* checkpointWorkspace(`${name}-other`) + : yield* repoWorktree(cwd, "switched"); + const threadId = ThreadId.make(`thread:${name}`); + const send = (id: string) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId, + messageId: MessageId.make(`message:${id}`), + text: id, + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const switchTo = (worktreePath: string, id: string) => + orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(id), + threadId, + worktreePath, + }); + const stored = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamStoredEvents.pipe( + Stream.filter(({ event }) => predicate(event)), + Stream.runHead, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), threadId, - messageId: MessageId.make(`message:${id}`), - text: id, - attachments: [], + projectId: ProjectId.make(`project:${name}`), + title: "Turn workspace", modelSelection: runSelection, - dispatchMode: { type: "start_immediately" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, createdBy: "user", creationSource: "web", }); - const switchTo = (worktreePath: string, id: string) => - orchestrator.dispatch({ - type: "thread.metadata.update", - commandId: CommandId.make(id), + yield* send("first"); + yield* switchTo(other, "switch"); + if (queueNext) yield* send("next"); + if (switchBack) yield* switchTo(cwd, "switch-back"); + yield* worker.drain(); + yield* stored( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + const first = started[0]!; + const ranIn = switchBack ? cwd : other; + assert.equal(first.runtimePolicy.cwd, ranIn); + yield* fs.writeFileString(path.join(ranIn, "edited-by-first.txt"), "first\n"); + + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), threadId, - worktreePath, + runId: first.runId, }); - const stored = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => - orchestrator.streamStoredEvents.pipe( - Stream.filter(({ event }) => predicate(event)), - Stream.runHead, + yield* worker.drain(); + yield* stored( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "interrupted", ); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create"), - threadId, - projectId: ProjectId.make(`project:${name}`), - title: "Turn workspace", - modelSelection: runSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - createdBy: "user", - creationSource: "web", - }); - yield* send("first"); - yield* switchTo(other, "switch"); - if (queueNext) yield* send("next"); - if (switchBack) yield* switchTo(cwd, "switch-back"); - yield* worker.drain(); - yield* stored( - (event) => event.type === "provider-turn.updated" && event.payload.status === "running", - ); - const first = started[0]!; - const ranIn = switchBack ? cwd : other; - assert.equal(first.runtimePolicy.cwd, ranIn); - yield* fs.writeFileString(path.join(ranIn, "edited-by-first.txt"), "first\n"); - - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("stop"), - threadId, - runId: first.runId, - }); - yield* worker.drain(); - yield* stored( - (event) => - event.type === "run.updated" && - event.payload.id === first.runId && - event.payload.status === "interrupted", - ); - // The stopped run's capture is queued behind its interrupt. - yield* worker.drain(); + // The stopped run's capture is queued behind its interrupt. + yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.equal(projection.runs.find((run) => run.id === first.runId)?.workspaceCwd, ranIn); - const checkpoint = projection.checkpoints.find( - (candidate) => candidate.runId === first.runId, - ); - assert.equal(checkpoint?.status, "ready"); - assert.deepEqual( - checkpoint?.files.map((file) => file.path), - ["edited-by-first.txt"], - ); - }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer))); - }), - ), + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs.find((run) => run.id === first.runId)?.workspaceCwd, ranIn); + const checkpoint = projection.checkpoints.find( + (candidate) => candidate.runId === first.runId, + ); + assert.equal(checkpoint?.status, "ready"); + assert.deepEqual( + checkpoint?.files.map((file) => file.path), + ["edited-by-first.txt"], + ); + }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer))); + }), + ), ); it.effect("queues a plain send behind the stopped queue and releases its hold", () => From 27353a0fbc7b676a956be4d9d6f1474dbf8bdd0a Mon Sep 17 00:00:00 2001 From: T3 Code Test Date: Sun, 15 Nov 2026 15:50:19 +0000 Subject: [PATCH 8/8] fix(server): the turn-start baseline is taken in the run's workspace The turn-start baseline is now forked as the session opens, before the run's workspace was worked out, so it was taken in the thread's shared scope. After a pre-start switch to another repository the run's checkpoint then had no baseline to diff against. The run's workspace scope is now set before the fork and used for the baseline, the run and its turn. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/ProviderTurnStartService.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 420ec46a1f216..d08c9d366a04a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -774,11 +774,15 @@ export const layer: Layer.Layer< }); if (!repaired.committed) return; } + // The turn runs where the thread is now. The thread's scope follows its latest root run, which + // may be queued behind this one or predate a worktree switch; this run's checkpoints stay here. + const workspaceCwd = resolvedRuntimePolicy.cwd ?? checkpointScope.cwd; + const runCheckpointScope = { ...checkpointScope, cwd: workspaceCwd }; // Opening a session does not prompt the provider, so the workspace is still unchanged. const baseline = yield* runExecution.forkBaseline({ appThread: projection.thread, run, - checkpointScope, + checkpointScope: runCheckpointScope, }); const sessionResult = yield* Effect.result( providerSessions.open({ @@ -1557,9 +1561,6 @@ export const layer: Layer.Layer< createdAt: providerThread.createdAt, updatedAt: now, }; - // The turn runs where the thread is now. The thread's scope follows its latest root run, which - // may be queued behind this one or predate a worktree switch; this run's checkpoints stay here. - const workspaceCwd = resolvedRuntimePolicy.cwd ?? checkpointScope.cwd; const runningRun: OrchestrationV2Run = { ...run, status: "running", @@ -1825,8 +1826,7 @@ export const layer: Layer.Layer< session: deliverySession, run: runningRun, rootNode: runningRootNode, - // The baseline taken as the turn starts belongs in the same workspace. - checkpointScope: { ...checkpointScope, cwd: workspaceCwd }, + checkpointScope: runCheckpointScope, providerThread: runningProviderThread, attempt: runningAttempt, attemptId: attempt.id,