Skip to content

perf(worktrees): run GC in background and enforce capacity - #164758

Merged
steipete merged 5 commits into
mainfrom
steipete/perf-micro-worktree-gc-background-and-cap-20260919
Oct 4, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/perf-micro-worktree-gc-background-and-cap-20260919

Conversation

@steipete

@steipete steipete commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Large managed-worktree fleets repeatedly rescan protected checkouts, block GC requests for an entire sweep, and exceed the old 100-worktree cleanup target indefinitely.

User Impact

One global worktreeMaxCount now applies across agents and repositories, defaulting to 4096. Eviction prefers merged branches, then detected squashes, then idle worktrees by age including unsaved data. Snapshots are best effort: snapshot failure does not prevent cap eviction. Live run leases refuse eviction and creation with a message naming the cap, live owners, and setting. Measured disk-space admission remains an independent guard.

worktrees.gc now returns an immediate background receipt. RPC clients must poll jobId and inspect state; openclaw worktrees gc --job <id> and the bundled Control UI use the same owner. Only the latest receipt is retained; restarting the Gateway discards it. --retry-deferred forces fresh inspection of remembered deferrals. Offline CLI cleanup still runs to completion under exclusive local ownership.

Recommended operator setting for the larger fleet: top-level worktreeMaxCount: 4096, also the default. No live deployment or configuration was changed. Lowering this setting can purge existing idle checkouts and unsaved data.

Why This Change Was Made

Creation, restoration, and background eviction share the existing allocation lease and atomic removal claims. The maintenance owner schedules eight-tree/five-second work batches, yields between them, exposes progress, and drains on shutdown. Filesystem inspection, hashing, and Git-result processing run in the Git worker; provisioned snapshot persistence runs in the SQLite worker. The host retains Git process launches, cancellation, and live authority, which remain part of measured main-thread activity. Registry revisions and checkout fingerprints invalidate remembered deferrals without rescanning unchanged trees after unrelated ref repacks.

The old operator-visible limit was WORKTREE_CLEANUP_TARGET = 100, returned by resolveWorktreeCleanupLimits() in service.ts. This removes that soft target, the unused aggregate byte limit, blocking RPC/health paths, and duplicate host-thread snapshot implementation. Native repository/HEAD inventory is prepared once per repository instead of spawning Git for every checkout.

Destructive eviction preserves source repositories and storage used by other managed checkouts, including borrowed objects from git clone --shared. Incoming creation/restoration holds source custody. A fresh, bounded worker census covers checkout files, native worktree administration directories, private/common metadata, and recursive object alternates; it repeats after awaited admission. It preserves both canonical storage and the lookup symlinks Git needs to reach it. Incomplete source object inspection refuses purge. Physical deletion targets are revalidated before purge.

The requested non-test/docs stat is +2856 / -666, net +2190, across 59 files. The requested path filter includes the Android Kotlin test correction (+14 net), six wrapper source-inventory entries, and one obsolete test-baseline deletion; runtime production growth remains +2171 lines. Growth is required by the newly requested hard-cap eviction policy, live/source custody during destructive operations, background receipt lifecycle, and worker snapshot persistence. Superseded synchronous implementations are removed.

Evidence

Current head is 5f4657b266acdf01111fab8db52d3d29e10ce710, tree d1dd5c047368d1c9082984a00e8c848f855b52c3. The worktree commits were rebased onto 5f5125bcb6a975351b6e2369e56397265582cece to resolve an upstream test conflict; git range-diff confirmed the first three commits stayed patch-identical. Main independently supplied the private-receipt settlement fix in #164490, so the duplicate was dropped while retaining the listener correction. The latest commit changes only Android test-fixture synchronization after the preceding head's independent CI failure. No upstream fix was copied into this lane. Final scope is 95 files; runtime production scope and LOC are unchanged. All changes have independent review and remote proof on their recorded revisions; all Testbox leases are stopped. Exact-head CI run 37188985875 passed: 121 successful jobs, 12 skipped, no failures, including Android Play and the aggregate gate. Merged as 3b16db73c0b5209aad2ee7c3fb5ddfb12fb208f9 after this successful run. Worktree/startup integration passed 118 cases on preceding head 16722076 with identical production bytes; the Android fixed replay and staged gate verified the current tree. CI run 37187319720 on 16722076 completed with 121 successful jobs, 12 skipped, one Android Play failure, and its aggregate-gate failure. The preceding CI run 37181792034 completed with 119 successful jobs and two failing Gateway tests (plus the aggregate gate): test-helpers.listener.test.ts hit EADDRINUSE, and the abandoned-timeout case in server.private-completion.test.ts read an absent completion row. The reviewed test-only corrections addressed those ordering assumptions without changing production code or weakening assertions; only the listener correction remains in this PR after the rebase.

The Android failure in that run was ChatComposerLayoutTest.branchOpeningRejectsQueuedRefreshAcrossAuthoritativeAba at showBranchChat:3009: a default 1000 ms readiness wait expired before request interception or the queued-refresh/ABA action. The tested merge was 441c4589aaa482fa7187e22b689eea5a767deef6 (main c071d238 plus lane 16722076). Its Android test/controller/ViewModel/runtime/screenshot-fixture inputs are unchanged by the worktree lane, and the fixture handles requests in-process. The original artifact reports 112/113 passing class cases but does not expose which readiness condition stayed false. This is attributed to the independent Android fixture; the exact original timing cause remains unknown.

The test-only follow-up makes the same three readiness conditions participate in Compose's existing IdlingResource mechanism, matching the class's branch-switch helpers. It preserves every branch/ABA assertion, unregisters in finally, and adds controller/ViewModel readiness diagnostics. It adds no timeout, retry, production seam, or production behavior. Independent review completed with no P0/P1 findings.

Blacksmith Testbox tbx_01m42zqy5jawv4d7apajvc4ryv (blacksmith-testbox, openclaw-check) executed the complete 113-case class once on unchanged source and once with only the reviewed Kotlin helper edit. Both passed: baseline class 27.403 s / command 57.144 s; fixed class 26.839 s / command 59.335 s. Baseline passing is a non-reproduction, not causal proof. The pinned toolchain matches CI's Temurin 21.0.12.1+1, Android platform 37.0, and build tools 36.0.0. The native policy selected four forks on Testbox versus two in CI, with one active processor per test JVM; this single class stays in one worker. No worker override was introduced. A first secondary replay omitted CI_RUNNER_BACKEND=blacksmith; it passed but is excluded from this comparison. A later source-identity preflight stopped before tests because Git abbreviated blob IDs differently (12 local / 8 remote); complete file/blob hashes proved identical source before continuing with canonical checks. Both authoritative XML case orders exactly match the original CI class. The native staged gate, node scripts/check-changed.mjs --staged, passed in 33.996 s total, including Android app/benchmark/Wear/shared Kotlin lint (40 Gradle tasks, 21 s). Final staged tree d1dd5c047368d1c9082984a00e8c848f855b52c3 and complete fixture blob were verified unchanged.

Fresh rebased-head proof on Blacksmith Testbox tbx_01m42yp0q1w3gqsvf88vbtmbk3 (blacksmith-testbox, openclaw-check, Node 24.19.0 / pnpm 12.5.1) passed 118 tests across 12 files, 239.99 s runner / 244.355 s Crabbox total. This covers current shared-state schema admission, allocation/capacity/eviction, cached deferrals, maintenance shutdown, and real Gateway agent-database startup/lifetime. All 108 pinned source hashes matched before and after; the complete tracked tree stayed clean. The lease is stopped. The unchanged protected-tree pass still performs zero repeat Git scans; 16 live leases cause zero writes or checkout inspections. No new static gate was duplicated for the patch-identical rebase; current-head CI owns that check.

The first complete CI run, 37178977398, tested head 976f8e0b merged with main 217efe0a. It exposed missing wrapper source-inventory entries, stale CLI GC fixtures, and an inline typed SQL expression rejected by the architecture guard. The correction uses the existing sqliteStringSet boundary, includes all six new transitive modules in the wrapper inventory, and proves queued receipts, completion polling, partial failures, and lost-reply custody through the CLI fixture. Its independent review is clean, with no findings.

Correction proof on Blacksmith Testbox tbx_01m42nj0anvkgrewd6ytdgs7ge (blacksmith-testbox, openclaw-check) passed 109 tests across six files, with one existing skip, in 206.83 s runner / 216.053 s total. All 16 native provisioning cases and 20 other wrapper closure/bootstrap cases passed, confirming that the missing inventory caused the private-store preload failures. Both formerly failing CLI files and the removal-claim registry regression passed. pnpm lint:kysely passed in 32.781 s total. All 93 candidate file hashes match tree 5f221061. The native changed-file gate against 976f8e0b passed all 35 checks in 1387.367 s (23m7s), including all 27 test type graphs, core types, lint, mock exports, and storage guards. The one-time frozen-lockfile install also passed (11.7 s pnpm / 15.947 s total).

The historical two-test follow-up awaited the real private input recorder's settlement before reading its receipt and removed the listener fixture's released-port override in favor of the existing retained reservation owner. All producer, terminal-write, listener, and claim assertions remain. Independent review of tree 2e7ba9df is clean. On Blacksmith Testbox tbx_01m42x6gpx4x1wqk204pbjtzgq (blacksmith-testbox, openclaw-check, Node 24.19.0, pnpm 12.5.1), the fixed 147 cases passed once in their original 8-file and 11-file CI orders. The unchanged baseline also passed once: these are non-reproductions, not causal proof that the original failures were repaired. The source analysis, retained safety assertions, and original CI failures remain the evidence for the corrections. The precise listener contention phase and CI's whole-host pressure were not reproduced.

Runtime proof used exact CI merge 6bb581b637fb35d039a35461e7033f2175fc8370 (main d60b0950 plus prior lane head 5e72dd92), first unchanged and then with only the two reviewed test edits. This preserves CI's scheduler context, which differs from the branch base. It is distinct from the exact-branch static proof on tree 2e7ba9df. All 120 source hashes, exact changed-file membership, and actual file execution orders were verified. Counts below overlap and are not 294 distinct tests; timing variation is not a performance comparison.

Ordered runtime replay Cases Vitest wall Crabbox total
Original listener shard 102 passed; non-reproduction 39.14 s 45.142 s
Original private-completion shard 45 passed; non-reproduction 99.69 s 105.926 s
Fixed listener shard, same order 102 passed 32.36 s 48.998 s
Fixed private-completion shard, same order 45 passed 83.03 s 88.750 s

An initial replay-harness attempt ran zero tests because Vitest 5 rejected a CLI sequencer path as a constructor. It was corrected using the repository's demonstrated temporary config-wrapper pattern, overriding only sequencing with the actual class. The same wrappers, one worker, and unchanged suite settings were used for all four replays. The first lease disappeared after roughly 71 minutes queued without running a command; its stop was reconciled before allocating the replacement. The replacement's frozen install passed once (7 s pnpm / 11.036 s total), final source verification passed, and its stop completed successfully.

After Testbox had queued for more than 20 minutes, the authorized Linux rig ran node scripts/check-changed.mjs --staged on exact branch candidate 2e7ba9df (base 5e72dd92 plus only the two reviewed test edits), with Node 26.8.1, pnpm 12.5.1, nice -n 10, ionice -c3, and task-local TMPDIR. The native gate exited 0; its log spans 06:41–06:52 UTC, and the complete source tree was verified unchanged afterward. The supplied helper retains the last 80 output lines, so only its reported timings are listed here:

Rig gate evidence Result
Native staged gate exit=0
Selected Gateway root test types passed, 97.3 s
Selected Gateway server test types passed, 77.7 s
Production / full-tree / script unused exports zero entries in each scan
Changed-file lint zero warnings and errors, 21.1 s
Formatting, dependency pins, plugin boundaries, wrapper shadowing, package patches, coercion declarations, deprecated API guard passed
Final tracked source exact tree 2e7ba9df, no unstaged diff

Three earlier CI failures were inherited and present in fetched main 39b4bdbb: session-progress-refresh.e2e.test.ts expected a retired animation name; mcp-app-bridge.cursor.test.ts passed a removed boolean argument; and the native declaration fixture imported format-duration-internal.js while copying only the .ts source. The two UI mismatches were introduced by 73149b26822a; the formatter import was introduced by 4fa690195797. Those failures did not recur in the later CI merge with main d60b0950. The implicated source and test blobs are unchanged by this PR. No upstream fix was copied into the lane, and no baseline, assertion, or gate was relaxed.

Independent Codex review completed with no actionable P0/P1 findings across both passes on tree 35629b2e. The branch was then rebased without conflicts onto 8a0b0c458bbdac520a8f99b4735144722f698be7 to include current allocation-failure recovery. git range-diff reports the patch unchanged (=), with the same 89-file scope. That reviewed head was 976f8e0bff8bee191550c632de3bd83cdbe61177 (tree 099d05cb). Its test-only follow-up also received a clean independent review; production behavior and assertions were unchanged. The five-file CI correction above received another clean independent review on tree 5f221061.

Post-rebase proof on fresh Blacksmith Testbox tbx_01m42hxy14n6e3ke50ry0ar0qj passed 103 distinct tests: 89 capacity/acceleration/eviction/restoration cases, including all new-main allocation-recovery cases (142.41 s runner / 146.378 s total), plus 14 isolated-policy/telemetry cases (12.35 s runner). The complete native changed-file gate passed all 39 checks in 1450.457 s (24m10s): all 27 test type graphs, production/UI types, dead exports, lint, docs, configuration metadata, and ratchets. The new mock policy is satisfied by documented fixture isolation; its generated baseline shrank 10858 → 10857 with no additions. All listed Testbox leases used provider blacksmith-testbox, profile openclaw-check, and native source sync. All 90 final source hashes were verified.

The matched Linux rig uses 800 real linked worktrees on ext4: 168 nested repositories, 232 moved branches, 364 live leases, and 36 manual checkouts. Base: 2df2d8455db0bec1488ccfe8790b093f90362a4b. These are synthetic source-owner/RPC-handler measurements, not a live deployment or full dist-Gateway stress test. Main-thread active time is event-loop active wall time, not CPU time. The rig samples RSS every 10 ms and polls/clones background receipts every 20 ms; the cold pass includes first cleanup-worker/source-loader startup. Observer and shared-host scheduling costs were not separated.

Metric Parent Candidate
Health call / enqueue wall 29,256.362 ms 0.572 ms
Cold completed sweep 29,256.362 ms 138,106.015 ms
Cold main-thread active time 13,472.622 ms 21,238.560 ms
Cold maximum / p99 event-loop delay 52.134 / 17.236 ms 58.851 / 3.285 ms
GC handler wall time 17,497.101 ms 4.650 ms
GC handler main-thread active time 13,894.777 ms 4.677 ms
Repeated sweep main-thread active time 13,894.777 ms 2,060.200 ms
Repeated sweep maximum event-loop delay 27.902 ms 31.048 ms
Cold peak RSS 1,113,686,016 B 1,194,450,944 B

The zero-purge measurement above uses measured pre-rebase tree 35629b2e. Repeated background completion takes 102,312.143 ms. About 100 seconds of intentional batch pauses dominate completion. Repeated main-thread activity falls 85.2%; cold total activity and peak RSS increase, and maximum delay does not improve. Delay percentiles include the pauses. These are single-run/shared-host measurements.

Measured pre-rebase tree 35629b2e uses the real create/removal owners. Both caps hold and dirty snapshots survive:

Create at cap 800 trees 4096 trees
Wall time 3.287 s 7.870 s
Main-thread active time 1.431 s 1.846 s
Maximum event-loop delay 32.67 ms 54.95 ms
Cleanup Git launches 5 4
Selected purge wall time 1.505 s 4.211 s

Source-loader startup was warmed on another repository. The cap fixtures share a source commit, and the 4096 cell reused an immutable classification pair from the 800 cell; a cold fleet of distinct unmerged branches was not measured. Before the inventory cutover this implementation took 23.053/114.663 s with 903/4610 launches. This compares two implementations of the new cap, which parent main did not enforce. Timings are single-run/shared-host evidence. No dependency-inspection budget refusal occurred.

Pre-rebase owner proof on tree 35629b2e ran on Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), lease tbx_01m42ebr9h3etgwyyb64qq96hg: 94/94 tests across seven files, 92.56 s runner / 98.026 s total. This includes all 27 native reader cases plus eviction, source preservation/restoration, cap, and GC cache behavior. The fixture still uses five cleanup Git launches for a 17-tree admission, zero Git rescans on an unchanged cleanup, and zero writes/checkout inspections for 16 live leases.

The four final source-completeness/alias regressions passed (23.02 s runner / 35.850 s total). Isolated prior-code substitutions failed at the intended assertions: both oversized-source purges wrongly succeeded (18.20 s / 22.173 s), and both alias cases lost required lookup paths (23.35 s / 28.146 s). Earlier controls independently reproduced native-administration deletion, moved source/deletion targets, shared-clone donor destruction, per-tree Git launch overhead, expired inspection budgets, and unnecessary rescans after unrelated ref packing. Candidate files and all 89 hashes were restored after negative controls.

Unchanged proof is reused with its original revision: the preceding 11-file retirement/exact-state/lifecycle suite passed 158/158 (173.15 s runner); the initial implementation passed 337 distinct cases across 21 files on lease tbx_01m425svvf5cw8hrngv0803fsx. Later Git/parser and cap/restore/lifecycle runs passed 99 and 105 cases on tbx_01m429n7jhb31xg81wn18k7rcq. Counts overlap and are not additive. Runner seconds include compilation; independent per-file process startup and future GitHub CI seconds were not separately measured.

The pre-correction complete changed gate ran on Testbox with its exact base and candidate source: core types 44.21 s, all 27 test type graphs 1009.22 s, UI types 35.71 s, dead exports 64.66 s, core lint 32.80 s, and script lint 22.92 s. All 39 checks passed; the later correction passed its 35 selected checks as recorded above. Earlier staged gates ran on the authorized Linux rig after prolonged admission queues. No tests, types, or builds ran on the constrained Mac.

Protocol checks passed against the measurement base, with the protocol inputs unchanged since that proof. pnpm build passed on Testbox in 491.515 s before later internal worker fixes, including all 151 SDK subpaths and UI; it is not an exact-final-tree build.

Earlier inherited UI-budget failure on base 2df2d845 (the final native gate did not select the bundle-size check): the native UI startup budget check measured exact base 374,444 B, candidate 374,445 B, against an unchanged 373,454 B budget. Both use eight startup requests and 1,211,163 raw bytes; CSS remains 50,756 B. No threshold or baseline changed. UI changes preserve appearance and adapt GC polling behavior; eight focused polling tests pass.

Ordered Gateway replay commands (same baseline and fixed sequences)

Temporary wrappers retain the original Gateway core/server configs and replace only the sequencer with a class that checks exact membership and imposes the following file order. Each command ran with CI=1, NODE_OPTIONS=--max-old-space-size=8192, and timeout --signal=TERM --kill-after=30s 600s.

node scripts/run-vitest.mjs --config .local/lane394-listener.repro.config.mts \
  src/gateway/session-lifecycle-state.test.ts \
  src/gateway/server/ws-connection/message-handler.suspension-admission.test.ts \
  src/gateway/worker-environments/node-workspace-transfer-retention.test.ts \
  src/gateway/worker-environments/repository-git-pack.test.ts \
  src/gateway/test-helpers.listener.test.ts \
  src/gateway/config-reload-plan.test.ts \
  src/gateway/control-ui-session-prs-mentions.test.ts \
  src/gateway/probe.close-drain.test.ts --maxWorkers=1
node scripts/run-vitest.mjs --config .local/lane394-private.repro.config.mts \
  src/gateway/server.native-hook-request-lifetime.test.ts \
  src/gateway/server.private-completion.test.ts \
  src/gateway/server.mcp-request-shutdown.test.ts \
  src/gateway/server.logs-tail.test.ts \
  src/gateway/server.qa-lab-rpc-replay.test.ts \
  src/gateway/server.users-preferences.test.ts \
  src/gateway/server.worker-placement-startup-context.test.ts \
  src/gateway/server.operator-presentation-lifetime.test.ts \
  src/gateway/server.rpc-wire-contracts.test.ts \
  src/gateway/server.e2e-ws-harness.test.ts \
  src/gateway/server.tools-effective.global-agent-gateway.test.ts --maxWorkers=1
Other affected test and type commands
pnpm install --frozen-lockfile
node scripts/run-vitest.mjs \
  src/cli/worktrees-cli.test.ts \
  src/cli/local-state-owner.process.test.ts \
  src/agents/worktrees/registry.test.ts \
  test/scripts/pr-worktree-provision.test.ts \
  test/scripts/eager-import-closure.test.ts \
  test/scripts/pr-wrapper-source-closure.test.ts \
  --maxWorkers=1
pnpm lint:kysely
env CI=1 node scripts/check-changed.mjs --base 976f8e0bff8bee191550c632de3bd83cdbe61177 --timed
node scripts/run-vitest.mjs \
  src/infra/git-root.test.ts \
  src/agents/worktrees/eviction.runtime.test.ts \
  src/agents/worktrees/service.eviction.test.ts \
  src/agents/worktrees/service.eviction-nesting.test.ts \
  src/agents/worktrees/service.gc-performance.test.ts \
  src/agents/worktrees/service.gc-maintenance.test.ts \
  src/agents/worktrees/service.restore-source.test.ts \
  --maxWorkers=1
env CI=1 node scripts/check-changed.mjs --base 8a0b0c458bbdac520a8f99b4735144722f698be7 --timed
pnpm tsgo:core
node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-agents-tools","core-test-infra"]'
Rebased-head integration command
node scripts/run-vitest.mjs \
  src/agents/worktrees/registry.test.ts \
  src/agents/worktrees/registry-read.test.ts \
  src/agents/worktrees/allocation.test.ts \
  src/agents/worktrees/service.capacity.test.ts \
  src/agents/worktrees/service.eviction.test.ts \
  src/agents/worktrees/service.gc-performance.test.ts \
  src/agents/worktrees/service.gc-maintenance.test.ts \
  src/gateway/worktree-maintenance.test.ts \
  src/state/openclaw-state-db-read-admission.test.ts \
  src/state/openclaw-database-preflight.startup-prepared.test.ts \
  src/gateway/server-agent-database-startup.test.ts \
  src/gateway/server-startup-lifetime.test.ts \
  --maxWorkers=1
Android fixture proof commands

Executed with the pinned CI toolchain and the native CI_RUNNER_BACKEND=blacksmith policy, from apps/android; the test task executed rather than reusing cached results:

./gradlew --no-daemon --build-cache --init-script "$OPENCLAW_ROBOLECTRIC_INIT" \
  :app:testPlayDebugUnitTest --tests ai.openclaw.app.ui.chat.ChatComposerLayoutTest

From repository root, with only the reviewed Kotlin file staged:

node scripts/check-changed.mjs --staged

@clawsweeper

clawsweeper Bot commented Oct 4, 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 agents Agent runtime and tooling size: XL labels Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed October 4, 2026, 4:34 AM ET / 08:34 UTC (Revision 8).

ClawSweeper review

What this changes

Managed worktrees gain background cleanup receipts, a configurable global capacity limit with eviction, worker-based inspection and snapshot persistence, and updated CLI, UI, and test integration.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 12 items remain

The performance work remains useful, but all three prior P1 blockers persist. The latest Android test correction leaves the affected production paths unchanged.

Priority: P1
Reviewed head: 5f4657b266acdf01111fab8db52d3d29e10ce710

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Substantial runtime evidence supports the performance work, but the unresolved authorization, session-custody, and shipped RPC regressions prevent merge readiness.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Authority-chain proof required: the hash-matched complete body preserves positive Linux production-owner evidence for background GC, 800/4096-tree cap enforcement, and dirty recovery. It does not show write-only rejection, revocation before deletion admission, or preparation-stage session custody; those final-effect cases remain required despite the trusted-author exemption. Snapshot persistence keeps its existing stored format. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🧂 unranked krab (1/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Authority-chain proof required: the hash-matched complete body preserves positive Linux production-owner evidence for background GC, 800/4096-tree cap enforcement, and dirty recovery. It does not show write-only rejection, revocation before deletion admission, or preparation-stage session custody; those final-effect cases remain required despite the trusted-author exemption. Snapshot persistence keeps its existing stored format. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 9 items Pinned introduction and review continuity: The introduced delta is merge-base 5f5125b to head 5f4657b. Comparing the previous reviewed head 1672207 with this head shows only the Android readiness helper change; the three previously flagged production paths are unchanged.
Creation now reaches global deletion: The new capacity admission runs before checkout creation and can evict unrelated registry worktrees. The Gateway still admits worktrees.create with operator.write, while worktrees.remove and worktrees.gc require operator.admin; normal creation requests without expectedOwnerId receive no deletion-authority guard.
Established method authorization boundary: The method descriptors explicitly distinguish write-scoped creation from admin-scoped removal, restoration, and GC.
Findings 3 actionable findings [P1] Require deletion authority before creation evicts global victims
[P1] Protect session admissions before capacity eviction
[P1] Negotiate background receipts without replacing legacy GC replies
Security Needs attention Creation can escalate into global checkout deletion: A write-only client can create in an authorized repository at capacity and cause eviction of unrelated managed checkouts, including dirty data, without the administrator authority required by explicit removal and GC.

How this fits together

Managed worktrees provide isolated Git checkouts for agents and operators. Creation, restoration, and Gateway maintenance consume registry and ownership facts before allocating or removing checkout files.

flowchart TD
  A[Agent and operator requests] --> B[Worktree service]
  C[Registry and live ownership] --> B
  D[Configured capacity] --> B
  B --> E[Capacity and cleanup decisions]
  E --> F[Git and snapshot workers]
  F --> G[Allocated or removed checkouts]
  E --> H[Background progress receipts]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Authority-chain proof required: the hash-matched complete body preserves positive Linux production-owner evidence for background GC, 800/4096-tree cap enforcement, and dirty recovery. It does not show write-only rejection, revocation before deletion admission, or preparation-stage session custody; those final-effect cases remain required despite the trusted-author exemption. Snapshot persistence keeps its existing stored format. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Require deletion authority before creation evicts global victims (P1) - At capacity, this new call can purge another agent's or repository's checkout. worktrees.create remains available to operator.write callers for authorized roots, whereas removal and GC require operator.admin; a request without expectedOwnerId reaches this path without a deletion-authority guard. Refuse unauthorized eviction before touching victims, and carry current deletion authority through destructive admission.
  • Protect session admissions before capacity eviction (P1) - This predicate recognizes only worktree-run leases. An admitted session turn can still be preparing before prepareAgentCommandExecution acquires that lease, and lifecycle or remote-placement custody also lives in the existing session owner policy. Capacity cleanup runs before ordinary owner-protected cleanup, so it can claim and purge that session's checkout during this gap. Compose the session owner's protection and revalidation into eviction admission.
  • Negotiate background receipts without replacing legacy GC replies (P1) - Every existing worktrees.gc request now receives successful queued counts instead of waiting for completed cleanup or receiving its partial-failure error. The latest release implements the completed-result contract, and existing clients have no negotiated selector distinguishing these meanings. Such clients can report success before deletion finishes and miss later failures. Make background receipts explicit and preserve legacy completion semantics through the same maintenance owner.
  • Resolve security concern: Creation can escalate into global checkout deletion - A write-only client can create in an authorized repository at capacity and cause eviction of unrelated managed checkouts, including dirty data, without the administrator authority required by explicit removal and GC.
  • Resolve merge risk (P1) - Final-effect authority proof remains incomplete: demonstrate write-only rejection, revocation before destructive admission, and active session-preparation custody through the production owners.
  • Resolve merge risk (P1) - Existing fleets above the new default cap can lose idle checkout files, including unsaved data when snapshots fail; fresh-default and published-driver upgrade evidence for a populated over-cap fleet remains missing.
  • Complete next step (P2) - Resolve the three repeated findings and add redacted final-effect authority and upgrade evidence before merge. Updating the PR body should trigger re-review automatically; otherwise a maintainer can comment @clawsweeper re-review.
  • Improve patch quality - Repair deletion authorization and session custody, then show final-effect rejection for a write-only principal and revocation before deletion admission using redacted runtime output.
  • Improve patch quality - Preserve legacy completed GC replies and demonstrate negotiated background receipts plus fresh-default and populated-fleet upgrade behavior.
  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.

Findings

  • [P1] Require deletion authority before creation evicts global victims — src/agents/worktrees/service.ts:594-598
  • [P1] Protect session admissions before capacity eviction — src/agents/worktrees/capacity-owner.ts:150-154
  • [P1] Negotiate background receipts without replacing legacy GC replies — src/gateway/server-methods/worktrees.ts:291-295
  • [high] Creation can escalate into global checkout deletion — src/agents/worktrees/service.ts:594
Agent review details

Security

Needs attention: The new capacity path lets write-scoped creation reach administrator-only destructive effects.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
New operator controls 1 config option, 2 CLI options, 2 RPC parameters The capacity policy and background-job contract add user-facing configuration and protocol surface.
Production versus test growth production +2832/-661, net +2171; tests +3224/-557, net +2667 The body explicitly justifies production growth through capacity enforcement, custody, background lifecycle, and worker snapshot persistence.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/worktrees/gc-removal.ts, unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Repair ownership and prove destructive admission (recommended)
    Preserve the admin deletion boundary and session custody, then supply allowed, forbidden, and revoked-authority observations before final deletion.
  2. Preserve client and upgrade contracts
    Negotiate background receipts through the shared owner and demonstrate fresh defaults plus an existing populated fleet upgrading safely.

Technical review

Best possible solution:

Keep one background maintenance owner while preserving deletion authorization, session custody, negotiated RPC behavior, and a proven upgrade path for existing fleets.

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

Yes, source establishes focused triggers: write-only creation at capacity, cleanup during session admission before run-lease acquisition, and a legacy GC request expecting completion. These paths were inspected but not executed in this read-only review.

Is this the best way to solve the issue?

No, the background owner is a useful direction, but it must retain the existing authorization and session owners and negotiate the changed RPC semantics.

Full review comments:

  • [P1] Require deletion authority before creation evicts global victims — src/agents/worktrees/service.ts:594-598
    At capacity, this new call can purge another agent's or repository's checkout. worktrees.create remains available to operator.write callers for authorized roots, whereas removal and GC require operator.admin; a request without expectedOwnerId reaches this path without a deletion-authority guard. Refuse unauthorized eviction before touching victims, and carry current deletion authority through destructive admission.
    Confidence: 0.99
  • [P1] Protect session admissions before capacity eviction — src/agents/worktrees/capacity-owner.ts:150-154
    This predicate recognizes only worktree-run leases. An admitted session turn can still be preparing before prepareAgentCommandExecution acquires that lease, and lifecycle or remote-placement custody also lives in the existing session owner policy. Capacity cleanup runs before ordinary owner-protected cleanup, so it can claim and purge that session's checkout during this gap. Compose the session owner's protection and revalidation into eviction admission.
    Confidence: 0.98
  • [P1] Negotiate background receipts without replacing legacy GC replies — src/gateway/server-methods/worktrees.ts:291-295
    Every existing worktrees.gc request now receives successful queued counts instead of waiting for completed cleanup or receiving its partial-failure error. The latest release implements the completed-result contract, and existing clients have no negotiated selector distinguishing these meanings. Such clients can report success before deletion finishes and miss later failures. Make background receipts explicit and preserve legacy completion semantics through the same maintenance owner.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The introduced deletion path can cross an authorization boundary and remove a session's checkout during preparation.
  • merge-risk: 🚨 security-boundary: Write-scoped creation can trigger global deletion that the existing RPC contract reserves for administrators.
  • merge-risk: 🚨 session-state: Capacity eviction bypasses active session-admission protection before a worktree-run lease exists.
  • merge-risk: 🚨 compatibility: Legacy GC clients receive queued success instead of completed results, and existing over-cap fleets face automatic destructive cleanup.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦐 gold shrimp and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Authority-chain proof required: the hash-matched complete body preserves positive Linux production-owner evidence for background GC, 800/4096-tree cap enforcement, and dirty recovery. It does not show write-only rejection, revocation before deletion admission, or preparation-stage session custody; those final-effect cases remain required despite the trusted-author exemption. Snapshot persistence keeps its existing stored format. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Security concerns:

  • [high] Creation can escalate into global checkout deletion — src/agents/worktrees/service.ts:594
    A write-only client can create in an authorized repository at capacity and cause eviction of unrelated managed checkouts, including dirty data, without the administrator authority required by explicit removal and GC.
    Confidence: 0.99

What I checked:

  • Pinned introduction and review continuity: The introduced delta is merge-base 5f5125b to head 5f4657b. Comparing the previous reviewed head 1672207 with this head shows only the Android readiness helper change; the three previously flagged production paths are unchanged. (apps/android/app/src/test/java/ai/openclaw/app/ui/chat/ChatComposerLayoutTest.kt:3006, 5f4657b266ac)
  • Creation now reaches global deletion: The new capacity admission runs before checkout creation and can evict unrelated registry worktrees. The Gateway still admits worktrees.create with operator.write, while worktrees.remove and worktrees.gc require operator.admin; normal creation requests without expectedOwnerId receive no deletion-authority guard. (src/agents/worktrees/service.ts:594, 5f4657b266ac)
  • Established method authorization boundary: The method descriptors explicitly distinguish write-scoped creation from admin-scoped removal, restoration, and GC. (src/gateway/methods/core-descriptors.ts:151, 5f4657b266ac)
  • Session custody bypass: Capacity enforcement protects only worktree-run lease scopes. The existing session owner policy separately protects active session work admissions, lifecycle mutations, and worker placements. Capacity cleanup runs before ordinary protected cleanup, and eviction's removal claim checks run leases without consuming those session protections. (src/agents/worktrees/capacity-owner.ts:154, 5f4657b266ac)
  • Shipped GC response contract: The latest release commit fc23bc8 waits for GC completion, reports partial failure as an RPC error, and returns completed removal counts. This branch instead returns an immediate receipt for the same legacy request. Current protocol versioning documentation also promises existing response contracts when additive owner fields are omitted. (src/gateway/server-methods/worktrees.ts, fc23bc864e45)
  • Complete captured proof inspected: The complete live body matched captured SHA-256 7111daa9f7e6273dfed2016c48cbdcfad26c39fd2fef98028b45a7a3d734c0a7; omitted ranges were inspected without executing embedded commands. It supplies positive Linux measurements through real creation/removal owners on 800- and 4096-worktree fleets, successful cap enforcement and dirty recovery, and remote test evidence. It does not provide final-effect observations for write-only rejection, revocation before deletion admission, or active session preparation without a worktree-run lease. (5f4657b266ac)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (7 earlier review cycles)
  • reviewed 2026-10-04T04:25:03.356Z sha 0afa6b7 :: blocked before merge. :: [P1] Protect session admissions before capacity eviction | [P1] Negotiate background receipts without replacing legacy GC replies | [P2] Update the offline GC assertions for the new CLI contract
  • reviewed 2026-10-04T05:14:12.660Z sha 976f8e0 :: needs real behavior proof before merge. :: [P1] Protect session admissions before capacity eviction | [P1] Require deletion authority before creation evicts global victims | [P1] Negotiate background receipts without replacing legacy GC replies | [P2] Update the offline GC assertions for the new CLI contract
  • reviewed 2026-10-04T06:12:23.340Z sha 5e72dd9 :: needs real behavior proof before merge. :: [P1] Require deletion authority before creation evicts global victims | [P1] Protect session admissions before capacity eviction | [P1] Negotiate background receipts without replacing legacy GC replies
  • reviewed 2026-10-04T06:33:24.188Z sha 5e72dd9 :: needs real behavior proof before merge. :: [P1] Require deletion authority before creation evicts global victims | [P1] Protect session admissions before capacity eviction | [P1] Negotiate background receipts without replacing legacy GC replies
  • reviewed 2026-10-04T07:54:27.246Z sha 548e65b277dcd9903c900f292b0b74b08b5f5f1f :: needs real behavior proof before merge. :: [P1] Require deletion authority before creation evicts global victims | [P1] Protect session admissions before capacity eviction | [P1] Negotiate background receipts without replacing legacy GC replies
  • reviewed 2026-10-04T08:03:34.592Z sha 1672207 :: needs real behavior proof before merge. :: [P1] Require deletion authority before creation evicts global victims | [P1] Protect session admissions before capacity eviction | [P1] Negotiate background receipts without replacing legacy GC replies
  • reviewed 2026-10-04T08:13:25.886Z sha 1672207 :: needs real behavior proof before merge. :: [P1] Require deletion authority before creation evicts global victims | [P1] Protect session admissions before capacity eviction | [P1] Negotiate background receipts without replacing legacy GC replies

@steipete
steipete marked this pull request as ready for review October 4, 2026 05:07
@steipete
steipete enabled auto-merge (squash) October 4, 2026 05:09
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 4, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 4, 2026
Replace the soft 100-tree cleanup target with a configurable global limit of 4096. Evict merged and squashed branches first, then idle trees by age including unsaved data, while retaining live leases and source storage custody.

Return GC receipts through one maintenance owner, move filesystem inspection and snapshot work to workers, and skip unchanged protected trees. Document the eviction policy and CLI progress contract.

Validated on Blacksmith Testbox and a synthetic Linux rig with 800 and 4096 worktrees; focused tests, affected native checks, and independent review pass. Cold source-runner activity and the inherited UI startup budget remain documented limitations.
Keep synthetic inventory and worker-free timer fixtures isolated under the new mock-export policy, and prune the superseded exact factory allowance.

Validated on Blacksmith Testbox with 14 focused cases and the complete 39-check changed gate. Independent review found no actionable P0/P1 issues.
Include the new worker/runtime modules in the native PR wrapper inventory so
provisioning can load its full dependency closure. Exercise queued cleanup,
progress readback, partial outcomes, and lost replies through the CLI owner
fixture. Use the existing SQLite bound-set helper for current removal claims.

The 109 focused tests and Kysely guard pass on Blacksmith Testbox. Independent
review found no actionable issues.
Join the private input recorder's persistence before inspecting its durable
timeout receipt, while keeping raw execution and terminal projection pending.
Use the harness's retained listener allocation instead of selecting and releasing
an OS port before reserving it again. Preserve the existing safety assertions.
@steipete
steipete force-pushed the steipete/perf-micro-worktree-gc-background-and-cap-20260919 branch from 548e65b to 1672207 Compare October 4, 2026 07:56
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Oct 4, 2026
@blacksmith-sh

This comment has been minimized.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Oct 4, 2026
Make Room-backed branch fixture startup participate in the existing Compose
idling owner instead of racing a one-second wall-clock poll. Preserve the
branch count, outbox restoration, loading, and pending-run requirements.
Report controller and ViewModel readiness if setup cannot settle.

The original CI failure occurred before the queued-refresh ABA action; its
artifact did not identify which readiness predicate remained false.
@openclaw-barnacle openclaw-barnacle Bot added the app: android App: android label Oct 4, 2026
@steipete
steipete merged commit 3b16db7 into main Oct 4, 2026
193 of 195 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-gc-background-and-cap-20260919 branch October 4, 2026 08:43
MarMarLabs added a commit to MarMarLabs/openclaw that referenced this pull request Oct 4, 2026
128 upstream commits, including background worktree GC with a capacity
limit (openclaw#164758), which adds a core config field, so the core count goes
from 2501 to 2502 and the core hash changes. Upstream also changed six
Feishu files, none of them files this branch changes.

Two generated conflicts, docs/.generated/config-baseline.counts.json and
config-baseline.sha256, regenerated from this merge rather than
hand-merged. build:docker ran in a separate detached checkout of this
commit. Counts core 2502, channel 3788 and plugin 4468. The core and plugin
hashes match upstream/main and the channel hash stays this branch's, as
predicted. The three generated-file checks pass there.

Feishu: 102 files and 1521 tests in the extension project, 17 files and 241
tests in the database-workers project, all passing. The forwarder test and
the routing guards pass, 499 tests. tsgo:core, tsgo:extensions,
tsgo:extensions:test, tsgo:test:root, the line-cap, max-lines and
assertion-safety ratchets against upstream/main, oxlint and oxfmt on the 43
changed code files all pass.
steipete added a commit that referenced this pull request Oct 4, 2026
Integrate main background GC and capacity work (#164758), retaining Git-worker snapshot capture and the existing provisioned-snapshot command. Reuse the run-end transaction, lease, receipt, and unknown-outcome owner; await eviction claims and settlement with whole-batch custody checks. Preserve busy-run details, rollback ownership, and accepted shutdown work. Stored formats, retention, and released worktree SDK signatures remain unchanged.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…164758)

* perf(worktrees): run bounded cleanup in background and enforce capacity

Replace the soft 100-tree cleanup target with a configurable global limit of 4096. Evict merged and squashed branches first, then idle trees by age including unsaved data, while retaining live leases and source storage custody.

Return GC receipts through one maintenance owner, move filesystem inspection and snapshot work to workers, and skip unchanged protected trees. Document the eviction policy and CLI progress contract.

Validated on Blacksmith Testbox and a synthetic Linux rig with 800 and 4096 worktrees; focused tests, affected native checks, and independent review pass. Cold source-runner activity and the inherited UI startup budget remain documented limitations.

* test(worktrees): document isolated maintenance mocks

Keep synthetic inventory and worker-free timer fixtures isolated under the new mock-export policy, and prune the superseded exact factory allowance.

Validated on Blacksmith Testbox with 14 focused cases and the complete 39-check changed gate. Independent review found no actionable P0/P1 issues.

* fix(worktrees): complete GC CLI and wrapper integration

Include the new worker/runtime modules in the native PR wrapper inventory so
provisioning can load its full dependency closure. Exercise queued cleanup,
progress readback, partial outcomes, and lost replies through the CLI owner
fixture. Use the existing SQLite bound-set helper for current removal claims.

The 109 focused tests and Kysely guard pass on Blacksmith Testbox. Independent
review found no actionable issues.

* test(gateway): await receipts and retain listener ownership

Join the private input recorder's persistence before inspecting its durable
timeout receipt, while keeping raw execution and terminal projection pending.
Use the harness's retained listener allocation instead of selecting and releasing
an OS port before reserving it again. Preserve the existing safety assertions.

* test(android): join branch fixture readiness with Compose idling

Make Room-backed branch fixture startup participate in the existing Compose
idling owner instead of racing a one-second wall-clock poll. Preserve the
branch count, outbox restoration, loading, and pending-run requirements.
Report controller and ViewModel readiness if setup cannot settle.

The original CI failure occurred before the queued-refresh ABA action; its
artifact did not identify which readiness predicate remained false.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: android App: android app: web-ui App: web-ui cli CLI command changes 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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