Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
2ae6f39
fix(server): a stopped run is checkpointed in its own worktree
navidnadali Nov 4, 2026
db3717b
Merge remote-tracking branch 'origin/main' into fix/checkpoint-in-run…
navidnadali Nov 4, 2026
bfef847
fix(server): a run is checkpointed where its turn started
navidnadali Nov 4, 2026
5aecfc2
test(server): turn-workspace checks wait for the run's own events
navidnadali Nov 4, 2026
4c213e6
test(server): turn-workspace checks wait on replayed events
navidnadali Nov 4, 2026
3c5456c
Merge remote-tracking branch 'origin/main' into fix/checkpoint-in-run…
navidnadali Nov 5, 2026
6928c58
Merge remote-tracking branch 'github/main' into fix/checkpoint-in-run…
maria-rcks Nov 5, 2026
fb57f43
Merge remote-tracking branch 'origin/main' into fix/checkpoint-in-run…
navidnadali Nov 6, 2026
21df066
Merge remote-tracking branch 'origin/main' into fix/checkpoint-in-run…
navidnadali Nov 10, 2026
7e386f3
Merge remote-tracking branch 'origin/main' into fix/checkpoint-in-run…
navidnadali Nov 11, 2026
0a9f1d3
Merge remote-tracking branch 'origin/main' into fix/checkpoint-in-run…
navidnadali Nov 15, 2026
b82776c
test(server): call the effect worker's runOnce as a function
Nov 15, 2026
73ff1d3
test(server): a run a worktree switch hands off is awaited from store…
Nov 15, 2026
e34e942
test(server): a run switched to another repo before its turn starts
Nov 15, 2026
27353a0
fix(server): the turn-start baseline is taken in the run's workspace
Nov 15, 2026
b8b9f11
Merge main into fix/checkpoint-in-run-workspace
navidnadali Nov 21, 2026
7ac2c76
Merge main into fix/checkpoint-in-run-workspace
navidnadali Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 221 additions & 0 deletions apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1146,6 +1146,227 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
}),
);

// 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<OrchestrationV2DomainEvent> = [
{
...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<string>();
const inWorkspace = (cwd: string) => Effect.sync(() => workspaces.add(cwd));
const excludedFromRoot: Array<ReadonlyArray<string>> = [];
const layerCapture = CheckpointCaptureService.layer.pipe(
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
CheckpointService.layer.pipe(
Layer.provide(
Layer.mergeAll(
IdAllocator.layer,
NodeCrypto.layer,
NodeServices.layer,
// Only the thread's latest worktree tracks a repository at `vendor/lib`.
Layer.mock(WorkspaceFolders.WorkspaceFolders)({
forThread: () =>
Effect.succeed({
folders: [
{ name: "lib", path: "/repo-next/vendor/lib", isGitRepository: true },
],
extraRoots: [],
}),
submodules: () => Effect.succeed([]),
}),
Layer.mock(CheckpointStore.CheckpointStore)({
isGitRepository: (cwd) => inWorkspace(cwd).pipe(Effect.as(true)),
hasCheckpointRef: ({ cwd }) => inWorkspace(cwd).pipe(Effect.as(true)),
resolveCleanHead: (cwd) => inWorkspace(cwd).pipe(Effect.as(null)),
captureCheckpoint: ({ cwd, excludePaths }) =>
inWorkspace(cwd).pipe(
Effect.andThen(
Effect.sync(() => {
if (cwd === "/repo") excludedFromRoot.push(excludePaths ?? []);
}),
),
),
diffCheckpoints: ({ cwd }) => inWorkspace(cwd).pipe(Effect.as("")),
listAuthoredPaths: ({ cwd }) => inWorkspace(cwd).pipe(Effect.as(null)),
}),
),
),
(layerCheckpoints) =>
Layer.effect(
CheckpointService.CheckpointServiceV2,
Effect.gen(function* () {
const checkpoints = yield* CheckpointService.CheckpointServiceV2;
return CheckpointService.CheckpointServiceV2.of({
...checkpoints,
capturesSoFar: (cwd) =>
inWorkspace(cwd).pipe(Effect.andThen(checkpoints.capturesSoFar(cwd))),
});
}),
).pipe(Layer.provide(layerCheckpoints)),
),
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, both baselines and the folder's capture count before them are taken where it
// ran, not in the thread's latest worktree, and none of it is left out for a repository only
// that worktree tracks.
assert.deepEqual(
[...workspaces].filter((cwd) => !cwd.startsWith("/repo-next/vendor/lib")),
["/repo"],
);
assert.deepEqual(excludedFromRoot, [[]]);
}),
);

// A thread on real Git checkouts: `folders` is what the project tracks, read at each turn.
const withTrackedRepositories = <A, E, R>(
name: string,
Expand Down
13 changes: 8 additions & 5 deletions apps/server/src/orchestration-v2/CheckpointCaptureService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,17 @@ 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 isPreserved = (ordinalWithinScope: number) =>
preservedCheckpointOrdinals.includes(ordinalWithinScope);
// The baselines this capture materializes are attributed to the run materializing them. The
// thread's scope may already be a later run's: one queued meanwhile, or sent after Stop.
const materializeBaseline = (ordinalWithinScope: number) =>
checkpoints.materializeBaselineCheckpoint({
scope,
scope: runScope,
ordinalWithinScope,
nodeId: rootNode.id,
capturedAt: run.requestedAt,
Expand All @@ -128,30 +131,30 @@ export const layer: Layer.Layer<
const nested =
repositoryScopes.length === 0
? undefined
: yield* checkpoints.nestedScopePaths([scope, ...repositoryScopes]);
: yield* checkpoints.nestedScopePaths([runScope, ...repositoryScopes]);
const excluded = (target: OrchestrationV2CheckpointScope) => {
const excludePaths = nested?.get(target.id);
return excludePaths === undefined ? {} : { excludePaths };
};
// Each scope is checked on its own, so a retried capture fills only what is missing.
const captureRoot = Effect.gen(function* () {
// Materializing a baseline waits on the folder's lock before the capture does.
const capturesBeforeLock = yield* checkpoints.capturesSoFar(scope.cwd);
const capturesBeforeLock = yield* checkpoints.capturesSoFar(runScope.cwd);
const threadStartCheckpoint =
baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0);
const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope)
? null
: yield* materializeBaseline(baselineOrdinalWithinScope);
const checkpoint = yield* checkpoints.capture({
scope,
scope: runScope,
runId: run.id,
nodeId: rootNode.id,
ordinalWithinScope: run.ordinal,
appRunOrdinal: run.ordinal,
capturedAt,
forceMissing: sideChat,
capturesBeforeLock,
...excluded(scope),
...excluded(runScope),
});
return { threadStartCheckpoint, baselineCheckpoint, checkpoint };
});
Expand Down
7 changes: 6 additions & 1 deletion apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3073,6 +3073,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,
Expand Down Expand Up @@ -6867,6 +6868,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,
Expand Down Expand Up @@ -8144,6 +8146,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
...(freshContext ? { freshContext: true } : {}),
...(checkpointScope === null ? {} : { workspaceCwd: checkpointScope.cwd }),
...output,
};
const attempt: OrchestrationV2RunAttempt = {
Expand Down Expand Up @@ -8567,6 +8570,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
...wakeWorkStartedAt(projection, command),
...(freshContext ? { freshContext: true } : {}),
...(checkpointScope === null ? {} : { workspaceCwd: checkpointScope.cwd }),
...output,
};
const attempt: OrchestrationV2RunAttempt = {
Expand Down Expand Up @@ -9379,6 +9383,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
...wakeWorkStartedAt(projection, command),
workspaceCwd: checkpointScope.cwd,
...output,
};
const attempt: OrchestrationV2RunAttempt = {
Expand Down Expand Up @@ -12565,7 +12570,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,
Expand Down
Loading
Loading