Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(worktrees): manage lifecycle on orchestrator v2 #5589

ClosedStiensWout(GitHub profile, opens in a new tab)wants to merge 8 commits intot3code/codex-turn-mapping fromrefs/pull/5589/headopened View on GitHub

Important

Stacked pull request. This targets t3code/codex-turn-mapping from #2829. After #2829 merges, rebase this branch and retarget the PR to main.

Problem

Thread worktrees pile up and there is no way to see them or remove one from the app. Settings → Storage (#11598) can remove them automatically, but only by rule, and you can't see what it kept or why. The base also recreates a missing worktree before a turn, but it skips the project's setup script, and when recreation fails it starts the provider in a directory that doesn't exist.

Solution

  • Build a per-environment inventory from Git and the V2 thread projections, and show it in Settings → Source Control → Worktrees for every connected environment that supports it. Each row shows the branch, a linked thread, last use, and sync state, then either Remove or what blocks removal. A removed row disappears as soon as the server confirms.
  • Allow removal only when a worktree has no active thread, no local changes, and no unpushed commits. The server recomputes all of that right before removing, and removal is never forced. The branch and checkpoint refs stay.
  • A detached worktree is treated like a branch without an upstream. It becomes removable once its commit is on the default branch; until then it shows as unmerged.
  • Before a provider turn, recreate a missing worktree from its retained branch and run the project's setup script there again, waiting for scripts marked to finish first. If recreation or a required script fails, the run fails and shows the reason. An existing worktree is never touched. A per-thread provider session restarts when its directory was recreated, while sessions shared across threads (Codex) stay open. This replaces the base's inline repair.
  • Removals and revival share one server-side permit, and Storage cleanup's removals now take it too. Every change, Storage cleanup included, bumps an inventory revision that open settings pages subscribe to. Creating a worktree skips the permit, so parallel launches keep checking out side by side.
  • The inventory runs one git status per worktree, concurrently with the ahead-of-default count. On a 2-vCPU machine with 8 worktrees it went from 5.0 s to 0.6 s.

Automatic cleanup is not part of this PR anymore. Earlier revisions had their own reaper, a "remove with last thread" option, and a 14-day retention setting. Storage cleanup covers all of that now, off by default and per project, so I dropped them along with the change that hid the desktop "delete the worktree too?" prompt.

Other details: git worktree list --porcelain -z is parsed everywhere, projects outside a Git repository are skipped instead of failing the inventory, registrations whose directory is gone are left out, paths are canonicalized, and revival rejects symlinked ancestors that escape the managed worktree root.

Screenshots

These predate the removal of the two cleanup policy rows above the list. The list itself is unchanged.

LightDark
Worktree settings, lightWorktree settings, dark

Verification

  • Typechecks pass for server, contracts, client runtime, and web.
  • Focused tests pass: worktree inventory and removal, revival, lifecycle, Git worktree parsing, Git workflow, turn start (including the memory test), delegated completion, the runtime layer, the project settings upgrade, RPC authorization, contracts, and settings search.
  • Targeted lint and format checks pass. Lint reports warnings only.

Initial implementation and the first refresh were produced with GPT-5.6 Sol via Codex in T3 Code. The one-line settings layout, detached-HEAD handling, inventory speed-up, and review follow-ups were done by Claude Fable 5 via Claude Code in T3 Code. The rebases through 2026-09-16 were done by Claude Fable 5.1 via Claude Code in T3 Code. The rebases on 2026-09-26 and 2026-09-30, the fixes for Macroscope's review, and dropping automatic cleanup in favor of Storage cleanup were done by Claude Opus 5.5 via Claude Code in T3 Code.

🤖 Generated with Claude Code

Note

Add server-side worktree lifecycle management to orchestrator v2

  • Introduces WorktreeService, WorktreeRevivalService, WorktreeLifecycle, WorktreeReaper, and WorktreeDeletionCleanup services that handle listing, pruning, reviving, and reaping worktrees on the server
  • ProviderTurnStartService now revives the thread's worktree before starting a provider turn, serializes session starts per ProviderSessionId, and closes/reopens the provider session when the worktree was revived or its generation/path changed
  • Adds three WebSocket RPCs (vcs.listWorktrees, vcs.subscribeWorktreeInventory, vcs.pruneWorktrees) with auth scopes, and a worktreeManagement capability flag so clients gate features on server support
  • Adds client UI in Source Control settings for viewing worktree inventory, configuring retention (autoPruneAfterDays default 14, deleteOrphanedImmediately default false), and pruning; useThreadActions skips legacy client-side orphan cleanup when the capability is present
  • GitWorkflowService methods (preparePullRequestThread, createWorktree, removeWorktree) now run under a WorktreeLifecycle mutation permit and signal inventory changes
  • Risk: ProviderTurnStartService no longer emits provider-session.updated and provider-thread.updated events during the initial running transition; consumers relying on those events in that phase will need to use run.updated, run-attempt.updated, or node.updated instead
📊 Macroscope summarized 67217c7. 34 files reviewed, 8 issues evaluated, 5 issues filtered, 3 comments posted

🗂️ Filtered Issues

apps/server/src/git/GitWorkflowService.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 380: removeWorktree now tries to acquire WorktreeLifecycle's non-reentrant single-permit semaphore even when invoked by WorktreeService.removeIfStillSafe, which already holds that permit. The nested acquisition waits forever, so every automatic/manual safe cleanup path that reaches this call hangs instead of removing the worktree. [ Out of scope (triage) ]
apps/server/src/vcs/WorktreeLifecycle.ts — 0 comments posted, 1 evaluated, 1 filtered
  • line 28: changes emits the current SubscriptionRef revision as a subscriber's first item, but the inventory RPC has no matching revision/snapshot handshake. A mutation can complete after a client starts vcsListWorktrees and before it subscribes: the list response is then stale while the first stream item is the already-incremented revision. The client treats that first revision as its baseline and does not refresh, so the settings inventory remains stale until another mutation or manual refresh. [ Previously rejected ]
apps/server/src/vcs/WorktreeReaper.ts — 1 comment posted, 2 evaluated, 1 filtered
  • line 65: The automatic call to pruneWorktrees can remove a worktree after its last thread has become active. pruneWorktrees's final thread snapshot is not synchronized with thread lifecycle updates (its implementation explicitly notes links/status can change without the mutation permit), so an unsettle or new turn can land after that snapshot but before Git removal. The reaper makes this race recurring; the active thread is left pointing at a removed working directory until a later revival path repairs it. [ Previously rejected ]
apps/server/src/vcs/WorktreeService.ts — 1 comment posted, 2 evaluated, 1 filtered
  • line 647: The thread snapshot is only a point-in-time check: a thread can be linked to this path after the loop at lines 618-624 (the comment explicitly says linking does not take the mutation permit) and before removeWorktree runs. In that interleaving the new active thread is absent from references, while the clean worktree is removed successfully, leaving its newly linked thread with a missing working directory. [ Previously rejected ]
apps/web/src/components/settings/SourceControlSettings.tsx — 0 comments posted, 1 evaluated, 1 filtered
  • line 1050: The first inventory revision is always ignored, even though the inventory RPC and the revision subscription are independent requests. If a worktree mutation completes after list has already read its Git worktree list but before the subscription is established, the subscription's initial value contains the new revision and is discarded here; the older list response is then rendered and no later refresh occurs. The Worktrees settings can therefore keep showing a removed or newly-created worktree until the user manually refreshes. [ Already posted ]

Note

High Risk Touches provider turn startup, shared session close/reopen, and automatic worktree deletion; race-sensitive paths are tested but mistakes could strand runs or remove worktrees incorrectly.

Overview Adds server-owned Git worktree lifecycle for orchestration v2: inventory from git worktree list, safe pruning rules, automatic retention/orphan cleanup, and revival of missing thread worktrees before provider turns run.

Git & workflow: New listWorkspaces / shared porcelain parsing (GitWorktree.ts), with output-size limits. GitWorkflowService routes create/remove/prepare-PR-thread work through WorktreeLifecycle (serialized mutations + inventory revision stream).

Orchestration: ProviderTurnStartService calls WorktreeRevivalService.reviveForThread, then serializes startup per ProviderSessionId via KeyedSerialExecutor. If a worktree was revived or its generation/path changed, it closes and reopens the shared provider session so cwd stays correct, with careful handling when runs are superseded mid-restart.

Background jobs: WorktreeDeletionCleanup reacts to thread.deleted events; WorktreeReaper periodically prunes inactive safe worktrees per settings. Both delegate to WorktreeService for last-moment safety checks.

Product surface: Enables worktreeManagement server capability and RPC auth for vcsListWorktrees, subscribeWorktreeInventory, and vcsPruneWorktrees. Layers wired in server.ts / startup after the effect worker starts.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bdc613b9f3f9fecc9d611b94a2fa014b393a27ab. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 241aad84-47f4-4428-b412-3c651f409505

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High src/worktrees.ts:80

      VcsPruneWorktreesInput.paths uses TrimmedNonEmptyString, whose decoder calls trim(). A worktree path with legitimate leading or trailing whitespace is silently altered during decode, so the server looks up a different path and returns unknown_worktree instead of pruning the intended worktree. Filesystem paths should be validated for non-emptiness without transforming the value.

      ✅ Resolved in f8965e05959435c85dca09cf0c75bf5c8572a87f

    4. Reviewed the new worktree services against the Effect service conventions. Four convention issues found: two standalone *Shape service interfaces, a redundant singleton operation discriminator plus free-form message on the new worktree error classes, and a hidden optional service dependency in ProviderTurnStartService.

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      orchestration-v2/ProviderTurnStartService.ts:168

      Effect.serviceOption hides WorktreeRevivalService from the layer's requirements (the annotation on lines 57-67 does not list it), so worktree revival silently no-ops whenever the layer is not wired in rather than failing at composition time.

      Consider acquiring it with const worktreeRevival = yield* WorktreeRevivalService in the constructor and adding WorktreeRevivalService to the declared Layer.Layer<..., never, ...> requirements; if some deployments genuinely have no revival, model that with an explicit no-op layer instead of an optional lookup.

      No longer relevant as of f8965e05959435c85dca09cf0c75bf5c8572a87f

    5. Effect service conventions review of the worktree management services. Prior findings on WorktreeLifecycle/WorktreeRevivalService shape interfaces, the unstructured worktree error payloads, and the Effect.serviceOption acquisition of WorktreeRevivalService all look addressed. A few smaller convention issues remain.

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      vcs/WorktreeReaper.ts:37

      This module is a concrete implementation already named for the service, so the constructor should be plain make (the sibling modules added in this PR — WorktreeLifecycle, WorktreeRevivalService, WorktreeService — all export make).

      Consider export const make = (options?: WorktreeReaperOptions) => ... and updating layer/layerWith below to call it.

      No longer relevant as of f88e3a6c77d5c8b88e745ae80eab3e4e75ad7ae9

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      vcs/WorktreeDeletionCleanup.ts:40

      Same naming convention as WorktreeReaper: in a concrete module named for the service, prefer plain make over makeWorktreeDeletionCleanup, and update layer/layerWithEventStream accordingly.

      No longer relevant as of f88e3a6c77d5c8b88e745ae80eab3e4e75ad7ae9

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      vcs/WorktreeService.ts:563

      mutationError (lines 146-166) is used exactly once, here, and does nothing but construct WorktreeMutationError. Consider constructing the error at the failure boundary and deleting the helper so the stage and cause stay visible at the call site.

            Effect.mapError(
              (cause) =>
                new WorktreeMutationError({ operation: "prune", stage: "revalidate_inventory", cause }),
            ),

      No longer relevant as of f88e3a6c77d5c8b88e745ae80eab3e4e75ad7ae9

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      vcs/GitVcsDriverCore.ts:242

      parseWorktreeBranchPaths is now a same-signature pass-through to the shared parseGitWorktreeBranchPaths. Consider deleting the wrapper and calling the shared parser directly at its single call site (line ~2489) instead of keeping a shim for the moved helper.

      No longer relevant as of 815a6c6fb3a29c548209108bad939e2be5347e6e

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

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

    8. One finding: raw git stderr is copied into a new error attribute. Everything flagged in earlier runs (service-shape interfaces, make/layer naming, the single-use mutationError helper, the parseWorktreeBranchPaths shim, structural stages on the new worktree errors, and the hidden WorktreeRevivalService requirement) is resolved in this revision.

      Posted via Macroscope — Effect Service Conventions
    9. Reviewed the Effect service conventions in this update. Previously flagged items (inline service interfaces, plain make/layer names, structural error stages with derived messages, required WorktreeRevivalService acquisition in ProviderTurnStartService, shared worktree porcelain parser, bounded git worktree list error context) all look resolved. One remaining error-modeling nit below.

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      src/worktrees.ts:138

      Every WorktreeInventoryError stage wraps a real failure (load_projects, load_threads, identify_repository, inspect_repository are all Effect.mapError wraps in WorktreeService), so cause should be required rather than optional — the sibling VCS boundary errors in contracts/src/vcs.ts already declare cause: Schema.Defect(). WorktreeMutationError is different: several of its stages are pure validation, so optional is correct there.

          cause: Schema.Defect(),

      No longer relevant as of 8bab9a4c4b9c89c209fdaeef2de827f4dc8e9a86

    10. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR introduces a large, user-facing worktree lifecycle feature that changes provider startup and cleanup behavior, performs Git/filesystem mutations, and adds authenticated RPCs and default capability exposure. Its cross-cutting runtime impact and auth-package change require human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    11. [claude-fable-5] RESPONDING ON BEHALF OF WOUT:


      Agreed — every construction site wraps a real failure. Fixed in 8bab9a4c4: cause is now required Schema.Defect() and the inventoryError helper takes it as a required parameter. WorktreeMutationError left optional as you note.

    12. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    13. One finding on the new GitVcsDriver.listWorkspaces truncation error: its context fields are hardcoded/fabricated rather than derived from the actual command and output.

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      vcs/GitVcsDriver.ts:597

      argumentCount and observedBytes are hardcoded here rather than derived from the actual invocation, so the error carries context that was never observed: observedBytes: MAX + 1 makes the message claim produced 16777217 bytes, and argumentCount already had to be hand-edited from 6 to 5 in this commit when -z was dropped. Every other construction of this error derives both from real values (VcsProcess.run uses input.args.length and the process boundary's observedBytes).

      Consider hoisting the arg list (const args = ["worktree", "list", "--porcelain"] as const) and deriving argumentCount from it (plus the two -C <cwd> args that gitCommand prepends), and reporting the captured output length instead of a synthetic count — or mirroring the GitVcsDriverCore.listWorkspaces variant added in this PR, which reports a constant detail plus stdoutLength/stderrLength.

      No longer relevant as of a6e11521c8165b380249ad9e425922c64982cdc9

    14. StiensWout(GitHub profile, opens in a new tab)commented

      [claude-fable-5] RESPONDING ON BEHALF OF WOUT:


      Fixed in a6e11521c (+ test alignment in 0eec832d5): the arg list is hoisted, argumentCount derives from it plus the -C <cwd> pair gitCommand prepends, and observedBytes reports the actually observed truncated stdout length.

    15. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    16. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/134d1348e340f777442040bbf6c2db76d714c2d8/apps/web/src/hooks/useThreadActions.ts#L332

      Deleting the last thread on a pre-worktreeManagement server no longer removes its orphaned worktree, so those worktrees accumulate and cannot be cleaned up through deletion. Because deleteThread is not capability-gated, retain the removed client-side cleanup path when the target environment lacks worktreeManagement.

      No longer relevant as of cbf066363f4cc0c4cc694bcdab8ba0fd4742e022

    17. Reviewed the changed web UI (SourceControlSettings.tsx, ProjectSettingsPanel.tsx copy, settingsSearch.ts, state/worktrees.ts, hooks/useThreadActions.ts). The new Worktrees section largely reuses the house primitives (SettingsSection, SettingsRow, SettingResetButton, Select, Switch, Badge, AlertDialog), and the retention Select and empty medallion match sibling settings panels. Three concrete consistency/behavior issues in the new controls are noted inline.

      Posted via Macroscope — UI Consistency
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      settings/SourceControlSettings.tsx:731

      hover:text-destructive never reaches the icon: Button's base sets [&_svg:not([class*='text-'])]:text-[var(--control-icon-color)], and the ghost variant pins --control-icon-color to var(--muted-foreground). Since the icon is the button's only content, both text-muted-foreground and hover:text-destructive are inert and the destructive hover affordance never renders. The repo idiom is to opt out of the indirection (see ui/toast.tsx, DiffPanel.tsx).

                  className="size-6 rounded-sm p-0 [--control-icon-color:currentColor] text-muted-foreground hover:text-destructive"

      No longer relevant as of cbf066363f4cc0c4cc694bcdab8ba0fd4742e022

    18. StiensWout(GitHub profile, opens in a new tab)commented

      [gpt-5.6-sol] RESPONDING ON BEHALF OF WOUT:


      Fixed in cbf066363. Servers advertising worktreeManagement keep server-owned orphan cleanup; older servers now retain the legacy confirm, remove, and VCS refresh fallback after deleting the last linked thread.

    19. StiensWout(GitHub profile, opens in a new tab)commented

      [gpt-5.6-sol] RESPONDING ON BEHALF OF WOUT:


      Fixed in cbf066363. The remove action now binds --control-icon-color to currentColor, so its destructive hover color reaches the icon.

    20. One UI consistency finding in the new worktree management section: the inline error strip reconstructs the shared Alert primitive with divergent, non-theme-aware tokens. The previously flagged icon-color indirection, header-action size/variant, and duplicated pending strip are all resolved.

      Posted via Macroscope — UI Consistency
    21. Reviewed the new worktree management UI in SourceControlSettings.tsx against the shared primitives. The empty medallion, pending strip, Alert error strip, and SettingsRow/SettingResetButton composition now follow the house patterns; two remaining items are noted inline (one hover-state regression on the Remove action, one inert layout wrapper that diverges from every other toggle row).

      Posted via Macroscope — UI Consistency

Sign in to join this conversation.