Skip to content

Commit ede6b4b

Browse files
fix(server): cleanup follows the branch an agent checked out (#68)
* fix(server): cleanup follows the checked-out branch Maintenance kept every worktree whose agent had switched branches, because nothing wrote HEAD back to the thread. A new WorktreeBranches service reads HEAD and rebinds the threads on that worktree. Cleanup keeps for one pass after a rebind, then applies the existing rules. A detached HEAD stays kept unless a ref outside refs/t3 holds its commit. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(server): threads learn their branch when a run ends A thread kept its old branch name after its agent switched branches, so the pull request refresh skipped it and cleanup had to repair it later. Run finalization now syncs the worktree branch before that refresh. A sync failure only logs, so it cannot block the next turn. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * refactor(server): launch rebinds threads through worktree branch sync Launch carried its own copy of the loop that writes a branch to every thread on a worktree. It now calls WorktreeBranches.sync after the rename, so one path writes thread.branch for a worktree. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(server): a rebound thread recreates on its new branch Pins the resume half of the cleanup change. Once a thread is rebound and its worktree is removed, the next turn recreates the checkout on the branch the agent switched to, at that commit, and not on the stale name. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(server): cleanup removes a deleted owner's worktree after a rebind A deleted owner's record cannot be rewritten, so only its surviving subagents are rebound. This pins that the group comparison still lets removal proceed on the next pass, and that the branch ref survives. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(server): branch sync leaves foreign checkouts and held branches alone An independent check of the cleanup change found three ways to lose or strand work. A different repository at the worktree path had its branch written to the thread, so the thread forgot its own branch. A branch another checkout holds was recorded even though the thread could not recreate its worktree there. And the detached HEAD check ran before later steps that gave a holding ref time to go. Sync now compares the worktree's repository with the project's before it writes, and treats a branch another checkout holds like the default branch. Cleanup checks the holding ref last, immediately before removal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(server): a prunable remote branch does not protect a detached commit Cleanup counted any remote-tracking ref as holding a detached commit. A routine `git fetch --prune` removes a remote branch that was deleted upstream, so the commit could become unreachable after its worktree was gone. Only local branches, tags, and the remote's default branch count now. A detached worktree held by any other remote branch stays kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(server): cleanup keeps what removal would strand and rebinds every thread Adversarial review reproduced more ways for this change to lose work or never finish. Removing a detached or default-branch worktree could lose a commit only its reflog held, or strand a thread whose recorded branch another checkout held. A remote-tracking ref counted as protecting a commit even though a routine prune or a stale origin/HEAD could remove that protection. A run end skipped a sibling whose write had been deferred to it. Threads with a trailing slash in their path or no recorded branch never rebound, and mismatched records on a detached or default-branch worktree were kept forever. A held index lock blocked rebinding, and main counted as the default branch when the remote's default was trunk. Cleanup now checks HEAD and the reflog against local branches and tags only, and keeps a worktree while another checkout holds a recorded branch. Sync compares HEAD with every thread on the worktree instead of the caller's record, reads HEAD without depending on the index lock, finds threads by the path each one stored, and asks the remote when no local HEAD ref names its default. Model: Opus 5.5 Harness: Claude Code in T3 Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(server): cleanup keeps commits only a reflog holds on every worktree An adversarial review of this branch reproduced commit loss that main prevents. A rebound worktree counted as bound on its next pass, which skipped the reflog check, so cleanup removed it and gc then pruned commits only its reflog held. A deleted owner with no surviving threads skipped the same check. Another repository's linked worktree at the path skipped the repository check and lost its untracked files to `git clean`. Two detached worktrees recording one branch were both removed, and with no local origin/HEAD a default other than main or master could become a thread's recorded branch. The reflog check now runs on every worktree. Rewritten commits land in the reflog too, so an amended or rebased worktree waits until gc expires those entries. Cleanup compares the worktree's repository with the project's before it reads the checkout, by file identity so a differently cased path still matches. It keeps a detached or default-branch worktree while a thread elsewhere records the same branch. The service asks the remote for its default whatever the name, once per checkout. Model: Opus 5.5 Harness: Claude Code in T3 Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(pstack): roles pin Ultracode off now that it is its own option The upstream sync split Ultracode out of the effort list into a boolean option. pstack pins every option except speed, so a role at effort=xhigh now resolves with ultracode false, which is what that effort meant before: not Ultracode. This test is fork-only, so the sync did not update it, and it left main's required Fork Check failing for every pull request. Model: Opus 5.5 Harness: Claude Code in T3 Code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent e4bdc60 commit ede6b4b

16 files changed

Lines changed: 1748 additions & 152 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)