The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 08:00 UTC
fix(server): subagents pick up their parent's renamed worktree branch (#20079)
maria committed
Oct 16, 2026 at 01:00 UTC
4e85a93b20c80c005f395c8cc3bc2c79e41ac175
9 files changed
+569
-17
apps/server/src/orchestration-v2/Orchestrator.ts
+11
@@ -2539,6 +2539,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2539
cause: `Thread ${command.threadId} worktree changed before the metadata update could be applied.`,
2540
});
2541
}
2542
+ if (
2543
+ command.type === "thread.metadata.update" &&
2544
+ command.expectedBranch !== undefined &&
2545
+ command.expectedBranch !== thread.branch
2546
+ ) {
2547
+ return yield* new OrchestratorDispatchError({
2548
+ commandId: command.commandId,
2549
+ commandType: command.type,
2550
+ cause: `Thread ${command.threadId} branch changed before the metadata update could be applied.`,
2551
+ });
2552
+ }
2553
if (command.type === "thread.metadata.update" && command.expectedEmpty === true) {
2554
const records = yield* projectionStore
2555
.getThreadRecords(command.threadId, ["runs"])
apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+310
@@ -1,9 +1,11 @@
1
import { assert, it } from "@effect/vitest";
2
+import * as NodeServices from "@effect/platform-node/NodeServices";
3
import {
4
CheckpointId,
5
CheckpointRef,
6
CheckpointScopeId,
7
MessageId,
8
+ GitCommandError,
9
type ModelSelection,
10
NodeId,
11
type OrchestrationV2AppThread,
@@ -28,6 +30,7 @@ import * as DateTime from "effect/DateTime";
30
import * as Deferred from "effect/Deferred";
31
import * as Fiber from "effect/Fiber";
32
import * as Effect from "effect/Effect";
33
+import * as FileSystem from "effect/FileSystem";
34
import * as Layer from "effect/Layer";
35
import * as SqlClient from "effect/sql/SqlClient";
36
import * as Stream from "effect/Stream";
@@ -35,6 +38,8 @@ import * as TestClock from "effect/testing/TestClock";
38
39
import { toolOutputImages } from "@t3tools/shared/toolOutput";
40
import * as SqlitePersistence from "../persistence/Sqlite.ts";
41
+import * as ServerConfig from "../config.ts";
42
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
43
import * as EventSink from "./EventSink.ts";
44
import * as EventStore from "./EventStore.ts";
45
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -58,12 +63,18 @@ const layerTestEventSink = EventSink.layer.pipe(
63
Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),
64
);
65
66
+const layerGit = GitVcsDriver.layer.pipe(
67
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "ingestor-git-" })),
68
+ Layer.provideMerge(NodeServices.layer),
69
+);
70
+
71
const layerTest = Layer.mergeAll(
72
layerTestDatabase,
73
layerTestStores,
74
layerTestEventSink,
75
IdAllocator.layer,
76
ThreadCommandExecutor.layer,
77
+ layerGit,
78
ProviderEventIngestor.layer.pipe(
79
Layer.provide(
80
Layer.mergeAll(
@@ -71,10 +82,35 @@ const layerTest = Layer.mergeAll(
82
layerTestEventSink,
83
IdAllocator.layer,
84
ThreadCommandExecutor.layer,
85
+ layerGit,
86
),
87
),
88
),
89
);
90
+
91
+const makeSharedWorktree = Effect.gen(function* () {
92
+ const fs = yield* FileSystem.FileSystem;
93
+ const git = yield* GitVcsDriver.GitVcsDriver;
94
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "ingestor-worktree-" });
95
+ const repo = `${directory}/repo`;
96
+ const worktreePath = `${directory}/shared`;
97
+ yield* fs.makeDirectory(repo);
98
+ const command = (cwd: string, args: string[]) =>
99
+ git.execute({ operation: "ingestor-test", cwd, args });
100
+ yield* command(repo, ["init", "-b", "main"]);
101
+ yield* command(repo, [
102
+ "-c",
103
+ "user.name=Test",
104
+ "-c",
105
+ "user.email=test@example.test",
106
+ "commit",
107
+ "--allow-empty",
108
+ "-m",
109
+ "initial",
110
+ ]);
111
+ yield* command(repo, ["worktree", "add", "-b", "t3/abcd1234", worktreePath]);
112
+ return { repo, worktreePath, command };
113
+});
114
const modelSelection = {
115
instanceId: ProviderInstanceId.make("codex"),
116
model: "gpt-5.4",
@@ -1729,6 +1765,280 @@ layer("ProviderEventIngestorV2", (it) => {
1765
}),
1766
);
1767
1768
+ it.effect.each([
1769
+ { parentMoved: false, failure: null },
1770
+ { parentMoved: true, failure: null },
1771
+ { parentMoved: false, failure: "write" },
1772
+ { parentMoved: false, failure: "git" },
1773
+ ])(
1774
+ "rechecks a pending native child's branch after the rename scan: %j",
1775
+ ({ parentMoved, failure }) =>
1776
+ Effect.gen(function* () {
1777
+ const { worktreePath, command } = yield* makeSharedWorktree;
1778
+ const git = yield* GitVcsDriver.GitVcsDriver;
1779
+ const now = yield* DateTime.now;
1780
+ const eventSink = yield* EventSink.EventSinkV2;
1781
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
1782
+ const ids = yield* IdAllocator.IdAllocatorV2;
1783
+ const rootEvent = yield* threadCreatedEvent(now);
1784
+ if (rootEvent.type !== "thread.created") throw new Error("Expected thread fixture");
1785
+ const parent = {
1786
+ ...rootEvent.payload,
1787
+ branch: "t3/abcd1234",
1788
+ worktreePath,
1789
+ };
1790
+ yield* eventSink.write({ events: [{ ...rootEvent, payload: parent }] });
1791
+ const childId = ids.derive.threadFromProviderThread({
1792
+ driver: CODEX_DRIVER,
1793
+ nativeThreadId: `child-created-during-rename:${parentMoved}:${failure}`,
1794
+ });
1795
+ const beforeCommit = yield* Deferred.make<
1796
+ void,
1797
+ ProviderEventIngestor.ProviderEventIngestorV2Error
1798
+ >();
1799
+ const allowCommit = yield* Deferred.make<void>();
1800
+ let correctionWrites = 0;
1801
+ const gatedSink = EventSink.EventSinkV2.of({
1802
+ ...eventSink,
1803
+ write: (input) => {
1804
+ if (
1805
+ input.events.some(
1806
+ (event) => event.type === "thread.metadata-updated" && event.threadId === childId,
1807
+ )
1808
+ ) {
1809
+ correctionWrites++;
1810
+ if (failure === "write" && correctionWrites === 1)
1811
+ return Effect.fail(new EventSink.EventSinkWriteError({ eventCount: 1 }));
1812
+ }
1813
+ return input.events.some(
1814
+ (event) => event.type === "thread.created" && event.threadId === childId,
1815
+ )
1816
+ ? Deferred.succeed(beforeCommit, undefined).pipe(
1817
+ Effect.andThen(Deferred.await(allowCommit)),
1818
+ Effect.andThen(eventSink.write(input)),
1819
+ )
1820
+ : eventSink.write(input);
1821
+ },
1822
+ });
1823
+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1824
+ Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1825
+ Effect.provideService(EventSink.EventSinkV2, gatedSink),
1826
+ Effect.provideService(GitVcsDriver.GitVcsDriver, {
1827
+ ...git,
1828
+ resolveBranchName: (cwd, refName) =>
1829
+ failure === "git"
1830
+ ? Effect.fail(
1831
+ new GitCommandError({
1832
+ operation: "ingestor-test",
1833
+ cwd,
1834
+ command: "rev-parse",
1835
+ detail: "Read failed",
1836
+ }),
1837
+ )
1838
+ : git.resolveBranchName(cwd, refName),
1839
+ }),
1840
+ );
1841
+ const providerSessionId = yield* ids.allocate.providerSession({
1842
+ providerInstanceId: modelSelection.instanceId,
1843
+ threadId: parent.id,
1844
+ });
1845
+ const creationInput = {
1846
+ providerSessionId,
1847
+ providerInstanceId: modelSelection.instanceId,
1848
+ threadId: parent.id,
1849
+ event: {
1850
+ type: "app_thread.created",
1851
+ driver: CODEX_DRIVER,
1852
+ appThread: {
1853
+ ...parent,
1854
+ id: childId,
1855
+ lineage: {
1856
+ parentThreadId: parent.id,
1857
+ rootThreadId: parent.id,
1858
+ relationshipToParent: "subagent",
1859
+ },
1860
+ },
1861
+ },
1862
+ } satisfies ProviderEventIngestor.ProviderEventIngestInput;
1863
+ const creation = yield* ingestor.ingestNormalized(creationInput).pipe(
1864
+ Effect.tapCause((cause) => Deferred.failCause(beforeCommit, cause)),
1865
+ Effect.forkScoped,
1866
+ );
1867
+ yield* Deferred.await(beforeCommit);
1868
+ yield* command(worktreePath, ["branch", "-m", "generated-branch"]);
1869
+ yield* eventSink.write({
1870
+ events: [
1871
+ {
1872
+ ...rootEvent,
1873
+ id: yield* ids.allocate.event({ threadId: parent.id }),
1874
+ type: "thread.metadata-updated",
1875
+ payload: {
1876
+ ...parent,
1877
+ branch: parentMoved ? "user/checkout" : "generated-branch",
1878
+ worktreePath: parentMoved ? `${worktreePath}-moved` : worktreePath,
1879
+ },
1880
+ },
1881
+ ],
1882
+ });
1883
+ // The rename's final scan finishes while the child is still uncommitted.
1884
+ const snapshot = yield* projections.getShellSnapshot();
1885
+ assert.isFalse(
1886
+ [...snapshot.threads, ...snapshot.archivedThreads].some(
1887
+ (thread) =>
1888
+ thread.worktreePath === parent.worktreePath && thread.branch === parent.branch,
1889
+ ),
1890
+ );
1891
+ yield* Deferred.succeed(allowCommit, undefined);
1892
+ const stored = yield* Fiber.join(creation);
1893
+ assert.equal(stored[0]?.event.type, "thread.created");
1894
+ const child = yield* projections.getThread(childId);
1895
+ assert.equal(child.branch, failure === null ? "generated-branch" : parent.branch);
1896
+ assert.equal(child.worktreePath, parent.worktreePath);
1897
+ assert.equal(correctionWrites, failure === "git" ? 0 : 1);
1898
+ assert.deepEqual(yield* ingestor.ingestNormalized(creationInput), []);
1899
+ }),
1900
+ );
1901
+
1902
+ it.effect.each(["explicit", "detached", "unchanged", "legacy"])(
1903
+ "preserves a native child's branch when the checkout needs no correction: %s",
1904
+ (scenario) =>
1905
+ Effect.gen(function* () {
1906
+ const { worktreePath, command } = yield* makeSharedWorktree;
1907
+ const git = yield* GitVcsDriver.GitVcsDriver;
1908
+ const branch =
1909
+ scenario === "explicit"
1910
+ ? "child-feature"
1911
+ : scenario === "legacy"
1912
+ ? "t3-abcd1234"
1913
+ : "t3/abcd1234";
1914
+ if (scenario === "explicit" || scenario === "legacy")
1915
+ yield* command(worktreePath, ["branch", "-m", branch]);
1916
+ if (scenario === "detached") yield* command(worktreePath, ["checkout", "--detach"]);
1917
+ const now = yield* DateTime.now;
1918
+ const sink = yield* EventSink.EventSinkV2;
1919
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
1920
+ const ids = yield* IdAllocator.IdAllocatorV2;
1921
+ const root = yield* threadCreatedEvent(now);
1922
+ if (root.type !== "thread.created") throw new Error("Expected thread fixture");
1923
+ yield* sink.write({
1924
+ events: [
1925
+ { ...root, payload: { ...root.payload, branch: "parent-feature", worktreePath } },
1926
+ ],
1927
+ });
1928
+ const childId = ids.derive.threadFromProviderThread({
1929
+ driver: CODEX_DRIVER,
1930
+ nativeThreadId: `no-correction:${scenario}`,
1931
+ });
1932
+ let gitReads = 0;
1933
+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1934
+ Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1935
+ Effect.provideService(GitVcsDriver.GitVcsDriver, {
1936
+ ...git,
1937
+ resolveBranchName: (cwd, refName) => {
1938
+ gitReads++;
1939
+ return git.resolveBranchName(cwd, refName);
1940
+ },
1941
+ }),
1942
+ );
1943
+ const stored = yield* ingestor.ingestNormalized({
1944
+ providerSessionId: yield* ids.allocate.providerSession({
1945
+ providerInstanceId: modelSelection.instanceId,
1946
+ threadId: root.threadId,
1947
+ }),
1948
+ providerInstanceId: modelSelection.instanceId,
1949
+ threadId: root.threadId,
1950
+ event: {
1951
+ type: "app_thread.created",
1952
+ driver: CODEX_DRIVER,
1953
+ appThread: {
1954
+ ...root.payload,
1955
+ id: childId,
1956
+ branch,
1957
+ worktreePath,
1958
+ lineage: {
1959
+ parentThreadId: root.threadId,
1960
+ rootThreadId: root.threadId,
1961
+ relationshipToParent: "subagent",
1962
+ },
1963
+ },
1964
+ },
1965
+ });
1966
+ assert.equal((yield* projections.getThread(childId)).branch, branch);
1967
+ assert.equal(stored.length, 1);
1968
+ assert.equal(gitReads, scenario === "explicit" ? 0 : 1);
1969
+ }),
1970
+ );
1971
+
1972
+ it.effect.each(
1973
+ ["codex", "claude"].flatMap((driver) =>
1974
+ ["/repo/shared", "/repo/isolated", null].map((worktreePath) => ({ driver, worktreePath })),
1975
+ ),
1976
+ )("records a native child with current shared workspace: %j", ({ driver, worktreePath }) =>
1977
+ Effect.gen(function* () {
1978
+ const { repo, worktreePath: sharedPath, command } = yield* makeSharedWorktree;
1979
+ const isolatedPath = `${sharedPath}-isolated`;
1980
+ yield* command(sharedPath, ["branch", "-m", "generated-branch"]);
1981
+ yield* command(repo, ["worktree", "add", "-b", "t3/abcd1234", isolatedPath]);
1982
+ const actualPath =
1983
+ worktreePath === "/repo/shared" ? sharedPath : worktreePath === null ? null : isolatedPath;
1984
+ const now = yield* DateTime.now;
1985
+ const eventSink = yield* EventSink.EventSinkV2;
1986
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1987
+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1988
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
1989
+ const rootEvent = yield* threadCreatedEvent(now);
1990
+ if (rootEvent.type !== "thread.created") throw new Error("Expected thread fixture");
1991
+ const childThreadId = idAllocator.derive.threadFromProviderThread({
1992
+ driver: ProviderDriverKind.make(driver),
1993
+ nativeThreadId: `late-native-subagent:${worktreePath}`,
1994
+ });
1995
+ const offered: OrchestrationV2AppThread = {
1996
+ ...rootEvent.payload,
1997
+ id: childThreadId,
1998
+ branch: "t3/abcd1234",
1999
+ worktreePath: actualPath,
2000
+ lineage: {
2001
+ parentThreadId: rootEvent.threadId,
2002
+ relationshipToParent: "subagent",
2003
+ rootThreadId: rootEvent.threadId,
2004
+ },
2005
+ };
2006
+ yield* eventSink.write({
2007
+ events: [
2008
+ {
2009
+ ...rootEvent,
2010
+ payload: {
2011
+ ...rootEvent.payload,
2012
+ branch: "generated-branch",
2013
+ worktreePath: sharedPath,
2014
+ },
2015
+ },
2016
+ ],
2017
+ });
2018
+ const providerSessionId = yield* idAllocator.allocate.providerSession({
2019
+ providerInstanceId: modelSelection.instanceId,
2020
+ threadId: rootEvent.threadId,
2021
+ });
2022
+ yield* ingestor.ingestNormalized({
2023
+ providerSessionId,
2024
+ providerInstanceId: modelSelection.instanceId,
2025
+ threadId: rootEvent.threadId,
2026
+ event: {
2027
+ type: "app_thread.created",
2028
+ driver: ProviderDriverKind.make(driver),
2029
+ appThread: offered,
2030
+ },
2031
+ });
2032
+ const child = yield* projectionStore.getThread(childThreadId);
2033
+ assert.equal(
2034
+ child.branch,
2035
+ worktreePath === "/repo/shared" ? "generated-branch" : offered.branch,
2036
+ );
2037
+ assert.equal(child.worktreePath, actualPath);
2038
+ assert.deepEqual(child.lineage, offered.lineage);
2039
+ }),
2040
+ );
2041
+
2042
it.effect("updates provider child metadata without recreating its saved thread", () =>
2043
Effect.gen(function* () {
2044
const now = yield* DateTime.now;
apps/server/src/orchestration-v2/ProviderEventIngestor.ts
+41
@@ -27,8 +27,10 @@ import * as Layer from "effect/Layer";
27
import * as Schema from "effect/Schema";
28
29
import { AgentScope } from "@t3tools/shared/AgentScope";
30
+import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
31
import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";
32
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
33
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
34
import * as EventSink from "./EventSink.ts";
35
import * as ProjectionStore from "./ProjectionStore.ts";
36
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
@@ -307,6 +309,7 @@ export const layer: Layer.Layer<
309
ProviderEventIngestorV2,
310
never,
311
| EventSink.EventSinkV2
312
+ | GitVcsDriver.GitVcsDriver
313
| IdAllocator.IdAllocatorV2
314
| ProjectionStore.ProjectionStoreV2
315
| ThreadCommandExecutor.ThreadCommandExecutor
@@ -314,6 +317,7 @@ export const layer: Layer.Layer<
317
ProviderEventIngestorV2,
318
Effect.gen(function* () {
319
const eventSink = yield* EventSink.EventSinkV2;
320
+ const git = yield* GitVcsDriver.GitVcsDriver;
321
const projections = yield* ProjectionStore.ProjectionStoreV2;
322
const idAllocator = yield* IdAllocator.IdAllocatorV2;
323
const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;
@@ -783,6 +787,43 @@ export const layer: Layer.Layer<
787
.pipe(Effect.mapError(mapWriteError));
788
return result.storedEvents;
789
}).pipe(
790
+ Effect.flatMap((storedEvents) =>
791
+ Effect.gen(function* () {
792
+ if (input.event.type !== "app_thread.created") return storedEvents;
793
+ const created = storedEvents.find((stored) => stored.event.type === "thread.created");
794
+ if (created?.event.type !== "thread.created") return storedEvents;
795
+ const child = created.event.payload;
796
+ if (
797
+ child.worktreePath === null ||
798
+ child.branch === null ||
799
+ !isTemporaryWorktreeBranch(child.branch)
800
+ )
801
+ return storedEvents;
802
+ // Git renames before scanning committed threads. If that scan missed this
803
+ // creation, HEAD already has the new name, even if the parent moved away.
804
+ const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");
805
+ if (branch === null || branch === child.branch) return storedEvents;
806
+ const now = yield* DateTime.now;
807
+ const event = yield* makeDomainEvent(input, {
808
+ type: "thread.metadata-updated",
809
+ threadId: child.id,
810
+ payload: { ...child, branch, updatedAt: now },
811
+ occurredAt: now,
812
+ });
813
+ const synced = yield* eventSink.write({ events: [event] });
814
+ return [...storedEvents, ...synced];
815
+ }).pipe(
816
+ Effect.catchCause((cause) =>
817
+ Effect.logWarning("Native thread worktree branch recheck failed", {
818
+ threadId:
819
+ input.event.type === "app_thread.created"
820
+ ? input.event.appThread.id
821
+ : input.threadId,
822
+ cause,
823
+ }).pipe(Effect.as(storedEvents)),
824
+ ),
825
+ ),
826
+ ),
827
Effect.flatMap((storedEvents) =>
828
storedEvents.length === 0 || input.event.type !== "subagent.updated"
829
? Effect.succeed(storedEvents)
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+4
@@ -48,6 +48,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
48
import * as ProjectionStore from "./ProjectionStore.ts";
49
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
50
import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
51
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
52
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
53
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
54
import * as CommandOutputHub from "./CommandOutputHub.ts";
@@ -545,6 +546,9 @@ function layerTest(input: {
546
IdAllocator.layer,
547
layerTestStores,
548
ThreadCommandExecutor.layer,
549
+ Layer.mock(GitVcsDriver.GitVcsDriver)({
550
+ resolveBranchName: () => Effect.succeed(null),
551
+ }),
552
),
553
),
554
);
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+143
-11
@@ -33,6 +33,7 @@ import * as DateTime from "effect/DateTime";
33
import * as Duration from "effect/Duration";
34
import * as Effect from "effect/Effect";
35
import * as Exit from "effect/Exit";
36
+import * as Fiber from "effect/Fiber";
37
import * as Layer from "effect/Layer";
38
import * as Option from "effect/Option";
39
import * as Ref from "effect/Ref";
@@ -1147,17 +1148,45 @@ it.effect("names the worktree itself when the client provides no branch", () =>
1148
}),
1149
);
1150
1150
-it.effect("renames a temporary t3/<hash> branch off the provisioning critical path", () =>
1151
+it.effect.each(
1152
+ [false, true].flatMap((archived) =>
1153
+ [false, true].map((parentMoved) => ({ archived, parentMoved })),
1154
+ ),
1155
+)("renames shared temporary branches with %j", ({ archived, parentMoved }) =>
1156
Effect.gen(function* () {
1152
- const branchNameStarted = yield* Deferred.make<void>();
1157
+ const fs = yield* FileSystem.FileSystem;
1158
+ const git = yield* GitVcsDriver.GitVcsDriver;
1159
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-rename-" });
1160
+ const repo = `${directory}/repo`;
1161
+ const worktreePath = `${directory}/shared`;
1162
+ const movedPath = `${directory}/moved`;
1163
+ yield* fs.makeDirectory(repo);
1164
+ const command = (cwd: string, args: string[]) =>
1165
+ git.execute({ operation: "launch-test", cwd, args });
1166
+ yield* command(repo, ["init", "-b", "main"]);
1167
+ yield* command(repo, [
1168
+ "-c",
1169
+ "user.name=Test",
1170
+ "-c",
1171
+ "user.email=test@example.test",
1172
+ "commit",
1173
+ "--allow-empty",
1174
+ "-m",
1175
+ "initial",
1176
+ ]);
1177
+ yield* command(repo, ["worktree", "add", "-b", "t3/abcd1234", worktreePath]);
1178
+ yield* command(repo, ["worktree", "add", "-b", "user/checkout", movedPath]);
1179
+ const branchNameStarted = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
1180
const allowBranchName = yield* Deferred.make<void>();
1181
const harness = makeHarness({
1182
createWorktree: (input) =>
1183
Effect.succeed({
1157
- worktree: { path: "/repo-worktrees/temp", refName: input.newRefName, headSha: "abc" },
1184
+ worktree: { path: worktreePath, refName: input.newRefName, headSha: "abc" },
1185
} as never),
1186
+ renameBranch: git.renameBranch,
1187
generateBranchName: () =>
1160
- Deferred.succeed(branchNameStarted, undefined).pipe(
1188
+ Effect.fiber.pipe(
1189
+ Effect.flatMap((fiber) => Deferred.succeed(branchNameStarted, fiber)),
1190
Effect.andThen(Deferred.await(allowBranchName)),
1191
Effect.as({ branch: "generated-branch" }),
1192
),
@@ -1173,7 +1202,7 @@ it.effect("renames a temporary t3/<hash> branch off the provisioning critical pa
1202
workspace: { type: "worktree", baseRef: "main", branch: "t3/abcd1234" },
1203
}),
1204
);
1176
- yield* Deferred.await(branchNameStarted);
1205
+ const renameFiber = yield* Deferred.await(branchNameStarted);
1206
assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.newRefName, "t3/abcd1234");
1207
yield* waitUntil(() =>
1208
threads
@@ -1184,19 +1213,122 @@ it.effect("renames a temporary t3/<hash> branch off the provisioning critical pa
1213
(yield* threads.getThreadProjection(launched.threadId)).thread.branch,
1214
"t3/abcd1234",
1215
);
1216
+ const parent = yield* threads.getThreadProjection(launched.threadId);
1217
+ const run = parent.runs[0]!;
1218
+ assert.isNotNull(run.rootNodeId);
1219
+ yield* threads.dispatch({
1220
+ type: "delegated_task.request",
1221
+ commandId: CommandId.make("command:launch:temp-branch:delegate"),
1222
+ parentThreadId: launched.threadId,
1223
+ parentRunId: run.id,
1224
+ parentNodeId: run.rootNodeId!,
1225
+ task: "Work in the parent's checkout",
1226
+ modelSelection,
1227
+ runtimeMode: "full-access",
1228
+ interactionMode: "default",
1229
+ createdBy: "agent",
1230
+ creationSource: "mcp",
1231
+ });
1232
+ const delegated = yield* threads.getThreadProjection(launched.threadId);
1233
+ const childThreadId = delegated.subagents[0]!.childThreadId!;
1234
+ const child = yield* threads.getThreadProjection(childThreadId);
1235
+ assert.equal(child.thread.branch, "t3/abcd1234");
1236
+ assert.equal(child.thread.worktreePath, worktreePath);
1237
+ assert.equal(child.thread.lineage.parentThreadId, launched.threadId);
1238
+
1239
+ const otherThreadId = ThreadId.make("thread:launch:other-branch");
1240
+ const otherPathThreadId = ThreadId.make("thread:launch:other-worktree");
1241
+ for (const [threadId, branch, otherWorktreePath] of [
1242
+ [otherThreadId, "other-feature", worktreePath],
1243
+ [otherPathThreadId, "t3/abcd1234", "/repo-worktrees/other"],
1244
+ ] as const) {
1245
+ yield* threads.dispatch({
1246
+ type: "thread.create",
1247
+ commandId: CommandId.make(`command:create:${threadId}`),
1248
+ threadId,
1249
+ projectId,
1250
+ title: "Unrelated thread",
1251
+ modelSelection,
1252
+ runtimeMode: "full-access",
1253
+ interactionMode: "default",
1254
+ branch,
1255
+ worktreePath: otherWorktreePath,
1256
+ createdBy: "user",
1257
+ creationSource: "web",
1258
+ });
1259
+ }
1260
+ if (archived) {
1261
+ for (const threadId of [childThreadId, otherThreadId, otherPathThreadId]) {
1262
+ yield* threads.dispatch({
1263
+ type: "thread.archive",
1264
+ commandId: CommandId.make(`command:archive:${threadId}`),
1265
+ threadId,
1266
+ });
1267
+ }
1268
+ }
1269
+ const unrelatedBeforeRename = yield* threads.getThreadProjection(otherThreadId);
1270
+ const otherPathBeforeRename = yield* threads.getThreadProjection(otherPathThreadId);
1271
+ if (parentMoved) {
1272
+ yield* threads.dispatch({
1273
+ type: "thread.metadata.update",
1274
+ commandId: CommandId.make("command:launch:parent-moved"),
1275
+ threadId: launched.threadId,
1276
+ branch: "user/checkout",
1277
+ worktreePath: movedPath,
1278
+ });
1279
+ }
1280
yield* Deferred.succeed(allowBranchName, undefined);
1188
- yield* waitUntil(() =>
1189
- threads
1190
- .getThreadProjection(launched.threadId)
1191
- .pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),
1281
+ yield* Fiber.await(renameFiber);
1282
+ assert.equal(yield* git.resolveBranchName(worktreePath, "HEAD"), "generated-branch");
1283
+ assert.equal(
1284
+ (yield* threads.getThreadProjection(launched.threadId)).thread.branch,
1285
+ parentMoved ? "user/checkout" : "generated-branch",
1286
+ );
1287
+ assert.equal(
1288
+ (yield* threads.getThreadProjection(launched.threadId)).thread.worktreePath,
1289
+ parentMoved ? movedPath : worktreePath,
1290
+ );
1291
+ assert.equal(
1292
+ (yield* threads.getThreadProjection(childThreadId)).thread.branch,
1293
+ "generated-branch",
1294
+ );
1295
+ assert.deepEqual(
1296
+ (yield* threads.getThreadProjection(otherThreadId)).thread,
1297
+ unrelatedBeforeRename.thread,
1298
+ );
1299
+ assert.deepEqual(
1300
+ (yield* threads.getThreadProjection(otherPathThreadId)).thread,
1301
+ otherPathBeforeRename.thread,
1302
+ );
1303
+ const staleUpdate = yield* threads
1304
+ .dispatch({
1305
+ type: "thread.metadata.update",
1306
+ commandId: CommandId.make("command:launch:stale-branch-update"),
1307
+ threadId: otherThreadId,
1308
+ branch: "generated-branch",
1309
+ expectedBranch: "t3/abcd1234",
1310
+ expectedWorktreePath: worktreePath,
1311
+ })
1312
+ .pipe(Effect.flip);
1313
+ assert.equal(staleUpdate._tag, "OrchestratorDispatchError");
1314
+ assert.deepEqual(
1315
+ (yield* threads.getThreadProjection(otherThreadId)).thread,
1316
+ unrelatedBeforeRename.thread,
1317
);
1318
assert.deepEqual(harness.renameBranch.mock.calls[0]?.[0], {
1194
- cwd: "/repo-worktrees/temp",
1319
+ cwd: worktreePath,
1320
oldBranch: "t3/abcd1234",
1321
newBranch: "generated-branch",
1322
});
1323
}).pipe(Effect.provide(harness.layer));
1199
- }),
1324
+ }).pipe(
1325
+ Effect.provide(
1326
+ GitVcsDriver.layer.pipe(
1327
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-git-" })),
1328
+ Layer.provideMerge(NodeServices.layer),
1329
+ ),
1330
+ ),
1331
+ ),
1332
);
1333
1334
it.effect("provisions under t3-<hash> when a plain t3 branch blocks t3/*", () =>
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+52
-6
@@ -518,12 +518,58 @@ const make = Effect.gen(function* () {
518
}),
519
),
520
Effect.flatMap((renamed) =>
521
- threads.dispatch({
522
- type: "thread.metadata.update",
523
- commandId: CommandId.make(`${input.commandId}:branch-rename`),
524
- threadId,
525
- branch: renamed.branch,
526
- worktreePath: worktreeCwd,
521
+ Effect.gen(function* () {
522
+ yield* threads
523
+ .dispatch({
524
+ type: "thread.metadata.update",
525
+ commandId: CommandId.make(`${input.commandId}:branch-rename`),
526
+ threadId,
527
+ branch: renamed.branch,
528
+ worktreePath: worktreeCwd,
529
+ expectedBranch: oldBranch,
530
+ expectedWorktreePath: worktreeCwd,
531
+ })
532
+ .pipe(
533
+ Effect.catchCause((cause) =>
534
+ Effect.logWarning("Parent thread worktree branch update failed", {
535
+ threadId,
536
+ cause,
537
+ }),
538
+ ),
539
+ );
540
+ // Updating the parent first makes later subagents inherit the new name.
541
+ // Re-read after each pass for children of subagents updated in that pass.
542
+ const visited = new Set([threadId]);
543
+ while (true) {
544
+ const snapshot = yield* threads.getShellSnapshot();
545
+ const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(
546
+ (thread) =>
547
+ !visited.has(thread.id) &&
548
+ thread.worktreePath === worktreeCwd &&
549
+ thread.branch === oldBranch,
550
+ );
551
+ if (sharing.length === 0) break;
552
+ for (const thread of sharing) {
553
+ visited.add(thread.id);
554
+ yield* threads
555
+ .dispatch({
556
+ type: "thread.metadata.update",
557
+ commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),
558
+ threadId: thread.id,
559
+ branch: renamed.branch,
560
+ expectedBranch: oldBranch,
561
+ expectedWorktreePath: worktreeCwd,
562
+ })
563
+ .pipe(
564
+ Effect.catchCause((cause) =>
565
+ Effect.logWarning("Shared thread worktree branch update failed", {
566
+ threadId: thread.id,
567
+ cause,
568
+ }),
569
+ ),
570
+ );
571
+ }
572
+ }
573
}),
574
),
575
Effect.catchCause((cause) =>
apps/server/src/orchestration-v2/runtimeLayer.ts
+2
@@ -1,6 +1,7 @@
1
import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";
2
import * as Scheduler from "../scheduling/Scheduler.ts";
3
import * as Layer from "effect/Layer";
4
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
5
import * as OrchestrationCommandReceipts from "../persistence/OrchestrationCommandReceipts.ts";
6
import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
7
import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
@@ -108,6 +109,7 @@ const layerProviderEventIngestorProvided = ProviderEventIngestor.layer.pipe(
109
IdAllocator.layer,
110
ProjectionStore.layer,
111
ThreadCommandExecutor.layer,
112
+ GitVcsDriver.layer,
113
),
114
),
115
);
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+5
@@ -19,6 +19,7 @@ import * as ThreadManagementService from "../ThreadManagementService.ts";
19
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
20
import * as McpSessionRegistryTestkit from "../../mcp/McpSessionRegistry.testkit.ts";
21
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
22
+import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts";
23
import * as VcsProcess from "../../vcs/VcsProcess.ts";
24
import * as CheckpointCaptureService from "../CheckpointCaptureService.ts";
25
import * as CheckpointService from "../CheckpointService.ts";
@@ -335,6 +336,10 @@ export function layerWithRegistry<Error>(
336
layerEventSinkProvided,
337
IdAllocator.layer,
338
ThreadCommandExecutor.layer,
339
+ GitVcsDriver.layer.pipe(
340
+ Layer.provide(layerServerConfig),
341
+ Layer.provide(NodeServices.layer),
342
+ ),
343
),
344
),
345
);
packages/contracts/src/orchestrationV2.ts
+1
@@ -2856,6 +2856,7 @@ export const OrchestrationV2Command = Schema.Union([
2856
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2857
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2858
expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2859
+ expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
2860
/** Reject unless no message or run has landed on this thread. */
2861
expectedEmpty: Schema.optional(Schema.Boolean),
2862
limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)),