Skip to content

fix(cli-runner): sweep orphaned bundle MCP temp dirs at gateway startup - #105643

Closed
totobusnello wants to merge 7 commits into
openclaw:mainfrom
totobusnello:fix/bundle-mcp-temp-sweep
Closed

totobusnello wants to merge 7 commits into
openclaw:mainfrom
totobusnello:fix/bundle-mcp-temp-sweep

Conversation

@totobusnello

@totobusnello totobusnello commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

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-memory cleanup() callback returned from prepareModeSpecificBundleMcpConfig. 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, mirroring sidecars.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, from injectClaudeMcpConfigArgs), 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:

    openclaw-cli-mcp-<pid>-<boot8>-<nsInode>-<startTicks>-<random>
    

    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 (boot8 differs from the current Linux boot id), or the pid reused by a different process (owner's /proc/<pid>/stat start 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//proc liveness is namespace-local, so a shared /tmp mount 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 (nons on either side, off-Linux/restricted) keeps the dir (over-protect) — each namespace reclaims its own dead owners. boot8 mismatch 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 warn with a count for explicit operator cleanup (stop the gateway, remove stale openclaw-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-exec window is closed by a descriptor inherited at fork, 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 at fork, strictly before exec, so from that instant the directory carries a durable claim — visible in /proc/<pid>/fd throughout 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's cleanup, 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 (spawnClaudeProcess in claude-live-process.ts, where current main'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 other supervisor.spawn call sites under src/agents are bash tooling and carry no preparedBackend, 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 that runCliAgentInternal invokes preparedBackend.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 unmodified main either. Second — decisive — current main tests the opposite ownership by name: cli-runner.spawn.test.ts has keeps non-capture live prepared backend cleanup with the whole-run owner and keeps captured live prepared backend cleanup with the whole-run owner, and cli-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 (/proc is 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 yet execed still carries the parent's argv, so nothing references its config until exec lands — 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, and exec follows fork within microseconds (libuv's immediate execvp). Waiting POST_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. schedulePostReadySidecarTask hands its run an AbortSignal; 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>/fd links report the resolved target while the sweep's candidates keep the temp root's own spelling, so a symlinked TMPDIR would 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-* (and openclaw-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 at mkdtemp (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 at fork; 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 -axww on POSIX, /proc walk fallback for minimal Linux containers without procps, PowerShell Get-CimInstance Win32_Process on Windows, all with timeouts.

  • The mcp.json write in bundle-mcp.ts is 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: compatibility concern (a newly-upgraded gateway no longer changes the treatment of an older gateway's dirs) and the merge-risk: availability concern (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:

novo temp dir: /tmp/openclaw-cli-mcp-V6tUnQ
>>> systemctl restart com run em voo...
LEAK REPRODUZIDO: /tmp/openclaw-cli-mcp-V6tUnQ sobreviveu ao restart do gateway
=== total dirs: 26

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:

novo temp dir detectado: /tmp/openclaw-cli-mcp-EB9IqM
SIGKILL enviado
dir foi limpo apesar do kill

Focused tests. bundle-mcp-sweep.test.ts covers, 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.ts asserts a config-write failure rolls the temp dir back end-to-end through the Claude backend, and bundle-mcp-runtime.test.ts asserts the shared writeTemporaryBundleMcpJson itself rolls back on a failed write. Lint (pnpm lint), tsgo:core, tsgo:core:test, check:temp-path-guardrails clean; deadcode:exports adds no export.

Rebase + shared-writer consolidation (review follow-up). The July 26 rebase onto current main first kept an inline mkdtemp + write + rollback for the Claude backend; per review, head 6ef864aa instead reuses main's shared writeTemporaryBundleMcpJson. 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 head 6ef864aa on a real Linux host (Node v22) with its real defaults: real process.kill(pid, 0) liveness, real boot id, real /proc/<pid>/stat start-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):

# #105643 owner-aware bundle-MCP sweep — real-host proof (head 6ef864aa)
kernel=7.0.0-27-generic  node=v22.22.2  platform=linux
real defaults: boot-id=5d******  self-pid/start=[live]  pid1/start=[live]  dead-pid=[unused]
scan-root=[tmp]/oc-proof-105643-******  (isolated; unmocked process.kill + /proc + boot-id)

PASS  live        expected=kept    got=kept
PASS  dead-owner  expected=removed got=removed
PASS  fresh-dead  expected=removed got=removed
PASS  pid-reuse   expected=removed got=removed
PASS  legacy      expected=kept    got=kept

legacy warning: bundle MCP temp sweep: retained 1 legacy (pre-ownership) temp dir(s); these are never auto-removed to stay rolling-upgrade safe. To reclaim pre-upgrade leaks, stop the gateway and remove stale openclaw-cli-mcp-* dirs by hand.
RESULT: ALL PASS (5/5)

The legacy old-format dir is kept (rolling-upgrade safe) with the operator warn firing; a reused pid (pid alive, real /proc start 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 /proc verification, 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 by bundle-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 exported sweepOrphanedBundleMcpTempDirs (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: real process.kill(pid, 0), real boot id, real /proc/<pid>/stat start time, and real /proc/self/ns/pid, in an isolated scan root. Redacted (no ns inode, boot id, tokens, endpoints, or host paths):

# #105643 PID-namespace fail-closed sweep — real-host proof (head c7cb42c462)
kernel=7.0.0-27-generic  node=v22.22.2  platform=linux
real defaults: boot=<redacted>  self-ns=<redacted>  self-start=[live]  foreign-ns=<synthetic ≠ self>  dead-pid=[unused]
scan-root=[tmp]/oc-proof-105643-ns-******  (isolated; unmocked process.kill + /proc + /proc/self/ns/pid)

PASS  live        expected=kept    got=kept
PASS  dead        expected=removed got=removed
PASS  freshDead   expected=removed got=removed
PASS  pidReuse    expected=removed got=removed
PASS  foreignNs   expected=kept    got=kept
PASS  ownerNons   expected=kept    got=kept
PASS  legacy      expected=kept    got=kept

legacy warning: bundle MCP temp sweep: retained 1 legacy (pre-ownership) temp dir(s); these are never auto-removed to stay rolling-upgrade safe. To reclaim pre-upgrade leaks, stop the gateway and remove stale openclaw-cli-mcp-* dirs by hand.
RESULT: ALL PASS (7/7)

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 in bundle-mcp-sweep.test.ts.

Rebase onto current main + owner-identity cache (review follow-up, head 2caef2d1ab, now superseded by d3714a91). The previous head was 383 commits behind and had gone CONFLICTING again. Rebased onto current main as a single commit; two files conflicted and both were semantic, not textual:

  • server-startup-post-attach.ts — main deleted the sidecars.memory block entirely (scheduleGatewayMemoryBackend no longer exists anywhere in src/). Resolution follows main (block dropped) and keeps only this PR's addition, the sidecars.bundle-mcp-temp-sweep post-ready task.
  • server-startup-post-attach.test.ts — sidecar-count assertions. main removed one gateway-lifetime sidecar and this PR adds one post-ready sidecar, so each count is main's value plus this PR's delta: post-ready 1→2, gmail 2→3, lifetime stays 3, postReadySidecarCount 3→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 /proc reads 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 on fs.readFile/fs.readlink and 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 head d3714a91 — the exported sweepOrphanedBundleMcpTempDirs itself, not a reimplementation — and re-run on a real Linux host with its real defaults: real process.kill(pid, 0) liveness, real boot id, real /proc/<pid>/stat start-time verification, real /proc/self/ns/pid, isolated scan root. Redacted (no tokens, endpoints, host paths, or boot id):

# #105643 owner-aware bundle-MCP sweep — real-host proof (head d3714a91)
kernel=7.0.0-27-generic  node=v22.23.2  platform=linux
real defaults: boot-id=5d******  self-pid/start=[live]  pid1/start=[live]  dead-pid=[unused]
scan-root=[tmp]/oc-proof-105643-******  (isolated; unmocked process.kill + /proc + boot-id)

PASS  live        expected=kept     got=kept
PASS  dead-owner  expected=removed  got=removed
PASS  fresh-dead  expected=removed  got=removed
PASS  pid-reuse   expected=removed  got=removed
PASS  legacy      expected=kept     got=kept

owner-identity cache: first=1244.5us cached-avg=0.1840us  stable=true
  (10k cached calls; no /proc re-read after the first)

legacy warning: bundle MCP temp sweep: retained 1 legacy (pre-ownership) temp dir(s); these are never auto-removed to stay rolling-upgrade safe. To reclaim pre-upgrade leaks, stop the gateway and remove stale openclaw-cli-mcp-* dirs by hand.

RESULT: ALL PASS (5/5)

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 /proc start 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 /proc I/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, isolated TMPDIR, real claude CLI on subscription auth, real turns through the agent RPC), measuring the rendered config directory at every lifecycle boundary. Same driver, same host, both trees:

Boundary A — unmodified main B — this branch
after a completed turn mcp-dirs=0 mcp-dirs=0 — the per-turn lifecycle leaks nothing on either tree
mid-turn, child running fd-holder-pids=none fd-holder-pids=<gateway>,<child> — the inherited claim, live
the dir's own name openclaw-cli-mcp-SVmIaN (legacy, unowned) openclaw-cli-mcp-<pid>-<boot8>-<ns>-<ticks>-… (owner-encoded)
after a dirty gateway kill mid-turn mcp-dirs=1 — orphan mcp-dirs=1 — orphan
next gateway boot mcp-dirs=1 — the leak, permanent mcp-dirs=0 — the startup sweep reclaimed it

Reading 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 — main never recovers the orphan, this branch does, and does so only after the child released its claim (it exits when its stdio breaks; the sweep confirmed fd-holder=none before 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 unmodified main too, so turn-end cleanup is the design, not the defect.

Durable ownership: the pre-exec claim, 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 with settleMs: 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:

# #105643 — inherited-descriptor ownership, real-host proof
kernel=7.0.0-27-generic  node=v22.23.2
boot-id=5d******  scan-root=[tmp]/oc-proof-105643-fd-******
settle DISABLED (settleMs=0) — nothing below depends on a timing bound

PASS  A pre-exec holder   expected=kept (descriptor)      got=kept + config-present=true
PASS  B holder gone       expected=removed (reclaimable)  got=removed

RESULT: ALL PASS (2/2)

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.json and reading that config — the moment a real child's exec lands. Both scenarios use the sweep's real process scan (no listCommandLines override); command lines are never printed or stored.

# #105643 — post-verdict settle: real-host race proof
kernel=7.0.0-27-generic  node=v22.23.2
boot-id=5d******  scan-root=[tmp]/oc-proof-105643-race-******
real process scan (no argv override)  pre-exec window=1000ms  settle=3000ms

PASS  A no-settle    expected=removed + child loses config   got=removed + CONFIG-LOST:ENOENT
PASS  B settle       expected=kept + child keeps config     got=kept + CONFIG-OK

RESULT: ALL PASS (2/2)

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 with ENOENT — 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 its mcp.json successfully. 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:

  • The settle timer must not be 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.
  • The first version of the proof driver used node -e <script> --mcp-config … for the argv-visible stand-in. Node parses argv after an inline script as its own flags and exits with bad 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 head d3714a91 (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 /proc probes, real inherited fds, settle disabled (settleMs: 0), redacted as before:

# A — pre-fix head d3714a91 (same driver, same host)
FAIL  1 symlink root, live holder   expected=kept (descriptor, canonical)  got=REMOVED WHILE HELD
PASS  1c holder gone, same symlink  expected=removed (reclaimable)         got=removed
FAIL  2 gemini dead owner           expected=removed (reclaimed)           got=LEAKED
FAIL  3 gemini attempt dead owner   expected=removed (prefix parsed)       got=LEAKED
PASS  4 gemini held by descriptor   expected=kept (fd, env-carried)        got=kept   (vacuous: pre-fix never scans gemini dirs)
FAIL  5 gemini legacy               expected=kept + warned                 got=kept + warned=false
RESULT: FAILURES (2/6)

# B — this branch (first run at 126b1b42; re-run unchanged at the current head 7f8aaae2, identical)
PASS  1 symlink root, live holder   expected=kept (descriptor, canonical)  got=kept
PASS  1c holder gone, same symlink  expected=removed (reclaimable)         got=removed
PASS  2 gemini dead owner           expected=removed (reclaimed)           got=removed
PASS  3 gemini attempt dead owner   expected=removed (prefix parsed)       got=removed
PASS  4 gemini held by descriptor   expected=kept (fd, env-carried)        got=kept
PASS  5 gemini legacy               expected=kept + warned                 got=kept + warned=true
RESULT: ALL PASS (6/6)

Case 1 is the P1 exactly as described: the sweep pointed at the symlink spelling of the root (what a symlinked TMPDIR produces), 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 only bundle-mcp-sweep.ts reverted to d3714a91, the real descriptor probe sees a holder through a symlinked temp root fails in both vitest projects (expected [ Array(1) ] to deeply equal [] — the held dir lands in removed); restored, the file is 72/72 on Linux (the symlink case is it.runIf(linux), so it runs there rather than skipping as it does off-Linux). The abort finding is pinned at unit level with a real AbortController: 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 at d3714a91; 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 head 7f8aaae2). The August 11 review correctly flagged that main's #121566 split claude-live-session.ts into concept modules and moved the persistent Claude child into claude-live-process.ts, so this branch's live-session edits targeted a file that no longer owned the spawn. Rebased onto current main (25e71131); the two live-session commits conflicted at whole-module scale and were resolved by taking main's structure and porting the behavior to the new owner:

  • spawnClaudeProcess (claude-live-process.ts) now hands the child the ownership descriptor at fork (inheritFd, preferring a per-attempt descriptor when one exists, since the attempt env is what the child actually reads);
  • the cleanup-adoption half of the earlier port was dropped after current main's own suites rejected it — see the ownership bullet in the Approach section. main's whole-run owner spawn tests and the forks a lifecycle-started resume stall reliability 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.ts was deleted by main's split): claude-live-turn.test.ts now asserts the descriptor reaches the live-process spawn and is absent when the prepared run has none. At this head, tsgo:core and tsgo:core:test are both 0 (the pre-existing approval-gateway-resolver failure 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 host bundle-mcp-sweep.test.ts + claude-live-turn.test.ts + cli-runner.reliability.test.ts are 306/306 with the symlink regression active — and still failing in both projects when only bundle-mcp-sweep.ts is 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: adding ownershipFd to the prepared backend changed the closure hash of exported harness types; the contract is regenerated with pnpm plugin-sdk:api:gen in its own commit (65 lines changed in place, no export added or removed) and plugin-sdk:api:check is 0 locally. checks-node-compact-large-1/-5: the failing cases were precisely main'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), and pnpm lint is 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 nons on 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.

Gate Result
tsgo:core, tsgo:core:test 0 (a pre-existing approval-gateway-resolver.test.ts failure present at the previous base was fixed upstream; both checks are fully clean at this head)
format:check (oxfmt) 0
lint (i18n + all oxlint shards) 0
deadcode:full (knip --production + all-exports), deadcode:exports 0
check:temp-path-guardrails, check:runtime-sidecar-loaders, runtime-sidecars:check, check:no-conflict-markers 0
vitest — the touched bundle-MCP, live-process/turn, capture + runtime suites (18 files at this head) 427 passed, 2 platform-skipped (macOS; the skips are the Linux-only symlink case, which runs on the Linux host above)

One batch-mode caveat, measured rather than assumed: running the whole cli-runner + process directories as a single vitest batch can fail execute.supervisor-capture.test.ts with 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.ts is 72/72 on Linux on its own (36 cases across the agents-core and agents-support projects), 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.ts pins the writer side: prepared and attempt settings dirs are owner-encoded and each carries its own ownership descriptor. execute.supervisor-capture.test.ts pins 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-exec case), 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 inject sleep and 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 real AbortController against the real timer with settleMs: 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 sentinel cases in server-startup-post-attach.test.ts, and a slack boundary dts step of pnpm lint). Re-measured today against a clean clone of main at c9d39979: server-startup-post-attach.test.ts is 70/70 on main and on this branch, and the slack boundary dts step does not fail on either. Those notes were true of an older main and went stale; they are withdrawn rather than left to send a reviewer looking for failures that are not there. For completeness, today's main does have one unrelated lint failure this branch predates — src/auto-reply/reply/get-reply-run.media-only.test.ts:22, an unused applySessionHints import — and pnpm lint on this branch is clean.

One note on src/process/supervisor/** — measured, not assumed. This change touches the supervisor (the descriptor has to reach spawn), and running that directory as a batch reports failures. They are not from this branch: measured on the same machine, unmodified main reports 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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 12, 2026
@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 12, 2026
@clawsweeper

clawsweeper Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 11, 2026, 10:16 AM ET / 14:16 UTC.

ClawSweeper review

What this changes

The PR adds crash-safe startup cleanup for abandoned CLI bundle-MCP temporary files while preserving files still owned by live provider processes.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

this 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
Reviewed head: 7f8aaae289e3e3b7edcb63c229520897a512e3d3

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real-host proof and a coherent lifecycle repair, pending rebase and process-boundary review.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The PR context provides exact-head, after-fix real-host evidence that abandoned files are reclaimed while active provider processes retain their files.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The PR context provides exact-head, after-fix real-host evidence that abandoned files are reclaimed while active provider processes retain their files.
Evidence reviewed 6 items Current main creates temporary MCP directories: The shared writer creates an OS temporary directory and returns only an in-memory cleanup callback; Claude and Gemini use it for their MCP settings.
Current main cleanup cannot survive process death: Cleanup is invoked only after the awaited run returns, so gateway termination before this block leaves the temporary directory behind.
Gateway has a suitable asynchronous startup owner: The existing post-ready sidecar facility carries a stopped predicate and abort signal, providing the lifecycle boundary for a cancellable recovery sweep.
Findings None None.
Security None None.

How this fits together

CLI-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]
Loading

Before merge

  • Resolve merge risk (P1) - The branch currently conflicts with main and needs rebase plus exact-head validation before merge.
  • Resolve merge risk (P1) - The inherited ownership descriptor crosses the generic supervisor boundary; confirm it stays runtime-private and cannot be serialized or supplied through plugin-facing data.
  • Resolve merge risk (P1) - Unsupported or indeterminate liveness checks retain files by design, which is safe but may leave cleanup incomplete outside the proven Linux path.
  • Complete next step (P2) - Manual review is required because the branch conflicts with main and changes the supervisor capability flow across process boundaries.
Agent review details

Security

None.

PR surface

Source +830, Tests +802, Generated 0. Total +1632 across 22 files.

View PR surface stats
Area Files Added Removed Net
Source 14 853 23 +830
Tests 7 812 10 +802
Docs 0 0 0 0
Config 0 0 0 0
Generated 1 65 65 0
Other 0 0 0 0
Total 22 1730 98 +1632

Review metrics

Metric Value Why it matters
Production versus test delta raw +1,730/-98 across 22 files; substantial test coverage added alongside the cross-process implementation This is a large repair for a cleanup defect, so its owner-boundary and security properties need review beyond test volume.
Lifecycle boundaries changed 3: CLI setup, child-process spawn, gateway post-ready startup The repair crosses all stages that create, retain, and reclaim temporary MCP files.

Stored data model

Persistent data-model change detected: serialized state: src/agents/cli-runner/bundle-mcp-runtime.test.ts, serialized state: src/agents/cli-runner/bundle-mcp-runtime.ts, serialized state: src/agents/cli-runner/bundle-mcp-sweep.test.ts, serialized state: src/agents/cli-runner/bundle-mcp.test.ts, serialized state: src/agents/cli-runner/execute.supervisor-capture.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #105641
Summary: This branch is the candidate repair for the canonical abandoned bundle-MCP temporary-file issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Rebase and validate ownership isolation (recommended)
    Resolve the conflict, then rerun exact-head tests and verify that the inherited descriptor remains private to child spawning.
  2. Pause the cleanup redesign
    Defer the PR if descriptor privacy or live-process preservation cannot be shown after the rebase.

Technical review

Best 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.

Labels

Label justifications:

  • P1: A gateway crash can leave CLI-agent MCP temporary files behind, while unsafe cleanup could disrupt active provider runs.
  • merge-risk: 🚨 compatibility: The PR changes CLI provider subprocess setup and the lifetime of their temporary MCP configuration.
  • merge-risk: 🚨 security-boundary: A new inherited descriptor crosses the generic child-process supervisor to establish ownership.
  • merge-risk: 🚨 availability: A liveness misclassification could remove MCP configuration still required by a running CLI agent.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR context provides exact-head, after-fix real-host evidence that abandoned files are reclaimed while active provider processes retain their files.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR context provides exact-head, after-fix real-host evidence that abandoned files are reclaimed while active provider processes retain their files.

Evidence

Acceptance criteria:

  • [P1] Rebase onto current main and run focused bundle-MCP cleanup tests.
  • [P1] Leave one provider process active, restart the gateway, and verify that only abandoned temporary files are removed.
  • [P1] Inspect the child-process payload to confirm the inherited descriptor remains non-serialized and inaccessible to plugin-facing callers.

What I checked:

  • Current main creates temporary MCP directories: The shared writer creates an OS temporary directory and returns only an in-memory cleanup callback; Claude and Gemini use it for their MCP settings. (src/agents/cli-runner/bundle-mcp-runtime.ts:20, 29fd6aaf6bb3)
  • Current main cleanup cannot survive process death: Cleanup is invoked only after the awaited run returns, so gateway termination before this block leaves the temporary directory behind. (src/agents/cli-runner.ts:1812, 29fd6aaf6bb3)
  • Gateway has a suitable asynchronous startup owner: The existing post-ready sidecar facility carries a stopped predicate and abort signal, providing the lifecycle boundary for a cancellable recovery sweep. (src/gateway/server-startup-post-attach.ts:272, 29fd6aaf6bb3)
  • Current-source provenance: The current temporary-file writer lines date to the recent CLI fallback-delivery work, identifying a recent contributor to the active boundary. (src/agents/cli-runner/bundle-mcp-runtime.ts:20, e5be751e4f5f)
  • PR implementation and proof: The reviewed PR head adds a fail-closed ownership sweep, preserves legacy directories, and its supplied exact-head real-host evidence is marked proof sufficient. (src/agents/cli-runner/bundle-mcp-sweep.ts:1, 7f8aaae289e3)
  • Child-process descriptor contract: Node's child-process types permit numeric file descriptors in stdio options, supporting the branch's inherited-descriptor transport rather than a serialized ownership token. (/usr/local/lib/node_modules/webpack/node_modules/@types/node/child_process.d.ts:575)

Likely related people:

  • joshavant: Current-main blame attributes the temporary bundle-MCP writer to this recent CLI runtime change. (role: recent area contributor; confidence: medium; commits: e5be751e4f5f; files: src/agents/cli-runner/bundle-mcp-runtime.ts)
  • steipete: Merged the bundle-MCP consolidation that established the shared adapter/runtime surface this repair extends. (role: recent adjacent contributor; confidence: medium; commits: 18ef074f4409; files: src/agents/bundle-mcp-adapter.ts, src/agents/cli-runner/bundle-mcp-runtime.ts)

Rank-up moves

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

  • Rebase and resolve the current conflict, then rerun exact-head validation.
  • Confirm that the descriptor is unavailable to plugin-facing and serialized supervisor inputs.

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 (41 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-10T19:05:43.178Z sha 4af6475b0d637bf7fa56e87c41ee6f8c13d5d572 :: needs real behavior proof before merge. :: [P1] Forward the ownership descriptor to the live-session child
  • reviewed 2026-08-10T20:54:08.899Z sha 132b56aae6a116416b70c4ece2b64eb9cee3b2da :: needs real behavior proof before merge. :: [P1] Transfer temporary-config cleanup to the live session
  • reviewed 2026-08-10T22:51:42.016Z sha d3714a91ec3416b1e01c0cfa2f947a9eca7f6351 :: needs changes before merge. :: [P1] Canonicalize descriptor ownership paths | [P2] Sweep Gemini's orphaned MCP settings too | [P2] Recheck cancellation before phase-two removal
  • reviewed 2026-08-10T23:00:29.159Z sha d3714a91ec3416b1e01c0cfa2f947a9eca7f6351 :: needs changes before merge. :: [P1] Canonicalize descriptor ownership paths | [P2] Recheck cancellation before phase-two removal | [P2] Sweep Gemini temporary MCP settings too
  • reviewed 2026-08-11T09:00:05.927Z sha 126b1b422743da8acc254f0133f73164dfa4e365 :: needs changes before merge. :: [P1] Port ownership to the current live-process owner
  • reviewed 2026-08-11T10:14:20.087Z sha 945c710e8df5ffad84dd689218936d91aa33ff28 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-11T12:01:03.738Z sha 7f8aaae :: needs maintainer review before merge. :: none
  • reviewed 2026-08-11T12:07:41.777Z sha 7f8aaae :: needs maintainer review before merge. :: none

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review — added after-fix exact-head proof (real host ps scanner, no mocks) showing orphan removal with persistent-session and concurrent-gateway directories preserved. See the updated Evidence section.

@clawsweeper

clawsweeper Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. and removed 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. labels Jul 12, 2026
@totobusnello

totobusnello commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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 src/agents/cli-runner/ and src/gateway/ (temp-dir sweep + a startup sidecar), with no changes to UI, dependencies, date formatting, or locale.

I'll rebase once the base CI settles so the head goes green. Flagging for triage in the meantime.

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Branch updated onto healed main (the check-dependencies failure was base dead code in ui/src/components/config-form.*, reconciled upstream by #105792 — peers #105711/#105709 merged green on the same check). Full suite is now green (56 pass, 0 fail) and the diff is unchanged from the platinum/proof-sufficient state.

@totobusnello

Copy link
Copy Markdown
Contributor Author

On the "Persistent data-model change detected" merge-readiness item: this PR introduces no data-model or schema change. The only state the flagged bundle-mcp-* files touch is the per-run bundle-MCP temp directory (os.tmpdir()/openclaw-cli-mcp-*/mcp.json) — ephemeral, created and reclaimed in place, never persisted or migrated. There's no store, table, or on-disk schema involved; the flagged paths are the sweep implementation plus its test fixtures, so there's no migration/upgrade-compat artifact to add.

Also: the head is now rebased on today's main (merge of 35c9c76), which clears the earlier "branch behind" item — required checks are green on b40a87.

@totobusnello

Copy link
Copy Markdown
Contributor Author

Rebuilt on current main to clear the merge conflict. New head 907e9d9c5f — one commit replacing the previous 19 (9 of which were main merges). The branch is MERGEABLE again.

Same change as before: 8 files, +899/-25. The three added files (bundle-mcp-sweep.ts, bundle-mcp-sweep.test.ts, bundle-mcp-runtime.test.ts) are byte-identical to the previous head, so nothing new to re-read there.

No production file conflicted. bundle-mcp.ts, bundle-mcp-runtime.ts, and server-startup-post-attach.ts applied cleanly, and the two APIs this PR builds on — writeTemporaryBundleMcpJson(prefix, value, fileName, atomic) and schedulePostReadySidecarTask({...}) — still have the same signatures.

Two test hunks needed a decision:

1. server-startup-post-attach.test.ts. #120503 renamed the sidecar stop helper: tests now call a local wrapper stopTrackedPostReadySidecarsAfterCloseStarted(...) instead of testing.stopPostReadySidecarsAfterCloseStarted(...) directly. Neither side of the conflict was right on its own — this branch called the old name (now gone), while main asserts toHaveLength(2) and knows nothing about the sweep sidecar this PR adds. Resolved as toHaveLength(3) with the new wrapper. All five sidecar-count assertions in that file go 2 → 3, which is exactly the one sidecar this PR registers.

2. bundle-mcp.test.ts. #120115 (Agent Plugins bundle format) added imports to the same block this branch touched. Resolved as the union: main's new helpers plus this branch's vi.

Local validation on the exact head (Node 26.5, macOS):

Gate Result
tsgo:core, tsgo:core:test 0
vitest — the 4 touched suites (7 files) 146/146
deadcode:full — knip --production + all-exports 0
lint — i18n + all oxlint shards 0
format:check — oxfmt 0
check:temp-path-guardrails, check:runtime-sidecar-loaders, runtime-sidecars:check, deadcode:exports, check:no-conflict-markers all pass

runtime-sidecars:check is green, so the new sweep sidecar needs no baseline update.

Still needed on current main: there is no startup reclamation path for openclaw-cli-mcp-* directories. The only cleanup is the in-memory callback, which dies with the gateway that created it — so a crash or restart with runs in flight still leaves the rendered loopback URL and resolved tokens on disk.

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Both blocking items from the August 8 review are addressed at head 2caef2d1ab, and the branch is MERGEABLE again.

1. Real behavior proof now matches the head. The previous proof targeted 6ef864aa/c7cb42c462 and went stale when the branch was rebuilt. The same driver — the exported sweepOrphanedBundleMcpTempDirs, esbuild-bundled from this exact head's source, real process.kill(pid, 0), real boot id, real /proc/<pid>/stat, real /proc/self/ns/pid, isolated scan root — was re-run on a real Linux host at 2caef2d1ab: 5/5 PASS, with the legacy dir retained and the operator warn firing. Full redacted output is in the PR body.

2. P2 — the immutable gateway owner identity is cached. bundleMcpOwnedMkdtempPrefixName() now memoizes its promise, so preparation no longer rereads boot id, PID namespace and start ticks before queue admission. Measured on the same real-host run: first resolution ~840µs, every subsequent call ~0.26µs, identity stable. Memoizing the promise (not the value) also collapses concurrent first-time callers onto one read; it cannot poison the cache because all three readers swallow their own errors and resolve to a fallback, so the promise never settles rejected. A new focused test spies on fs.readFile/fs.readlink and asserts neither is called after the first resolution.

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 — main deleted the sidecars.memory block entirely (resolution follows main, keeping only this PR's sidecars.bundle-mcp-temp-sweep addition), and the sidecar-count assertions are main's values plus this PR's delta.

Pre-existing upstream failures, unrelated to this branch — both reproduce identically on unmodified main, so please don't attribute them here: three restart sentinel cases in server-startup-post-attach.test.ts (67 passed / 3 failed on main and on this branch alike) and the slack boundary dts step of pnpm lint (@slack/types portability under extensions/slack/**). Everything this PR touches is clean: bundle-mcp-sweep.test.ts 42/42, oxfmt --check clean, oxlint clean, and tsgo reports nothing in any file this PR changes.

@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The P1 from the August 9 review is closed at head 2cac73e3f2, with the decisive case proven rather than argued.

1. child-execs-after-final-scan — closed by settling after the death verdict, not by another scan. You were right that the second argv scan is a time-of-check/time-of-use boundary; no number of scans closes it. But a child in that blind spot was forked strictly before its owner died, which is strictly before the death verdict, and exec follows fork within microseconds. So the sweep now waits POST_VERDICT_SETTLE_MS (5s) between proving an owner dead and the final re-scan, which guarantees any surviving child is argv-visible by then. That turns the re-scan into a decisive check.

This deliberately is not the ownership protocol you suggested: there is no atomic handoff available to a process that has not execed yet. Removing the race was cheaper and stronger than trying to arbitrate it.

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 … --mcp-config <dir>/mcp.json and reading that config. Both scenarios use the sweep's real process scan, no listCommandLines override:

PASS  A no-settle    expected=removed + child loses config   got=removed + CONFIG-LOST:ENOENT
PASS  B settle       expected=kept + child keeps config     got=kept + CONFIG-OK

A is the control and it is the point: with the settle disabled, your race lands and the child dies with ENOENT — the failure reproduced end to end. Without A, B would be an assertion with no evidence the test can detect the failure at all. The five owner-liveness cases were re-run on the same host at this head: 5/5. Full redacted output in the body.

3. Two bugs that only running it exposed, both fixed and both in the body: the settle timer must not be unref()'d (an unref'd timer does not hold the event loop, so the sweep's promise never settled — Node exits 13; every unit test still passed, because the runner keeps the loop alive), and the proof driver's first stand-in used node -e … --mcp-config, which Node rejects as its own flag, producing a false negative in scenario B.

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 restart sentinel cases, and a slack boundary dts lint step). Re-measured today against a clean clone of main at c9d39979: server-startup-post-attach.test.ts is 70/70 on main and on this branch, and that lint step does not fail on either. Those notes were true of an older main and went stale; they are withdrawn rather than left to send you looking for failures that are not there.

Every gate is green at this head: tsgo:core / tsgo:core:test, format:check, pnpm lint, deadcode:full, deadcode:exports, the four sidecar/temp-path guardrail checks, and 152/152 across the four touched suites.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The P2 is fixed at head 57f92b49. The P1 is left as-is, deliberately — see below.

P2 — sidecar cancellation is now honored. You were right on both halves, and I verified the premise before acting: schedulePostReadySidecarTask does hand its run an AbortSignal (server-startup-post-attach.ts:276), and the sweep's registration dropped it. The signal is now forwarded and respected in two places: the settle resolves immediately on abort, and an aborted run returns with every candidate kept and nothing removed. A cleanup must not outlive the cancellation that asked it to stop.

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 sleep proves ordering, not behaviour): one uses a real AbortController against the real timer with settleMs: 30_000, so the assertion is that the suite finishes in seconds instead of hanging for thirty; the other passes an already-aborted signal and asserts the sweep never waits at all. Both assert nothing was removed.

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 fork — that is, before exec — so the sweep could test the lock and see the directory as in use during exactly the window that argv cannot cover. That closes the race by construction instead of bounding it. It is a larger change (it touches prepare and spawn) and I did not want to build it speculatively.

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: tsgo:core / tsgo:core:test, format:check, pnpm lint, deadcode:full, deadcode:exports, the sidecar/temp-path guardrails, and 156/156 across the four touched suites.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The P1 is addressed at head 4af6475b, with the durable handoff you asked for rather than a wider timing margin.

The claim is a descriptor inherited at fork. Preparation opens a descriptor on the rendered config and hands it to the CLI child. Inheritance happens at fork — strictly before exec — so from that instant the directory carries a claim visible in /proc/<pid>/fd, throughout exactly the window in which the child's argv still belongs to its parent and names no config. The sweep reads that claim before deciding.

The distinction that makes this a contract rather than a bound: argv answers which config is this process using, and only after exec. The descriptor answers is anyone holding this directory at all, and it survives the fork→exec transition because inheritance precedes it.

Proven with the settle switched off entirely, so nothing in the result depends on an interval:

settle DISABLED (settleMs=0) — nothing below depends on a timing bound

PASS  A pre-exec holder   expected=kept (descriptor)      got=kept + config-present=true
PASS  B holder gone       expected=removed (reclaimable)  got=removed

A is the case your review said the code could not establish: settleMs: 0, a provably dead owner, no argv reference anywhere, and the dir is kept purely because a live process holds a descriptor into it. B is the control that keeps this from being a trade of a race for a permanent leak: once the holder is gone, the dir is reclaimed. Real host, real /proc, real exported sweep.

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 execed yet. You were right to reject a margin as a substitute for a contract, and that claim was simply wrong — descriptor inheritance is such a handoff, and it was available the whole time.

Cost. This adds ~180 production lines: a SpawnStdioEntry that accepts a parent descriptor, an opt-in openOwnershipFd on the shared temp-config writer, the field threaded from prepare to spawn, and the /proc/*/fd probe. Measured at 75ms for a full scan across 210 processes, paid once at startup. I recognise this cuts against your size-versus-benefit note, and it is the honest price of the boundary you specified — worth stating plainly so it can be weighed rather than discovered.

One measurement to pre-empt a misread. This touches src/process/supervisor/**, and running that directory as a batch reports failures. They are not from this branch: unmodified main reports more of them on the same machine, and the count swings in both directions between runs. File-by-file, every supervisor suite passes identically with and without this change (2, 24, 2, 3, 24, 18). I measured the baseline before writing this rather than asserting it — the same discipline I failed at in an earlier revision of this body, and had to retract.

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 tsgo:core / tsgo:core:test / format:check / pnpm lint / deadcode:full / deadcode:exports / the sidecar and temp-path guardrails all clean.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

You found a real gap and it was mine. Fixed at head 132b56aa.

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 claude-live-session.ts, so that path stayed on the timing-based recheck. Worse than an oversight in the abstract — the live session is the longest-lived holder of a bundled config, the one that persists across turns for days (#73244). The path that most needed the durable claim was the one running without it.

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 supervisor.spawn under src/agents: five in total, and the other three are bash tooling that carries no preparedBackend, so they are genuinely out of scope rather than merely unexamined.

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 inheritFd). Reverting the fix fails it in both vitest projects; with the fix, both pass. I checked that explicitly, because a test that passes without the power to detect the regression would be worth nothing here — which is the same objection you raised against my earlier settle test, and it was correct then too.

Proof re-run at this head (the body describes 132b56aa now, so the earlier runs no longer describe this code): owner-liveness cases 5/5, the descriptor claim with the settle switched off 2/2, the delayed-child settle control 2/2 — 9/9 on a real Linux host.

Gates: tsgo:core, tsgo:core:test, format:check, pnpm lint, deadcode:full, deadcode:exports, check:temp-path-guardrails, runtime-sidecars:check all clean, and 217/217 across the twelve touched bundle-MCP, live-session and gateway suites.

The src/process/supervisor/** batch note from my previous comment still applies unchanged: those batch failures reproduce more heavily on unmodified main than here, and every supervisor suite passes file-by-file with and without this change.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Head d3714a91 — rebased onto current main (the branch had gone CONFLICTING), with the live-session finding addressed in code AND measured against the real runtime, end to end.

The end-to-end proof you asked for. An ephemeral gateway built from each tree — isolated state, isolated TMPDIR, a real claude CLI child on subscription auth, real turns through the agent RPC — measuring the rendered config directory at every lifecycle boundary, A/B against unmodified main. The full table is in the body; the two rows that decide the review:

  • After a completed live turn: mcp-dirs=0 on BOTH trees. A captured live turn deliberately closes its session at turn end (claude-live-session.ts — the MCP capture key lives in the process environment, so a captured turn must end its process before the key is released). There is no persistent child left behind for the turn-end cleanup to hurt: turn-end release is the design, on unmodified main too. This is direct runtime evidence on the exact scenario your P1 described.
  • Dirty gateway kill mid-turn, then next boot: main keeps the orphan forever; this branch reclaims it — and only after the child released its claim. The mid-turn measurement also caught the inherited descriptor operating in the real spawn path: gateway and child both holding the config, on a directory whose name carries the full owner encoding, while the same measurement on main shows an unowned legacy name and no holders.

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 main; one conflict (upstream refactored the capability-test helper to an options object; resolved as the union). One pre-existing failure to not attribute here: tsgo:core:test fails on unmodified main in src/infra/approval-gateway-resolver.test.ts — a file this branch does not touch, byte-identical to main (git diff = 0 lines). Everything else is green at this head: tsgo:core, format:check, pnpm lint, deadcode:full, deadcode:exports, the sidecar/temp-path guardrails, and 269/269 across the fourteen touched suites.

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.

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@totobusnello

Copy link
Copy Markdown
Contributor Author

@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.

@clawsweeper

clawsweeper Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

totobusnello and others added 5 commits August 11, 2026 11:06
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
@totobusnello

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Rebased onto current main (25e7113) and ported the ownership handoff to the new live-process owner, exactly as the finding asked: spawnClaudeProcess in claude-live-process.ts now hands the child the inherited descriptor at fork and adopts preparedBackend.cleanup once the spawn succeeds, releasing it exactly once at process close. The three pinning tests moved to claude-live-turn.test.ts with the code. Everything was re-proven at this exact head before pushing: the real-host drivers (6/6, 5/5, 2/2, 2/2), 138/138 on Linux with the symlink regression active (and still failing when only the sweep is reverted), 427 green locally, and both tsgo checks now fully 0. Details in the updated body's rebase note.

@clawsweeper

clawsweeper Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

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).
@totobusnello

Copy link
Copy Markdown
Contributor Author

@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 (ownershipFd changed exported closure hashes; no export added or removed). The node-shard failures turned out to be current main rejecting the cleanup-adoption experiment by its own named contract (whole-run owner spawn tests and the resume-stall fork case) — that commit is dropped, ownership stays with the run as main tests it, and the body's Approach section documents the withdrawal with those tests as evidence. check-lint failed at runner level with no failing step; pnpm lint is 0 locally. All drivers re-run at this exact head on the Linux host (6/6, 5/5, 2/2, 2/2), 306/306 there including the reliability case, 425 green locally, both tsgo checks and plugin-sdk:api:check at 0.

@clawsweeper

clawsweeper Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bundled MCP temp configs (openclaw-cli-mcp-*) leak when the gateway exits with runs in flight

1 participant