Skip to content

Commit a15be6d

Browse files
fix(server): omit discarded turns from thread split history
Ignore rolled-back runs and cancelled runs that never started when reconstructing the prior conversation for split suggestions. Match the associated user message as well as runId because canonical user messages can have a null runId. Keep cancelled turns that did start visible. This prevents abandoned turns from suppressing suggestions or introducing discarded context into model requests. Add regression coverage for all three run states and the exact history sent to the decision model. Also merge current main and preserve the Android test platform variable. Focused tests, the selected check:changed tests, direct server typechecking, formatting, lint, both knip scans, and GraphQL validation pass. The aggregate typecheck launcher is blocked by the environment's seccomp supervisor.
2 parents 810d7e1 + ede6b4b commit a15be6d

19 files changed

Lines changed: 1863 additions & 153 deletions

‎apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,7 @@ function makeLocalCommandHarness(input: {
295295
readonly resolveKnowledge?: ProjectKnowledge.ProjectKnowledge["Service"]["resolveForTurn"];
296296
readonly readSentDeliveries?: ProjectKnowledge.ProjectKnowledge["Service"]["readSentDeliveries"];
297297
readonly worktreePath?: string;
298+
readonly branch?: string;
298299
readonly worktreesDir?: string;
299300
readonly workspaceRoot?: string;
300301
readonly gitWorkflow?: GitWorkflow.GitWorkflowService["Service"];
@@ -396,7 +397,7 @@ function makeLocalCommandHarness(input: {
396397
id: threadId,
397398
activeProviderThreadId: providerThreadId,
398399
projectId: ProjectId.make("project-native-account-command"),
399-
branch: input.worktreePath === undefined ? null : "feature/restore",
400+
branch: input.worktreePath === undefined ? null : (input.branch ?? "feature/restore"),
400401
worktreePath: input.worktreePath ?? null,
401402
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
402403
} as OrchestrationV2ThreadProjection["thread"],
@@ -1317,6 +1318,53 @@ effectIt.effect(
13171318
}).pipe(Effect.scoped, Effect.provide(layerRealGit)),
13181319
);
13191320

1321+
effectIt.effect("recreates a rebound thread on the branch its agent switched to", () =>
1322+
Effect.gen(function* () {
1323+
const fileSystem = yield* FileSystem.FileSystem;
1324+
const path = yield* Path.Path;
1325+
const gitWorkflow = yield* GitWorkflow.GitWorkflowService;
1326+
const driver = yield* GitVcsDriver.GitVcsDriver;
1327+
const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-rebound-" });
1328+
const workspaceRoot = path.join(root, "project");
1329+
const worktreesDir = path.join(root, "worktrees");
1330+
const worktreePath = path.join(worktreesDir, "project", "restore");
1331+
yield* fileSystem.makeDirectory(workspaceRoot);
1332+
const git = (cwd: string, args: ReadonlyArray<string>) =>
1333+
driver
1334+
.execute({ operation: "test.worktreeRebound", cwd, args })
1335+
.pipe(Effect.map((result) => result.stdout.trim()));
1336+
yield* git(workspaceRoot, ["init", "-b", "main"]);
1337+
yield* git(workspaceRoot, ["config", "user.name", "Test"]);
1338+
yield* git(workspaceRoot, ["config", "user.email", "test@example.com"]);
1339+
yield* git(workspaceRoot, ["commit", "--allow-empty", "-m", "base"]);
1340+
yield* git(workspaceRoot, ["worktree", "add", "-b", "feature/restore", worktreePath]);
1341+
yield* git(worktreePath, ["switch", "-c", "agent/work"]);
1342+
yield* git(worktreePath, ["commit", "--allow-empty", "-m", "agent work"]);
1343+
const agentTip = yield* git(worktreePath, ["rev-parse", "HEAD"]);
1344+
yield* fileSystem.remove(worktreePath, { recursive: true });
1345+
const harness = makeLocalCommandHarness({
1346+
text: "Continue",
1347+
branch: "agent/work",
1348+
workspaceRoot,
1349+
worktreePath,
1350+
worktreesDir,
1351+
fileSystem,
1352+
gitWorkflow,
1353+
failReadsAfterRunning: true,
1354+
});
1355+
const open = harness.open.getMockImplementation()!;
1356+
harness.open.mockImplementation(() =>
1357+
Effect.gen(function* () {
1358+
expect(yield* git(worktreePath, ["branch", "--show-current"])).toBe("agent/work");
1359+
expect(yield* git(worktreePath, ["rev-parse", "HEAD"])).toBe(agentTip);
1360+
return yield* open();
1361+
}).pipe(Effect.orDie),
1362+
);
1363+
yield* harness.start;
1364+
expect(harness.open).toHaveBeenCalledOnce();
1365+
}).pipe(Effect.scoped, Effect.provide(layerRealGit)),
1366+
);
1367+
13201368
effectIt.effect(
13211369
"preserves recreation interrupts and retries, then fails the final attempt before provider start",
13221370
() =>

‎apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import * as RunFinalization from "./RunFinalizationService.ts";
2323
import * as RuntimeRequests from "./RuntimeRequestService.ts";
2424
import * as ThreadManagement from "./ThreadManagementService.ts";
2525
import * as ThreadTitles from "./ThreadTitleRegenerationService.ts";
26+
import * as WorktreeBranches from "./WorktreeBranches.ts";
2627

2728
it.effect.each([
2829
["starts the next turn after a post-capture Git status failure", false],
@@ -73,6 +74,7 @@ it.effect.each([
7374
Layer.mergeAll(
7475
projections,
7576
observer,
77+
Layer.mock(WorktreeBranches.WorktreeBranches)({}),
7678
Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({
7779
execute: () =>
7880
Effect.gen(function* () {

‎apps/server/src/orchestration-v2/RunFinalizationService.test.ts‎

Lines changed: 171 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@ import * as NodeFSP from "node:fs/promises";
44
import * as NodeOS from "node:os";
55
import * as NodePath from "node:path";
66

7+
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8+
import * as NodeServices from "@effect/platform-node/NodeServices";
79
import { assert, it } from "@effect/vitest";
810
import {
911
CheckpointScopeId,
12+
GitCommandError,
1013
MessageId,
1114
ProjectId,
1215
ProviderInstanceId,
@@ -18,22 +21,27 @@ import * as Deferred from "effect/Deferred";
1821
import * as DateTime from "effect/DateTime";
1922
import * as Effect from "effect/Effect";
2023
import * as Fiber from "effect/Fiber";
24+
import * as FileSystem from "effect/FileSystem";
2125
import * as Layer from "effect/Layer";
2226
import * as Stream from "effect/Stream";
2327
import * as Option from "effect/Option";
2428
import * as TestClock from "effect/testing/TestClock";
2529

30+
import * as ServerConfig from "../config.ts";
2631
import * as CodeIntelligence from "../project/knowledge/CodeIntelligence.ts";
2732
import * as ModelEvaluations from "../modelEvaluations/ModelEvaluations.ts";
2833
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34+
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
2935
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
3036
import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
3137
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
3238
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
3339
import * as CheckpointCapture from "./CheckpointCaptureService.ts";
3440
import * as ProjectionStore from "./ProjectionStore.ts";
41+
import * as Orchestrator from "./Orchestrator.ts";
3542
import * as ProjectStore from "./ProjectStore.ts";
3643
import * as RunFinalization from "./RunFinalizationService.ts";
44+
import * as WorktreeBranches from "./WorktreeBranches.ts";
3745

3846
it.effect("coalesces completed turns without starving later project refreshes", () => {
3947
const projectA = ProjectId.make("project-turn-refresh-a");
@@ -76,7 +84,7 @@ it.effect("coalesces completed turns without starving later project refreshes",
7684
}).pipe(Effect.provide(layer));
7785
});
7886

79-
it.effect.each(["workspace refresh", "evaluation enqueue"] as const)(
87+
it.effect.each(["workspace refresh", "evaluation enqueue", "branch sync"] as const)(
8088
"preserves completed checkpoint finalization when %s fails",
8189
(failure) => {
8290
const threadId = ThreadId.make("thread_refresh_failure");
@@ -120,6 +128,26 @@ it.effect.each(["workspace refresh", "evaluation enqueue"] as const)(
120128
checkpointScopes: [{ id: scopeId, runId, kind: "root_run" as const, cwd: "/repo" }],
121129
checkpoints: [],
122130
}),
131+
getThreadShell: () =>
132+
Effect.succeed({
133+
id: threadId,
134+
branch: "feature",
135+
worktreePath: "/repo",
136+
} as OrchestrationV2ThreadShell),
137+
}),
138+
Layer.mock(WorktreeBranches.WorktreeBranches)({
139+
sync: () =>
140+
Effect.gen(function* () {
141+
captured.push("sync");
142+
if (failure === "branch sync")
143+
return yield* new GitCommandError({
144+
operation: "test",
145+
command: "git",
146+
cwd: "/repo",
147+
detail: "Git index is locked.",
148+
});
149+
return { _tag: "Bound" as const, branch: "feature" };
150+
}),
123151
}),
124152
Layer.succeed(RunFinalization.RunFinalizationObserver, {
125153
refresh: () =>
@@ -151,7 +179,7 @@ it.effect.each(["workspace refresh", "evaluation enqueue"] as const)(
151179
return Effect.gen(function* () {
152180
const service = yield* RunFinalization.RunFinalizationService;
153181
yield* service.finalize({ threadId, runId, scopeId });
154-
assert.deepEqual(captured, ["checkpoint", "evaluation", "refresh"]);
182+
assert.deepEqual(captured, ["checkpoint", "evaluation", "sync", "refresh"]);
155183
}).pipe(Effect.provide(layer));
156184
},
157185
);
@@ -239,6 +267,146 @@ it.effect.each(
239267
}).pipe(Effect.provide(layer));
240268
});
241269

270+
it.live.each(
271+
(
272+
[
273+
{
274+
label: "rebinds a thread that ended on a new branch before its pull request refresh",
275+
checkout: ["switch", "-c", "agent/work"],
276+
worktreePath: "worktree",
277+
refName: "agent/work",
278+
branch: "agent/work",
279+
lookups: 1,
280+
},
281+
{
282+
label: "leaves a thread that ended on a detached HEAD alone",
283+
checkout: ["switch", "--detach"],
284+
worktreePath: "worktree",
285+
refName: null,
286+
branch: "feature",
287+
lookups: 0,
288+
},
289+
{
290+
label: "leaves a thread that ended on the default branch alone",
291+
checkout: ["switch", "main"],
292+
worktreePath: "worktree",
293+
refName: "main",
294+
branch: "feature",
295+
lookups: 0,
296+
},
297+
{
298+
label: "leaves a thread working in the project root alone",
299+
checkout: ["switch", "-c", "agent/work"],
300+
worktreePath: null,
301+
refName: "agent/work",
302+
branch: "feature",
303+
lookups: 0,
304+
},
305+
] as const
306+
).map((scenario) => [scenario.label, scenario] as const),
307+
)("%s", ([, scenario]) =>
308+
Effect.gen(function* () {
309+
const threadId = ThreadId.make("thread-branch-sync");
310+
const runId = RunId.make("completed-run");
311+
const scopeId = CheckpointScopeId.make("scope-branch-sync");
312+
const lookedUp = yield* Deferred.make<void>();
313+
const fs = yield* FileSystem.FileSystem;
314+
const git = yield* GitVcsDriver.GitVcsDriver;
315+
const root = yield* fs.realPath(
316+
yield* fs.makeTempDirectoryScoped({ prefix: "t3-branch-sync-" }),
317+
);
318+
const repo = `${root}/repo`;
319+
const worktree = `${root}/feature`;
320+
yield* fs.makeDirectory(repo);
321+
const command = (cwd: string, args: ReadonlyArray<string>) =>
322+
git.execute({ operation: "run-finalization-test", cwd, args });
323+
yield* command(repo, ["init", "-b", "main"]);
324+
yield* command(repo, ["config", "user.email", "finalize@example.test"]);
325+
yield* command(repo, ["config", "user.name", "Finalize test"]);
326+
yield* command(repo, ["commit", "--allow-empty", "-m", "initial"]);
327+
yield* command(repo, ["worktree", "add", "-b", "feature", worktree]);
328+
if (scenario.refName === "main") yield* command(repo, ["switch", "--detach"]);
329+
yield* command(worktree, scenario.checkout);
330+
331+
let thread = {
332+
id: threadId,
333+
branch: "feature",
334+
worktreePath: scenario.worktreePath === null ? null : worktree,
335+
activeRunId: null,
336+
archivedAt: null,
337+
createdAt: DateTime.makeUnsafe(0),
338+
} as OrchestrationV2ThreadShell;
339+
let lookups = 0;
340+
const projections = Layer.mock(ProjectionStore.ProjectionStoreV2)({
341+
getCheckpointContext: () =>
342+
Effect.succeed({
343+
runs: [],
344+
checkpointScopes: [{ id: scopeId, runId, kind: "root_run" as const, cwd: worktree }],
345+
checkpoints: [],
346+
}),
347+
getThreadShell: () => Effect.sync(() => thread),
348+
});
349+
const layer = RunFinalization.layer.pipe(
350+
Layer.provideMerge(RunFinalization.layerObserver),
351+
Layer.provide(WorktreeBranches.layer),
352+
Layer.provide(
353+
Layer.mergeAll(
354+
projections,
355+
Layer.mock(ProjectStore.ProjectStoreV2)({
356+
getShell: () => Effect.succeedSome({ workspaceRoot: repo }) as never,
357+
}),
358+
Layer.mock(ModelEvaluations.ModelEvaluations)({}),
359+
Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({ execute: () => Effect.void }),
360+
Layer.mock(Orchestrator.OrchestratorV2)({
361+
getShellSnapshot: () =>
362+
Effect.sync(() => ({ threads: [thread], archivedThreads: [] })) as never,
363+
dispatch: ((command: { readonly branch: string }) =>
364+
Effect.sync(() => {
365+
thread = { ...thread, branch: command.branch };
366+
})) as never,
367+
}),
368+
Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
369+
Layer.mock(CodeIntelligence.CodeIntelligence)({ refreshIfIndexed: () => Effect.void }),
370+
Layer.mock(PullRequestService.PullRequestService)({
371+
refreshAfterTurn: () => Effect.void,
372+
}),
373+
Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
374+
refreshLocalStatus: () =>
375+
Effect.succeed({
376+
isRepo: true,
377+
hasPrimaryRemote: false,
378+
isDefaultRef: scenario.refName === "main",
379+
refName: scenario.refName,
380+
hasWorkingTreeChanges: false,
381+
workingTree: { files: [], insertions: 0, deletions: 0 },
382+
}),
383+
refreshPullRequestStatus: () =>
384+
Effect.suspend(() => {
385+
lookups++;
386+
return Deferred.succeed(lookedUp, undefined).pipe(Effect.as(null));
387+
}),
388+
}),
389+
),
390+
),
391+
);
392+
yield* Effect.gen(function* () {
393+
const service = yield* RunFinalization.RunFinalizationService;
394+
yield* service.finalize({ threadId, runId, scopeId });
395+
if (scenario.lookups > 0) yield* Deferred.await(lookedUp);
396+
assert.equal(thread.branch, scenario.branch);
397+
assert.equal(lookups, scenario.lookups);
398+
}).pipe(Effect.provide(layer));
399+
}).pipe(
400+
Effect.provide(
401+
GitVcsDriver.layer.pipe(
402+
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-branch-sync-" })),
403+
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
404+
),
405+
),
406+
Effect.scoped,
407+
),
408+
);
409+
242410
it.effect("finalizes a run without waiting for the code index refresh its checkpoint started", () =>
243411
Effect.acquireUseRelease(
244412
Effect.promise(async () => {
@@ -263,6 +431,7 @@ it.effect("finalizes a run without waiting for the code index refresh its checkp
263431
Layer.provide(
264432
Layer.mergeAll(
265433
Layer.mock(ModelEvaluations.ModelEvaluations)({}),
434+
Layer.mock(WorktreeBranches.WorktreeBranches)({}),
266435
Layer.mock(CheckpointCapture.CheckpointCaptureServiceV2)({
267436
execute: () => Effect.void,
268437
}),

‎apps/server/src/orchestration-v2/RunFinalizationService.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
1313
import * as ModelEvaluations from "../modelEvaluations/ModelEvaluations.ts";
1414
import * as CheckpointCapture from "./CheckpointCaptureService.ts";
1515
import * as ProjectionStore from "./ProjectionStore.ts";
16+
import * as WorktreeBranches from "./WorktreeBranches.ts";
1617

1718
export class RunFinalizationError extends Schema.TaggedError<RunFinalizationError>()(
1819
"RunFinalizationError",
@@ -57,6 +58,7 @@ const make = Effect.gen(function* () {
5758
const projections = yield* ProjectionStore.ProjectionStoreV2;
5859
const observer = yield* RunFinalizationObserver;
5960
const modelEvaluations = yield* ModelEvaluations.ModelEvaluations;
61+
const worktreeBranches = yield* WorktreeBranches.WorktreeBranches;
6062

6163
const finalize: RunFinalizationService["Service"]["finalize"] = Effect.fn(
6264
"RunFinalizationService.finalize",
@@ -94,6 +96,20 @@ const make = Effect.gen(function* () {
9496
);
9597
}
9698
if (cwd !== undefined) {
99+
yield* projections.getThreadShell(input.threadId).pipe(
100+
Effect.flatMap((thread) =>
101+
// An exact match excludes project-root threads and nested-repo checkpoint scopes.
102+
thread?.worktreePath === cwd
103+
? worktreeBranches.sync({ worktreePath: cwd, runId: input.runId })
104+
: Effect.void,
105+
),
106+
Effect.catchCause((cause) =>
107+
Effect.logWarning("Failed to sync worktree branch after checkpoint capture", {
108+
...input,
109+
cause,
110+
}),
111+
),
112+
);
97113
// Retrying a display refresh after the checkpoint is durable blocks the next turn.
98114
yield* observer.refresh({ cwd, threadId: input.threadId, runId: input.runId }).pipe(
99115
Effect.catchTags({

0 commit comments

Comments
 (0)