Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): threads follow branches their agents rename #19870

Closedruck-syu(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/19870/headopened View on GitHub

Fixes #16559 (confirmed in triage).

Problem

A thread's recorded branch only changes through T3's own commands. When an agent runs git branch -m or git checkout -b in the thread's worktree, thread.branch stays on the old name. Delete merged worktrees then skips the worktree, because branchChanged sees a different checkout, and the merged-PR lookup searches for the old branch name. The sweep reports success and removes nothing. In V1, CheckpointReactor handled this (#5159), but that behavior wasn't ported to V2: RunFinalizationObserver.refresh returns early when thread.branch !== local.refName.

Fix

As the triage suggested, adopt the checked-out branch after a run completes, when the worktree belongs to exactly one thread:

  • RunFinalizationObserver.refresh now returns the branch it just read (null when detached or on the default ref).
  • RunFinalizationService.finalize dispatches thread.metadata.update with that branch when:
    • the run's cwd is the thread's worktree, and no other thread uses that worktree;
    • the thread has a recorded branch and the branch actually differs;
    • the branch isn't a temporary t3code/<hex> name, which the launch rename replaces;
    • no newer run is active.
  • The command ID is deterministic (branch-adopt:<runId>), so effect retries replay the receipt, and expectedWorktreePath drops the update if the worktree moved. A failed adoption logs a warning instead of failing checkpoint finalization.

Cleanup's equality guard is unchanged, so a worktree shared by several threads keeps its recorded branches. A branch change emits thread.metadata-updated, which ThreadPullRequestService already syncs, so the PR badge follows the new name too.

The adoption lives in RunFinalizationService rather than the observer. The observer is provided to the runtime from outside, and RunExecutionService depends on it, so giving it ThreadManagementService would create a layer cycle.

Verification

  • New cases in RunFinalizationService.test.ts cover:
    • adopting a renamed branch;
    • leaving a shared worktree alone;
    • ignoring temporary branch names;
    • ignoring a cwd that isn't the thread's worktree;
    • doing nothing when the branch is unchanged.
  • vp test run on RunFinalizationService.test.ts and RunExecutionService.test.ts: 60 passed.
  • vp test run on runtimeLayer.test.ts, ThreadStop.test.ts and ThreadFork.execution.test.ts, which use the changed layer wiring: 106 passed.
  • vp run --filter t3 typecheck passes. vp lint and vp fmt are clean on the changed files.

Not checked: an end-to-end run of the cleanup sweep against a real merged PR on GitHub. Renames made by hand between turns are adopted at the end of the next turn, not immediately, which matches V1.

Written with Claude Opus 5.5 in Claude Code (via T3 Code).

🤖 Generated with Claude Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. Approvability

      Verdict: Approved at 825aec0

      Macroscope's review found this PR approvable — This is a narrowly scoped server bug fix that reconciles agent-renamed branches with existing thread metadata, while protecting shared worktrees, temporary branches, and stale runs. The production logic is guarded and supported by targeted tests, with no schema, deployment, default, or static-analysis configuration changes.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. 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: d238632b-778d-468e-9d2d-7cce66d370f2
      📥 Commits

      Reviewing files that changed from the base of the PR and between 00cdceb196edf661652dee6efe983c0d40662971 and 825aec0203f73ba91d522011f2495157b62d6532.

      📒 Files selected for processing: 5
      • apps/server/src/orchestration-v2/RunExecutionService.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; 9 remain after this review.

      📝 Walkthrough

      Run finalization now receives a checked-out branch from the workspace refresh. When branch adoption checks pass, it dispatches a thread metadata update. Runtime and replay test layers provide thread management to the finalization service.

      Changes: Branch adoption

      Layer / File(s)Summary
      Branch refresh and metadata adoption
      apps/server/src/orchestration-v2/RunFinalizationService.ts, apps/server/src/orchestration-v2/RunFinalizationService.test.ts, apps/server/src/orchestration-v2/RunExecutionService.test.ts, apps/server/src/orchestration-v2/runtimeLayer.ts, apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
      The refresh returns a branch name or null. Finalization dispatches a metadata update when the thread, run, branch, and worktree ownership checks pass. Tests cover adoption conditions, and runtime layers provide thread management to finalization.

      Priority: ➖ Normal

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

      Change: Bug fix · Severity of issue fixed: Medium

      Sequence Diagram(s)

      sequenceDiagram
        participant Observer as RunFinalizationObserver
        participant Finalization as RunFinalizationService
        participant ThreadManagement as ThreadManagementService
        Finalization->>Observer: Refresh workspace and request branch
        Observer-->>Finalization: Return branch name or null
        Finalization->>Finalization: Check thread, run, branch, and worktree ownership
        Finalization->>ThreadManagement: Dispatch metadata update when checks pass

      Suggested reviewers: juliusmarminge

      Merge Risk: ⚪ Minimal · up to 825ae

      Renamed branches can be adopted after a run, and cleanup checks their PR status when needed. The change is mergeable after normal checks.

      Security architecture risk: 🔵 Low · up to 825ae

      Branch reconciliation is narrowly scoped, but its run and ownership checks are not atomic with the metadata update. Concurrent activity can leave stale branch state. Existing cleanup checks limit the consequences; no introduced privilege escalation or unsafe deletion was established.

      Retained concerns

      • Low · reliability · inferred: The new automatic writer checks active-run identity and worktree ownership before acquiring the metadata dispatch lock. If newer run or branch activity intervenes while the worktree path remains unchanged, an older finalization can overwrite current branch metadata. This introduces a bounded state-authority race absent from the previous refresh-only flow; cleanup’s independent rechecks limit deletion consequences.
      Security review details

      Security Blast Radius

      • inferred — A process able to rename or switch the run’s checkout can now influence that thread’s persisted branch and derived pull-request and cleanup decisions. The branch value does not select the target thread ID or worktree path; those come from finalization context. The intended scope is one matching, singly owned worktree, subject to the snapshot race identified above.

      Trust Boundaries and Controls

      • observed — Cleanup does not treat adopted metadata alone as deletion authorization. It checks managed-root containment, symlinks, linked-worktree identity, shared ownership, idle state and local changes. Merged-PR eligibility requires integration or matching branch, default base and exact head commit; ownership, activity, branch and commit are checked again before removal.

      Resilience and Maintainability Implications

      • inferred — Stale or failed adoption primarily leaves inconsistent branch metadata and can keep cleanup from proceeding. A checkout mismatch makes cleanup retain the worktree, and newer activity or shared ownership independently blocks removal. These controls contain the observed state-consistency risk rather than repairing it.

      Hardening Proposals

      • proposed — Make adoption’s expected run and previous branch explicit commit-time preconditions, and coordinate sole-owner validation with worktree ownership changes. This would prevent an older finalization from overwriting newer authority decisions while retaining best-effort checkpoint finalization.
      Pre-merge checks: Passed 4
      Passed Passed checks: 4 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the main change: updating thread branches when agents rename them.
      Description checkPassedThe description includes the problem, fix, scope reference through issue #16559, detailed verification results, limitations, and agent attribution. It matches the required template and provides suffic…
      Linked Issues checkPassedIssue #16559 requires cleanup to follow a branch renamed in a thread worktree. RunFinalizationObserver.refresh returns the checked-out branch. RunFinalizationService adopts that branch when the th…
      Out of Scope Changes checkPassedThe changed observer contract, finalization logic, dependency wiring, test updates, and replay-harness wiring all support branch adoption for issue #16559. The changes do not show an unrelated product…
      ✨ 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.

Sign in to join this conversation.