fix(server): a thread's branch and worktree follow the agent when it moves #15989
Closedshivamhwp(GitHub profile, opens in a new tab)wants to merge 0 commits into
main fromfix/v2-follow-worktree-driftopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 7013OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -6975,3 +6999,15 @@69756999 canUseTool,69767000 onUserDialog,69777001 supportedDialogKinds: ["resume_return"],7002+ hooks: {7003+ PostToolUse: [7004+ {7005+ matcher: "^(EnterWorktree|ExitWorktree)$",7006+ hooks: [7007+ (hookInput) =>7008+ runPromise(7009+ Effect.gen(function* () {7010+ // agent_id is present only for a subagent's own7011+ // tool call; a subagent's worktree is its own7012+ // isolated concern, not this (root) session's.7013+ if (hookInput.hook_event_name === "PostToolUse" && !hookInput.agent_id) {apps/server/src/orchestration-v2/RunFinalizationService.ts lines 371 to 377OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -104,6 +276,10 @@104276 );105277 if (local.refName === null || local.isDefaultRef) return;106278 const thread = yield* projections.getThreadShell(threadId);107- if (!thread || thread.branch !== local.refName) return;279+ if (!thread) return;108280 if (thread.activeRunId !== null && thread.activeRunId !== runId) return;281+ if (thread.branch !== local.refName) {282+ yield* followBranchDrift(thread, local.refName, runId);283+ return;284+ }109285 yield* vcsStatus.refreshPullRequestStatus(cwd).pipe(packages/contracts/src/orchestrationV2.ts line 2630OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2612,3 +2612,19 @@26122612 branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),26132613 worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),26142614 expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),2615+ expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),2616+ /**2617+ * Only adopt `branch` while this thread's (new, if `worktreePath` is also2618+ * set) worktree is exclusive to it. Set by the server's own2619+ * worktree-location follow (#11078): a worktree two threads both point at2620+ * makes "whose branch is it" ambiguous. Rechecked against the live2621+ * projection when the command is decided, not against a stale read, so a2622+ * thread that starts sharing the worktree in between cannot be adopted2623+ * into. When `worktreePath` is also present, a shared worktree still2624+ * commits with `branch` dropped (the location is always worth tracking;2625+ * only adopting its branch is not) rather than rejecting the command;2626+ * without a `worktreePath` change, there is nothing else worth keeping,2627+ * so the whole command is rejected instead.2628+ */2629+ requireExclusiveWorktree: Schema.optional(Schema.Boolean),2630+ /**apps/server/src/orchestration-v2/ProjectionStore.ts line 4522OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4502,3 +4515,8 @@45024515 Effect.map((rows) => rows[0]?.count ?? 0),45034516 Effect.mapError(controlReadError(threadId)),45044517 );4518+4519+ const hasSiblingThreadWithWorktreePath: ProjectionStoreV2Shape["hasSiblingThreadWithWorktreePath"] =4520+ (input) =>4521+ sql<{ readonly thread_id: string }>`4522+ SELECT thread_id FROM orchestration_v2_projection_threadsapps/server/src/orchestration-v2/ThreadLaunchService.ts line 445OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -436,3 +436,10 @@436436 threadId,437437 branch: renamed.branch,438438 worktreePath: worktreeCwd,439+ // Generation and the actual `git branch -m` both take a beat,440+ // during which the agent can check out a real branch itself441+ // (followBranchDrift then corrects the stamp before this442+ // lands). A compare-and-swap drops the rename instead of443+ // overwriting that correction with a branch nothing has444+ // checked out.445+ expectedBranch: oldBranch,
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/RunFinalizationService.ts line 101OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -63,3 +90,12 @@6390 (cause) => new RunFinalizationError({ ...input, operation: "capture-checkpoint", cause }),6491 ),6592 );93+ // Best-effort: this follow is independent of (and must not block) the94+ // checkpoint-cwd branch refresh below, so a failure here is logged and95+ // swallowed rather than aborting the rest of finalize.96+ yield* observer.followWorktreeMove({ threadId: input.threadId, runId: input.runId }).pipe(97+ Effect.catchCause((cause) =>98+ Effect.logWarning("worktree-location follow failed", {99+ threadId: input.threadId,100+ runId: input.runId,101+ cause: Cause.pretty(cause),apps/server/src/orchestration-v2/RunFinalizationService.ts line 179OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -96,0 +159,21 @@159+ yield* threads160+ .dispatch({161+ type: "thread.metadata.update",162+ // Keyed by the run being finalized, not the branch: a retry of the163+ // same at-least-once effect must reuse this id (see164+ // checkpoint.capture below), but a later run drifting back to an165+ // earlier branch is a fresh occurrence, not a duplicate.166+ commandId: CommandId.make(`command:effect:worktree-branch-drift:${runId}`),167+ threadId: thread.id,168+ branch: refName,169+ expectedBranch: thread.branch,170+ expectedWorktreePath: thread.worktreePath,171+ requireExclusiveWorktree: true,172+ })173+ .pipe(174+ Effect.catch((error) =>175+ Effect.logWarning("failed to follow worktree branch drift after run completion", {176+ threadId: thread.id,177+ previousBranch: thread.branch,178+ branch: refName,179+ detail: error.message,
- apps/server/src/orchestration-v2/RunFinalizationService.ts lines 279 to 284OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -104,5 +276,9 @@104276 );105277 if (local.refName === null || local.isDefaultRef) return;106278 const thread = yield* projections.getThreadShell(threadId);107- if (!thread || thread.branch !== local.refName) return;279+ if (!thread) return;108280 if (thread.activeRunId !== null && thread.activeRunId !== runId) return;281+ if (thread.branch !== local.refName) {282+ yield* followBranchDrift(thread, local.refName, runId);283+ return;284+ }
- apps/server/src/orchestration-v2/RunFinalizationService.ts line 236OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -96,0 +216,21 @@216+ // Claude's EnterWorktree/ExitWorktree) moving away from the thread's217+ // recorded worktreePath (#11078). Unlike followBranchDrift, the218+ // worktreePath itself is always worth tracking here, so it commits even219+ // into a shared worktree; only the branch adoption is conditional, via220+ // the same exclusivity check (requireExclusiveWorktree).221+ const followWorktreeMove = ({222+ threadId,223+ runId,224+ }: {225+ readonly threadId: ThreadId;226+ readonly runId: RunId;227+ }) =>228+ Effect.gen(function* () {229+ const thread = yield* projections.getThreadShell(threadId);230+ if (!thread) return;231+ if (thread.activeRunId !== null && thread.activeRunId !== runId) return;232+ const providerContext = yield* projections.getThreadProviderContext(threadId);233+ // Most recently updated, not last in array order: ProjectionStoreV2's234+ // SQL path already returns these ordered by updated_at, but235+ // layerMemory does not, so picking explicitly here works under both.236+ const liveCwd = providerContext.providerSessionsapps/server/src/orchestration-v2/RunFinalizationService.ts line 123OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -63,3 +120,4 @@63120 (cause) => new RunFinalizationError({ ...input, operation: "capture-checkpoint", cause }),64121 ),65122 );123+ // Best-effort: this follow is independent of (and must not block) the
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/RunFinalizationService.ts line 310OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -96,0 +290,21 @@290+ commandId: CommandId.make(`command:effect:worktree-location-follow:${runId}`),291+ threadId,292+ worktreePath: newWorktreePath,293+ expectedWorktreePath: thread.worktreePath,294+ branch: checkedOutBranch,295+ // The session itself moved and is already working from the new296+ // location; detaching it (the default for an explicit worktree297+ // handoff) would kill useful, in-progress work.298+ preserveProviderSession: true,299+ ...(checkedOutBranch !== null ? { requireExclusiveWorktree: true } : {}),300+ })301+ .pipe(302+ Effect.catch((error) =>303+ Effect.logWarning("failed to follow the provider session into its new worktree", {304+ threadId,305+ worktreePath: newWorktreePath,306+ category: failureCategory(error),307+ }),308+ ),309+ );310+ }).pipe(
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 3335OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3313,3 +3315,21 @@33133315 const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>33143316 Queue.offer(events, event).pipe(Effect.asVoid);331533173318+ // Live-tracks this session's actual cwd, separately from `session`3319+ // (the snapshot ProviderSessionManager first registered this session3320+ // with). Claude's EnterWorktree/ExitWorktree tools move the running3321+ // session's cwd without going through any T3 command (#11078); the3322+ // PostToolUse hook below reports that move here so the server can3323+ // follow it at turn end, the same way it already follows a plain3324+ // branch change (git checkout) inside an unmoved cwd.3325+ const trackedCwd = yield* Ref.make(session.cwd);3326+ const followWorktreeCwdChange = Effect.fn("ClaudeAdapterV2.followWorktreeCwdChange")(3327+ function* (nextCwd: string) {3328+ const previousCwd = yield* Ref.get(trackedCwd);3329+ if (nextCwd === previousCwd) return;3330+ yield* Ref.set(trackedCwd, nextCwd);3331+ const updatedAt = yield* DateTime.now;3332+ yield* emitProviderEvent({3333+ type: "provider_session.updated",3334+ driver: CLAUDE_PROVIDER,3335+ providerSession: { ...session, cwd: nextCwd, updatedAt },
- apps/server/src/server.ts line 505OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -495,3 +495,11 @@495495 Layer.provide(ProjectionStoreV2.layer),496496 Layer.provide(layerPullRequestService),497497 Layer.provide(RuntimeLayer.layerProjectService),498+ // layerThreadManagementProvided is the same orchestrator instance499+ // RuntimeLayer.layerProduction runs; its own remaining requirements500+ // (satisfied for that instance above) must be repeated here too, since a501+ // dependency's open requirements are not inherited from a sibling502+ // `Layer.provide` step. Layer memoization still builds each of these once503+ // and shares it, so this is one orchestrator, not two.504+ Layer.provide(505+ RuntimeLayer.layerThreadManagementProvided.pipe(
- apps/server/src/orchestration-v2/RunFinalizationService.ts lines 222 to 228OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -98,0 +208,21 @@208+ // belongs to exactly this thread. For a shared worktree, whose branch it209+ // is would be ambiguous, so leave the stamp alone.210+ // Returns whether it dispatched the follow.211+ const followBranchDrift = Effect.fn("RunFinalizationService.followBranchDrift")(function* (212+ thread: OrchestrationV2ThreadShell,213+ cwd: string,214+ refName: string,215+ runId: RunId,216+ ) {217+ // No branch to compare-and-swap against, no dedicated worktree to own218+ // exclusively, the first-turn auto-rename is still in flight, or `cwd`219+ // is not the thread's worktree. The last one happens when220+ // followWorktreeMove just moved the thread out of the checkpoint cwd:221+ // that cwd's branch belongs to where the thread was, not where it is.222+ if (223+ thread.branch === null ||224+ thread.worktreePath === null ||225+ thread.worktreePath !== cwd ||226+ isTemporaryWorktreeBranch(refName)227+ ) {228+ return false;
juliusmarminge assignedjuliusmarminge
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 3765 to 3785OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3761,0 +3765,21 @@3765+ // A root session can move without a T3 worktree handoff.3766+ const trackedCwd = yield* Ref.make(session.cwd);3767+ const followWorktreeCwdChange = Effect.fn("ClaudeAdapterV2.followWorktreeCwdChange")(3768+ function* (nextCwd: string) {3769+ const previousCwd = yield* Ref.get(trackedCwd);3770+ if (nextCwd === previousCwd) return;3771+ yield* Ref.set(trackedCwd, nextCwd);3772+ const updatedAt = yield* DateTime.now;3773+ const context = yield* Ref.get(activeTurn);3774+ yield* emitProviderEvent({3775+ type: "provider_session.updated",3776+ driver: CLAUDE_PROVIDER,3777+ providerSession: {3778+ ...session,3779+ cwd: nextCwd,3780+ cwdChangeSource: context?.input.runtimePolicy.cwd ?? undefined,3781+ updatedAt,3782+ },3783+ });3784+ },3785+ );
juliusmarminge added labelsbugfix
juliusmarminge added labelspr:gate-failed
juliusmarminge removed labelspr:gate-failed
juliusmarminge added labelspr:needs-julius
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed