TypeScript
fix(server): subagents pick up their parent's renamed worktree branch (#20079)
maria4e85a93b20c8
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex a0e1c1fc788..5e889b17eb9 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -2539,6 +2539,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocause: `Thread ${command.threadId} worktree changed before the metadata update could be applied.`,});}+ if (+ command.type === "thread.metadata.update" &&+ command.expectedBranch !== undefined &&+ command.expectedBranch !== thread.branch+ ) {+ return yield* new OrchestratorDispatchError({+ commandId: command.commandId,+ commandType: command.type,+ cause: `Thread ${command.threadId} branch changed before the metadata update could be applied.`,+ });+ }if (command.type === "thread.metadata.update" && command.expectedEmpty === true) {const records = yield* projectionStore.getThreadRecords(command.threadId, ["runs"])diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.tsindex f2a8ed7ff0e..36505433308 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts@@ -1,9 +1,11 @@import { assert, it } from "@effect/vitest";+import * as NodeServices from "@effect/platform-node/NodeServices";import {CheckpointId,CheckpointRef,CheckpointScopeId,MessageId,+ GitCommandError,type ModelSelection,NodeId,type OrchestrationV2AppThread,@@ -28,6 +30,7 @@ import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";import * as Fiber from "effect/Fiber";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as SqlClient from "effect/sql/SqlClient";import * as Stream from "effect/Stream";@@ -35,6 +38,8 @@ import * as TestClock from "effect/testing/TestClock";import { toolOutputImages } from "@t3tools/shared/toolOutput";import * as SqlitePersistence from "../persistence/Sqlite.ts";+import * as ServerConfig from "../config.ts";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as EventSink from "./EventSink.ts";import * as EventStore from "./EventStore.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";@@ -58,12 +63,18 @@ const layerTestEventSink = EventSink.layer.pipe(Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),);+const layerGit = GitVcsDriver.layer.pipe(+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "ingestor-git-" })),+ Layer.provideMerge(NodeServices.layer),+);+const layerTest = Layer.mergeAll(layerTestDatabase,layerTestStores,layerTestEventSink,IdAllocator.layer,ThreadCommandExecutor.layer,+ layerGit,ProviderEventIngestor.layer.pipe(Layer.provide(Layer.mergeAll(@@ -71,10 +82,35 @@ const layerTest = Layer.mergeAll(layerTestEventSink,IdAllocator.layer,ThreadCommandExecutor.layer,+ layerGit,),),),);++const makeSharedWorktree = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const git = yield* GitVcsDriver.GitVcsDriver;+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "ingestor-worktree-" });+ const repo = `${directory}/repo`;+ const worktreePath = `${directory}/shared`;+ yield* fs.makeDirectory(repo);+ const command = (cwd: string, args: string[]) =>+ git.execute({ operation: "ingestor-test", cwd, args });+ yield* command(repo, ["init", "-b", "main"]);+ yield* command(repo, [+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "commit",+ "--allow-empty",+ "-m",+ "initial",+ ]);+ yield* command(repo, ["worktree", "add", "-b", "t3/abcd1234", worktreePath]);+ return { repo, worktreePath, command };+});const modelSelection = {instanceId: ProviderInstanceId.make("codex"),model: "gpt-5.4",@@ -1729,6 +1765,280 @@ layer("ProviderEventIngestorV2", (it) => {}),);+ it.effect.each([+ { parentMoved: false, failure: null },+ { parentMoved: true, failure: null },+ { parentMoved: false, failure: "write" },+ { parentMoved: false, failure: "git" },+ ])(+ "rechecks a pending native child's branch after the rename scan: %j",+ ({ parentMoved, failure }) =>+ Effect.gen(function* () {+ const { worktreePath, command } = yield* makeSharedWorktree;+ const git = yield* GitVcsDriver.GitVcsDriver;+ const now = yield* DateTime.now;+ const eventSink = yield* EventSink.EventSinkV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const ids = yield* IdAllocator.IdAllocatorV2;+ const rootEvent = yield* threadCreatedEvent(now);+ if (rootEvent.type !== "thread.created") throw new Error("Expected thread fixture");+ const parent = {+ ...rootEvent.payload,+ branch: "t3/abcd1234",+ worktreePath,+ };+ yield* eventSink.write({ events: [{ ...rootEvent, payload: parent }] });+ const childId = ids.derive.threadFromProviderThread({+ driver: CODEX_DRIVER,+ nativeThreadId: `child-created-during-rename:${parentMoved}:${failure}`,+ });+ const beforeCommit = yield* Deferred.make<+ void,+ ProviderEventIngestor.ProviderEventIngestorV2Error+ >();+ const allowCommit = yield* Deferred.make<void>();+ let correctionWrites = 0;+ const gatedSink = EventSink.EventSinkV2.of({+ ...eventSink,+ write: (input) => {+ if (+ input.events.some(+ (event) => event.type === "thread.metadata-updated" && event.threadId === childId,+ )+ ) {+ correctionWrites++;+ if (failure === "write" && correctionWrites === 1)+ return Effect.fail(new EventSink.EventSinkWriteError({ eventCount: 1 }));+ }+ return input.events.some(+ (event) => event.type === "thread.created" && event.threadId === childId,+ )+ ? Deferred.succeed(beforeCommit, undefined).pipe(+ Effect.andThen(Deferred.await(allowCommit)),+ Effect.andThen(eventSink.write(input)),+ )+ : eventSink.write(input);+ },+ });+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(+ Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),+ Effect.provideService(EventSink.EventSinkV2, gatedSink),+ Effect.provideService(GitVcsDriver.GitVcsDriver, {+ ...git,+ resolveBranchName: (cwd, refName) =>+ failure === "git"+ ? Effect.fail(+ new GitCommandError({+ operation: "ingestor-test",+ cwd,+ command: "rev-parse",+ detail: "Read failed",+ }),+ )+ : git.resolveBranchName(cwd, refName),+ }),+ );+ const providerSessionId = yield* ids.allocate.providerSession({+ providerInstanceId: modelSelection.instanceId,+ threadId: parent.id,+ });+ const creationInput = {+ providerSessionId,+ providerInstanceId: modelSelection.instanceId,+ threadId: parent.id,+ event: {+ type: "app_thread.created",+ driver: CODEX_DRIVER,+ appThread: {+ ...parent,+ id: childId,+ lineage: {+ parentThreadId: parent.id,+ rootThreadId: parent.id,+ relationshipToParent: "subagent",+ },+ },+ },+ } satisfies ProviderEventIngestor.ProviderEventIngestInput;+ const creation = yield* ingestor.ingestNormalized(creationInput).pipe(+ Effect.tapCause((cause) => Deferred.failCause(beforeCommit, cause)),+ Effect.forkScoped,+ );+ yield* Deferred.await(beforeCommit);+ yield* command(worktreePath, ["branch", "-m", "generated-branch"]);+ yield* eventSink.write({+ events: [+ {+ ...rootEvent,+ id: yield* ids.allocate.event({ threadId: parent.id }),+ type: "thread.metadata-updated",+ payload: {+ ...parent,+ branch: parentMoved ? "user/checkout" : "generated-branch",+ worktreePath: parentMoved ? `${worktreePath}-moved` : worktreePath,+ },+ },+ ],+ });+ // The rename's final scan finishes while the child is still uncommitted.+ const snapshot = yield* projections.getShellSnapshot();+ assert.isFalse(+ [...snapshot.threads, ...snapshot.archivedThreads].some(+ (thread) =>+ thread.worktreePath === parent.worktreePath && thread.branch === parent.branch,+ ),+ );+ yield* Deferred.succeed(allowCommit, undefined);+ const stored = yield* Fiber.join(creation);+ assert.equal(stored[0]?.event.type, "thread.created");+ const child = yield* projections.getThread(childId);+ assert.equal(child.branch, failure === null ? "generated-branch" : parent.branch);+ assert.equal(child.worktreePath, parent.worktreePath);+ assert.equal(correctionWrites, failure === "git" ? 0 : 1);+ assert.deepEqual(yield* ingestor.ingestNormalized(creationInput), []);+ }),+ );++ it.effect.each(["explicit", "detached", "unchanged", "legacy"])(+ "preserves a native child's branch when the checkout needs no correction: %s",+ (scenario) =>+ Effect.gen(function* () {+ const { worktreePath, command } = yield* makeSharedWorktree;+ const git = yield* GitVcsDriver.GitVcsDriver;+ const branch =+ scenario === "explicit"+ ? "child-feature"+ : scenario === "legacy"+ ? "t3-abcd1234"+ : "t3/abcd1234";+ if (scenario === "explicit" || scenario === "legacy")+ yield* command(worktreePath, ["branch", "-m", branch]);+ if (scenario === "detached") yield* command(worktreePath, ["checkout", "--detach"]);+ const now = yield* DateTime.now;+ const sink = yield* EventSink.EventSinkV2;+ const projections = yield* ProjectionStore.ProjectionStoreV2;+ const ids = yield* IdAllocator.IdAllocatorV2;+ const root = yield* threadCreatedEvent(now);+ if (root.type !== "thread.created") throw new Error("Expected thread fixture");+ yield* sink.write({+ events: [+ { ...root, payload: { ...root.payload, branch: "parent-feature", worktreePath } },+ ],+ });+ const childId = ids.derive.threadFromProviderThread({+ driver: CODEX_DRIVER,+ nativeThreadId: `no-correction:${scenario}`,+ });+ let gitReads = 0;+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(+ Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),+ Effect.provideService(GitVcsDriver.GitVcsDriver, {+ ...git,+ resolveBranchName: (cwd, refName) => {+ gitReads++;+ return git.resolveBranchName(cwd, refName);+ },+ }),+ );+ const stored = yield* ingestor.ingestNormalized({+ providerSessionId: yield* ids.allocate.providerSession({+ providerInstanceId: modelSelection.instanceId,+ threadId: root.threadId,+ }),+ providerInstanceId: modelSelection.instanceId,+ threadId: root.threadId,+ event: {+ type: "app_thread.created",+ driver: CODEX_DRIVER,+ appThread: {+ ...root.payload,+ id: childId,+ branch,+ worktreePath,+ lineage: {+ parentThreadId: root.threadId,+ rootThreadId: root.threadId,+ relationshipToParent: "subagent",+ },+ },+ },+ });+ assert.equal((yield* projections.getThread(childId)).branch, branch);+ assert.equal(stored.length, 1);+ assert.equal(gitReads, scenario === "explicit" ? 0 : 1);+ }),+ );++ it.effect.each(+ ["codex", "claude"].flatMap((driver) =>+ ["/repo/shared", "/repo/isolated", null].map((worktreePath) => ({ driver, worktreePath })),+ ),+ )("records a native child with current shared workspace: %j", ({ driver, worktreePath }) =>+ Effect.gen(function* () {+ const { repo, worktreePath: sharedPath, command } = yield* makeSharedWorktree;+ const isolatedPath = `${sharedPath}-isolated`;+ yield* command(sharedPath, ["branch", "-m", "generated-branch"]);+ yield* command(repo, ["worktree", "add", "-b", "t3/abcd1234", isolatedPath]);+ const actualPath =+ worktreePath === "/repo/shared" ? sharedPath : worktreePath === null ? null : isolatedPath;+ const now = yield* DateTime.now;+ const eventSink = yield* EventSink.EventSinkV2;+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const rootEvent = yield* threadCreatedEvent(now);+ if (rootEvent.type !== "thread.created") throw new Error("Expected thread fixture");+ const childThreadId = idAllocator.derive.threadFromProviderThread({+ driver: ProviderDriverKind.make(driver),+ nativeThreadId: `late-native-subagent:${worktreePath}`,+ });+ const offered: OrchestrationV2AppThread = {+ ...rootEvent.payload,+ id: childThreadId,+ branch: "t3/abcd1234",+ worktreePath: actualPath,+ lineage: {+ parentThreadId: rootEvent.threadId,+ relationshipToParent: "subagent",+ rootThreadId: rootEvent.threadId,+ },+ };+ yield* eventSink.write({+ events: [+ {+ ...rootEvent,+ payload: {+ ...rootEvent.payload,+ branch: "generated-branch",+ worktreePath: sharedPath,+ },+ },+ ],+ });+ const providerSessionId = yield* idAllocator.allocate.providerSession({+ providerInstanceId: modelSelection.instanceId,+ threadId: rootEvent.threadId,+ });+ yield* ingestor.ingestNormalized({+ providerSessionId,+ providerInstanceId: modelSelection.instanceId,+ threadId: rootEvent.threadId,+ event: {+ type: "app_thread.created",+ driver: ProviderDriverKind.make(driver),+ appThread: offered,+ },+ });+ const child = yield* projectionStore.getThread(childThreadId);+ assert.equal(+ child.branch,+ worktreePath === "/repo/shared" ? "generated-branch" : offered.branch,+ );+ assert.equal(child.worktreePath, actualPath);+ assert.deepEqual(child.lineage, offered.lineage);+ }),+ );+it.effect("updates provider child metadata without recreating its saved thread", () =>Effect.gen(function* () {const now = yield* DateTime.now;diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.tsindex d749669164d..5ae0a86c8ff 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts@@ -27,8 +27,10 @@ import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";import { AgentScope } from "@t3tools/shared/AgentScope";+import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";import * as AnalyticsService from "../telemetry/AnalyticsService.ts";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as EventSink from "./EventSink.ts";import * as ProjectionStore from "./ProjectionStore.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";@@ -307,6 +309,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2,never,| EventSink.EventSinkV2+ | GitVcsDriver.GitVcsDriver| IdAllocator.IdAllocatorV2| ProjectionStore.ProjectionStoreV2| ThreadCommandExecutor.ThreadCommandExecutor@@ -314,6 +317,7 @@ export const layer: Layer.Layer<ProviderEventIngestorV2,Effect.gen(function* () {const eventSink = yield* EventSink.EventSinkV2;+ const git = yield* GitVcsDriver.GitVcsDriver;const projections = yield* ProjectionStore.ProjectionStoreV2;const idAllocator = yield* IdAllocator.IdAllocatorV2;const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor;@@ -783,6 +787,43 @@ export const layer: Layer.Layer<.pipe(Effect.mapError(mapWriteError));return result.storedEvents;}).pipe(+ Effect.flatMap((storedEvents) =>+ Effect.gen(function* () {+ if (input.event.type !== "app_thread.created") return storedEvents;+ const created = storedEvents.find((stored) => stored.event.type === "thread.created");+ if (created?.event.type !== "thread.created") return storedEvents;+ const child = created.event.payload;+ if (+ child.worktreePath === null ||+ child.branch === null ||+ !isTemporaryWorktreeBranch(child.branch)+ )+ return storedEvents;+ // Git renames before scanning committed threads. If that scan missed this+ // creation, HEAD already has the new name, even if the parent moved away.+ const branch = yield* git.resolveBranchName(child.worktreePath, "HEAD");+ if (branch === null || branch === child.branch) return storedEvents;+ const now = yield* DateTime.now;+ const event = yield* makeDomainEvent(input, {+ type: "thread.metadata-updated",+ threadId: child.id,+ payload: { ...child, branch, updatedAt: now },+ occurredAt: now,+ });+ const synced = yield* eventSink.write({ events: [event] });+ return [...storedEvents, ...synced];+ }).pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("Native thread worktree branch recheck failed", {+ threadId:+ input.event.type === "app_thread.created"+ ? input.event.appThread.id+ : input.threadId,+ cause,+ }).pipe(Effect.as(storedEvents)),+ ),+ ),+ ),Effect.flatMap((storedEvents) =>storedEvents.length === 0 || input.event.type !== "subagent.updated"? Effect.succeed(storedEvents)diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.tsindex e191cc38f40..6f94118fcc8 100644--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts@@ -48,6 +48,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ProjectionStore from "./ProjectionStore.ts";import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";import * as ProviderSessionManager from "./ProviderSessionManager.ts";import * as CommandOutputHub from "./CommandOutputHub.ts";@@ -545,6 +546,9 @@ function layerTest(input: {IdAllocator.layer,layerTestStores,ThreadCommandExecutor.layer,+ Layer.mock(GitVcsDriver.GitVcsDriver)({+ resolveBranchName: () => Effect.succeed(null),+ }),),),);diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.tsindex 26e9b8c8d78..44d70d5df4c 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts@@ -33,6 +33,7 @@ import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";+import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Ref from "effect/Ref";@@ -1147,17 +1148,45 @@ it.effect("names the worktree itself when the client provides no branch", () =>}),);-it.effect("renames a temporary t3/<hash> branch off the provisioning critical path", () =>+it.effect.each(+ [false, true].flatMap((archived) =>+ [false, true].map((parentMoved) => ({ archived, parentMoved })),+ ),+)("renames shared temporary branches with %j", ({ archived, parentMoved }) =>Effect.gen(function* () {- const branchNameStarted = yield* Deferred.make<void>();+ const fs = yield* FileSystem.FileSystem;+ const git = yield* GitVcsDriver.GitVcsDriver;+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-rename-" });+ const repo = `${directory}/repo`;+ const worktreePath = `${directory}/shared`;+ const movedPath = `${directory}/moved`;+ yield* fs.makeDirectory(repo);+ const command = (cwd: string, args: string[]) =>+ git.execute({ operation: "launch-test", cwd, args });+ yield* command(repo, ["init", "-b", "main"]);+ yield* command(repo, [+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "commit",+ "--allow-empty",+ "-m",+ "initial",+ ]);+ yield* command(repo, ["worktree", "add", "-b", "t3/abcd1234", worktreePath]);+ yield* command(repo, ["worktree", "add", "-b", "user/checkout", movedPath]);+ const branchNameStarted = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();const allowBranchName = yield* Deferred.make<void>();const harness = makeHarness({createWorktree: (input) =>Effect.succeed({- worktree: { path: "/repo-worktrees/temp", refName: input.newRefName, headSha: "abc" },+ worktree: { path: worktreePath, refName: input.newRefName, headSha: "abc" },} as never),+ renameBranch: git.renameBranch,generateBranchName: () =>- Deferred.succeed(branchNameStarted, undefined).pipe(+ Effect.fiber.pipe(+ Effect.flatMap((fiber) => Deferred.succeed(branchNameStarted, fiber)),Effect.andThen(Deferred.await(allowBranchName)),Effect.as({ branch: "generated-branch" }),),@@ -1173,7 +1202,7 @@ it.effect("renames a temporary t3/<hash> branch off the provisioning critical paworkspace: { type: "worktree", baseRef: "main", branch: "t3/abcd1234" },}),);- yield* Deferred.await(branchNameStarted);+ const renameFiber = yield* Deferred.await(branchNameStarted);assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.newRefName, "t3/abcd1234");yield* waitUntil(() =>threads@@ -1184,19 +1213,122 @@ it.effect("renames a temporary t3/<hash> branch off the provisioning critical pa(yield* threads.getThreadProjection(launched.threadId)).thread.branch,"t3/abcd1234",);+ const parent = yield* threads.getThreadProjection(launched.threadId);+ const run = parent.runs[0]!;+ assert.isNotNull(run.rootNodeId);+ yield* threads.dispatch({+ type: "delegated_task.request",+ commandId: CommandId.make("command:launch:temp-branch:delegate"),+ parentThreadId: launched.threadId,+ parentRunId: run.id,+ parentNodeId: run.rootNodeId!,+ task: "Work in the parent's checkout",+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ createdBy: "agent",+ creationSource: "mcp",+ });+ const delegated = yield* threads.getThreadProjection(launched.threadId);+ const childThreadId = delegated.subagents[0]!.childThreadId!;+ const child = yield* threads.getThreadProjection(childThreadId);+ assert.equal(child.thread.branch, "t3/abcd1234");+ assert.equal(child.thread.worktreePath, worktreePath);+ assert.equal(child.thread.lineage.parentThreadId, launched.threadId);++ const otherThreadId = ThreadId.make("thread:launch:other-branch");+ const otherPathThreadId = ThreadId.make("thread:launch:other-worktree");+ for (const [threadId, branch, otherWorktreePath] of [+ [otherThreadId, "other-feature", worktreePath],+ [otherPathThreadId, "t3/abcd1234", "/repo-worktrees/other"],+ ] as const) {+ yield* threads.dispatch({+ type: "thread.create",+ commandId: CommandId.make(`command:create:${threadId}`),+ threadId,+ projectId,+ title: "Unrelated thread",+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch,+ worktreePath: otherWorktreePath,+ createdBy: "user",+ creationSource: "web",+ });+ }+ if (archived) {+ for (const threadId of [childThreadId, otherThreadId, otherPathThreadId]) {+ yield* threads.dispatch({+ type: "thread.archive",+ commandId: CommandId.make(`command:archive:${threadId}`),+ threadId,+ });+ }+ }+ const unrelatedBeforeRename = yield* threads.getThreadProjection(otherThreadId);+ const otherPathBeforeRename = yield* threads.getThreadProjection(otherPathThreadId);+ if (parentMoved) {+ yield* threads.dispatch({+ type: "thread.metadata.update",+ commandId: CommandId.make("command:launch:parent-moved"),+ threadId: launched.threadId,+ branch: "user/checkout",+ worktreePath: movedPath,+ });+ }yield* Deferred.succeed(allowBranchName, undefined);- yield* waitUntil(() =>- threads- .getThreadProjection(launched.threadId)- .pipe(Effect.map((projection) => projection.thread.branch === "generated-branch")),+ yield* Fiber.await(renameFiber);+ assert.equal(yield* git.resolveBranchName(worktreePath, "HEAD"), "generated-branch");+ assert.equal(+ (yield* threads.getThreadProjection(launched.threadId)).thread.branch,+ parentMoved ? "user/checkout" : "generated-branch",+ );+ assert.equal(+ (yield* threads.getThreadProjection(launched.threadId)).thread.worktreePath,+ parentMoved ? movedPath : worktreePath,+ );+ assert.equal(+ (yield* threads.getThreadProjection(childThreadId)).thread.branch,+ "generated-branch",+ );+ assert.deepEqual(+ (yield* threads.getThreadProjection(otherThreadId)).thread,+ unrelatedBeforeRename.thread,+ );+ assert.deepEqual(+ (yield* threads.getThreadProjection(otherPathThreadId)).thread,+ otherPathBeforeRename.thread,+ );+ const staleUpdate = yield* threads+ .dispatch({+ type: "thread.metadata.update",+ commandId: CommandId.make("command:launch:stale-branch-update"),+ threadId: otherThreadId,+ branch: "generated-branch",+ expectedBranch: "t3/abcd1234",+ expectedWorktreePath: worktreePath,+ })+ .pipe(Effect.flip);+ assert.equal(staleUpdate._tag, "OrchestratorDispatchError");+ assert.deepEqual(+ (yield* threads.getThreadProjection(otherThreadId)).thread,+ unrelatedBeforeRename.thread,);assert.deepEqual(harness.renameBranch.mock.calls[0]?.[0], {- cwd: "/repo-worktrees/temp",+ cwd: worktreePath,oldBranch: "t3/abcd1234",newBranch: "generated-branch",});}).pipe(Effect.provide(harness.layer));- }),+ }).pipe(+ Effect.provide(+ GitVcsDriver.layer.pipe(+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-git-" })),+ Layer.provideMerge(NodeServices.layer),+ ),+ ),+ ),);it.effect("provisions under t3-<hash> when a plain t3 branch blocks t3/*", () =>diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.tsindex a4d94977097..9c85b8d2208 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts@@ -518,12 +518,58 @@ const make = Effect.gen(function* () {}),),Effect.flatMap((renamed) =>- threads.dispatch({- type: "thread.metadata.update",- commandId: CommandId.make(`${input.commandId}:branch-rename`),- threadId,- branch: renamed.branch,- worktreePath: worktreeCwd,+ Effect.gen(function* () {+ yield* threads+ .dispatch({+ type: "thread.metadata.update",+ commandId: CommandId.make(`${input.commandId}:branch-rename`),+ threadId,+ branch: renamed.branch,+ worktreePath: worktreeCwd,+ expectedBranch: oldBranch,+ expectedWorktreePath: worktreeCwd,+ })+ .pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("Parent thread worktree branch update failed", {+ threadId,+ cause,+ }),+ ),+ );+ // Updating the parent first makes later subagents inherit the new name.+ // Re-read after each pass for children of subagents updated in that pass.+ const visited = new Set([threadId]);+ while (true) {+ const snapshot = yield* threads.getShellSnapshot();+ const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(+ (thread) =>+ !visited.has(thread.id) &&+ thread.worktreePath === worktreeCwd &&+ thread.branch === oldBranch,+ );+ if (sharing.length === 0) break;+ for (const thread of sharing) {+ visited.add(thread.id);+ yield* threads+ .dispatch({+ type: "thread.metadata.update",+ commandId: CommandId.make(`${input.commandId}:branch-rename:${thread.id}`),+ threadId: thread.id,+ branch: renamed.branch,+ expectedBranch: oldBranch,+ expectedWorktreePath: worktreeCwd,+ })+ .pipe(+ Effect.catchCause((cause) =>+ Effect.logWarning("Shared thread worktree branch update failed", {+ threadId: thread.id,+ cause,+ }),+ ),+ );+ }+ }}),),Effect.catchCause((cause) =>diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.tsindex d4ba1508484..45b89e49ce0 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts@@ -1,6 +1,7 @@import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";import * as Scheduler from "../scheduling/Scheduler.ts";import * as Layer from "effect/Layer";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as OrchestrationCommandReceipts from "../persistence/OrchestrationCommandReceipts.ts";import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";@@ -108,6 +109,7 @@ const layerProviderEventIngestorProvided = ProviderEventIngestor.layer.pipe(IdAllocator.layer,ProjectionStore.layer,ThreadCommandExecutor.layer,+ GitVcsDriver.layer,),),);diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.tsindex 2d01f430380..ff6c1d18e47 100644--- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts+++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts@@ -19,6 +19,7 @@ import * as ThreadManagementService from "../ThreadManagementService.ts";import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";import * as McpSessionRegistryTestkit from "../../mcp/McpSessionRegistry.testkit.ts";import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";+import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts";import * as VcsProcess from "../../vcs/VcsProcess.ts";import * as CheckpointCaptureService from "../CheckpointCaptureService.ts";import * as CheckpointService from "../CheckpointService.ts";@@ -335,6 +336,10 @@ export function layerWithRegistry<Error>(layerEventSinkProvided,IdAllocator.layer,ThreadCommandExecutor.layer,+ GitVcsDriver.layer.pipe(+ Layer.provide(layerServerConfig),+ Layer.provide(NodeServices.layer),+ ),),),);diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex d505631439e..f08eec7345b 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -2856,6 +2856,7 @@ export const OrchestrationV2Command = Schema.Union([branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),+ expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),/** Reject unless no message or run has landed on this thread. */expectedEmpty: Schema.optional(Schema.Boolean),limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)),