Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): threads follow branches the agent renames in their worktree #22805

Closedlnieuwenhuis(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/22805/headopened View on GitHub

Problem

When an agent renames the branch in its thread's worktree (git branch -m, or git checkout -b), thread.branch keeps the old name. Merged-worktree cleanup then bails at branchChanged with "Repository or branch changed", and its merged-PR lookup searches by the stale name. As a result, worktrees whose PRs merged are never removed. In #22312 this filled a disk. Fixes #22312, and fixes #16559.

Change

  • After each run, RunFinalizationService already reads the checked-out branch, but it threw the result away when the name differed. refresh() now returns that branch. It returns null for a detached HEAD or the default branch.
  • When the run's cwd is the thread's own worktree and no newer run is active on the thread, finalization dispatches the existing thread.metadata.update. It does this for every thread in that worktree that still records the old name, so a root thread and the subagents sharing its worktree move together. Cleanup requires that.
  • Each update carries expectedBranch and expectedWorktreePath, so a concurrent change rejects it instead of overwriting.
  • Command ids are deterministic per run and thread, so retries replay the receipt instead of applying the update twice.
  • Failures are logged and never fail finalization.
  • storageCleanup.ts is unchanged. Once thread.branch is accurate, its existing checks work.

This follows the approach of #19870, which its author closed unmerged. That PR's "worktree not shared" guard is dropped because it would block the reported case, a root thread plus subagents in one worktree. Its "skip temporary branch" guard is dropped because the launch-time rename already reconciles through expectedBranch.

Things to know:

  • The thread follows the branch actually checked out in its worktree, so a branch switch is adopted, not only a rename. The default branch and a detached HEAD are never adopted. Cleanup still never deletes branches and refuses dirty trees.
  • This fixes things going forward. Threads that are already idle with a stale name update at the end of their next completed turn; there is no backfill.
  • A detached HEAD (part of #17813) is not handled here.

Scope and approval

This is the bug triaged in #16559 and re-reported in #22312, with no new settings or UI.

Verification

  • vp test run on RunFinalizationService.test.ts and RunFinalizationQueue.test.ts: 10/10 pass.
  • RunExecutionService.test.ts: 37/37 pass.
  • New cases:
    • the thread and a subagent in the same worktree are updated, while a thread on a different branch and a thread in another worktree are left alone;
    • a run whose cwd is outside the thread's worktree changes nothing;
    • a newer active run blocks the update.
  • The main case fails with the update step disabled.
  • vp run --filter t3 typecheck is clean.
  • Not run: an end-to-end cleanup sweep against a real merged PR.

Model/harness: Claude Opus 5.5 / Claude Code (in T3 Code).

🤖 Generated with Claude Code

    1. Approvability

      Verdict: Approved at abceb60

      Macroscope's review found this PR approvable — This focused server bug fix reconciles thread metadata when an agent renames a branch in its worktree, including shared subagent worktrees, while preserving guards for concurrent changes and default or detached checkouts. It reuses existing commands and cleanup behavior and adds targeted tests without changing product defaults or static-analysis settings.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    2. Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: Path: .coderabbit.config.ts
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: 5dc47e29-689c-4671-9779-5173e5003dbb
      📥 Commits

      Reviewing files that changed from the base of the PR and between e27a03e94d43b504cfc3933282af913763312afd and abceb6068a29b0d7e7f14fad1190b8d8dd167d0d.

      📒 Files selected for processing: 6
      • apps/server/src/orchestration-v2/RunExecutionService.test.ts
      • apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts
      • apps/server/src/orchestration-v2/RunFinalizationService.test.ts
      • apps/server/src/orchestration-v2/RunFinalizationService.ts
      • apps/server/src/orchestration-v2/runtimeLayer.ts
      • apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

      📝 Walkthrough

      Finalization refresh now returns the refreshed branch name when applicable. When that name differs from the recorded branch, finalization dispatches guarded metadata updates for matching threads in the same worktree. Runtime and replay wiring provide thread-management dependencies, and tests cover matching and excluded threads.

      Changes: Branch Rename Adoption

      Layer / File(s)Summary
      Return refreshed branch from observer
      apps/server/src/orchestration-v2/RunFinalizationService.ts
      The observer returns a branch name or null based on the thread and branch state.
      Adopt renamed branch during finalization
      apps/server/src/orchestration-v2/RunFinalizationService.ts, apps/server/src/orchestration-v2/runtimeLayer.ts, apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
      Finalization dispatches guarded metadata updates for eligible threads. Runtime and replay wiring provide the thread-management dependency.
      Validate adoption and update test dependencies
      apps/server/src/orchestration-v2/RunFinalizationService.test.ts, apps/server/src/orchestration-v2/RunFinalizationQueue.test.ts, apps/server/src/orchestration-v2/RunExecutionService.test.ts
      Tests check which threads receive metadata updates and provide the updated observer result and service dependencies.

      Priority: ➖ Normal

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Change: Bug fix · Severity of issue fixed: Medium

      Sequence Diagram(s)

      sequenceDiagram
        participant RunFinalizationService
        participant RunFinalizationObserver
        participant ThreadManagementService
        RunFinalizationService->>RunFinalizationObserver: refresh
        RunFinalizationObserver-->>RunFinalizationService: branch name or null
        RunFinalizationService->>ThreadManagementService: dispatch guarded metadata updates

      Suggested reviewers: juliusmarminge, shshajek-cpu

      Merge Risk: ⚪ Minimal · up to abceb

      The renamed-branch cleanup path has no established merge-blocking issue. A cleanup sweep that races with adoption may defer removal until a later sweep.

      Security architecture risk: 🔵 Low · up to abceb

      Branch adoption remains scoped to the same worktree and retains existing deletion safeguards. Partial updates can nevertheless leave related threads out of sync and block cleanup until they are separately reconciled.

      Retained concerns

      • Low · reliability · inferred: The new multi-thread adoption transition lacks convergent recovery after partial success. If the initiating thread updates but a sibling update fails, finalization logs the failure and succeeds. Repeating finalization then returns early because the initiating thread already has the new branch, leaving the sibling stale. Existing cleanup conservatively refuses such mixed-branch groups, so cleanup remains blocked unless another operation reconciles the stale thread. This is a recovery limitation in the new mechanism, not a newly introduced destructive-deletion path.
      Security review details

      Security Blast Radius

      • inferred — An actor able to change the checked-out branch can influence branch metadata for matching threads sharing that exact worktree, including archived threads. The new fan-out is bounded by the worktree path and previous branch, rather than limited to the initiating thread alone.

      Security Findings and Attack Paths

      • inferred — Adoption can make a previously stale worktree eligible for cleanup, but the inspected path does not bypass independent deletion checks. Cleanup still validates shared ownership, managed-directory containment, actual branch, activity, commit and local changes before worktree removal.

      Trust Boundaries and Controls

      • observed — The orchestrator rejects updates when recorded branch or worktree differs from the supplied expectations. These guards protect metadata concurrency, not concurrent checkout changes; cleanup separately rechecks actual branch and commit before removal.

      Resilience and Maintainability Implications

      • observed — Mixed branch metadata fails conservatively: cleanup keeps the shared worktree when any member records a different branch. This contains destructive exposure while leaving the partial-adoption recovery limitation unresolved.

      Hardening Proposals

      • proposed — Consider durable shared-worktree reconciliation that can resume unfinished sibling updates even when the initiating thread already records the current branch, while retaining the existing per-thread expected-state guards.
      Pre-merge checks: Passed 4
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main change: threads now follow branches renamed by the agent within their worktree.
      Description checkPassedThe description includes complete Problem, Change, Scope and approval, and Verification sections. It explains the bug, implementation, scope, test results, limitations, and agent details.
      Linked Issues checkPassedThe implementation satisfies the coding requirements in [#22312] and [#16559]. RunFinalizationObserver.refresh returns the checked-out non-default branch and returns null for detached HEAD or the …
      Out of Scope Changes checkPassedThe changes stay within the scope of [#22312] and [#16559]. The runtime dependency wiring and test updates support the branch-adoption behavior. The implementation does not alter storageCleanup.ts, …
      Full details: Linked Issues check

      Explanation

      The implementation satisfies the coding requirements in [#22312] and [#16559]. RunFinalizationObserver.refresh returns the checked-out non-default branch and returns null for detached HEAD or the default branch. RunFinalizationService adopts that branch only when the run cwd matches the thread worktree and no newer run is active. It dispatches thread.metadata.update for all matching threads in the worktree, including shared subagents. The updates include expectedBranch and expectedWorktreePath, and deterministic command IDs. Failures are logged without failing finalization. These updates let the existing cleanup flow use the current branch for branch validation and merged-PR lookup. The added tests cover shared worktrees, unrelated worktrees, other branches, and newer active runs.

      Full details: Out of Scope Changes check

      Explanation

      The changes stay within the scope of [#22312] and [#16559]. The runtime dependency wiring and test updates support the branch-adoption behavior. The implementation does not alter storageCleanup.ts, add settings or UI, delete branches, or change dirty-worktree cleanup. Branch-switch adoption is within scope because [#22312] documents branch switching as observed impact.

      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Comment `@coderabbitai help` to get the list of available commands.
    3. Nice, yes I need this too.

      Until this is merged, adding "If you are running in t3code, do not change the name of the worktree branch." to your AGENTS.md goes some way to making this less likely to result in "out of disk space" errors.

    4. Nice, yes I need this too.

      Until this is merged, adding "If you are running in t3code, do not change the name of the worktree branch." to your AGENTS.md goes some way to making this less likely to result in "out of disk space" errors.

      I wasn't really experiencing this personally, I don't really have agents renaming worktrees or branches all that often. I was just having Claude go through recent issues without a fix, and with clear criteria to create easy bugfixes for the maintainers to merge.

    5. Ah! Well my agents found this thread whilst I was debugging exactly this.

      I hit this in production today on a remote NixOS server over Tailscale, using Claude through T3 nightly 0.1.1-nightly.20261019.3348.

      On an VPS - the disk filled up, and new threads started failing during workspace preparation with git worktree add failed. I reduced settled-worktree retention to two days and clicked Delete now, but T3 reported 0 removed, 92 kept, 0 B recovered despite many being in the window and ready to delete.

      It turned out the cause was that 90%+ of my worktrees had changed the branch name since t3 created the worktree. This was likely due to an errant line in AGENTS.md asking them to stylize the branch names in a certain way, but the reason is not super relevant - t3 should have handled it better and not lost track (it did not used to).

      This change would fix that.

    6. closing at @StiensWout's request under Establish the problem and scope first.

      The substantial worktree cleanup repair exceeds the maintainer-triaged direction it cites. Julius directed adoption only for a worktree belonging to exactly one thread; this implementation deliberately removes that ownership restriction and updates all threads sharing the worktree, including on branch switches. No maintainer approved that broadened ownership and cleanup behavior.

      Obtain explicit maintainer agreement on adopting switches and propagating branch changes across shared worktrees, or submit a repair within the approved ownership restriction while preserving the shared-worktree problem report.

      thanks for trying to help improve t3 code. if you think this closure was a mistake, please open a fresh pr addressing the requirement above, and link back to this one.

Sign in to join this conversation.