Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): storage cleanup counts a thread's subagents as part of its worktree #16474

ClosedInfo-Cado(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/16474/headopened View on GitHub

Problem

Automatic storage cleanup never removes the worktree of a thread that used a subagent (#16472).

V2 stores every subagent thread (provider-native ones, and delegate_task children) with its parent's worktreePath. cleanWorktrees (apps/server/src/storageCleanup.ts:215-222) only considered a worktree path that exactly one thread owned, and the re-check before removal required latest.length === 1. So any thread with a subagent kept its worktree forever, whatever its age, merge state or status. That rule came from V1 (#11598), where subagents were not app threads. On the reporter's machine, 17 of 23 finished worktrees in one project were shared with 1–12 subagent threads, and all 133 subagent threads with a worktree used their parent's path.

Change

storageCleanupWorktreeOwner(sharers, threadsById, now) decides who owns a checkout:

  • Exactly one non-subagent thread may use the path, and it must pass the existing idle check.
  • Every other thread on the path must be a subagent whose parent chain reaches that owner through subagent links only. The walk has a cycle guard, and a missing parent fails it.
  • Each subagent must not be busy: no active run, an idle/failed status, no pending background task or runtime request, and no queued turn. These are the same checks as before, without the branch requirement.
  • A delegated subagent can take messages later. ProviderTurnStartService recreates a missing checkout only from the thread's own branch, so a delegated subagent must have the owner's branch. Provider-native subagents cannot take messages, so their branch: null is fine.
  • Any other sharing, such as two top-level threads or a fork, still keeps the worktree.

storageCleanupThreadIdle keeps its behavior. Its activity checks moved into a private storageCleanupThreadBusy so subagents can reuse them. worktreeAfterDays now measures from the latest activity of the owner and its subagents. The re-check before removal runs the same owner rule on a fresh snapshot and compares that activity. The session, terminal, Git, ignored-file and policy checks are unchanged. The storage guide sentence about shared worktrees now covers subagents.

Related, not changed here:

  • #15146 / #15150: the idle check still rejects completed threads, so most real owners also wait on that fix. #15150 edits the status line that moved into storageCleanupThreadBusy, so expect a trivial conflict.
  • #16473: archived threads are missing from the cleanup snapshot on main, so an archived subagent would not be seen here until that lands. That is the same existing gap that already hides archived top-level sharers.

Scope and approval

Fixes #16472. The issue was filed today and is not triaged yet. I am happy to adjust the ownership rule if maintainers prefer another direction.

Verification

  • vp test run apps/server/src/storageCleanup.test.ts: 16 passed. New V2 storage cleanup worktree owner cases:
    • single-thread behavior unchanged
    • owner plus idle native, nested and delegated subagents → owner
    • busy native or delegated subagent → kept
    • delegated subagent with null or a different branch → kept
    • subagent with an unknown parent → kept
    • two top-level threads, or another thread's subagent → kept
    • inactivity uses the latest subagent activity
  • With the old single-owner rule swapped back in, counts the owner's idle subagents, including nested ones, toward the owner fails.
  • tsc --noEmit in apps/server: no errors in the changed files. The only errors are 10 in src/process/externalLauncher.test.ts, which already fail on main at 9bd1d8009a. vp lint and vp fmt on the changed files are clean.
  • A Codex review (GPT-6.1-Sol, high) found no blocking issues. I applied its non-blocking notes: doc wording, plus the missing-parent, different-branch and inactivity tests.

Not checked: a live sweep in a running app, and a subagent turning busy between the Git checks and the re-check. The sweep needs Git, settings, terminal and session services, and no test harness covers it today.

Written by Claude Opus 5.5 in T3 Code's Claude Code harness, reviewed by GPT-6.1-Sol in T3 Code's Codex harness.

🤖 Generated with Claude Code

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

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — The PR broadens automatic worktree deletion to cases shared with idle subagents and adds nontrivial lineage, branch, and activity checks in the production cleanup path. Because this is a destructive runtime behavior change rather than a small mechanical fix, human validation is warranted.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      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: 6ec31257-17ff-4292-af93-da48087af0c6
      📥 Commits

      Reviewing files that changed from the base of the PR and between 4e53e7f481a29f6e0f36e08d795a4d6d9a6ad5cf and 9b96f6bff98913c084023c6d381c43e9675ae1fd.

      📒 Files selected for processing (3)
      • apps/server/src/storageCleanup.test.ts
      • apps/server/src/storageCleanup.ts
      • docs/user/project-settings.md

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


      📝 Walkthrough

      Walkthrough

      Storage cleanup now considers a worktree eligible when one idle non-subagent owner shares it only with eligible idle subagents. Cleanup checks activity across all sharers and revalidates ownership and activity before removal.

      Changes

      Shared-worktree cleanup

      Layer / File(s)Summary
      Determine eligible worktree owners
      apps/server/src/storageCleanup.ts, apps/server/src/storageCleanup.test.ts
      Idle checks account for active runs, thread status, pending tasks and requests, and queued turn starts. Owner eligibility requires exactly one idle non-subagent owner. Other sharers must be idle subagents in that owner’s lineage; delegated subagents must match the owner’s branch, while provider-native subagents bypass that check. Tests cover these rules and related ownership cases.
      Select and recheck cleanup candidates
      apps/server/src/storageCleanup.ts, docs/user/project-settings.md
      Live candidates use the owner eligibility check. Age checks and the final recheck use activity across all sharers. Documentation clarifies the exclusions for shared worktrees and busy subagents.

      Priority: ➖ Normal

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

      Change: Bug fix · Severity of issue fixed: Medium

      Suggested reviewers: juliusmarminge

      Merge Risk: ⚪ Minimal · up to 9b96f

      The cleanup recheck cancels removal if ownership changes. No merge-blocking issue was identified; the change is ready for normal checks.

      Security Architecture Review

      Security architecture risk: 🟡 Moderate · up to 9b96f

      Automatic cleanup can now remove checkouts shared with idle subagents. Ownership and filesystem safeguards remain, but deletion and a concurrent resume are not synchronized, so a newly starting turn may lose its checkout.

      Retained concerns

      • Medium · reliability · inferred: Newly eligible shared worktrees lack an atomic cleanup/startup handoff. A delegated subagent can resume after cleanup’s last activity and session observations, observe an existing checkout, and then overlap its removal. Non-forced Git deletion protects against observed dirty state, but does not establish that a clean checkout is unused. The owner-only version predates the PR; shared worktrees were previously excluded.
      Security review details

      Security Blast Radius

      • inferred — The changed destructive unit is a local linked worktree shared by one owner and its eligible descendants. The new rule does not take a separate deletion path from a child. Effective caller privileges and protections against forged projection or policy data remain unresolved.

      Security Findings and Attack Paths

      • inferred — A concurrent delegated resume is a plausible trigger for checkout removal during startup: the existence check and subsequent session opening are not synchronized with cleanup’s lease. The supported concern is local availability and failure containment; an attacker-controlled exploit or privilege escalation has not been established.

      Trust Boundaries and Controls

      • observed — Deletion remains restricted to canonical managed roots that are not filesystem roots. Cleanup rejects symlinked worktree directories, project roots or directories containing them, and main checkouts. Git removal is non-forced and explicitly enables untracked-file visibility.
      • observed — Activity controls cover active runs, nonterminal statuses, pending background tasks, runtime requests and queued turns for every sharer. Fresh validation also checks owner identity, aggregate activity, terminals, sessions, branch, HEAD and current policy.

      Resilience and Maintainability Implications

      • observed — Cleanup preserves branch/path metadata, and later turn startup attempts to recreate a missing checkout from that branch. Recreation failures are logged rather than enforced as a mandatory startup barrier. Removal failures are logged, already-missing worktrees are treated as no-ops, and subsequent sweeps reevaluate eligibility.

      Hardening Proposals

      • proposed — Coordinate cleanup and turn startup through one workspace-keyed handoff, with live eligibility revalidation and active-session registration before releasing startup’s reservation. This would close the post-observation window rather than relying on another snapshot check.
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Out of Scope Changes check⚠️ WarningThe changes since the previous review add behavior outside issue #16472. storageCleanupThreadBusy now allows completed, interrupted, cancelled, and rolled_back threads. `storageCleanupPullRe…Revert the completed-status behavior change, the pull-request merge eligibility change, and their tests and documentation from this pull request. Keep the subagent worktree ownership and activity changes. If the additional behavior is requi…
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely describes the main change: storage cleanup now treats a thread's subagents as part of its worktree ownership.
      Description check✅ PassedThe description includes the required Problem, Change, Scope and approval, and Verification sections. It explains the behavior, implementation, issue reference, tests, known limitations, and unverifie…
      Linked Issues check✅ PassedIssue #16472 requires a thread's own idle subagents to count toward worktree cleanup, while unrelated sharing, busy subagents, missing parents, and invalid delegated branches must keep the worktree. T…
      Approvability✅ PassedPasses Approvability. The pull request changes only apps/server/src/storageCleanup.ts, its tests, and docs/user/project-settings.md. It is a focused storage-cleanup bug fix, with no default change…
      Full details: Out of Scope Changes check

      Explanation

      The changes since the previous review add behavior outside issue #16472. storageCleanupThreadBusy now allows completed, interrupted, cancelled, and rolled_back threads. storageCleanupPullRequestMerged changes squash and rebase merge cleanup. The related issue explicitly separates completed-status and squash-merge work from #16472. The tests and user guide update cover these additional changes.

      Resolution

      Revert the completed-status behavior change, the pull-request merge eligibility change, and their tests and documentation from this pull request. Keep the subagent worktree ownership and activity changes. If the additional behavior is required, move it to a separately scoped change linked to the relevant issue.

      • Fix all pre-merge checks with AI
      ✨ Finishing Touches 💡 1
      🛠️ Fix failing CI checks 💡
      • Commit to this branch
      • Create a new PR
      🧪 Generate unit tests (beta)
      • Create a new PR
      • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Comment `@coderabbitai help` to get the list of available commands.
    4. juliusmarminge added labelsmacroscope-review

    5. Note

      Grok responding on behalf of Julius.

      Closing as superseded by #19748, which just landed on main and fixes #16472. Storage cleanup now treats a thread and its complete subagent chain on one worktree path as a single owner, so those checkouts can be removed. Thanks for digging into this and for the thorough write-up.

    6. juliusmarminge closed this

Sign in to join this conversation.