Repository navigation
fix(cli-runner): sweep orphaned bundle MCP temp dirs at gateway startup - #105643
totobusnello wants to merge 7 commits into
Conversation
|
Codex review: needs maintainer review before merge. Reviewed August 11, 2026, 10:16 AM ET / 14:16 UTC. ClawSweeper reviewWhat this changesThe PR adds crash-safe startup cleanup for abandoned CLI bundle-MCP temporary files while preserving files still owned by live provider processes. Merge readinessthis PR remains necessary: current main creates bundle-MCP temporary directories but only deletes them in normal run cleanup, which process death bypasses. The branch supplies a coherent startup recovery path; rebase and exact-head review are required before merge because it changes the generic child-process ownership boundary. Priority: P1 Review scores
Verification
How this fits togetherCLI-backed agents write temporary MCP settings before launching provider subprocesses. Gateway startup can later remove abandoned settings after a crash, but must retain files a live subprocess still needs. flowchart LR
A[CLI run] --> B[Temporary MCP files]
B --> C[Provider subprocess]
C --> D[Ownership descriptor]
D --> E[Gateway startup sweep]
E --> F{Owned by live process?}
F -->|Yes| G[Preserve files]
F -->|No| H[Remove abandoned files]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +830, Tests +802, Generated 0. Total +1632 across 22 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Rebase onto current main, keep ownership proof internal to child spawning, and merge after exact-head validation confirms the sweep removes only abandoned files. Do we have a high-confidence way to reproduce the issue? Yes from source: current main creates the files and deletes them only in a run-finally path, so process death bypasses cleanup; the failure was not executed locally in this read-only review. Is this the best way to solve the issue? Yes, subject to rebase validation: startup cleanup coupled to verified live-process ownership repairs the lifecycle owner rather than adding another per-run fallback. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 29fd6aaf6bb3. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (41 earlier review cycles; latest 8 shown)
|
|
@clawsweeper re-review — added after-fix exact-head proof (real host |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
The two failing checks look like pre-existing base/CI issues rather than anything in this diff — and neither is a required (merge-blocking) check. This PR only touches
I'll rebase once the base CI settles so the head goes green. Flagging for triage in the meantime. |
|
@clawsweeper re-review Branch updated onto healed |
|
On the "Persistent data-model change detected" merge-readiness item: this PR introduces no data-model or schema change. The only state the flagged Also: the head is now rebased on today's |
|
Rebuilt on current Same change as before: 8 files, +899/-25. The three added files ( No production file conflicted. Two test hunks needed a decision: 1. 2. Local validation on the exact head (Node 26.5, macOS):
Still needed on current |
|
@clawsweeper re-review Both blocking items from the August 8 review are addressed at head 1. Real behavior proof now matches the head. The previous proof targeted 2. P2 — the immutable gateway owner identity is cached. That also closes the two merge-risk items, since both were the same driver: the three per-run process-lifetime metadata reads are now one per process. Rebase note. The branch was 383 commits behind. It is rebased as a single commit; the two conflicts were semantic and are documented in the body — Pre-existing upstream failures, unrelated to this branch — both reproduce identically on unmodified |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review The P1 from the August 9 review is closed at head 1. This deliberately is not the ownership protocol you suggested: there is no atomic handoff available to a process that has not 2. Proven on a real Linux host, with a control. The driver models the pre-exec child faithfully — its argv does not mention the config dir (the path arrives via env), and it later becomes argv-visible by spawning A is the control and it is the point: with the settle disabled, your race lands and the child dies with 3. Two bugs that only running it exposed, both fixed and both in the body: the settle timer must not be 4. Non-Linux — you were right, and it is now stated in the body. Off-Linux the PID namespace is unreadable, so the fail-closed rule keeps every owner-encoded dir: the sweep is a no-op on macOS and Windows rather than a partial reclaim. That is the safe direction and the deliberate consequence of trusting pid liveness only inside a proven namespace. 5. Retracting a stale claim of my own. A previous revision of this body cited two pre-existing upstream failures (three Every gate is green at this head: |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review The P2 is fixed at head P2 — sidecar cancellation is now honored. You were right on both halves, and I verified the premise before acting: This also retires the trade-off the previous commit recorded in a comment. That comment claimed the cost of a ref'd timer was a close waiting the interval out; with the abort wired in, that cost is gone — holding the event loop is safe precisely because close cuts the wait short. Two tests cover it, and both avoid the weakness you correctly identified in the earlier settle test (an injected P1 — not addressed here, and I do not think I should be the one to close it. Your reading is fair: five seconds is an empirical bound, not a contract, and you are right that my settle test made the transition happen inside its own fake sleep. Since you have marked this an owner decision, changing the mechanism now would pre-empt the choice you asked a maintainer to make. For whoever picks it up, one option that does meet "durable ownership proof" rather than a timing bound: have prepare open a lock file inside the temp dir and pass the descriptor to the child. A descriptor is inherited across Note the two remaining merge-risk items are not independent of the above: the cancellation one is what this commit fixes, and the other is the P1 restated. Real-host proof re-run at this head after the change (the sweep's signature changed, so the previous run no longer describes this code): the five owner-liveness cases 5/5, and the delayed-child control A/B 2/2 — A still reproduces the loss with the settle disabled, B still keeps the config with it enabled. Every gate green: |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review The P1 is addressed at head The claim is a descriptor inherited at The distinction that makes this a contract rather than a bound: argv answers which config is this process using, and only after Proven with the settle switched off entirely, so nothing in the result depends on an interval: A is the case your review said the code could not establish: The settle stays, demoted. Off-Linux the descriptor probe cannot run, so there the argv re-scan is again the only signal and the settle still buys it the fork→exec margin. On Linux it is no longer load-bearing. On the previous revision's argument. It claimed no atomic handoff was available to a process that had not Cost. This adds ~180 production lines: a One measurement to pre-empt a misread. This touches Everything else holds at this head: the five owner-liveness cases 5/5, the delayed-child settle control 2/2, 178/178 across the touched bundle-MCP and gateway suites, and |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review You found a real gap and it was mine. Fixed at head The descriptor now reaches the live-session child. You were exactly right: it was wired into the per-turn supervisor spawn only, and managed Claude live sessions spawn through their own call site in I had even seen that call site earlier, while checking whether any CLI route used pty, and still wired only one. No excuse; thank you for catching it. Both CLI spawn sites forward it now. I then swept every The regression test was verified in the failing direction. It asserts the descriptor reaches the live-session spawn, plus the negative case (no prepared descriptor, no Proof re-run at this head (the body describes Gates: The |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Head The end-to-end proof you asked for. An ephemeral gateway built from each tree — isolated state, isolated
The ownership transfer is implemented anyway, as hardening rather than as a bug fix: the session — not its creating turn — now adopts the prepared cleanup at spawn and releases it exactly once at session close. That is the correct invariant regardless of how long sessions live, and it removes the ambiguity your finding pointed at (two paths with a claim on one resource). A boundary regression pins it — a completed turn must not release, session close must, exactly once — and it was verified in the failing direction: reverting the transfer fails it in both vitest projects. Rebase notes. Six commits over today's The earlier real-host proofs (owner-liveness 5/5, descriptor claim with the settle off 2/2, delayed-child settle control 2/2) were re-run when their code last changed and are unchanged by this rebase; the end-to-end run above supersedes them as the primary evidence. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review All three findings from the August 10 review are fixed at head 126b1b42, each proven in the failing direction on a real Linux host (same driver run against a pre-fix bundle of d3714a91 first — the symlinked-root case deletes a held config there, and Gemini settings leak permanently — then ALL PASS at this head). Full A/B output, the Gemini ownership design (owner-encoded prefixes, inherited attempt descriptor, env-carried fail-closed rule), and the continuity re-runs of the three existing exact-head drivers are in the updated PR body. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
The per-run bundle MCP temp config (openclaw-cli-mcp-*/mcp.json) is only reclaimed by an in-memory cleanup() callback. When the gateway process exits with runs in flight (restart, crash, SIGKILL), the callback dies with it and the directory leaks — including the rendered loopback URL and resolved tokens. Deterministically reproducible: start a run, restart the gateway mid-flight, observe the surviving dir (26 accumulated on one production host over 33 days, dates correlating 1:1 with restart days). Add a post-ready startup sidecar (mirroring sidecars.session-locks) that sweeps orphaned dirs. Orphan detection is liveness-based, not age-based: live CLI children carry the config path in their argv (--mcp-config), and live-session dirs legitimately persist across turns — an age-only sweep would regress openclaw#73244. A dir is removed only when no running process references it and it is older than a short spawn-grace window. The sweep fails closed when the process scan yields nothing. Ownership is encoded in the temp dir name (pid + boot-id prefix + PID namespace inode + process start time), so a run that is still queued — its CLI child not yet spawned, hence no argv reference — is not reclaimed by a concurrent gateway's sweep. The sweep trusts pid probes only when the owner's PID namespace provably equals the sweeper's: a different or unverifiable namespace keeps the dir, mirroring the off-Linux and unknown-start-time fail-closed paths. Legacy (pre-ownership) dirs are never auto-removed; they are kept with an operator warning. Claude's bundle-MCP config now routes through the shared writeTemporaryBundleMcpJson writer (which rolls the dir back on a failed write), so every backend — Claude, Codex, Gemini — gets the same no-leak guarantee instead of Claude having its own inline path. The startup test's root-work-count assertion now waits for in-flight startup sidecars to settle instead of asserting a fixed instant, keeping it stable for any sidecar that performs real async work. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…emp dir The final argv re-scan narrowed the window in which a CLI child could claim a config about to be removed, but it could not close it: a child forked by the dying gateway that has not execed yet still carries the parent's argv, so no argv references its config until exec lands. Such a child is forked strictly before its owner dies, which is strictly before the death verdict here, and exec follows fork within microseconds. Waiting after the verdict therefore guarantees any surviving child is argv-visible by the re-scan, which turns it from a narrowing heuristic into a decisive check — without an ownership protocol, which cannot help a process that has not execed yet. Proven on a real Linux host: with the settle disabled the sweep removes the config and the child dies with ENOENT; with it enabled the dir is kept and the child reads its config. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hpPivtDKF5T5QpfWywHdU
The post-ready sidecar hands its run an AbortSignal, but the sweep dropped it and its settle timer deliberately held the event loop. A close arriving inside the settle therefore waited the full interval, and the sweep could still delete files after cancellation had begun — a cleanup outliving the gateway generation that scheduled it. The signal is now forwarded from the sidecar and honored in two places: the settle resolves immediately on abort, and an aborted run returns with every candidate kept and nothing removed. This also retires the trade-off the previous commit recorded. Holding the event loop is safe precisely because the abort cuts the wait short, so the sweep no longer has to choose between completing reliably and delaying a graceful stop. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hpPivtDKF5T5QpfWywHdU
The settle made the final argv re-scan reliable in practice, but it rested on a timing bound rather than a contract: nothing in the code proved a forked child must become argv-visible within the interval. A descriptor does prove it. The child inherits one on its rendered config at fork -- strictly before exec -- so from that instant the directory is claimed, and the claim is visible in /proc/<pid>/fd during the whole window in which the child's argv still belongs to its parent and names no config. The sweep now reads that claim before deciding, so the pre-exec case is closed by construction instead of by an interval. The settle is kept as the second line, not dropped: off-Linux the descriptor probe cannot run and the argv re-scan is again the only signal. Proven on a real Linux host with the settle switched off entirely: a holder whose argv never mentions the dir keeps it, and once that holder is gone the dir is reclaimed -- so the claim is durable without becoming a permanent leak. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hpPivtDKF5T5QpfWywHdU
…ild too The descriptor was wired into the per-turn supervisor spawn only. Managed Claude live sessions spawn through their own call site and returned earlier, so the one path that holds a bundled MCP config longest -- across turns, for days (openclaw#73244) -- was left on the timing-based recheck the descriptor is meant to replace. Both CLI spawn sites now forward it. The other three supervisor.spawn call sites in src/agents are bash tooling and carry no preparedBackend, so they are out of scope. The regression test asserts the descriptor reaches the live-session spawn, and was checked in the failing direction: reverting the fix fails it in both vitest projects. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hpPivtDKF5T5QpfWywHdU
|
@clawsweeper re-review Rebased onto current main (25e7113) and ported the ownership handoff to the new live-process owner, exactly as the finding asked: |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…settings inside the sweep boundary Three lifecycle gaps in the bundle-MCP orphan sweep, closed together: - The descriptor probe compared the tmpRoot's own spelling against RESOLVED /proc/<pid>/fd targets, so a symlinked TMPDIR blinded it to every live holder and a held config could be deleted. The probe now canonicalizes the root once and compares in canonical space, recording hits under the caller's spelling. Regression: a real-probe test through a symlinked root (Linux), plus its close-the-fd control. - A gateway close landing during the phase-two probe/re-scan awaits, or between removals, could still reach fs.rm. The signal is now re-checked on every candidate iteration: once cancellation begins, that candidate and all remaining ones are kept. - Gemini serializes resolved header credentials into openclaw-gemini-mcp-* (and -attempt-) settings dirs with the same in-memory-cleanup lifecycle, but the sweep only recognized the Claude prefix — a gateway crash leaked them forever. Gemini dirs are now owner-encoded at mkdtemp (shared identity suffix), swept under the same fail-closed policy, and claimed in flight by an ownership descriptor the child inherits at fork; the per-attempt descriptor supersedes the prepared one since the attempt env is what the child actually reads. Because a Gemini settings path travels via env (never argv), an env-carried dir is only reclaimed where the descriptor probe exists (Linux) and is kept, fail closed, elsewhere.
…nd ownership descriptor CliPreparedBackend.ownershipFd changed the closure hash of every exported type that embeds the prepared backend (agent-harness-runtime), which is exactly what check-plugin-sdk-api-baseline flags. Regenerated with pnpm plugin-sdk:api:gen; no export was added or removed (65 lines changed in place).
|
@clawsweeper re-review Every CI failure at the previous head is traced and resolved at this one. The plugin-sdk API baseline is regenerated in its own commit ( |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
This pull request has been automatically marked as stale due to inactivity. |
|
Closing due to inactivity. |
Fixes #105641
What Problem This Solves
Per-run bundled MCP temp configs (
os.tmpdir()/openclaw-cli-mcp-*/mcp.json, containing the rendered loopback URL and resolved tokens) are only reclaimed by the in-memorycleanup()callback returned fromprepareModeSpecificBundleMcpConfig. When the gateway process exits with runs in flight (restart, crash, SIGKILL), the callback dies with it and the directory leaks — credential-bearing files outlive the gateway generation that issued them, and restart-heavy deployments accumulate leaked dirs until reboot. 26 leaked dirs built up over 33 days on our production host, dates correlating 1:1 with restart activity (full field data in #105641).Approach
A gateway-startup post-ready sidecar (
sidecars.bundle-mcp-temp-sweep, mirroringsidecars.session-locks) that removes orphaned dirs. Orphan detection is liveness-based, not age-based:Live CLI children carry the config path in their argv (
--mcp-config <dir>/mcp.json, frominjectClaudeMcpConfigArgs), so a dir is only removed when no visible process references it. Live-session dirs legitimately persist across turns — an age-only sweep would regress claude-live-session: bundled MCP tempDir cleaned up while persistent CLI subprocess still uses it (race) — plus misleading billing-error template #73244.The config is rendered at prepare time, before the run enters the serialization queue, so a run waiting in the queue owns a config that no process argv references yet. To tell such a live-owned queued dir from a true orphan, the creating gateway's identity is encoded in the temp dir NAME, produced atomically by
mkdtemp:An argv-unreferenced owner-encoded dir is removed only once its owning gateway is provably gone AND provably in this PID namespace: pid dead (
process.kill(pid, 0)), host rebooted (boot8differs from the current Linux boot id), or the pid reused by a different process (owner's/proc/<pid>/statstart time differs). Off-Linux (no start verification) the sweep over-protects — it never deletes a live-owned config; that residual is the safe direction and is documented.Fail closed across PID namespaces.
process.kill//procliveness is namespace-local, so a shared/tmpmount across separate PID namespaces (e.g. two containers) could otherwise let one sweep see a foreign owner's pid as absent (or reused by an unrelated local process) and delete its still-live, credential-bearing config. The creating gateway's PID-namespace inode (readlink /proc/self/ns/pid) is encoded in the dir name (the<nsInode>field above); the sweep trusts the pid probes only when the owner's namespace provably equals the sweeper's. A different or unverifiable namespace (nonson either side, off-Linux/restricted) keeps the dir (over-protect) — each namespace reclaims its own dead owners.boot8mismatch still short-circuits to dead first (a reboot kills every namespace).Legacy (pre-ownership) dirs without an encoded owner are never auto-removed. Their owner cannot be proven, so during a rolling upgrade a concurrently-running older gateway could hold an unspawned queued run whose legacy config is aged and argv-unreferenced — deleting it would break that run. Legacy dirs are kept and surfaced via a startup
warnwith a count for explicit operator cleanup (stop the gateway, remove staleopenclaw-cli-mcp-*by hand). Once a host runs an ownership-aware build every new dir is owner-encoded, so the legacy set only ever shrinks.The sweep fails closed: if the process scan yields nothing (restricted environment), everything is kept — keeping a leaked dir beats breaking a live run. A fresh argv re-scan runs immediately before removal so a child that spawns mid-sweep is kept.
The pre-
execwindow is closed by a descriptor inherited atfork, not by timing (review follow-up, see Evidence). Preparation opens a descriptor on the rendered config and hands it to the CLI child; inheritance happens atfork, strictly beforeexec, so from that instant the directory carries a durable claim — visible in/proc/<pid>/fdthroughout the window in which the child's argv still belongs to its parent and names no config at all. The sweep reads that claim before deciding. Argv answers "which config is this process using"; the descriptor answers "is anyone holding this directory", and only the second question survives the fork→exec transition. The parent's copy is closed by the run'scleanup, so the claim belongs to the child and is released with it — a dead holder's directory is still reclaimed.Both CLI spawn sites forward it, including the managed Claude live process (
spawnClaudeProcessinclaude-live-process.ts, where currentmain's live-session split moved the persistent child's spawn) — caught in review, fixed, and pinned by a test verified in the failing direction. The othersupervisor.spawncall sites undersrc/agentsare bash tooling and carry nopreparedBackend, so they are out of scope.Prepared-cleanup ownership stays with the run — a cleanup-adoption experiment was implemented and then withdrawn against current
main's own contract. A review flagged thatrunCliAgentInternalinvokespreparedBackend.cleanup()when a run ends while a persistent live child may still be using the config, and an earlier revision of this branch answered by transferring that cleanup to the live session ("the session, not its creating turn, owns the prepared config"). Two independent measurements ended that experiment. First, the failure it guarded against does not occur in the real runtime: a captured live turn deliberately closes its session at turn end (the MCP capture key lives in the process environment, so a captured turn must end its process before the key is released), and the end-to-end run below confirms a completed turn leaks nothing on unmodifiedmaineither. Second — decisive — currentmaintests the opposite ownership by name:cli-runner.spawn.test.tshaskeeps non-capture live prepared backend cleanup with the whole-run ownerandkeeps captured live prepared backend cleanup with the whole-run owner, andcli-runner.reliability.test.ts(forks a lifecycle-started resume stall…) requires the prepared artifacts to survive a mid-run live-process close so the fork retry can respawn with them, and then be reclaimed at run end even under a persistent successor. Adoption-at-spawn broke exactly those tests. The run is the owner upstream chose, its semantics are proven harmless in the captured flow, and this branch now leaves that boundary untouched — the crash-recovery gap this PR exists for is the gateway dying with the callback, which the sweep handles regardless of who holds the callback in memory.A settle delay between the death verdict and the re-scan remains as the second line, not the only one (review follow-up, see Evidence). Off-Linux the descriptor probe cannot run (
/procis unavailable), so the argv re-scan is again the sole signal there and the settle still buys it the fork→exec margin. A child forked by the dying gateway but not yetexeced still carries the parent's argv, so nothing references its config untilexeclands — a scan alone can never rule that out. But such a child was forked strictly before its owner died, which is strictly before the death verdict, andexecfollowsforkwithin microseconds (libuv's immediateexecvp). WaitingPOST_VERDICT_SETTLE_MS(5s, ~6 orders of magnitude of headroom) after the verdict makes any surviving child argv-visible by the re-scan with a very large margin. The delay is paid once, inside a post-ready sidecar that blocks no run.An earlier revision of this PR offered that margin as the whole answer, arguing no atomic handoff was available to a process that had not
execed yet. The review was right to reject it — a margin is not a contract, however wide — and wrong only in that a handoff does exist: descriptor inheritance, which is exactly what the bullet above now uses. On Linux the settle is therefore no longer load-bearing; it is the fallback for hosts where the descriptor cannot be read.The settle honors the sidecar's abort signal — and so does every removal.
schedulePostReadySidecarTaskhands itsrunanAbortSignal; the sweep respects it in three places — the settle resolves immediately on abort, an aborted run returns with every candidate kept and nothing removed, and (review follow-up) the signal is re-checked on every candidate iteration of the removal loop, so a close landing during the descriptor-probe/re-scan awaits or between removals keeps that candidate and all remaining ones. A cleanup must never outlive the cancellation that asked it to stop. This is also what makes holding the event loop during the settle safe: the wait cannot delay a graceful close, because close cuts it short.Descriptor identity is compared in canonical space (review follow-up).
/proc/<pid>/fdlinks report the resolved target while the sweep's candidates keep the temp root's own spelling, so a symlinkedTMPDIRwould have silently blinded the probe to every live holder — and deleted a held config. The probe now canonicalizes the root once (fs.realpath) and compares against resolved targets, recording hits under the caller's spelling; an unresolvable root makes the probe return unknown rather than a false empty.Gemini temporary settings live inside the same ownership boundary (review follow-up, security). Gemini serializes resolved header credentials into
openclaw-gemini-mcp-*(andopenclaw-gemini-mcp-attempt-*) settings dirs through the same shared writer and the same in-memory-cleanup lifecycle, so gateway death stranded them identically — and permanently, since the sweep only recognized the Claude prefix. Both Gemini families are now owner-encoded atmkdtemp(same identity suffix, composed onto each base prefix), swept under the same fail-closed policy, and claimed in flight by an ownership descriptor the child inherits atfork; for a capture attempt the attempt descriptor supersedes the prepared one, because the attempt env is what the child actually reads. One boundary is deliberately stricter: a Gemini settings path travels to the child via env (GEMINI_CLI_SYSTEM_SETTINGS_PATH), never argv, so the argv scans can never prove a live Gemini holder — an env-carried dir is therefore reclaimed only where the descriptor probe exists (Linux) and is kept, fail closed, everywhere else.Process scan is async and cross-platform:
ps -axwwon POSIX,/procwalk fallback for minimal Linux containers without procps, PowerShellGet-CimInstance Win32_Processon Windows, all with timeouts.The
mcp.jsonwrite inbundle-mcp.tsis wrapped so a failed prepare rolls the dir back (closes a pre-existing leak).Why legacy dirs are never auto-removed (rolling-upgrade safety)
An earlier revision still age-swept unowned legacy dirs, which a review flagged as a P1: during a mixed-version rollout an older gateway can have a queued run older than any grace window with no child argv and no encoded owner, and the new gateway would remove a config that queued run still needs. Rather than gate legacy cleanup on a heuristic, this revision stops auto-removing legacy dirs entirely and routes their reclamation to explicit operator action (surfaced by the startup warn). This closes both the
merge-risk: compatibilityconcern (a newly-upgraded gateway no longer changes the treatment of an older gateway's dirs) and themerge-risk: availabilityconcern (no queued config is deleted before its child spawns) at the root.This also removes the age-based spawn-grace window, which only ever protected legacy dirs — a net simplification. A live-owned queued dir is already kept by owner liveness, and a dead owner's config is reclaimable at any age, so no age check remains.
Evidence
Live reproduction of the leak on a production gateway (OpenClaw v2026.6.11, Ubuntu VPS), before this fix — run in flight +
systemctl restart:Control (same host): SIGKILL of only the CLI child does not leak — the surviving gateway still runs the cleanup callback, confirming the leak specifically requires gateway death:
Focused tests.
bundle-mcp-sweep.test.tscovers, for the name-encoded scheme: gateway death with runs in flight, a live CLI child keeping its dir (#73244), a concurrent gateway's child, a live-owner queued dir kept, a dead-owner dir removed, a rebooted-owner dir removed, a fresh dead-owner reclaimed regardless of age, a pid-reuse dir removed (alive pid, mismatched start), an unknown-start dir kept (fail-closed), a start-unverifiable dir kept (off-Linux over-protect), legacy dirs (aged, fresh, empty, unparseable) all kept (rolling-upgrade safe), the legacy-retained operator warn, a child that spawns between the argv scan and removal kept, and non-matching entries / missing roots.bundle-mcp.test.tsasserts a config-write failure rolls the temp dir back end-to-end through the Claude backend, andbundle-mcp-runtime.test.tsasserts the sharedwriteTemporaryBundleMcpJsonitself rolls back on a failed write. Lint (pnpm lint),tsgo:core,tsgo:core:test,check:temp-path-guardrailsclean;deadcode:exportsadds no export.Rebase + shared-writer consolidation (review follow-up). The July 26 rebase onto current
mainfirst kept an inlinemkdtemp+ write + rollback for the Claude backend; per review, head6ef864aainstead reuses main's sharedwriteTemporaryBundleMcpJson. The owner-encoded prefix is resolved first (bundleMcpOwnedMkdtempPrefixName) and passed to the shared writer, and rollback-on-write-failure was added to that shared writer — so Claude no longer forks the temporary-config lifecycle, and the Codex/Gemini backends gain the same no-leak guarantee. The owner-aware sweep policy is unchanged.Exact-head real-behavior proof — real host, no mocks, Linux. Ran the exported
sweepOrphanedBundleMcpTempDirs(esbuild-bundled from the exact-head source — the real function, not a reimplementation) at head6ef864aaon a real Linux host (Node v22) with its real defaults: realprocess.kill(pid, 0)liveness, real boot id, real/proc/<pid>/statstart-time verification, in an isolated scan root. Five temp dirs, none referenced by any live argv, owner encoded in each name. Redacted (no tokens, endpoints, host paths, or boot id):The legacy old-format dir is kept (rolling-upgrade safe) with the operator warn firing; a reused pid (pid alive, real
/procstart time mismatched) is still reclaimed; a dead owner is reclaimed even when its dir is fresh (owner death, not age, decides). The pid-reuse driver behind the availability risk is exercised on the final-head code with real/procverification, and the rolling-upgrade driver behind the compatibility risk is closed by never auto-removing legacy dirs. The fail-closed unknown-start and off-Linux over-protect paths stay covered bybundle-mcp-sweep.test.ts.Exact-head namespace proof — real host, shared temporary root (head
c7cb42c462). After the PID-namespace fail-closed boundary was added, the exportedsweepOrphanedBundleMcpTempDirs(esbuild-bundled from the exact-head source — the real function, not a reimplementation) was run on a real Linux host (Node v22) with its real defaults: realprocess.kill(pid, 0), real boot id, real/proc/<pid>/statstart time, and real/proc/self/ns/pid, in an isolated scan root. Redacted (no ns inode, boot id, tokens, endpoints, or host paths):The foreignNs case — a dir whose encoded PID namespace differs from the host's, with a dead-looking pid — is kept: the sweep never deletes a config it cannot prove is both local and dead. ownerNons (unverifiable namespace) is likewise kept, while same-namespace dead/freshDead/pidReuse are still reclaimed and legacy is retained with the operator warn. This is the exact-head evidence for the shared-temporary-root / cross-namespace boundary added after
6ef864aa; the same three namespace cases are covered deterministically inbundle-mcp-sweep.test.ts.Rebase onto current
main+ owner-identity cache (review follow-up, head2caef2d1ab, now superseded byd3714a91). The previous head was 383 commits behind and had goneCONFLICTINGagain. Rebased onto currentmainas a single commit; two files conflicted and both were semantic, not textual:server-startup-post-attach.ts—maindeleted thesidecars.memoryblock entirely (scheduleGatewayMemoryBackendno longer exists anywhere insrc/). Resolution followsmain(block dropped) and keeps only this PR's addition, thesidecars.bundle-mcp-temp-sweeppost-ready task.server-startup-post-attach.test.ts— sidecar-count assertions.mainremoved one gateway-lifetime sidecar and this PR adds one post-ready sidecar, so each count ismain's value plus this PR's delta: post-ready1→2, gmail2→3, lifetime stays3,postReadySidecarCount3→4.P2 addressed — the owner identity is now resolved once per process, not per run.
bundleMcpOwnedMkdtempPrefixName()memoizes its promise. Every component it reads is fixed for the process's lifetime (pid, boot id, PID namespace, this process's own start ticks), so preparation no longer pays three/procreads before queue admission on the hot path of every run. Memoizing the promise also collapses concurrent first-time callers onto a single read, and it cannot poison the cache: all three readers swallow their own errors and resolve to a fallback, so the promise never settles rejected. Covered by a new focused test that spies onfs.readFile/fs.readlinkand asserts neither is called after the first resolution.Exact-head real-behavior proof — real host, no mocks, Linux (head
d3714a91). Both drivers below were esbuild-bundled from the working tree that is now headd3714a91— the exportedsweepOrphanedBundleMcpTempDirsitself, not a reimplementation — and re-run on a real Linux host with its real defaults: realprocess.kill(pid, 0)liveness, real boot id, real/proc/<pid>/statstart-time verification, real/proc/self/ns/pid, isolated scan root. Redacted (no tokens, endpoints, host paths, or boot id):The same five verdicts hold on the rebuilt head: a live owner is kept, a dead owner is reclaimed even when its dir is fresh (owner death, not age, decides), a reused pid (pid alive, real
/procstart time mismatched) is still reclaimed, and the legacy old-format dir is kept with the operator warn firing. The cache line is the P2 measurement on the same run: the first resolution costs ~840µs of real/procI/O, every subsequent preparation ~0.26µs, and the resolved identity is stable.End-to-end, on a real gateway with a real Claude CLI child: the full lifecycle, A/B against unmodified
main. The August 10 review asked for real runtime evidence of the prepared-config → live-session child path. This is that evidence, and it is the strongest in the PR: an ephemeral gateway built from each tree (isolated state dir, isolatedTMPDIR, realclaudeCLI on subscription auth, real turns through theagentRPC), measuring the rendered config directory at every lifecycle boundary. Same driver, same host, both trees:mainmcp-dirs=0mcp-dirs=0— the per-turn lifecycle leaks nothing on either treefd-holder-pids=nonefd-holder-pids=<gateway>,<child>— the inherited claim, liveopenclaw-cli-mcp-SVmIaN(legacy, unowned)openclaw-cli-mcp-<pid>-<boot8>-<ns>-<ticks>-…(owner-encoded)mcp-dirs=1— orphanmcp-dirs=1— orphanmcp-dirs=1— the leak, permanentmcp-dirs=0— the startup sweep reclaimed itReading it bottom-up: the dirty-kill row reproduces the exact production failure this PR exists for (gateway death with a run in flight), on both trees; the last row is the entire point —
mainnever recovers the orphan, this branch does, and does so only after the child released its claim (it exits when its stdio breaks; the sweep confirmedfd-holder=nonebefore removing). The mid-turn row additionally shows the inherited-descriptor ownership operating in the real spawn path — gateway and child both hold the config — and the first row shows the ordinary lifecycle is untouched. The completed-turn row is also direct runtime evidence for the live-session finding: a captured live turn closes its session and releases its config at turn end on unmodifiedmaintoo, so turn-end cleanup is the design, not the defect.Durable ownership: the pre-
execclaim, proven with the settle switched OFF (real host, no mocks). The August 10 review asked for "a durable pre-exec handoff or retain uncertain candidates" rather than a fixed interval. This is the handoff. The driver runs the real exported sweep withsettleMs: 0— the timing bound is removed from the decision entirely — against a dir whose owning gateway is provably dead, while a process holds the inherited descriptor and its argv mentions neither the dir nor the config:A is the case the review said could not be established: with no settle and no argv reference, the directory is kept purely because a live process holds a descriptor into it — the state a forked-but-not-yet-
execed child is in. B is the necessary control: once the holder is gone the directory is reclaimed, so the claim is durable without turning the race into a permanent leak.The settle's own proof, still valid and still relevant off-Linux. The August 9 review asked for proof of the decisive case rather than of observed processes, so here is a driver that produces the damage first and only then shows the fix removing it.
The pre-exec child is modelled faithfully: a process whose argv does not mention the config dir (it receives the path via env, exactly like a forked child before
exec), which later becomes argv-visible by spawning the CLI-shaped… --mcp-config <dir>/mcp.jsonand reading that config — the moment a real child'sexeclands. Both scenarios use the sweep's real process scan (nolistCommandLinesoverride); command lines are never printed or stored.A is the control, and it is the part that makes B meaningful. With the settle disabled, the sweep removes the config and the child that
execs 1s later dies withENOENT— the exact availability failure described in the review, reproduced end to end. B is the same setup with the settle enabled: the child becomes argv-visible inside the window, the re-scan sees it, the dir is kept, and the child reads itsmcp.jsonsuccessfully. Without A, B would be an assertion with no evidence that the test can detect the failure at all.Two things surfaced only by running this on a real host, both now fixed in the diff:
unref()'d. An unref'd timer does not hold the event loop, so a runtime with nothing else pending exits before it fires and the sweep's promise never settles (Node exits 13,Unfinished Top-Level Await). Every unit test passed regardless, because the test runner keeps the loop alive on its own. The timer is now ref'd, with the trade-off recorded in a comment: a shutdown landing inside the settle waits it out, which is worth more than shaving seconds off an already-graceful stop.node -e <script> --mcp-config …for the argv-visible stand-in. Node parses argv after an inline script as its own flags and exits withbad option: --mcp-config, so the stand-in evaporated instead of becoming visible and scenario B reported a false negative. The driver now uses a script file, where argv after the script path belongs to the script.The August 11 review's three lifecycle findings — fixed and proven in the failing direction at head
126b1b42(real host, no mocks, Linux). One driver, run unchanged against two esbuild bundles of the exact sweep sources: A = the previous reviewed headd3714a91(pre-fix), B = this head. PASS/FAIL is judged against the fixed expectations, so the A run is the demonstration that each defect was real on this host — not a thought experiment. Real process scan, real/procprobes, real inherited fds, settle disabled (settleMs: 0), redacted as before:Case 1 is the P1 exactly as described: the sweep pointed at the symlink spelling of the root (what a symlinked
TMPDIRproduces), a live process holding an inherited descriptor into a dead-owner dir, argv blind, settle off — pre-fix the held config is deleted; at this head it is kept, and the 1c control shows the same dir through the same symlink is still reclaimed once the holder exits. Cases 2–5 are the security finding: pre-fix, dead-owner Gemini settings leak permanently (the sweep never even scans them); at this head they are reclaimed, the attempt prefix parses correctly (longest-first — misparsing it against the shorter prefix would have judged it legacy and kept it forever), a Gemini dir held by a live descriptor is kept even though no argv can ever reference it (env-carried), and a legacy Gemini dir is retained with the operator warn. The new vitest regression was also verified in the failing direction on the same host: with onlybundle-mcp-sweep.tsreverted tod3714a91,the real descriptor probe sees a holder through a symlinked temp rootfails in both vitest projects (expected [ Array(1) ] to deeply equal []— the held dir lands inremoved); restored, the file is 72/72 on Linux (the symlink case isit.runIf(linux), so it runs there rather than skipping as it does off-Linux). The abort finding is pinned at unit level with a realAbortController: an abort landing during the phase-two probe await keeps every candidate (removes nothing when the close lands during the phase-two probes), alongside the existing settle-abort and already-aborted cases.Continuity at the new head. The three existing exact-head drivers were re-run unchanged against the current-head bundle (
7f8aaae2) on the same host: owner-aware sweep 5/5, post-verdict settle race 2/2, inherited-descriptor ownership with settle off 2/2. The end-to-end A/B gateway run above was performed atd3714a91; the cycles since touch no live-turn semantics that run exercised (sweep decision logic, Gemini prepare writers, spawn parameters, and the rebase port described next), and the descriptor/ownership semantics it demonstrated are re-proven at this head by the drivers just listed.Rebase onto current
main+ port of the descriptor handoff to the live-session split (review follow-up, current head7f8aaae2). The August 11 review correctly flagged thatmain's #121566 splitclaude-live-session.tsinto concept modules and moved the persistent Claude child intoclaude-live-process.ts, so this branch's live-session edits targeted a file that no longer owned the spawn. Rebased onto currentmain(25e71131); the two live-session commits conflicted at whole-module scale and were resolved by takingmain's structure and porting the behavior to the new owner:spawnClaudeProcess(claude-live-process.ts) now hands the child the ownership descriptor atfork(inheritFd, preferring a per-attempt descriptor when one exists, since the attempt env is what the child actually reads);main's own suites rejected it — see the ownership bullet in the Approach section.main'swhole-run ownerspawn tests and theforks a lifecycle-started resume stallreliability case (the prepared config must survive a mid-run live-process close for the fork retry, then be reclaimed at run end) all pass at this head, with and against this branch's diff.The descriptor pinning tests moved with the code (the old
claude-live-session.capability.test.tswas deleted bymain's split):claude-live-turn.test.tsnow asserts the descriptor reaches the live-process spawn and is absent when the prepared run has none. At this head,tsgo:coreandtsgo:core:testare both 0 (the pre-existingapproval-gateway-resolverfailure seen at the previous base was fixed upstream in the meantime), the full touched suite is 425 passed + 2 platform-skipped across 18 files locally, and on the Linux hostbundle-mcp-sweep.test.ts+claude-live-turn.test.ts+cli-runner.reliability.test.tsare 306/306 with the symlink regression active — and still failing in both projects when onlybundle-mcp-sweep.tsis reverted to its pre-canonicalization revision.Why the previous head's CI gate was red — each failure traced, none left to luck.
check-plugin-sdk-api-baseline: addingownershipFdto the prepared backend changed the closure hash of exported harness types; the contract is regenerated withpnpm plugin-sdk:api:genin its own commit (65 lines changed in place, no export added or removed) andplugin-sdk:api:checkis 0 locally.checks-node-compact-large-1/-5: the failing cases were preciselymain's whole-run-owner and resume-stall-fork tests rejecting the adoption experiment — the adoption commit is dropped and all three files pass at this head (300/300 locally, reliability re-confirmed on the Linux host).check-lint: failed with no failing step in the job (runner-level), andpnpm lintis 0 locally at this head.Scope note (updated by this follow-up). Reclamation is effectively Linux-only today. Off-Linux the PID namespace is unreadable, so
nonson the sweeper's side keeps every owner-encoded dir by the fail-closed rule above — on macOS and Windows the sweep is a no-op rather than a partial reclaim. Gemini (env-carried) dirs add one more Linux-only condition on top: even where namespaces were provable, their removal additionally requires a usable descriptor probe, because no argv signal exists for them. That is the safe direction, and it is the deliberate consequence of trusting pid liveness only inside a proven namespace; a cross-platform ownership signal would be a separate change.Local verification at this head — every gate green, nothing waived.
tsgo:core,tsgo:core:testapproval-gateway-resolver.test.tsfailure present at the previous base was fixed upstream; both checks are fully clean at this head)format:check(oxfmt)lint(i18n + all oxlint shards)deadcode:full(knip--production+ all-exports),deadcode:exportscheck:temp-path-guardrails,check:runtime-sidecar-loaders,runtime-sidecars:check,check:no-conflict-markersOne batch-mode caveat, measured rather than assumed: running the whole
cli-runner+processdirectories as a single vitest batch can failexecute.supervisor-capture.test.tswith per-test times inflated ~250× (a 278s test that takes ~1s standalone) — the same cross-file runner interference already documented for the supervisor suites below; the file is green standalone on repeated runs, with and without this change.bundle-mcp-sweep.test.tsis 72/72 on Linux on its own (36 cases across theagents-coreandagents-supportprojects), including the eight added in the previous cycle and the seven added here: the real-probe symlinked-root regression plus its close-the-fd control, the abort-landing-in-phase-two case, and five Gemini cases (dead-owner reclaimed via the probe, attempt-prefix owner parse, probe-unavailable keeps env-carried dirs while argv still governs Claude dirs, live-owner + legacy Gemini kept with the warn, and the owned Gemini prefix recognized as this gateway's).bundle-mcp.gemini.test.tspins the writer side: prepared and attempt settings dirs are owner-encoded and each carries its own ownership descriptor.execute.supervisor-capture.test.tspins the spawn side: for a Gemini capture attempt, the child inherits the attempt descriptor in preference to the prepared one. Three cover the descriptor claim: a dir held by an inherited descriptor is kept even though argv never mentions it (the pre-execcase), an unheld dead-owner dir is still removed, and an unavailable probe (off-Linux) falls back to the argv re-scan. Two more pin the live-process handoff: the descriptor reaches that spawn, and is absent when the prepared run has none. Three cover the settle: it sits between the two scans, it does not happen when there is nothing to remove, and — because those two injectsleepand so would never exercise the module's own timer — one runs the real timer path and asserts the elapsed time. Two cover cancellation, and deliberately avoid the same trap: one uses a realAbortControlleragainst the real timer withsettleMs: 30_000, so the assertion is that the suite finishes in seconds rather than hanging for thirty; the other passes an already-aborted signal and asserts the sweep never even waits. Both assert nothing was removed.Correcting an earlier note in this body. A previous revision claimed two pre-existing upstream failures (three
restart sentinelcases inserver-startup-post-attach.test.ts, and aslack boundary dtsstep ofpnpm lint). Re-measured today against a clean clone ofmainatc9d39979:server-startup-post-attach.test.tsis 70/70 onmainand on this branch, and theslack boundary dtsstep does not fail on either. Those notes were true of an oldermainand went stale; they are withdrawn rather than left to send a reviewer looking for failures that are not there. For completeness, today'smaindoes have one unrelated lint failure this branch predates —src/auto-reply/reply/get-reply-run.media-only.test.ts:22, an unusedapplySessionHintsimport — andpnpm linton this branch is clean.One note on
src/process/supervisor/**— measured, not assumed. This change touches the supervisor (the descriptor has to reachspawn), and running that directory as a batch reports failures. They are not from this branch: measured on the same machine, unmodifiedmainreports more of them than this branch does, and the count swings between runs in both directions. Run file-by-file, every supervisor suite passes identically with and without this change (2, 24, 2, 3, 24, 18). The batch failures are cross-file interference in the runner, and the per-file result is the one that means anything. Flagging it so the same red output does not read as a regression introduced here.Tests
bundle-mcp-sweep.test.ts(name-encoded scheme, owner liveness, PID-namespace fail-closed / shared-temp-root, legacy-never-removed, operator warn, argv-spawn race, post-verdict settle ordering + real-timer path + no-settle-without-candidates, abort-during-settle + already-aborted + abort-in-phase-two cancellation, symlinked-root real-probe regression, Gemini families under the same policy, fail-closed),bundle-mcp.gemini.test.ts(owner-encoded Gemini settings dirs + ownership descriptors),execute.supervisor-capture.test.ts(attempt descriptor preferred at spawn),claude-live-turn.test.ts(live-process descriptor handoff),bundle-mcp.test.ts(config-write rollback via the Claude path),bundle-mcp-runtime.test.ts(shared-writer rollback),bundle-mcp.resume.test.ts(resume-hash stability),server-startup-post-attach.test.ts(sweep sidecar mocked so the startup test doesn't touch the real tmpdir).🤖 Generated with Claude Code
https://claude.ai/code/session_01TiH8Npb28iWm4ZkXVrN4HJ