Skip to content

fix(exec): settle process lifecycles and approval outcomes - #177940

Merged
joshavant merged 8 commits into
mainfrom
fix/160864-stack-b
Oct 20, 2026
Merged

joshavant merged 8 commits into
mainfrom
fix/160864-stack-b

Conversation

@joshavant

@joshavant joshavant commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #160864. Stack unit 2 of 5; A has landed: #177939. This PR now targets main. Next: #177941.

Current source: captured upstream f7908148d72e52c7deeca5520e1dfa71fa0c2655 → head ea2d849e032286701405f53611c1fd1b4b2a1e3f. The signed merge keeps prior B as its first parent and the A-containing main checkpoint as its second parent. C, D, and E are unchanged. This unit has 4,471 no-renames added-plus-deleted lines (+3,211/−1,260) across 62 files. Prior evidence below remains bound to its named source; new preparation results and limitations follow.

What Problem This Solves

Process cancellation and automation changes can report completion before cleanup is confirmed or report a committed change as rolled back when follow-up cleanup fails.

User Impact

Stop results distinguish a requested cancellation from confirmed termination. Failed cleanup retains ownership for reconciliation and blocks replacement; rejected stream updates leave the existing source running. A committed update remains reported as committed even if later cleanup needs attention.

Why This Change Was Made

Join process-tree and backend finalization, recheck process identity after awaited cleanup, and commit stream updates before stopping their prior source. Consume one-use approval only through its live owner and matching committed transaction, then acknowledge durable resolution before best-effort follow-ups. Preserve captured ownership through background-result publication. The existing sandbox lifecycle keeps setup and cleanup while sharing container allocation with the later stream adapter.

This depends on A's background-result mutation classification. It supplies the ordinary approval and container-allocation contracts used by C and D.

Derived from the stream work by Agustin Rivera (@eleqtrizit); contributor credit is preserved in the commit.

Evidence

Preparation after A landed — October 20

A landed as bc3092fceb5d1353a60647c21c816198ee54d501. The actual B/main conflict resolution preserves upstream's continuation-fixture refactor and B's existing scheduler-registration/wake handling. The background-result test keeps its required database-worker routing exactly once; main's assertion-baseline shrink remains intact. Sixty of B's 62 affected files retain identical bytes and modes to prior B; only the continuation fixture and assertion baseline required reconciliation. No additional production change, dependency, test, timeout, or authorization relaxation was introduced by this preparation.

The existing continuation E2E passed on prepared tree dcd02da7a1c1db5cf2a78e89455b38cb592eeedc: eight model steps, two durable run receipts, rearming, creator disconnect, and reconnect/history behavior. Command: node scripts/run-vitest.mjs test/e2e/qa-lab/runtime/gateway-authorized-continuation.e2e.test.ts --maxWorkers=1. One test passed; test body 35.844s, Vitest 69.23s, full wrapper 339.078s including the isolated cold runtime build. These are test execution costs, not product performance measurements. New-head CI seconds are not yet available.

The owning E2E type graph (17.578s), scoped typed lint (18.702s), formatting, assertion-safety and line-cap ratchets, and whitespace checks pass. The initial pre-commit line-cap invocation selected the old ancestry merge base and flagged unchanged upstream core-descriptors.ts; that file is byte-identical to captured main. The supported explicit prepared-base selection passed without source, baseline, or policy changes. This tooling qualification remains recorded with the original failure.

Fresh independent review found no actionable P0–P2 findings in the resolution. Its scope was the resolution and supplied owner/caller context, not a new whole-campaign audit; it did not include every E2E cleanup definition. Root separately inspected the cleanup owner, and the real continuation execution passed. Unchanged behavior reuses the source-bound evidence below. New-head pull-request CI run 39394835555 is attached to ea2d849e0322 and in progress; no current-head broad CI success is claimed. B is prepared, not merged.

Prior controlled restack evidence (0f5116e05126)

The controlled restack reconciles seven actual conflict paths against pinned upstream. This unit reconciles the Docker lifecycle owner and Gateway cron fixture with upstream changes.

An automatically merged namespace-recovery regression in D was reproduced by the existing reused-PID test and fixed: each owner proves its namespace before shared PID/start-time classification. Unknown namespaces remain conservative.

Focused proof and review: 45 affected sandbox allocation/access/cleanup cases passed (52.8s wrapper). The final shared integration run passed 365 cases, including 129 cron/lifecycle/drain cases (411.9s wrapper total). Core and Gateway fixture types, focused lint/format, line-cap, assertion, mock-export and SQLite worker ratchets passed; the resolution review was scoped-clean.

Prior CI: run 39388782157 completed successfully on prior head 0f5116e0512656f8047ab49660b985f3fbaa1284: 83 successful jobs, 23 skipped. This is prior-head evidence, not CI clearance for the prepared merge. No manual workflow dispatch or rerun occurred. Earlier runs remain bound to their original heads.

Scope remains operation-level, with ordinary streaming and mixed requests. The message-tool interface is unchanged; broad prose consistency and native Codex/Claude enforcement remain outside this guarantee. Historical source qualifications and unresolved failures below remain in force. No new benchmark is claimed.

Prior review and CI triage

Fresh hosted review at f93bc59b707e reports no actionable code findings. Its installed process/package evidence remains tied to the earlier named revisions; the revised composition has focused harness proof. Exact-head CI run39380683082 completed successfully.

CI repair and stack integration

Preserved real exports in the logger mock and explicitly documented isolated external/runtime mock owners. The standalone B checkout passes 34 exec/lifecycle cases (105.01s wrapper), scoped typed lint and mock-export checks. Upstream independently repaired the native-runtime fixtures; integration retains its public service registration and capability assertions plus the isolated probe setting. The background-result owner retains live authority, cancellation, exact replay, commit and publication checks while accepting upstream’s removal of an unused success-return field; media still consumes the message ID from the actual commit receipt.

The complete repaired source 992e8d57e9b passed the canonical build (252.91s), production/test/UI type checks, scoped typed lint, import-cycle/export guards and shrink ratchets. Canonical prompt snapshots are current. Two fresh scoped repair reviews found no actionable issue; their diff-only limitations are retained. Test costs include cold compilation and owner waits; hosted CI cost for these new heads is not yet available. The repaired pinned-base assembly exactly matches that integration tree.

After integration onto fixed upstream 7a255a1990a3b0c280339fc730672bdf9d8cc122, all 30 native/background-result cases pass (145.04s wrapper), as does the selected media promotion-failure/retry case (89.87s; 10 unrelated cases excluded). Production and agent-test types, scoped lint, assertion/mock ratchets and the 372-file line-cap ratchet pass. The canonical complete-stack CI plan passes with 98 selected rows (57.28s); this runs planning locally, not hosted CI. A tree comparison verifies that only the three inspected conflicts differ from Git’s automatic merge; all other upstream integrations are unchanged. Each PR remains below 10,000 changed lines. No benchmark, workflow rerun/dispatch or merge was performed. Fresh full-build evidence is for the repaired pre-rebase tree; the three conflict resolutions received the focused post-rebase checks above.

Prior review repairs

The description consumer now checks its capability contract instead of duplicating whole prose strings. The two exit-order tests await the actual processExited operation after process completion, retaining the stale-output and pending-loss assertions. Before repair, the description suite had 13 passes/1 failure and the exit-order suite had 9 passes/2 failures; afterward they pass 14/14 and 11/11. Narrowed liveness wording assertions and shrank the assertion-safety baseline from two casts to one for lazy-process-tool.ts.

The affected native-plugin fixtures now register through the public plugin/service contract and read the registered ACP runtime; no retired private facade or getRuntime shim remains. The Custodian fixture advertises/provides the current chat-history method. These failures were reproduced, then the native suites passed 21 cases and the browser case passed using the existing supported Chromium override. This is fixture repair, not native Codex/Claude stream-enforcement parity.

The continuation fixture now captures the real scheduler channel through its post-ready registration and delivers wakes when advancing the test clock. Its old prefix matched the earlier history channel, while the real worker timer ignored the fake Gateway clock. The initial delayed 84.874s pass is not credited as a fix. With the registration correction, the full continuation passes all eight model steps, two durable run receipts, rearm and reconnect/history assertions in 18.398s, before the original 60-second real-time deadline. No production scheduler, timeout, or authorization assertion changed. All seven existing helper consumers also pass: 46 cases across eight files including continuation, 177.27s grouped wrapper wall.

The other focused group passes 54 cases in 194.55s wrapper wall; browser proof costs 92.65s including build (about 17s test body). Four selected type graphs pass in 64.78s; the final cron/E2E graphs, typed lint, line-cap, shrink-only assertion ratchet and whitespace checks pass. Grouped costs are not per-file measurements; revised-head CI costs are unavailable. Fresh scoped P3 review found no actionable findings in these repairs; it is static review of this delta, not full-campaign or native-enforcement certification.

  • Removed four duplicate conversational-wrapper cases; the retained process-supervisor suite has nine behavioral cases. The complete approval-lifetime/process-supervisor/Tool Search sibling run passed 27 tests in 62.184s grouped wrapper wall (node scripts/run-vitest.mjs <three files> --maxWorkers=1). CI seconds are unavailable.
  • The new borrowed-handle proof ships in C, where the real cron mutation consumer exists. On the revised assembled tree it prepares the one-use handle, waits at storage preparation, and then commits or rejects the protected cron write using a real admitted owner. Current authority survives manager retirement; revoking that owner before the transaction prevents both the job write and approval consumption. This is composed coverage of B's contract, not a B-only test result.
  • Affected test type graphs and scoped lint/format passed. The fresh supplied-delta review found no actionable findings; it does not replace the retained broader review or execution evidence.

Selected verbatim Vitest output from the local assembled-tree run above, which preceded the final C fixture correction. The quoted test files are byte-identical at packaged source 4733afc513466 and final complete-stack source 191c7fe10d189; this is not a separate intermediate-unit run. These two composed consumer tests ship in C and exercise the protected cron write.

 ✓ |gateway-database-workers| src/gateway/exec-approval-manager.lifetime.test.ts > ExecApprovalManager lifetime > settles a borrowed current approval with its cron write after storage preparation waits 584ms
 ✓ |gateway-database-workers| src/gateway/exec-approval-manager.lifetime.test.ts > ExecApprovalManager lifetime > settles a borrowed revoked approval with its cron write after storage preparation waits 527ms

Retained earlier proof (not rerun after rebase):

  • 583 selected cases across 30 files passed at bd6dbed4c773; the original published B head 92a87cbdddf4 had unchanged production code. Its later test-only work had separate proof: a byte-identical worker-fixture relocation, 13 registered lifecycle cases, and focused static checks.
  • Lifecycle replay: 166 cases / 152.006 seconds wrapper wall. Other grouped runtime proof: 398 / 295.895 seconds. The remaining 19 completed cases come from an interrupted run, which is not counted as an overall pass. Final lifecycle cleanup check: 13 / 74.995 seconds; fixture-relocation check: 1 / 71.483 seconds.
  • The broad runs used node scripts/run-vitest.mjs <selected files>; separate per-file --maxWorkers=1 wall measurements and CI seconds were not recorded. Selected core/test types, lint and formatting passed.
  • Stale duplicated stop-before-commit/count assertions were removed after mapping all six scenarios to retained registered lifecycle coverage. The original failures remain recorded; passing retries alone are not the justification.
  • Scoped code, test-cutover and cleanup reviews found no actionable P0–P2 findings. Whole-stack installed process/package proof and performance are in fix(agents): preserve safe inspection and outcomes during recovery #177943; they are not individual B performance results.

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 20, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR preserves process cleanup ownership and accurately reports cancellation requests, committed automation changes, and approval outcomes.

Example: An operator disables a running stream automation, but process cleanup fails after the disable commits.

  • Before: The old source can be interrupted before the update commits, and cleanup does not confirm process-tree extinction.
  • After: The disable commits before interruption, remains successful, and retains cleanup failure state without admitting a replacement.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful repair with no remaining actionable finding; current authority proof is substantive, while fresh validation is strongest through the in-process composition and aggregate CI is incomplete.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (logs): The supplied composed approval run exercises the new consumption contract through real admitted authority and the cron transaction, including revocation during storage preparation and verification that neither protected write commits; process cleanup regressions cover pending finalization, failed cleanup, and foreign-scope rejection.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Stopping work can appear complete before cleanup is confirmed, and automation or approval actions can appear unsuccessful after their durable changes already committed.
Reason: The maintainer-authored direction fixes concrete outcome and cleanup contracts without introducing configuration or a new public capability.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: the lifecycle repair remains useful, prior findings are addressed, and no new actionable defect was found.

Priority: P2
Reviewed head: f93bc59b707e68c919c888f7db2c591fc231796a

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Installed process/package evidence remains tied to earlier named stack revisions; the revised composition has focused harness evidence rather than a fresh installed-entry-point run.
Agent review details

How this fits together

Agent exec/process tools and Gateway cron mutations feed existing process, approval, database, and session owners, which return execution outcomes and persist committed results.

flowchart TD
  A[Agent request] --> B[Exec and process tools]
  B --> C[Process supervisor]
  C --> D[Cleanup and terminal result]
  A --> E[Approval manager]
  E --> F[Cron mutation owner]
  F --> G[SQLite transaction]
  G --> C
  D --> H[Session result publication]
Loading

Technical review

Best possible solution:

Land the existing-owner lifecycle repair in stack order once its prerequisite and required current-head CI are clear.

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

Current-main source shows transport completion being used without confirming process-tree cleanup; supplied regression scenarios exercise delayed cleanup and rejected or committed cron mutations, but this read-only review ran no reproduction.

Is this the best way to solve the issue?

The repair keeps process, approval, cron mutation, and transcript decisions with their existing owners; the extracted allocation code replaces its original implementation rather than adding competing policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Requested-stop observations keeps the original intent (6d786ff: Separate a confirmed requested stop from an unexpected process failure.)
  • Stream mutation and lifecycle ordering changes intended behavior with a stated reason (14c1305: Consolidate lifecycle ownership while preserving source-effect authority and accepting bounded internal ordering tradeoffs; this PR explains commit-before-stop and cleanup custody changes.)
  • One-use approval consumption keeps the original intent (3f5e7f8: Consume allow-once approvals atomically to prevent replay.)
  • Approval persistence ownership keeps the original intent (5e2b898: Move approval persistence into existing workers while retaining durable decision semantics.)
  • Approval acknowledgement keeps the original intent (f462f36: Acknowledge durable decisions before best-effort delivery notices can time out the resolving request.)
  • Container allocation keeps the original intent (4ba02b8: Share container behavior across Docker and Podman while preserving backend-specific policy.)
  • Background result publication keeps the original intent (cbc53ac: Keep bundled session reads and authority with their worker owners.)
  • Exec continuation guidance changes intended behavior with a stated reason (204d2b1: Compress model-facing instructions; this PR corrects their description of exit-triggered continuation and cancellation confirmation.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 98742bc adds src/gateway/cron-stream-job-owner.ts:75 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 98742bc2c7f2; files: src/gateway/cron-stream-job-owner.ts)
  • rick-stevens-ai: Raw commit 4e371eb adds src/agents/bash-tools.process.ts:211 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4e371ebb67e5; files: src/agents/bash-tools.process.ts)

PR surface

Source +492, Tests +1375, Docs +24, Other 0. Total +1891 across 61 files. Added test files: 4.

View PR surface stats
Area Files Added Removed Net
Source 29 1174 682 +492
Tests 29 1712 337 +1375
Docs 2 31 7 +24
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 61 2918 1027 +1891

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This repairs bounded process and automation lifecycle failures without evidence of an urgent widespread outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-20T02:13:20.699Z sha 92a87cb :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-20T04:42:28.769Z sha 668cb1571e121193136be5017ef5210da1cff39d :: needs changes before merge. :: [P2] Update the canonical-description consumer alongside the new guidance | [P2] Make exit-order tests await the newly asynchronous cleanup boundary
  • reviewed 2026-10-20T04:53:33.548Z sha 668cb1571e121193136be5017ef5210da1cff39d :: needs changes before merge. :: [P2] Update the canonical-description consumer alongside the new guidance | [P2] Make exit-order tests await the asynchronous cleanup boundary
  • reviewed 2026-10-20T06:01:02.677Z sha 096a2e7 :: needs changes before merge. :: [P2] Preserve real exports in the new first-party mock factories

Reviewed October 20, 2026, 2:42 AM ET / 06:42 UTC (Revision 5).

@joshavant
joshavant marked this pull request as ready for review October 20, 2026 04:33
@joshavant

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 20, 2026
@clawsweeper clawsweeper Bot removed the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Oct 20, 2026
Base automatically changed from fix/160864-stack-a to main October 20, 2026 08:25
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: ea2d849e032286701405f53611c1fd1b4b2a1e3f
  • Maintainer: @joshavant
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/exec-approval-result.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/container-allocation.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/agents/sandbox/docker.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/gateway/exec-approval-consumption.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/gateway/exec-approval-manager.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/gateway/exec-approval-manager.types.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts commands Command implementations labels Oct 20, 2026
Preserve B's lifecycle changes while reconciling the continuation fixture with main and retaining its database-worker test routing.
@openclaw-barnacle openclaw-barnacle Bot removed scripts Repository scripts commands Command implementations labels Oct 20, 2026
@joshavant
joshavant enabled auto-merge (squash) October 20, 2026 08:43
@joshavant
joshavant merged commit 1c1b6e0 into main Oct 20, 2026
174 checks passed
@joshavant
joshavant deleted the fix/160864-stack-b branch October 20, 2026 09:04
@joshavant

Copy link
Copy Markdown
Collaborator Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
…177940)

* fix(sessions): preserve durable input and current execution authority

* fix(sessions): retain original source checks through input admission

* test(sessions): preserve admission and history fixture contracts

* test(ai): consume canonical npm pack JSON

* fix(exec): settle process lifecycles and approval outcomes

Preserve process ownership through cleanup and route committed stream updates through the existing lifecycle owner. Keep approval consumption and committed outcome diagnostics consistent for ordinary execution.

Co-authored-by: Agustin Rivera <[email protected]>

* test(exec): align lifecycle consumers with current owners

* test(exec): preserve mock exports and isolate lifecycle effects

---------

Co-authored-by: Agustin Rivera <[email protected]>
obviyus added a commit that referenced this pull request Nov 15, 2026
…99079)

## Problem

When the agent starts a process that must keep running, OpenClaw stops it.

- A completed host `exec` call cancels its whole process tree. This stops `cmd &` and `nohup cmd &`. On Linux, the child subreaper also adopts and stops processes that left with `setsid` or a double fork, such as `nginx` and `sshd`.
- A one-shot `openclaw agent --local` run cancels every process in its exec scope when it exits. This also stops `background: true` services.
- Result: on Linux, no start style survives the CLI. The agent reports success, and the service is gone before anything can use it.
- `background: true` services also inherit the 1800 s exec timeout unless the model passes `timeoutSeconds: 0`.
- The model-facing text was wrong. `background` said "Start an independent service now; survives request Stop", but the service did not survive the CLI.

#150750 made the killing deliberate. Its real problem was that OpenClaw's own relay and owner processes stayed alive with the user's processes. It fixed that by stopping the user's processes too.

## Fix

This is PR 1: stop killing, stay bounded.

1. **Hand off on a normal exit.** When the root command exits normally, the process-group owner (anchor) does not signal its group. It reads the process table, reports every live process the command left, stops observing lineage, and exits. On Linux it exits as the subreaper, so adopted processes go to init. If a released process still holds the command's stdout or stderr pipe, the anchor keeps draining that pipe until it closes, so the service never gets SIGPIPE or EPIPE when it logs. The cap bounds these drain anchors.
2. **Every survivor is accounted for.** The report has no size limit. It includes the owner's group members, the processes the Linux subreaper adopted (these are the owner's direct children, and they stay the command's), and all of their descendants, also those in a new session (for example the `sleep` under `setsid sh -c 'sleep 300 & wait'`). If the process table cannot be read, the anchor stops the tree like a cancellation instead of releasing processes it cannot name.
3. **Adopt survivors as sessions.** Each survivor becomes an ordinary background session in the process registry, under the session that ran the command.
   - The tool result names its PID and session ID. `process list` shows it, and `process kill` stops it.
   - It is pinned to its start time. Every signal re-checks that identity, so a reused PID is never signalled.
   - OpenClaw drops it within 5 s of its exit. Gateway stop stops it.
4. **A stop counts only when the exit is observed.** OpenClaw sends SIGTERM, then SIGKILL after the 5 s grace, then waits up to 2 s for the recorded identity to disappear. If a signal is denied (for example EPERM after a UID change) or the process does not disappear, the record stays, the session is marked as cleanup-uncertain, and the result says so. This applies to `process kill`, session reset and delete, Gateway stop and over-limit survivors. A later stop retries.
5. **Admission caps.** At most 16 services per session and 64 per Gateway. A service is a background session or an adopted survivor.
   - A `background: true` start reserves its slot before approval and startup and holds it until its session runs or startup fails, so concurrent starts cannot pass the limit.
   - Over the cap, a new `background: true` start fails with an error that names `process list` and `process kill`.
   - Over the cap, a foreground command's new survivors are stopped by identity, and the result lists their PIDs and the reason. A survivor whose stop is not confirmed stays tracked over the limit, so nothing escapes custody.
   - OpenClaw never stops an older process to make room.
6. **Stopping stays the same where it matters.** Timeout, no-output timeout, cancellation, request Stop, `process kill`, memory limit, host loss and launch failure still stop the whole tree, including Linux `setsid` and double-fork escapees. Scopes with `required-all` cleanup (the local TUI shell, managed workers, cron exit watchers, update repair, desktop helpers) keep strict cleanup on exit.
7. **Every reset path stops everything the session runs.** Chat `/new` and `/reset`, Gateway `sessions.reset` and session delete all call one shared step, `stopSessionResetProcesses`, after the session's subagents stop and before the replacement conversation is committed. It stops in-flight commands, `background: true` services and adopted survivors by identity. If a stop is not confirmed, the reset fails and asks to retry. Durable processes are not affected.
8. **One-shot exit hands services off.** At the end of `openclaw agent --local`:
   - `background: true` services and adopted survivors are handed off, and only in-flight work is cancelled. The order from #177940 stays: hand-off, then scope cleanup, then join.
   - The CLI prints what it left running (PID and command) to stderr.
   - If the CLI dies without cleanup, host loss still stops work that was not handed off.
9. **No built-in timeout for services.** `background: true` no longer inherits the 1800 s default. An explicit `timeoutSeconds` or a configured `tools.exec.timeoutSeconds` still applies. In a subagent or cron run that can wait for the command with `sessions_yield`, the default still bounds that wait, as current main requires.
   - `host=node` ignores `background` and runs synchronously through remote `system.run`, so it is not a service. It keeps the ordinary node timeouts (a 1800 s program timer and a longer Gateway invocation deadline, as designed in 6872be8). Without this, `exec {host:"node", background:true}` sent a zero program timer and a 10 s Gateway deadline, and the caller got an outcome-unknown failure before the command returned.
10. **The model sees the truth.** The tool result names every survivor and every stop, with PID and reason. The `background` description and the background-process docs state the real lifetime.

The relay and the anchor still exit after every completed command, so #150750 does not regress.

## Proof

"Base" is the behaviour without this change. "Previous head" is the head that review rated (`3549c2b`, then `bb2b295`).

| # | Proof | Tier | Base / previous head | Head |
|---|---|---|---|---|
| 1 | 50 calls that each leave a survivor: 16 are adopted, 34 are stopped with the reason in the result, 0 relay or anchor processes remain (#150750); `process list` shows them; `process kill` stops one by identity; an exited one drops out within one reap interval; Gateway stop ends the rest | vitest-source, macOS | previous head: fails | pass |
| 2 | One command leaves 20 survivors: 16 tracked, 4 stopped, every PID named, none alive and untracked; then `background: true` is refused and a new survivor is stopped | vitest-source, macOS | previous head: fails (only 16 reported) | pass |
| 3 | Two concurrent `background: true` starts at 15 of 16: exactly one starts | vitest-source, macOS | previous head: fails (both start, 17 running) | pass |
| 4 | A survivor's child in a new session is tracked; stopping the session ends both | vitest-source, macOS | previous head: fails (child untracked) | pass |
| 5 | Real Linux run in `node:24-bookworm` (root, subreaper active) of `bash-tools.exec-group-cleanup.real.test.ts`, `subagent-reset.lifecycle.test.ts` and `worker.runtime.test.ts`: survivors, cap, reservation, descendant closure, `setsid sh -c 'sleep & wait'`, timeout of `setsid`/double-fork children, unconfirmed stops, chat/RPC reset | vitest-source, Linux container (fresh `pnpm install`, no skips) | `bb2b295`: 8 failed (every survivor test: the subreaper-adopted survivors were classed as helpers, so nothing was reported) | 96 of 96 passed, 0 skipped |
| 6 | Signals to a survivor are denied (EPERM): reset fails, the session stays running with cleanup uncertainty in its output, the process is still tracked; after signals work, a retry stops it and settles the record | vitest-source, macOS | previous head: fails (reset reported success, record dropped) | pass |
| 7 | Chat `/reset` (`initSessionState`) and Gateway `sessions.reset` each stop a running `background: true` service and a `cmd &` survivor before the new session is committed | vitest-source, macOS | previous head: chat path fails (both processes still alive); RPC path passes | pass, both paths |
| 9 | Detached styles (`node &`, `nohup`, plain `&`, double fork) survive a completed call; a timeout still stops what the call started; one-shot cleanup hands off and prints services and stops in-flight work; handed-off servers that log every request answer 20 of 20 requests 10 s after the run | vitest-source, macOS | — | pass |
| 10 | A timeout stops `setsid` and double-fork children | vitest-source, Linux container | — | pass (part of row 5) |
| 11 | Supervisor, relay, anchor, exec, process tool, exec follow-up (`sessions_yield`), cron exit watchers (`required-all` extinction), session reset/delete, agent delete, TUI, desktop and chat session suites | vitest-source, macOS | — | see "Test results" below |
| 12 | CLI lifecycle, real model: `openclaw agent --local` with five start styles; the server is probed 0, 3 and 10 s after the CLI exits, then sent 20 requests | source (`ocx src`), macOS | base (`669576890a1f`): 1 of 5 alive (only the double-fork daemon, which leaves the group); `background: true` answers 200 during the run, then dies at CLI exit | 5 of 5 alive, each answers 20 of 20 requests; the CLI prints every handed-off PID; 0 relay/anchor processes after the servers stop |
| 13 | Gateway lifecycle, real model, one session: start `background: true`, `nohup &` and plain `&` servers; check them in the next turn; chat `/reset`; start again; RPC `sessions.reset`; start again; stop the Gateway | source (`ocx src -- gateway run`), macOS | base: `nohup &` and plain `&` die at the end of their own call; `background: true` survives chat `/reset` and RPC reset | all 3 survive across turns; chat `/reset` stops all 3; RPC reset stops all 3; Gateway stop stops all 3; 0 relay/anchor processes left |
| 14 | Upgrade: latest stable `2026.11.3` runs on a state dir with `tools.exec.timeoutSeconds: 90`, then this head (`doctor --fix --non-interactive`, as update does) runs on the same state | stable: published npm package; head: source (`ocx src`), macOS | stable reads 90 | head still reads 90 after doctor; a `background: true` call gets a deadline 90 s after its start ("times out in 1m30s"); without a configured timeout, the same call on head has no deadline |
| 15 | Linux: five styles plus a timeout case in `node:24-bookworm` as root, `openclaw agent --local`, Node runtime | dist-nodts, Linux (this head's `dist/` laid over the `2026.11.5-beta.3` install) | published `2026.11.5-beta.2`: 0 of 5 alive | 5 of 5 alive, each answers 20 of 20 requests 10 s after the CLI exits; the timeout case stops both the `setsid` server and the double-fork daemon |
| 16 | `exec {host:"node", background:true}` through `createExecTool` to the node `system.run` invocation keeps the ordinary 1800 s program timer and 1805 s Gateway deadline, and completes | vitest-source, macOS | previous head: fails (program timer 0) | pass |

<details>
<summary>Redacted captures (CLI and Gateway, head and base)</summary>

CLI, base `669576890a1f`, `nohup … &` (the agent's own check fails, then the probes):

```text
exec: nohup python3 -m http.server 18972 --bind 127.0.0.1 --directory /tmp > /tmp/oc-srv-18972.log 2>&1 &
result: completed 0, (no output)
exec: sleep 2; curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:18972/
result: 000 (Command exited with code 7)
reply: FAILED 18972 000
after_exit_plus=0s curl=000 · 3s curl=000 · 10s curl=000 · twenty_requests_after_10s=0/20
```

CLI, head, `nohup … &`:

```text
exec result: pid 70493 (…/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp) keeps running as background
  session mild-sage:2b822b901780: process list shows it and process kill mild-sage:2b822b901780 stops it. Its later
  output to this command's stdout/stderr is discarded; redirect it to a file to keep it.
reply: STARTED 18982 200
stderr: [openclaw] Left running after this run (OpenClaw no longer tracks them; stop with kill <pid>):
          pid 70493  …/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp
after_exit_plus=0s curl=200 · 3s curl=200 · 10s curl=200 · twenty_requests_after_10s=20/20
```

Gateway, base:

```text
[turn1] exit=0 reply=STARTED 
[after-start-1] port=18991 curl=200
[after-start-1] port=18992 curl=000
[after-start-1] port=18993 curl=000
[turn2] exit=0 reply=18991=200 18992=000 18993=000 
[after-next-turn] port=18991 curl=200
[after-next-turn] port=18992 curl=000
[after-next-turn] port=18993 curl=000
[turn3] exit=0 reply=✅ Session reset. 
[after-chat-reset] port=18991 curl=200
[after-chat-reset] port=18992 curl=000
[after-chat-reset] port=18993 curl=000
[turn4] exit=0 reply=STARTED 
[after-start-2] port=18991 curl=200
[after-start-2] port=18992 curl=000
[after-start-2] port=18993 curl=000
[rpc-reset] ok=true
[after-rpc-reset] port=18991 curl=200
[after-rpc-reset] port=18992 curl=000
[after-rpc-reset] port=18993 curl=000
[turn5] exit=0 reply=STARTED 
[after-start-3] port=18991 curl=200
[after-start-3] port=18992 curl=000
[after-start-3] port=18993 curl=000
[after-gateway-stop] port=18991 curl=000
[after-gateway-stop] port=18992 curl=000
[after-gateway-stop] port=18993 curl=000
helpers_left=0
```

Gateway, head:

```text
[turn1] exit=0 reply=STARTED 
[after-start-1] port=18991 curl=200
[after-start-1] port=18992 curl=200
[after-start-1] port=18993 curl=200
[turn2] exit=0 reply=18991=200 18992=200 18993=200 
[after-next-turn] port=18991 curl=200
[after-next-turn] port=18992 curl=200
[after-next-turn] port=18993 curl=200
[turn3] exit=0 reply=✅ Session reset. 
[after-chat-reset] port=18991 curl=000
[after-chat-reset] port=18992 curl=000
[after-chat-reset] port=18993 curl=000
[turn4] exit=0 reply=STARTED 
[after-start-2] port=18991 curl=200
[after-start-2] port=18992 curl=200
[after-start-2] port=18993 curl=200
[rpc-reset] ok=true
[after-rpc-reset] port=18991 curl=000
[after-rpc-reset] port=18992 curl=000
[after-rpc-reset] port=18993 curl=000
[turn5] exit=0 reply=STARTED 
[after-start-3] port=18991 curl=200
[after-start-3] port=18992 curl=200
[after-start-3] port=18993 curl=200
[after-gateway-stop] port=18991 curl=000
[after-gateway-stop] port=18992 curl=000
[after-gateway-stop] port=18993 curl=000
helpers_left=0  (the script counted 1, an unrelated test-runner process whose arguments name the helper files; a direct check found 0 relay/anchor processes)
```

</details>

## Test results (head)

- `ocx test` on 139 files (supervisor, relay, anchor, exec, process tool, exec follow-up, cron exit watchers, session reset/delete, agent delete, chat session, subagent reset, TUI, desktop): 10 shards pass, 1456 tests passed, 0 failed (previous head).
- After the CI fixes: exec, worker runtime, supervisor, relay, anchor, adapters, TUI shell, exec follow-up, process scope and subagent reset suites: 5 shards, 416 passed, 0 failed (macOS); the Linux container run in row 5.
- Not in that run: `bash-tools.exec.approval-id.test.ts`. One of its checks fails in this worktree only because the worktree path contains the word "process"; it passes on CI paths.
- `pnpm tsgo:core` clean; oxlint and oxfmt clean on the changed files.

## Limits

- The `--dts` build and packed smoke did not run. `ocx build --dts` fails locally with `PLUGIN SDK DTS TOO LARGE` on clean main commits too; CI's `build-artifacts` job on main measured the declarations under the limit. The Linux proof uses the dist-nodts build laid over a published install.
- On macOS, a process that leaves the command's process group (`setsid`, double fork) re-parents to launchd before the census unless a tracked parent still holds it. OpenClaw does not see it, so it is not adopted, not capped, and it keeps running after session reset and Gateway stop, as in every other harness compared below. On Linux the subreaper sees it.
- A process that a tracked survivor forks after the hand-off is not tracked separately; stopping the survivor does not stop it.
- Test lines exceed the 400-line allowance by 150; `config/test-lines-allocations/199079-exec-detached-process-ownership.txt` records them. Each added test is a real-process regression for one review finding.
- Adopted services count as live background sessions, so, like `background: true` services, they block a safe Gateway restart until they exit or are stopped.

## How this compares

| Harness | Process left by a completed command | Bound while running | Session reset / new | Host stop | One-shot CLI exit |
|---|---|---|---|---|---|
| Codex | Survives; only timeout or Ctrl-C kills the group | No | Session shutdown terminates all its unified-exec processes | Killed with the session | Survives |
| Pi | Survives; only in-flight commands are tracked | No | Kills in-flight commands only | Kills in-flight commands only | Survives |
| OMP | Survives; the shell is kept while background jobs run, reaped every 5 s | 15 running background jobs; over the limit, new jobs fail | `newSession()` cancels the session's own async jobs | Kept shells and their jobs die with the harness | Killed with the harness |
| Hermes | Tracked in a session-scoped process registry | 64 tracked records; prunes only finished ones | Agent close and session end kill the session's processes, except explicitly persisted ones | — | — |
| OpenClaw before | Killed at the end of the call (Linux: daemons too) | — | Killed earlier, at the end of the call | Killed | Killed |
| OpenClaw after | Survives as a tracked background session, reaped every 5 s, named in the result and `process list` | 16 per session, 64 per Gateway; over the limit, new services are refused or stopped, old ones never evicted | Stops in-flight work, `background: true` services and survivors; durable processes stay | Stopped | Handed off and printed (as Codex and Pi) |

In every harness, a process that daemonized itself and was never tracked keeps running.

Sources: Codex `codex-rs/core/src/exec.rs`, `spawn.rs` and `core/src/session/handlers.rs` (`terminate_all_processes`); Pi `packages/coding-agent/src/core/tools/bash.ts`; OMP `packages/coding-agent/src/exec/bash-executor.ts` (`RETAIN_REAP_INTERVAL_MS`), `src/async/job-manager.ts` (`DEFAULT_MAX_RUNNING_JOBS = 15`) and `newSession()` (`#cancelOwnAsyncJobs`); Hermes `tools/process_registry.py` (`MAX_PROCESSES = 64`, `kill_all`).

## Follow-ups (PR 2 and later)

- A strict process scope for cron and heartbeat runs, with a tool notice that everything ends with the run.
- A durable PID ledger so services are still owned after a Gateway crash.
- One ownership policy: remove the service-marker and platform predicates and the PTY rejection.
- cgroup and RSS memory budgets for adopted services.
- File-backed stdio for all exec, which removes the drain anchor.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…enclaw#199079)

## Problem

When the agent starts a process that must keep running, OpenClaw stops it.

- A completed host `exec` call cancels its whole process tree. This stops `cmd &` and `nohup cmd &`. On Linux, the child subreaper also adopts and stops processes that left with `setsid` or a double fork, such as `nginx` and `sshd`.
- A one-shot `openclaw agent --local` run cancels every process in its exec scope when it exits. This also stops `background: true` services.
- Result: on Linux, no start style survives the CLI. The agent reports success, and the service is gone before anything can use it.
- `background: true` services also inherit the 1800 s exec timeout unless the model passes `timeoutSeconds: 0`.
- The model-facing text was wrong. `background` said "Start an independent service now; survives request Stop", but the service did not survive the CLI.

openclaw#150750 made the killing deliberate. Its real problem was that OpenClaw's own relay and owner processes stayed alive with the user's processes. It fixed that by stopping the user's processes too.

## Fix

This is PR 1: stop killing, stay bounded.

1. **Hand off on a normal exit.** When the root command exits normally, the process-group owner (anchor) does not signal its group. It reads the process table, reports every live process the command left, stops observing lineage, and exits. On Linux it exits as the subreaper, so adopted processes go to init. If a released process still holds the command's stdout or stderr pipe, the anchor keeps draining that pipe until it closes, so the service never gets SIGPIPE or EPIPE when it logs. The cap bounds these drain anchors.
2. **Every survivor is accounted for.** The report has no size limit. It includes the owner's group members, the processes the Linux subreaper adopted (these are the owner's direct children, and they stay the command's), and all of their descendants, also those in a new session (for example the `sleep` under `setsid sh -c 'sleep 300 & wait'`). If the process table cannot be read, the anchor stops the tree like a cancellation instead of releasing processes it cannot name.
3. **Adopt survivors as sessions.** Each survivor becomes an ordinary background session in the process registry, under the session that ran the command.
   - The tool result names its PID and session ID. `process list` shows it, and `process kill` stops it.
   - It is pinned to its start time. Every signal re-checks that identity, so a reused PID is never signalled.
   - OpenClaw drops it within 5 s of its exit. Gateway stop stops it.
4. **A stop counts only when the exit is observed.** OpenClaw sends SIGTERM, then SIGKILL after the 5 s grace, then waits up to 2 s for the recorded identity to disappear. If a signal is denied (for example EPERM after a UID change) or the process does not disappear, the record stays, the session is marked as cleanup-uncertain, and the result says so. This applies to `process kill`, session reset and delete, Gateway stop and over-limit survivors. A later stop retries.
5. **Admission caps.** At most 16 services per session and 64 per Gateway. A service is a background session or an adopted survivor.
   - A `background: true` start reserves its slot before approval and startup and holds it until its session runs or startup fails, so concurrent starts cannot pass the limit.
   - Over the cap, a new `background: true` start fails with an error that names `process list` and `process kill`.
   - Over the cap, a foreground command's new survivors are stopped by identity, and the result lists their PIDs and the reason. A survivor whose stop is not confirmed stays tracked over the limit, so nothing escapes custody.
   - OpenClaw never stops an older process to make room.
6. **Stopping stays the same where it matters.** Timeout, no-output timeout, cancellation, request Stop, `process kill`, memory limit, host loss and launch failure still stop the whole tree, including Linux `setsid` and double-fork escapees. Scopes with `required-all` cleanup (the local TUI shell, managed workers, cron exit watchers, update repair, desktop helpers) keep strict cleanup on exit.
7. **Every reset path stops everything the session runs.** Chat `/new` and `/reset`, Gateway `sessions.reset` and session delete all call one shared step, `stopSessionResetProcesses`, after the session's subagents stop and before the replacement conversation is committed. It stops in-flight commands, `background: true` services and adopted survivors by identity. If a stop is not confirmed, the reset fails and asks to retry. Durable processes are not affected.
8. **One-shot exit hands services off.** At the end of `openclaw agent --local`:
   - `background: true` services and adopted survivors are handed off, and only in-flight work is cancelled. The order from openclaw#177940 stays: hand-off, then scope cleanup, then join.
   - The CLI prints what it left running (PID and command) to stderr.
   - If the CLI dies without cleanup, host loss still stops work that was not handed off.
9. **No built-in timeout for services.** `background: true` no longer inherits the 1800 s default. An explicit `timeoutSeconds` or a configured `tools.exec.timeoutSeconds` still applies. In a subagent or cron run that can wait for the command with `sessions_yield`, the default still bounds that wait, as current main requires.
   - `host=node` ignores `background` and runs synchronously through remote `system.run`, so it is not a service. It keeps the ordinary node timeouts (a 1800 s program timer and a longer Gateway invocation deadline, as designed in 90a62a0). Without this, `exec {host:"node", background:true}` sent a zero program timer and a 10 s Gateway deadline, and the caller got an outcome-unknown failure before the command returned.
10. **The model sees the truth.** The tool result names every survivor and every stop, with PID and reason. The `background` description and the background-process docs state the real lifetime.

The relay and the anchor still exit after every completed command, so openclaw#150750 does not regress.

## Proof

"Base" is the behaviour without this change. "Previous head" is the head that review rated (`3549c2b`, then `bb2b295`).

| # | Proof | Tier | Base / previous head | Head |
|---|---|---|---|---|
| 1 | 50 calls that each leave a survivor: 16 are adopted, 34 are stopped with the reason in the result, 0 relay or anchor processes remain (openclaw#150750); `process list` shows them; `process kill` stops one by identity; an exited one drops out within one reap interval; Gateway stop ends the rest | vitest-source, macOS | previous head: fails | pass |
| 2 | One command leaves 20 survivors: 16 tracked, 4 stopped, every PID named, none alive and untracked; then `background: true` is refused and a new survivor is stopped | vitest-source, macOS | previous head: fails (only 16 reported) | pass |
| 3 | Two concurrent `background: true` starts at 15 of 16: exactly one starts | vitest-source, macOS | previous head: fails (both start, 17 running) | pass |
| 4 | A survivor's child in a new session is tracked; stopping the session ends both | vitest-source, macOS | previous head: fails (child untracked) | pass |
| 5 | Real Linux run in `node:24-bookworm` (root, subreaper active) of `bash-tools.exec-group-cleanup.real.test.ts`, `subagent-reset.lifecycle.test.ts` and `worker.runtime.test.ts`: survivors, cap, reservation, descendant closure, `setsid sh -c 'sleep & wait'`, timeout of `setsid`/double-fork children, unconfirmed stops, chat/RPC reset | vitest-source, Linux container (fresh `pnpm install`, no skips) | `bb2b295`: 8 failed (every survivor test: the subreaper-adopted survivors were classed as helpers, so nothing was reported) | 96 of 96 passed, 0 skipped |
| 6 | Signals to a survivor are denied (EPERM): reset fails, the session stays running with cleanup uncertainty in its output, the process is still tracked; after signals work, a retry stops it and settles the record | vitest-source, macOS | previous head: fails (reset reported success, record dropped) | pass |
| 7 | Chat `/reset` (`initSessionState`) and Gateway `sessions.reset` each stop a running `background: true` service and a `cmd &` survivor before the new session is committed | vitest-source, macOS | previous head: chat path fails (both processes still alive); RPC path passes | pass, both paths |
| 9 | Detached styles (`node &`, `nohup`, plain `&`, double fork) survive a completed call; a timeout still stops what the call started; one-shot cleanup hands off and prints services and stops in-flight work; handed-off servers that log every request answer 20 of 20 requests 10 s after the run | vitest-source, macOS | — | pass |
| 10 | A timeout stops `setsid` and double-fork children | vitest-source, Linux container | — | pass (part of row 5) |
| 11 | Supervisor, relay, anchor, exec, process tool, exec follow-up (`sessions_yield`), cron exit watchers (`required-all` extinction), session reset/delete, agent delete, TUI, desktop and chat session suites | vitest-source, macOS | — | see "Test results" below |
| 12 | CLI lifecycle, real model: `openclaw agent --local` with five start styles; the server is probed 0, 3 and 10 s after the CLI exits, then sent 20 requests | source (`ocx src`), macOS | base (`0a8e0b7d9cd0`): 1 of 5 alive (only the double-fork daemon, which leaves the group); `background: true` answers 200 during the run, then dies at CLI exit | 5 of 5 alive, each answers 20 of 20 requests; the CLI prints every handed-off PID; 0 relay/anchor processes after the servers stop |
| 13 | Gateway lifecycle, real model, one session: start `background: true`, `nohup &` and plain `&` servers; check them in the next turn; chat `/reset`; start again; RPC `sessions.reset`; start again; stop the Gateway | source (`ocx src -- gateway run`), macOS | base: `nohup &` and plain `&` die at the end of their own call; `background: true` survives chat `/reset` and RPC reset | all 3 survive across turns; chat `/reset` stops all 3; RPC reset stops all 3; Gateway stop stops all 3; 0 relay/anchor processes left |
| 14 | Upgrade: latest stable `2026.11.3` runs on a state dir with `tools.exec.timeoutSeconds: 90`, then this head (`doctor --fix --non-interactive`, as update does) runs on the same state | stable: published npm package; head: source (`ocx src`), macOS | stable reads 90 | head still reads 90 after doctor; a `background: true` call gets a deadline 90 s after its start ("times out in 1m30s"); without a configured timeout, the same call on head has no deadline |
| 15 | Linux: five styles plus a timeout case in `node:24-bookworm` as root, `openclaw agent --local`, Node runtime | dist-nodts, Linux (this head's `dist/` laid over the `2026.11.5-beta.3` install) | published `2026.11.5-beta.2`: 0 of 5 alive | 5 of 5 alive, each answers 20 of 20 requests 10 s after the CLI exits; the timeout case stops both the `setsid` server and the double-fork daemon |
| 16 | `exec {host:"node", background:true}` through `createExecTool` to the node `system.run` invocation keeps the ordinary 1800 s program timer and 1805 s Gateway deadline, and completes | vitest-source, macOS | previous head: fails (program timer 0) | pass |

<details>
<summary>Redacted captures (CLI and Gateway, head and base)</summary>

CLI, base `0a8e0b7d9cd0`, `nohup … &` (the agent's own check fails, then the probes):

```text
exec: nohup python3 -m http.server 18972 --bind 127.0.0.1 --directory /tmp > /tmp/oc-srv-18972.log 2>&1 &
result: completed 0, (no output)
exec: sleep 2; curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:18972/
result: 000 (Command exited with code 7)
reply: FAILED 18972 000
after_exit_plus=0s curl=000 · 3s curl=000 · 10s curl=000 · twenty_requests_after_10s=0/20
```

CLI, head, `nohup … &`:

```text
exec result: pid 70493 (…/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp) keeps running as background
  session mild-sage:2b822b901780: process list shows it and process kill mild-sage:2b822b901780 stops it. Its later
  output to this command's stdout/stderr is discarded; redirect it to a file to keep it.
reply: STARTED 18982 200
stderr: [openclaw] Left running after this run (OpenClaw no longer tracks them; stop with kill <pid>):
          pid 70493  …/Python -m http.server 18982 --bind 127.0.0.1 --directory /tmp
after_exit_plus=0s curl=200 · 3s curl=200 · 10s curl=200 · twenty_requests_after_10s=20/20
```

Gateway, base:

```text
[turn1] exit=0 reply=STARTED 
[after-start-1] port=18991 curl=200
[after-start-1] port=18992 curl=000
[after-start-1] port=18993 curl=000
[turn2] exit=0 reply=18991=200 18992=000 18993=000 
[after-next-turn] port=18991 curl=200
[after-next-turn] port=18992 curl=000
[after-next-turn] port=18993 curl=000
[turn3] exit=0 reply=✅ Session reset. 
[after-chat-reset] port=18991 curl=200
[after-chat-reset] port=18992 curl=000
[after-chat-reset] port=18993 curl=000
[turn4] exit=0 reply=STARTED 
[after-start-2] port=18991 curl=200
[after-start-2] port=18992 curl=000
[after-start-2] port=18993 curl=000
[rpc-reset] ok=true
[after-rpc-reset] port=18991 curl=200
[after-rpc-reset] port=18992 curl=000
[after-rpc-reset] port=18993 curl=000
[turn5] exit=0 reply=STARTED 
[after-start-3] port=18991 curl=200
[after-start-3] port=18992 curl=000
[after-start-3] port=18993 curl=000
[after-gateway-stop] port=18991 curl=000
[after-gateway-stop] port=18992 curl=000
[after-gateway-stop] port=18993 curl=000
helpers_left=0
```

Gateway, head:

```text
[turn1] exit=0 reply=STARTED 
[after-start-1] port=18991 curl=200
[after-start-1] port=18992 curl=200
[after-start-1] port=18993 curl=200
[turn2] exit=0 reply=18991=200 18992=200 18993=200 
[after-next-turn] port=18991 curl=200
[after-next-turn] port=18992 curl=200
[after-next-turn] port=18993 curl=200
[turn3] exit=0 reply=✅ Session reset. 
[after-chat-reset] port=18991 curl=000
[after-chat-reset] port=18992 curl=000
[after-chat-reset] port=18993 curl=000
[turn4] exit=0 reply=STARTED 
[after-start-2] port=18991 curl=200
[after-start-2] port=18992 curl=200
[after-start-2] port=18993 curl=200
[rpc-reset] ok=true
[after-rpc-reset] port=18991 curl=000
[after-rpc-reset] port=18992 curl=000
[after-rpc-reset] port=18993 curl=000
[turn5] exit=0 reply=STARTED 
[after-start-3] port=18991 curl=200
[after-start-3] port=18992 curl=200
[after-start-3] port=18993 curl=200
[after-gateway-stop] port=18991 curl=000
[after-gateway-stop] port=18992 curl=000
[after-gateway-stop] port=18993 curl=000
helpers_left=0  (the script counted 1, an unrelated test-runner process whose arguments name the helper files; a direct check found 0 relay/anchor processes)
```

</details>

## Test results (head)

- `ocx test` on 139 files (supervisor, relay, anchor, exec, process tool, exec follow-up, cron exit watchers, session reset/delete, agent delete, chat session, subagent reset, TUI, desktop): 10 shards pass, 1456 tests passed, 0 failed (previous head).
- After the CI fixes: exec, worker runtime, supervisor, relay, anchor, adapters, TUI shell, exec follow-up, process scope and subagent reset suites: 5 shards, 416 passed, 0 failed (macOS); the Linux container run in row 5.
- Not in that run: `bash-tools.exec.approval-id.test.ts`. One of its checks fails in this worktree only because the worktree path contains the word "process"; it passes on CI paths.
- `pnpm tsgo:core` clean; oxlint and oxfmt clean on the changed files.

## Limits

- The `--dts` build and packed smoke did not run. `ocx build --dts` fails locally with `PLUGIN SDK DTS TOO LARGE` on clean main commits too; CI's `build-artifacts` job on main measured the declarations under the limit. The Linux proof uses the dist-nodts build laid over a published install.
- On macOS, a process that leaves the command's process group (`setsid`, double fork) re-parents to launchd before the census unless a tracked parent still holds it. OpenClaw does not see it, so it is not adopted, not capped, and it keeps running after session reset and Gateway stop, as in every other harness compared below. On Linux the subreaper sees it.
- A process that a tracked survivor forks after the hand-off is not tracked separately; stopping the survivor does not stop it.
- Test lines exceed the 400-line allowance by 150; `config/test-lines-allocations/199079-exec-detached-process-ownership.txt` records them. Each added test is a real-process regression for one review finding.
- Adopted services count as live background sessions, so, like `background: true` services, they block a safe Gateway restart until they exit or are stopped.

## How this compares

| Harness | Process left by a completed command | Bound while running | Session reset / new | Host stop | One-shot CLI exit |
|---|---|---|---|---|---|
| Codex | Survives; only timeout or Ctrl-C kills the group | No | Session shutdown terminates all its unified-exec processes | Killed with the session | Survives |
| Pi | Survives; only in-flight commands are tracked | No | Kills in-flight commands only | Kills in-flight commands only | Survives |
| OMP | Survives; the shell is kept while background jobs run, reaped every 5 s | 15 running background jobs; over the limit, new jobs fail | `newSession()` cancels the session's own async jobs | Kept shells and their jobs die with the harness | Killed with the harness |
| Hermes | Tracked in a session-scoped process registry | 64 tracked records; prunes only finished ones | Agent close and session end kill the session's processes, except explicitly persisted ones | — | — |
| OpenClaw before | Killed at the end of the call (Linux: daemons too) | — | Killed earlier, at the end of the call | Killed | Killed |
| OpenClaw after | Survives as a tracked background session, reaped every 5 s, named in the result and `process list` | 16 per session, 64 per Gateway; over the limit, new services are refused or stopped, old ones never evicted | Stops in-flight work, `background: true` services and survivors; durable processes stay | Stopped | Handed off and printed (as Codex and Pi) |

In every harness, a process that daemonized itself and was never tracked keeps running.

Sources: Codex `codex-rs/core/src/exec.rs`, `spawn.rs` and `core/src/session/handlers.rs` (`terminate_all_processes`); Pi `packages/coding-agent/src/core/tools/bash.ts`; OMP `packages/coding-agent/src/exec/bash-executor.ts` (`RETAIN_REAP_INTERVAL_MS`), `src/async/job-manager.ts` (`DEFAULT_MAX_RUNNING_JOBS = 15`) and `newSession()` (`#cancelOwnAsyncJobs`); Hermes `tools/process_registry.py` (`MAX_PROCESSES = 64`, `kill_all`).

## Follow-ups (PR 2 and later)

- A strict process scope for cron and heartbeat runs, with a tool notice that everything ends with the run.
- A durable PID ledger so services are still owned after a Gateway crash.
- One ownership policy: remove the service-marker and platform predicates and the PTY rejection.
- cgroup and RSS memory budgets for adopted services.
- File-backed stdio for all exec, which removes the drain anchor.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: XL 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.

1 participant