Skip to content

fix(worktrees): stop leaving branches after recovery expires - #195484

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-orphaned-worktree-branches-20260919
Nov 9, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-orphaned-worktree-branches-20260919

Conversation

@steipete

@steipete steipete commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Managed branches retained for snapshot-loss or detached-worktree recovery survived after expiry removed their recovery refs and registry rows. Repeated retirement accumulated orphaned local branches.

User Impact

Recovery expiry now deletes eligible managed branches and retains retryable ownership when deletion fails. Ordinary openclaw worktrees gc also cleans existing orphaned openclaw/* branches in repositories recorded by the registry or pending allocations. It reports failures through the existing GC receipt and logs successful deletion counts.

The extra orphan-cleanup RPC request and CLI mode from the first revision have been removed. There are no protocol, generated-validator, UI, config, schema, or retention-period changes. GC selects repositories from its existing owner inventory; callers cannot supply arbitrary cleanup targets. Repositories with no remaining registry or pending records are not discovered by this sweep.

Safety and Recovery

Only direct managed heads without an attached Git worktree, live/retained registry reference, or pending allocation are eligible. Unknown recovery refs preserve every candidate in the repository. Native Git retains its checked-out-branch protection. Existing leases and the clean Git environment own deletion; the same closure-bound guard is revalidated synchronously after ref-queue admission and immediately before each native deletion command.

Normal removal keeps its ancestry-safe branch deletion (#148765). Missing Git metadata with surviving checkout files preserves recovery ownership. Explicit snapshot retirement requires an independent ordinary branch or remote-tracking source; a managed branch cannot provide durable custody after its row is forgotten.

Evidence

Exact head 69823b6f1ec8f2db21d71c25843e327674064dba passed CI run 42550750226, including the original failing checks-node-changed-compact-small-2 shard.

CI run 42540143974 failed two interrupted-expiry cases because their last assertions still required orphan branches after complete retirement. The repaired tests keep every interruption/custody assertion, additionally prove the branch survives the interrupted pass, and require it to disappear after settlement. The new authority test uses real GC, state-owner capture, and guards; it covers write-only, revoked, replaced-owner, and authorized requests. A delayed native-effect test checks actual allocation-lease expiry, and a persisted v2026.11.2-shaped row verifies restore and expiry without any new cleanup field.

Focused proof: 43 exact-state race cases, 25 GC cases, 21 removal-safety cases, 20 snapshot-retirement cases, five orphan/upgrade/churn cases, and four real GC authority cases. The existing zero-allocation and single-linked-worktree-inventory no-op guarantees remain asserted; GC inventory performance cases are separated into their own file to preserve the line cap, and assert the exact new repository metadata work; the GC test also discovers a branch added between passes. The two updated branch-deletion assertions fail against the pinned pre-fix lifecycle owners because the branch survives settlement; all 43 cases pass on the final fixed sources (185.94 s).

pnpm check:changed completed. Three unnecessary default type arguments in the new tests were corrected and focused core lint passed. Every other code/type/format/schema/export gate passed. The remaining failure is the same 20 changelog-attribution violations reproduced by the actual guard on exact main parent 61db4b336f89957d7916580871b288d0d8c9ba82. #194364 / 266a7aa0fe69e2b5fe6445c4ceb1e15b5360c957 introduced that signature without correcting historical release artifacts; its parent already had a different failing signature. This is an unresolved main regression for follow-up, not a passing check.

Codex P0–P2 autoreview is scoped-clean. The exact test-line allocation is +479 lines (6,589,675 total / 6,589,707 ceiling; 32 slack). Handwritten production growth is +237 lines, with zero generated changes, reduced from +295 handwritten / +14 generated. The remaining growth implements safe ownership classification, native batch deletion/reconciliation, and existing GC/retirement integration. No production system was accessed or modified.

Follow-up CI exposed two stale GC inventory expectations, now reproduced and corrected with exact metadata-command assertions and the existing checkout/lease constraints intact. The extracted inventory and maintenance files pass together (20 passed, one platform-specific skip). CI also merged in newer main containing #195488 (3908a3e4619905ab8589d220147292779f1df2f1): its shared transport renamed the temporary directory, leaving the existing clone-identity test watching a removed prefix. The test now invokes the real shared transport helper and revokes identity at its handoff after awaited staging setup, preserving every revocation and authorized-effect assertion. It no longer depends on the temporary-directory name, so it also remains compatible with peer #195505. The three refresh cases fail with the same boundary assertion on an unmodified checkout of exact main parent 61db4b336f89957d7916580871b288d0d8c9ba82; all six clone/refresh cases pass after repairing the boundary hook. This is a proven main test regression with a named introducer, fixed here. The final rebase preserves all reviewed worktree owner changes byte-for-byte.

Synthetic scale proof uses 13,531 refs, 3,145 local heads, 1,843 managed heads, 1,598 real linked worktrees and 1,228 registry records. Every one of five cleanup samples removes exactly 615 orphan heads, preserves the entire remaining ref set, and finds zero candidates on the next pass: 12,916 total refs / 1,228 managed heads. On macOS/APFS with Node 26.12.1, collector median wall time is 812 ms populated preview, 2,757 ms cleanup, 992 ms clean next pass. Median Node CPU is 652/674/646 ms; native Git CPU 330/2,170/500 ms; main V8 allocation 5.681/8.405/6.819 MiB. Five A/A previews have 814 ms median and 1,037 ms p95 (31.67% range/median); shared-host variance prevents a speedup claim. This measures the collector under real custody, excluding fixture setup, GC preflight and other GC stages. It does not measure publication fetch latency or unrelated agent databases/workspace files.

This PR remains open and must not be merged automatically.

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes scripts Repository scripts agents Agent runtime and tooling size: XL labels Nov 9, 2026
@steipete
steipete marked this pull request as ready for review November 9, 2026 00:25
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T02:26:33.260411Z 69823b6 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR deletes eligible managed branches when recovery expires and adds owner-routed orphan cleanup with a preview mode.

Example: The 30-day recovery period for openclaw/retired-task expires.

  • Before: Cleanup removes the recovery refs and registry entry but leaves the local branch.
  • After: Cleanup also deletes the unattached, otherwise unowned branch, retaining the registry entry if deletion fails.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, coherent repair with no concrete code finding; supplied evidence does not yet settle the destructive RPC authority boundary or existing-state upgrade compatibility.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Repeated worktree retirement leaves local managed branches behind after their recovery entries expire.
Reason: The maintainer-authored direction repairs a demonstrated lifecycle leak and provides a bounded cleanup path for existing orphans.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this PR open: it addresses a source-confirmed recovery-expiry leak that remains on main, and its maintainer-authored direction is approved. No concrete introduced code defect was found.

Priority: P2
Reviewed head: 928235da942854fca90996a18bc82505e6159a42

Before merge

  • Add real behavior proof - Authority-chain proof required: the supplied native Git lifecycle tests and synthetic service benchmark exercise cleanup, but the RPC proof mocks the deletion owner and guard; show authorized deletion and refusal for a write-scoped client, revoked requester, and replaced owner before Git effects. Existing persisted recovery cleanup also lacks a latest-stable upgrade run demonstrating that unexpired snapshots, branches, and checkout bytes remain intact. Redact credentials and non-public endpoints from supplied logs or terminal output. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Resolve security review attention item - Source inspection found live-owner and administrator guards, with final-effect authority validation still outstanding.
  • Resolve merge risk - PR owner: establish that the new destructive RPC refuses a write-scoped client and a revoked administrator or replaced owner before the final Git deletion.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Supply final-effect authority rejection evidence through the real RPC owner and a latest-stable upgrade run preserving unexpired recovery state.
Agent review details

How this fits together

The managed-worktree service receives CLI, administrator RPC, and maintenance requests, reconciles Git refs against registry and pending-allocation ownership, and returns cleanup outcomes.

flowchart TD
  A[CLI or administrator RPC] --> B[Managed worktree service]
  C[Recovery expiry] --> B
  B --> D[Existing lifecycle leases]
  D --> E[Registry and Git ownership checks]
  E --> F[Native Git branch deletion]
  F --> G[Cleanup result or retained retry row]
Loading

Technical review

Best possible solution:

Keep cleanup in the existing worktree lifecycle owner, preserving native Git protections, recovery custody, and visible retry outcomes.

Do we have a high-confidence way to reproduce the issue?

Current-main expiry source shows the branch leak, and the PR supplies native Git regressions for snapshot-loss and detached recovery expiry; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The fix uses existing leases, registry ownership, and native Git deletion rather than adding another state owner; the separate cleanup mode also repairs branches already orphaned by older versions.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against f9206425face.

Merge-risk options

Maintainer options:

  1. Prove rejection at the Git boundary (recommended)
    The PR owner should exercise the real RPC and lifecycle owners with native Git, showing authorized deletion and zero deletion for a write-scoped client, revoked requester, and replaced owner.

Provenance checked

  • Ordinary removal branch safety keeps the original intent (530ce23: Preserve uncaptured commits and bind ordinary branch deletion to the completed snapshot.)
  • Detached recovery expiry changes intended behavior with a stated reason (1520154: Retain exact checkout state for the existing recovery period, then expire its retained checkout.)
  • Explicit redundant snapshot retirement keeps the original intent (d7b45d7: Allow exact-ID early retirement only while independent source custody remains proven.)
  • GC receipt and local-owner routing keeps the original intent (4e8da9c: Route mutations through the selected live state owner without local fallback after refusal or uncertain outcomes.)

Testing

Proof path: in-process harness.

Security

Needs attention: Source inspection found live-owner and administrator guards, with final-effect authority validation still outstanding.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 623d8e0 adds src/agents/worktrees/snapshot-host.ts:206 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 623d8e02a5d8; files: src/agents/worktrees/snapshot-host.ts)
  • Jason (Json): Raw commit d7b45d7 adds src/agents/worktrees/snapshot-host.ts:195 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d7b45d7e76c6; files: src/agents/worktrees/snapshot-host.ts)

PR surface

Source +309, Tests +263, Docs +41, Other +246. Total +859 across 19 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 675 366 +309
Tests 7 272 9 +263
Docs 1 53 12 +41
Config 0 0 0 0
Generated 0 0 0 0
Other 3 249 3 +246
Total 19 1249 390 +859

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
New operator controls 2 CLI flags and 1 RPC mode --orphan-branches and --dry-run expose repository-scoped cleanup through worktrees.gc.orphanBranches; no configuration setting or database schema is added.

Labels

Label changes:

  • add P2: Expired recovery accumulates local branches; this is a bounded lifecycle cleanup defect without evidence of an urgent user outage.
  • add merge-risk: 🚨 compatibility: Automatic expiry now deletes branches retained by earlier versions, and compatibility with existing recovery state needs upgrade evidence.
  • add merge-risk: 🚨 security-boundary: The new administrator RPC reaches destructive Git effects, requiring final-effect authority proof beyond mocked routing checks.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: Expired recovery accumulates local branches; this is a bounded lifecycle cleanup defect without evidence of an urgent user outage.
  • merge-risk: 🚨 security-boundary: The new administrator RPC reaches destructive Git effects, requiring final-effect authority proof beyond mocked routing checks.
  • merge-risk: 🚨 compatibility: Automatic expiry now deletes branches retained by earlier versions, and compatibility with existing recovery state needs upgrade evidence.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add final-effect proof that a write-scoped client, revoked administrator, and replaced owner cannot trigger Git deletion.
  • Demonstrate cleanup after upgrading existing recovery state from v2026.11.2.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 8, 2026, 7:43 PM ET / November 9, 2026, 00:43 UTC.

@steipete
steipete force-pushed the steipete/perf-micro-orphaned-worktree-branches-20260919 branch from 928235d to 6bc19d1 Compare November 9, 2026 01:29
@openclaw-barnacle openclaw-barnacle Bot added size: L size: XL and removed app: web-ui App: web-ui cli CLI command changes size: XL size: L labels Nov 9, 2026
Delete eligible managed branches when recovery expires, retain failed cleanup for retry, and preserve checkout files awaiting recovery. Add owner-routed orphan branch cleanup with dry-run and native Git safety checks. Require independent retained source for early snapshot retirement.
Remove the direct orphan-cleanup RPC and CLI mode. Discover managed branch
orphans through GC's recorded repositories, preserving its no-op lease and
worktree-inventory costs and retaining lifecycle authority at native deletion.

Keep interrupted expiry recovery assertions and require the branch to retire
only after settlement. Prove actual GC authorization, expired allocation
custody, and restoration/expiry of a v2026.11.2-shaped persisted recovery row.

Allocate exactly 422 net test lines for the complete lifecycle, orphan safety,
authority, stable-record, work-count, and churn regressions in this PR.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 68fe503c9d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +63 to +67
const refs = await requireGit(
repoRoot,
[
"for-each-ref",
"--format=%(refname)%09%(symref)",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Verify repository identity before sweeping branch refs

If a registered nested repository loses its .git directory while its path and registry row remain, Git discovers the enclosing repository instead. Both the new preflight and this inventory accept that repository, but ownership protection still filters records by the stale nested repoRoot. Consequently, ordinary GC can delete unattached openclaw/* branches from the enclosing repository rather than the recorded source, potentially losing unmerged work (git branch -h describes -D as “delete branch (even if not merged)”). This discovery/deletion behavior is reproducible with a nested Git fixture; clearing inherited Git variables does not prevent it. Verify the discovered canonical repository/common directory against the recorded repository identity before admitting branch cleanup.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the steipete/perf-micro-orphaned-worktree-branches-20260919 branch from 68fe503 to c2cb16c Compare November 9, 2026 02:07
@steipete

steipete commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

Landing note: ClawSweeper's findings on 928235da are addressed at 69823b6. The new destructive RPC/CLI surface is removed (existing GC owns orphan cleanup; retirement deletes branches when recovery obligations end). Real (non-mocked) authority tests cover refusal for write-scoped/revoked/replaced owners before any Git effect. The final-effect lease is revalidated immediately before each branch deletion. A latest-stable record upgrade test passes, and the race shard that failed (service.exact-state-races) is green. Exact-head CI is green.

@steipete
steipete merged commit 4bb2f1a into main Nov 9, 2026
144 checks passed
@steipete
steipete deleted the steipete/perf-micro-orphaned-worktree-branches-20260919 branch November 9, 2026 02:40
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
…w#195484)

* fix(worktrees): retire orphaned branches with recovery

Delete eligible managed branches when recovery expires, retain failed cleanup for retry, and preserve checkout files awaiting recovery. Add owner-routed orphan branch cleanup with dry-run and native Git safety checks. Require independent retained source for early snapshot retirement.

* fix(worktrees): route orphan branch cleanup through existing GC

Remove the direct orphan-cleanup RPC and CLI mode. Discover managed branch
orphans through GC's recorded repositories, preserving its no-op lease and
worktree-inventory costs and retaining lifecycle authority at native deletion.

Keep interrupted expiry recovery assertions and require the branch to retire
only after settlement. Prove actual GC authorization, expired allocation
custody, and restoration/expiry of a v2026.11.2-shaped persisted recovery row.

Allocate exactly 422 net test lines for the complete lifecycle, orphan safety,
authority, stable-record, work-count, and churn regressions in this PR.

* test(worktrees): account for GC branch inventory work

* test(gateway): report project refresh boundary failures

* test(gateway): follow the shared refresh transport boundary

* test(gateway): fence refresh at the transport handoff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant