fix(server): clean squash-merged worktrees using exact PR heads #14849
main fromrefs/pull/14849/head·opened View on GitHubProblem#
Squash merging replaces commit ancestry, so Delete merged worktrees retains an otherwise eligible checkout before it can read the merged PR. Fixes #14742.
Change#
Allow the existing fresh branch-PR lookup to prove a squash/rebase merge when the PR is merged, its head branch matches, its base is the project's default branch, and its head SHA equals the checkout's current HEAD. Carry the optional SHA through GitHub's GraphQL batch, CLI fallback and provider mapping into GitManager.
Keep default-branch ancestry as the existing proof. The unchanged-worktree rule, primary remote/default-branch selection, safety gates, final HEAD/policy checks, retained branches and thread history are unchanged. No target resolver or setting is introduced. Other source-control providers without head SHA evidence retain the existing behavior.
Scope and approval#
Follows #14742's focused triage and replaces only the squash-repair portion of #14651, closed for bundling target selection. The closure itself is not approval to merge.
Related, left open: #14758 (release/stack target ancestry) and #14843 (secondary-remote ancestry for fork checkouts). This PR does not implement either target-selection proposal.
Verification#
Reproduction script, observations and logs.
Created new .t3 SQLite state through orchestration commands, local bare remotes, and actual squash commits/worktrees. Ran the production cleanup worker and awaited its drain, with real Git, GitManager, GitHub CLI/adapter and persisted snapshot queries. Host process responses and idle resources were manufactured; no live T3 state was read or copied. The host fixture returns only requested --json fields, covering the no-saved-PR discovery gap identified in #14651's review.
| Fixture | Baseline cleanup (6c8fed35dd) | Fixed cleanup |
|---|---|---|
Exact PR head, merged into main | Retained; no PR lookup | Removed; fresh PR lookup |
| Later local commit | Retained | Retained |
| Release or stack-parent base | Retained | Retained |
| Missing SHA or failed lookup | Retained | Retained |
| Different head branch or closed-unmerged PR | Retained | Retained |
Unchanged-only rule, squash into main | Retained; no PR lookup | Retained; no PR lookup |
All nine fixtures fail default-branch ancestry. Branches and persisted threads survive in every case. Only merged cleanup is enabled except for the unchanged-only control; inactivity and deleted-thread cleanup are disabled.
pnpm exec vp test run apps/server/src/orchestration/ThreadSettlementReactor.test.ts apps/server/src/git/GitManager.test.ts apps/server/src/sourceControl/GitHubCli.test.ts apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts— 221 passed. Includes stale merged snapshots, a HEAD change during cleanup, existing safety gates, fresh cache reads, and SHA propagation through GraphQL and CLI fallback.pnpm --filter t3 typecheckand targetedvp lint— passed.- Shared server behavior covers web, desktop, mobile and remote environments; no UI or agent-provider adapter changes.
Linux, Git 2.43.0, Node 24.3.0 (below the declared engine), Vite+ 1.0.0. No live GitHub squash merge or browser/device run was performed; hosted metadata is a fixture. CI checks the supported toolchain.
GPT-6-Astra through the Codex harness in T3 Code.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
ebc6ba7Macroscope's review found this PR approvable — This is a focused fix to the existing opt-in merged-worktree cleanup path, using exact PR head, branch, and default-base evidence while preserving existing safety checks and fallback behavior. The remaining changes only propagate optional metadata, update documentation, or expand targeted tests.
Notes:
- Diff unchanged. Approvability was decided on eligibility alone.
juliusmarminge added labelsmacroscope-review
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
🧰 Additional context used
📚 Code guidelines (2)
docs/internals/effect-services.md — configured AGENTS.md — auto-discoveredNo actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository: pingdotgg/t3code/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
9e934382-5f42-4809-9136-dd52cb0f8455📥 Commits
Reviewing files that changed from the base of the PR and between 6c8fed35dded9ff71c5b46807125457acbb76be6 and ebc6ba7e0e142cbb656d738b2afeab1a295ec972.
📒 Files selected for processing (11)
apps/server/src/git/GitManager.test.tsapps/server/src/git/GitManager.tsapps/server/src/orchestration/ThreadSettlementReactor.test.tsapps/server/src/sourceControl/GitHubCli.test.tsapps/server/src/sourceControl/GitHubCli.tsapps/server/src/sourceControl/GitHubSourceControlProvider.test.tsapps/server/src/sourceControl/GitHubSourceControlProvider.tsapps/server/src/sourceControl/gitHubPullRequests.tsapps/server/src/storageCleanup.tsdocs/user/project-settings.mdpackages/contracts/src/sourceControl.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
Walkthrough#
The change carries pull-request head SHAs through GitHub and source-control results. Worktree cleanup uses a confirmed merged pull request’s head branch, default base branch, and head SHA to identify an exact-head merge.
Changes#
Merged worktree cleanup
Layer / File(s) Summary Pull-request head SHA propagation
packages/contracts/src/sourceControl.ts,apps/server/src/sourceControl/gitHubPullRequests.ts,apps/server/src/sourceControl/GitHubCli.ts,apps/server/src/sourceControl/GitHubSourceControlProvider.ts,apps/server/src/git/GitManager.ts, corresponding*.test.tsfilesPull-request head SHAs are requested from GitHub, normalized, and passed through source-control and branch-pull-request results. Tests check SHA extraction and propagation. Exact-head merged cleanup
apps/server/src/storageCleanup.ts,apps/server/src/orchestration/ThreadSettlementReactor.test.ts,docs/user/project-settings.mdCleanup can qualify a merged PR when its head branch and SHA match the worktree and its base is the project default branch. Tests cover matching and non-matching PR states and lookup cases. The documentation describes the updated merge cleanup behavior. Priority: ⬇️ Low
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix · Severity of issue fixed: Low
Suggested reviewers:
juliusmarmingeMerge Risk: ⚪ Minimal · up to
ebc6bThis change lets clean worktrees from squash-merged pull requests be cleaned up when the checkout's exact head matches the merged pull request. Existing safeguards are unchanged, and no concrete risk was found. It has not been run against live GitHub.
Security Architecture Review#
Security architecture risk: 🔵 Low · up to
ebc6bExact commit matching and repeated safety checks substantially limit accidental removal. However, matching a branch name and commit does not establish that the merge occurred in the project's selected repository. This matters when pull-request lookup selects another repository. Local branches and thread history are retained, limiting the impact.
Retained concerns
- Medium · security · inferred: The new non-ancestry proof does not bind the merged PR's destination repository to the repository selected for project-default-branch cleanup. Hosting lookup can select another repository, while cleanup checks only merged state, branch names, and exact head SHA and ignores the returned repositoryKey. If that repository contains a matching merged PR, an otherwise unintegrated checkout can become eligible for removal. Repository-selection behavior predates this PR, but allowing it to authorize non-ancestor cleanup is new. Existing cleanliness and ownership checks and retained local branches limit the consequence.
Security review details
Security Blast Radius
- inferred — The identified concern affects otherwise eligible managed worktrees whose configured hosting lookup selects a different destination repository. It does not establish arbitrary filesystem deletion, credential disclosure, or loss of retained Git branches.
Security Findings and Attack Paths
- inferred — A conditional path exists when hosting lookup resolves an alternate repository containing a merged PR with the expected source branch, source identity, SHA, and base branch name. That evidence can now authorize removal without integration into the project's fetched default branch. An adversarial case requires influence over the selected destination's merge outcome or local repository-selection configuration; ordinary control of PR text alone is insufficient. Runtime exploitation was not demonstrated.
Trust Boundaries and Controls
- observed — PR candidates undergo branch and available head-repository identity filtering. Refreshed lookup validates cached remote identities and rejects unverifiable changes. These controls protect source identity and cache consistency, but do not compare the PR destination repository with cleanup's selected default-branch repository.
Resilience and Maintainability Implications
- observed — After host calls, cleanup rereads ownership and activity, checks terminal/session use where applicable, and rejects changed HEAD or policy. Missing SHA or failed lookup cannot qualify through the new proof. These checks preserve failure containment but cannot repair a destination-repository mismatch.
Hardening Proposals
- proposed — Bind exact-head merge evidence to the repository already selected for project-default-branch cleanup, using verified destination identity, and retain the checkout when that identity is missing or differs.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 10 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold. ✅ Passed checks (4 passed)
Check name Status Explanation Title check ✅ Passed The title is concise, specific, and accurately describes the primary change: cleaning squash-merged worktrees using exact pull-request heads. Description check ✅ Passed The description covers the problem, implementation, scope and approval, verification results, limitations, and related follow-up issues. It provides focused test commands and observed outcomes. Linked Issues check ✅ Passed The PR meets the coding requirements in [ #14742].storageCleanup.tskeeps default-branch ancestry as the existing proof and adds a fallback only when a refreshed pull-request lookup reportsmerged…Out of Scope Changes check ✅ Passed The changes stay within [ #14742]. GitHub, provider, contract, and GitManager changes carry the head SHA required by the cleanup decision. Storage-cleanup tests and documentation support the same behav…Full details: Docstring Coverage
Explanation
Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 10 files. (1 skipped: 1 unsupported.)
- Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create a new PR
- Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Autopilot is currently an internal CodeRabbit preview.
Comment `@coderabbitai help` to get the list of available commands.Note
GPT-6-Astra responding on behalf of @tris203
Reviewed CodeRabbit's retained repository-identity advisory. This is the same tradeoff discussed in #14651: requiring the PR destination to equal the primary remote would exclude upstream PR evidence in fork workflows. The subsequent #14742 triage specifies merged state, matching head branch, default base name, and exact current head SHA as the focused proof. This PR implements those checks and preserves existing branch-lookup identity validation and final checkout protections. Branches and thread history remain intact.
The advisory correctly distinguishes the PR destination from the primary remote; this is an explicit scope tradeoff, not a claim that they are always identical. Broader ancestry/remote selection remains tracked separately in #14843. No target resolver or repository-policy change is being added here.
The docstring percentage warning concerns existing mapping functions touched to carry one optional field. Their purpose is evident locally; the non-obvious cleanup proof is explained beside the eligibility check. Keeping those functions and the coverage configuration unchanged follows the repository's guidance against metric-only changes.
Verification remains green at ebc6ba7: 221 focused tests, the attached manufactured-state reproduction, server typecheck, targeted lint, and CI. Macroscope approved; CodeRabbit reported no actionable comments.
Closing as a duplicate of #14847, which fixes the same issue (#14742). This PR's extra test cases (closed-unmerged pull request, stale merged snapshot, stack-parent base,
HEADmoving during cleanup, head SHA through the GraphQL read and its fallback) are now on that branch, and its integrated evidence is linked from that description.Two things from here were left out on purpose:
headRefOidon thegh pr viewand open-PR list reads, which the cleanup lookup does not use, and swallowing a failed lookup tonull, since the sweep already catches the failure, keeps the worktree, and logs why.tris203(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