Skip to content

fix(exec): keep processes the agent detaches, tracked and bounded - #199079

Merged
obviyus merged 1 commit into
mainfrom
fix/exec-detached-process-lifetime
Nov 15, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/exec-detached-process-lifetime

Conversation

@obviyus

@obviyus obviyus commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

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 fix(exec): settle process lifecycles and approval outcomes #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
Redacted captures (CLI and Gateway, head and base)

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

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 … &:

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:

[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:

[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)

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.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@obviyus

obviyus commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling labels Nov 14, 2026
@clawsweeper

clawsweeper Bot commented Nov 14, 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. P2 Normal backlog priority with limited blast radius. 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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 14, 2026
@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Preserves detached host processes as bounded, manageable background sessions and hands independent services off when a one-shot CLI run ends.

Example: An agent starts nohup python3 -m http.server 18982 & through host exec.

  • Before: The shell reports success, but command cleanup stops the server.
  • After: The server remains available, its PID and process-session handle are reported, and session reset stops it.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful lifecycle repair with production-entry-point evidence, focused regressions, and the previous blockers resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied redacted real-model CLI and Gateway output exercises detached-service survival, cross-turn availability, reset and shutdown cleanup, with Linux CLI coverage and a stable-upgrade timeout-preservation scenario.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Services started successfully by the agent disappear during command cleanup or when the one-shot CLI exits.
Reason: The maintainer-authored direction restores usable service lifetimes with visible ownership and limits, and explicitly documents platform limitations.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a current exec lifecycle failure, resolves the previous findings, and has no new actionable correctness finding; current-head CI remains pending.

Priority: P2
Reviewed head: dfb3323daa22577b77172a5913573ddac3761921

Before merge

None.

Findings

None.

Agent review details

How this fits together

The exec tool launches commands through the process supervisor and relay/anchor owners; surviving processes enter the existing process registry for inspection, termination, and lifecycle cleanup.

flowchart TD
  A[Agent exec call] --> B[Service admission]
  B --> C[Process supervisor]
  C --> D[Relay and anchor]
  D --> E[Command and descendants]
  D --> F[Survivor receipt]
  F --> G[Process registry]
  G --> H[Process kill and session cleanup]
Loading

Technical review

Best possible solution:

Use the existing supervisor and process registry to preserve detached services while retaining admission limits and strict cancellation cleanup.

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

Current-main source explicitly cancels completed host-command descendants and one-shot scopes, matching the supplied before-fix CLI and Gateway traces; no target code was executed during this review.

Is this the best way to solve the issue?

The change repairs lifetime ownership at the existing supervisor boundary, reuses the process registry, and preserves strict cleanup for cancellation and required-all scopes.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Completed host-command descendant cleanup changes intended behavior with a stated reason (ce9a07f: Prevent completed commands from retaining background descendants and relay/anchor groups until Gateway restart.)
  • One-shot exec scope settlement changes intended behavior with a stated reason (1c1b6e0: Join process-tree cleanup and backend finalization before releasing invocation state.)
  • Strict process-tree cancellation keeps the original intent (ffc94d0: Stop forked commands on timeout without signaling the Gateway's shared process group or trusting stale numeric group identity.)
  • Successful root outcome during uncertain cleanup keeps the original intent (f8306b2: Preserve an observed successful command result when a detached daemon prevents confirmed descendant extinction.)
  • Ordinary node command timeout keeps the original intent (6872be8: Keep synchronous remote execution bounded by its program timeout and a longer invocation deadline.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still terminates completed-command descendants: Fetched main calls managedRun.cancel during host exec finalization and cancels the complete one-shot scope; the PR's central change is therefore still needed. (src/agents/bash-tools.exec-runtime.ts:434, cccfab319848)
  • Previous node-timeout finding resolved: Service classification now excludes host=node, and the added exec-boundary regression checks the ordinary 1800000 ms program timeout and 1805000 ms invocation deadline. (src/agents/bash-tools.exec-run.ts:283, dfb3323daa22)
  • Earlier lifecycle findings addressed: Survivor discovery includes subreaper-adopted children and descendant closure, receipts are not truncated by survivor count, uncertain stops retain records, background startup reserves capacity, and chat/RPC reset share process cleanup. (src/process/supervisor/service-child-group-ownership.ts:400, dfb3323daa22)
  • Supplied production behavior and upgrade evidence: The full PR body supplies redacted real-model CLI and Gateway output showing service survival, next-turn availability, chat/RPC reset, and Gateway-stop cleanup; it also reports Linux CLI coverage and preservation of tools.exec.timeoutSeconds=90 when upgrading from v2026.11.3. (dfb3323daa22)
  • Intentional change to earlier cleanup policy: fix(process): release exec child groups when their tool call settles #150750 intentionally stopped shell-backgrounded descendants to prevent process exhaustion; this maintainer-authored PR explains replacing that behavior with tracked survivors and admission caps while retaining strict cancellation cleanup. (src/agents/bash-tools.exec-runtime.ts:435, ce9a07f765ab)
  • Current merge and gate state: GitHub reports the reviewed head as mergeable, with CI still running; dependency review and security-sensitive review report success. (dfb3323daa22)

Likely related people:

  • Peter Steinberger: Raw commit ce9a07f adds src/agents/bash-tools.exec-runtime.ts:805 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ce9a07f765ab; files: src/agents/bash-tools.exec-runtime.ts)
  • Josh Avant: Raw commit 1c1b6e0 adds src/agents/bash-process-control.ts:51 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1c1b6e00fbe6; files: src/agents/bash-process-control.ts)

PR surface

Source +1097, Tests +550, Docs +5, Other +2. Total +1654 across 41 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 29 1289 192 +1097
Tests 10 629 79 +550
Docs 1 30 25 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 41 1950 296 +1654

Preflight source

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

Review metrics

Metric Value Why it matters
Service limits 16 per session; 64 per Gateway New fixed admission limits bound retained services without adding configuration.
Service timeout default 1800 seconds → no built-in timeout Explicit services retain configured or per-call deadlines, while synchronous node commands keep ordinary defaults.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster 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: 🐚 platinum hermit, 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: Useful exec lifecycle repair with a limited process-management blast radius and concrete production evidence.
  • merge-risk: 🚨 compatibility: Intentionally changes descendant survival, one-shot service lifetime, reset cleanup, and the unconfigured service timeout; the maintainer-authored direction explains these tradeoffs.
  • merge-risk: 🚨 availability: Changes process retention and shutdown behavior, where missed ownership can exhaust processes or delay restart; caps, cleanup paths, and supplied lifecycle proof address the demonstrated cases.
  • 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.
  • 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 (3 earlier review cycles)
  • reviewed 2026-11-14T18:27:53.238Z sha 3549c2b :: needs changes before merge. :: [P1] Account for survivors beyond the receipt limit | [P2] Include descendants beneath adopted process-group leaders | [P2] Retain adopted ownership when termination is unconfirmed | [P2] Reserve capacity across asynchronous background startup | [P2] Apply process cleanup to chat reset and new-session commands
  • reviewed 2026-11-15T04:40:04.986Z sha bb2b295 :: needs changes before merge. :: [P1] Include subreaper-adopted children in the survivor receipt
  • reviewed 2026-11-15T05:24:34.029Z sha df4cdaa :: needs changes before merge. :: [P2] Preserve ordinary timeout defaults for synchronous node commands

Reviewed November 15, 2026, 1:00 AM ET / 06:00 UTC (Revision 4).

@openclaw-barnacle openclaw-barnacle Bot reopened this Nov 14, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Nov 14, 2026
@obviyus
obviyus force-pushed the fix/exec-detached-process-lifetime branch from 3549c2b to bb2b295 Compare November 15, 2026 04:33
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Nov 15, 2026
@obviyus
obviyus force-pushed the fix/exec-detached-process-lifetime branch from bb2b295 to df4cdaa Compare November 15, 2026 05:17
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Nov 15, 2026
A completed host exec cancelled its whole process tree, and a one-shot
`openclaw agent --local` run cancelled its background sessions on exit. So
`cmd &`, `nohup`, `setsid`, daemons (nginx, sshd) and `background: true`
services all died before anyone could use them.

The process-group owner now hands off instead of signalling when the root
exits normally: it reports every live process the command left (group
members, subreaper-adopted processes and all their descendants), stops
observing them, keeps draining pipes they still hold, and exits. Without a
process census it stops the tree instead. OpenClaw's own relay and owner
processes still exit, so completed commands do not leak helpers. Timeout,
cancellation, request Stop, `process kill`, host loss and `required-all`
scopes still stop the whole tree.

Each survivor becomes a background session: the result names its PID and
session, `process list` shows it, `process kill` stops it by identity (PID
plus start time), it is reaped within 5 s of exiting, and Gateway stop ends
it. A stop counts only when the exit is observed; denied or unobserved stops
keep the record and report cleanup uncertainty. Admission caps of 16
services per session and 64 per Gateway reserve a slot for each
`background: true` start through approval and startup, refuse starts at the
limit, and stop a foreground command's extra survivors with the reason,
never evicting old ones. Chat `/new` and `/reset`, Gateway reset and session
delete stop everything the session runs through one shared step before the
replacement conversation is committed; durable processes stay. One-shot run
cleanup hands services off, cancels in-flight work and prints what it left
running.

`background: true` no longer inherits the 1800 s default timeout; an explicit
or configured timeout still applies, and a run that can await the command
with sessions_yield keeps the default bound. The `background` description
and the background-process docs now state the real lifetime.

host=node ignores background and runs synchronously, so it is not a
service and keeps the ordinary node program timer and Gateway deadline.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the fix/exec-detached-process-lifetime branch from df4cdaa to dfb3323 Compare November 15, 2026 05:53
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 15, 2026
@obviyus
obviyus merged commit 237111e into main Nov 15, 2026
162 of 163 checks passed
@obviyus
obviyus deleted the fix/exec-detached-process-lifetime branch November 15, 2026 06:20
@obviyus

obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 237111e.

  • Bug: a finished exec call, and the exit of openclaw agent --local, stopped every process the agent started on purpose. On Linux this included nohup, setsid and daemonized servers such as nginx and sshd, so the agent reported a running service that was already gone.
  • Fix: processes left by a completed command are kept. Each one is adopted as a tracked background session, with a cap of 16 per session and 64 per Gateway. A stop counts only when the process is seen to exit. Every reset path, and Gateway stop, stops the session's processes; one-shot exit hands them off. OpenClaw's own relay and anchor processes still exit (fix(process): release exec child groups when their tool call settles #150750).
  • Proof:
    • CLI and Gateway lifecycle runs on macOS: base 1/5 alive, head 5/5.
    • Linux container: published beta 0/5 alive, head 5/5, each answering 20/20 requests after the CLI exits.
    • Real Linux suite: 96/96.
    • Stable-upgrade check with an explicit tools.exec.timeoutSeconds.

steipete added a commit that referenced this pull request Nov 15, 2026
Keep service limits, capacity errors and default-timeout resolution private to
their owners after #199079 removed their external production consumers.

Use the documented 16-service contract as the real-process integration suite's
independent expectation instead of importing a test-only production export.
Preserve existing behavior, assertions and platform conditions.
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
Keep service limits, capacity errors and default-timeout resolution private to
their owners after openclaw#199079 removed their external production consumers.

Use the documented 16-service contract as the real-process integration suite's
independent expectation instead of importing a test-only production export.
Preserve existing behavior, assertions and platform conditions.
obviyus added a commit that referenced this pull request Nov 16, 2026
…0250)

## Problem

#199079 adopts every process a completed host `exec` command leaves running as a service, up to 16 per session and 64 per Gateway. Over that limit it stops the new survivors.

The census runs at the instant the root command exits. Helpers that are still exiting at that instant (`git`, `cp`, `tee`, `tail`, a short `sleep`) are counted as services. Two bad results follow:

- Helpers fill the 16 slots and push out real work. In one evening of a production Gateway, 5 sessions hit "16 of 16 allowed services" while the Gateway held only 18 to 36 of 64. OpenClaw stopped 2 to 14 processes in each: test-harness `nohup` loops, a test `gateway run`, the `git` processes of a worktree switch.
- Each helper is reported to the model as a background session that "keeps running", although it exits a moment later.

Agents then spent calls killing leftovers or restarting stopped work.

## Fix

Two changes to the existing owners. No new state.

1. **Adopt after a settle window** (`service-child-group-ownership.ts`). After the root exits, the process owner repeats its survivor census every 100 ms until nothing is left or 2 s pass. Only what still runs at the end is reported and adopted. Each census keeps the earlier survivors that still run the same command, so a process cannot escape custody by outliving the parent that tied it to the command. A root that still runs (a one-shot hand-off of a `background: true` service) is handed off at once. A cancellation during the window owns the tree, as before. No command names are special-cased.
2. **Never stop a survivor for capacity** (`bash-process-adopted.ts`). The cap is checked only where a service is declared (`reserveServiceSlot`, `background: true`). Adoption now tracks every survivor and never stops one as over the limit. The overflow kill and `killReleasedProcess` are deleted. Survivors still count, so a `background: true` start is still refused at the limit.

Production code: +67 / −71 lines.

## User impact

- Short-lived helpers no longer take service slots, are not reported as services, and are never stopped.
- A real service a command leaves running (`nohup server &`, a fork loop) is still tracked, listed by `process list`, stopped by `process kill`, session reset and Gateway stop.
- Commands that leave a real process running now return up to 2 s later. Commands that leave nothing running are not delayed.
- At the limit, a declared `background: true` service is refused. A survivor over the limit is tracked instead of stopped.

## Proof

**Real Gateway E2E** (dist build, macOS, scratch state, service-managed exec path, real model `claude-opus-5-5`). Base is the merge base `aa4d490a`. Each arm is one Gateway with three sessions driven through `chat.send`.

| Journey | Base | Head |
|---|---|---|
| 20 calls of `for i in $(seq 18); do (git status --short; sleep 0.5) & done; git status --short; cp a.txt b.txt` | every call at "16 of 16": 288 helpers adopted as services, 431 stopped as over the limit | 0 adopted, 0 stopped, 20 of 20 clean results |
| `nohup python3 -m http.server &`, then 16 × `nohup sleep &` | 16 adopted, the 17th stopped | 17 adopted and listed; no process stopped |
| then a 17th declared service (`background: true`) | (not run on base) | refused: "This session runs 17 of 16 allowed services" |
| busy fork loop `while :; do sleep 0.05; done &` | adopted, listed | adopted, listed |
| Gateway stop | all tagged processes gone | all tagged processes gone (17 → 0) |

**Regression test** (`bash-tools.exec-group-cleanup.real.test.ts`, vitest-source, real processes, macOS): one call leaves 17 helpers of `sleep 0.5`, 20 times, then a fork loop.
- Base: fails, "Stopped 1 process the command left running, over the service limit … 16 of 16 allowed services".
- Head: passes; no helper is adopted or stopped, and the loop is adopted.

The cap tests now assert that every survivor stays tracked past the limit and that `background: true` is still refused. Whole file on head: 10 passed, 3 skipped (Linux only).

Gates: `tsgo:core`, `check:test-types`, oxlint and oxfmt on changed files, `ocx build --dts` and a packed install smoke (`openclaw --version`).

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

## Problem

openclaw#199079 adopts every process a completed host `exec` command leaves running as a service, up to 16 per session and 64 per Gateway. Over that limit it stops the new survivors.

The census runs at the instant the root command exits. Helpers that are still exiting at that instant (`git`, `cp`, `tee`, `tail`, a short `sleep`) are counted as services. Two bad results follow:

- Helpers fill the 16 slots and push out real work. In one evening of a production Gateway, 5 sessions hit "16 of 16 allowed services" while the Gateway held only 18 to 36 of 64. OpenClaw stopped 2 to 14 processes in each: test-harness `nohup` loops, a test `gateway run`, the `git` processes of a worktree switch.
- Each helper is reported to the model as a background session that "keeps running", although it exits a moment later.

Agents then spent calls killing leftovers or restarting stopped work.

## Fix

Two changes to the existing owners. No new state.

1. **Adopt after a settle window** (`service-child-group-ownership.ts`). After the root exits, the process owner repeats its survivor census every 100 ms until nothing is left or 2 s pass. Only what still runs at the end is reported and adopted. Each census keeps the earlier survivors that still run the same command, so a process cannot escape custody by outliving the parent that tied it to the command. A root that still runs (a one-shot hand-off of a `background: true` service) is handed off at once. A cancellation during the window owns the tree, as before. No command names are special-cased.
2. **Never stop a survivor for capacity** (`bash-process-adopted.ts`). The cap is checked only where a service is declared (`reserveServiceSlot`, `background: true`). Adoption now tracks every survivor and never stops one as over the limit. The overflow kill and `killReleasedProcess` are deleted. Survivors still count, so a `background: true` start is still refused at the limit.

Production code: +67 / −71 lines.

## User impact

- Short-lived helpers no longer take service slots, are not reported as services, and are never stopped.
- A real service a command leaves running (`nohup server &`, a fork loop) is still tracked, listed by `process list`, stopped by `process kill`, session reset and Gateway stop.
- Commands that leave a real process running now return up to 2 s later. Commands that leave nothing running are not delayed.
- At the limit, a declared `background: true` service is refused. A survivor over the limit is tracked instead of stopped.

## Proof

**Real Gateway E2E** (dist build, macOS, scratch state, service-managed exec path, real model `claude-opus-5-5`). Base is the merge base `ed37fd25`. Each arm is one Gateway with three sessions driven through `chat.send`.

| Journey | Base | Head |
|---|---|---|
| 20 calls of `for i in $(seq 18); do (git status --short; sleep 0.5) & done; git status --short; cp a.txt b.txt` | every call at "16 of 16": 288 helpers adopted as services, 431 stopped as over the limit | 0 adopted, 0 stopped, 20 of 20 clean results |
| `nohup python3 -m http.server &`, then 16 × `nohup sleep &` | 16 adopted, the 17th stopped | 17 adopted and listed; no process stopped |
| then a 17th declared service (`background: true`) | (not run on base) | refused: "This session runs 17 of 16 allowed services" |
| busy fork loop `while :; do sleep 0.05; done &` | adopted, listed | adopted, listed |
| Gateway stop | all tagged processes gone | all tagged processes gone (17 → 0) |

**Regression test** (`bash-tools.exec-group-cleanup.real.test.ts`, vitest-source, real processes, macOS): one call leaves 17 helpers of `sleep 0.5`, 20 times, then a fork loop.
- Base: fails, "Stopped 1 process the command left running, over the service limit … 16 of 16 allowed services".
- Head: passes; no helper is adopted or stopped, and the loop is adopted.

The cap tests now assert that every survivor stays tracked past the limit and that `background: true` is still refused. Whole file on head: 10 passed, 3 skipped (Linux only).

Gates: `tsgo:core`, `check:test-types`, oxlint and oxfmt on changed files, `ocx build --dts` and a packed install smoke (`openclaw --version`).

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 18, 2026
…pinner (#201157)

Related: #199079

## What Problem This Solves

When a hidden subagent finishes, fails, times out or is stopped, the servers and `nohup … &` processes it started keep running, with nothing left to manage them. Its parent's sidebar row keeps spinning, because the leftover processes still count on the dead child. Archiving a chat had the same gap. On 2026-11-18 a stopped worker left an isolated Gateway, a mock server and an HTTP server running until someone killed them by hand. The process-lifetime audit reproduced this on every subagent end path and on archive.

## User Impact

- A hidden subagent's `yieldMs` commands, `background: true` services and leftover processes (`cmd &`, `nohup`) stop when its task ends: it finishes, fails, times out or is stopped. A subagent waiting in `sessions_yield` keeps the command it waits on, and that command's exit still wakes it.
- Archiving a chat stops its processes, as reset and delete already do. If the stop cannot be confirmed, the archive fails with a retryable error and the chat stays unarchived.
- The parent row and the agent header stop spinning once the child's own run ends. A child's processes still show on its own row.
- **Behavior change:** to keep a service after a subagent ends, use `durable: true` or start it from the parent. Main chats, visible spawned sessions and the one-shot `agent --local` hand-off are unchanged.

## Why This Change Was Made

The chat stays the only owner of its processes (#199079, #200097), and `stopSessionExecProcesses` stays the only stop. Two chat ends never called it:
- **Subagent task end:** one subscriber on the registry's persistence publication derives "task ended" from the stored rows. All rows ended; none yielded, steer-restart or a visible session. It then stops the child's scope keys (key and session id, the same keys the row counts). Every end path writes its terminal row through that bus, so a new end path is covered automatically.
- **Archive:** calls the same stop after the lifecycle drain.
- **Sidebar:** one helper, `childShowsParentWorking`, replaces the two duplicated fold rules (session tree and team header). A child folds into its parent only while its run is visible, or while it is a yielded subagent waiting on its own command. No protocol change.
- **Text:** the `background` exec description and the background-process and subagent docs.

## Evidence

- **Contract table** (`subagent-task-end-processes.lifecycle.test.ts`, real processes: a service, a hand-off and a survivor per row). Complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5, the branch passes. The yielded child and the visible-session child keep their processes on both. About 20 s of test time.
- **Archive** (`server.sessions.archive-lifecycle.test.ts -t "archive stops the chat"`): both processes stop; an unconfirmed stop returns retryable `UNAVAILABLE` and does not archive. Base fails, the branch passes.
- **Sidebar** (`app-sidebar-session-tree.test.ts`): a `historical` child with processes does not spin its parent or the team header; `paused` and `active` children do. Base fails, the branch passes.
- tsgo core/ui/core-test, oxlint, format and `agent-tools.prefix-stability.test.ts`: green.

**Fault matrix rerun** (isolated Gateways, `env -i`, service marker set, scripted model; base `c8da4b7fbc40` → this branch). R2 = `yieldMs`, R3 = `background:true`, R4 = `nohup &`. L = alive and counted, C = clean.

| Cell | Base R2/R3/R4 | Head R2/R3/R4 |
|---|---|---|
| Subagent normal completion | L/L/L | **C/C/C** |
| Subagent model failure (400) | L/L/L | **C/C/C** |
| Subagent kill | C/L/L | **C/C/C** |
| Parent delete, child running | C/L/L | **C/C/C** |
| Parent delete, child completed | C/L/L | **C/C/C** |
| Archive | C/L/L | **C/C/C** |
| Subagent yielded on its hand-off | kept | kept (`paused`, count 1; exit resumes it) |
| Main chat: completion / abort / failure | L/L/L | unchanged by design |

A `setsid` double fork stays untracked on macOS, unchanged (follow-up).

**Real model** (`openai/gpt-6.2-sol`, this branch): a hidden subagent started a `background:true` HTTP server and a `nohup` process and was then killed. Both processes were gone afterwards, and the child row went from count 2 to no count.

**Control UI**, screenshot taken 12 s after the kill without a reload (base used the scripted model):

| Before (base) | After (this branch) |
| --- | --- |
| ![Base: parent row still spinning after the worker was killed](https://github.com/user-attachments/assets/70a79031-46d9-40ff-87f3-de7b98bcec88) | ![Branch: parent row shows a static dot after the worker was killed](https://github.com/user-attachments/assets/bf5fb28d-4485-4869-8593-8148fbdc3870) |
| ![Still spinning highlighted](https://github.com/user-attachments/assets/9501efca-61a2-42be-8d9d-7e5f11b7f7ff) | ![Stopped highlighted](https://github.com/user-attachments/assets/a6947c14-1553-4798-8bb8-82729f8966b2) |

## Merge danger and blast radius

- Two-way door: no stored rows, schema, config or protocol change; a revert fully restores the old lifetime.
- Hidden subagents that start services meant to outlive them now lose them at task end. Archive stops a chat's dev server.
- The stop touches only an ended hidden child's scope, and its `assertCurrent` re-derives the condition, so a resumed child is not stopped. An unconfirmed stop is logged and retried on the next publication for that child; a publication never throws.
- Cost: one map lookup per changed run per registry publication.
- Size: production +134/−18. The design estimated about +60 of logic; the rest is import formatting, the hoisted archive key list and the review fix that bounds the stop by the task's end time (a reset child key keeps its later processes). Tests: +376/−4.

## Left for later

PR 2: group kill for adopted survivors, the relay on macOS without the marker, a required `scopeKey` with a single factory and a teardown census, cron run sessions, `canStop: false` on killed children. PR 3: crash recovery for adopted survivors (needs approval) and Linux `cgroup.kill`.

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

Related: openclaw#199079

## What Problem This Solves

When a hidden subagent finishes, fails, times out or is stopped, the servers and `nohup … &` processes it started keep running, with nothing left to manage them. Its parent's sidebar row keeps spinning, because the leftover processes still count on the dead child. Archiving a chat had the same gap. On 2026-11-18 a stopped worker left an isolated Gateway, a mock server and an HTTP server running until someone killed them by hand. The process-lifetime audit reproduced this on every subagent end path and on archive.

## User Impact

- A hidden subagent's `yieldMs` commands, `background: true` services and leftover processes (`cmd &`, `nohup`) stop when its task ends: it finishes, fails, times out or is stopped. A subagent waiting in `sessions_yield` keeps the command it waits on, and that command's exit still wakes it.
- Archiving a chat stops its processes, as reset and delete already do. If the stop cannot be confirmed, the archive fails with a retryable error and the chat stays unarchived.
- The parent row and the agent header stop spinning once the child's own run ends. A child's processes still show on its own row.
- **Behavior change:** to keep a service after a subagent ends, use `durable: true` or start it from the parent. Main chats, visible spawned sessions and the one-shot `agent --local` hand-off are unchanged.

## Why This Change Was Made

The chat stays the only owner of its processes (openclaw#199079, openclaw#200097), and `stopSessionExecProcesses` stays the only stop. Two chat ends never called it:
- **Subagent task end:** one subscriber on the registry's persistence publication derives "task ended" from the stored rows. All rows ended; none yielded, steer-restart or a visible session. It then stops the child's scope keys (key and session id, the same keys the row counts). Every end path writes its terminal row through that bus, so a new end path is covered automatically.
- **Archive:** calls the same stop after the lifecycle drain.
- **Sidebar:** one helper, `childShowsParentWorking`, replaces the two duplicated fold rules (session tree and team header). A child folds into its parent only while its run is visible, or while it is a yielded subagent waiting on its own command. No protocol change.
- **Text:** the `background` exec description and the background-process and subagent docs.

## Evidence

- **Contract table** (`subagent-task-end-processes.lifecycle.test.ts`, real processes: a service, a hand-off and a survivor per row). Complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5, the branch passes. The yielded child and the visible-session child keep their processes on both. About 20 s of test time.
- **Archive** (`server.sessions.archive-lifecycle.test.ts -t "archive stops the chat"`): both processes stop; an unconfirmed stop returns retryable `UNAVAILABLE` and does not archive. Base fails, the branch passes.
- **Sidebar** (`app-sidebar-session-tree.test.ts`): a `historical` child with processes does not spin its parent or the team header; `paused` and `active` children do. Base fails, the branch passes.
- tsgo core/ui/core-test, oxlint, format and `agent-tools.prefix-stability.test.ts`: green.

**Fault matrix rerun** (isolated Gateways, `env -i`, service marker set, scripted model; base `70d9c782b6ca` → this branch). R2 = `yieldMs`, R3 = `background:true`, R4 = `nohup &`. L = alive and counted, C = clean.

| Cell | Base R2/R3/R4 | Head R2/R3/R4 |
|---|---|---|
| Subagent normal completion | L/L/L | **C/C/C** |
| Subagent model failure (400) | L/L/L | **C/C/C** |
| Subagent kill | C/L/L | **C/C/C** |
| Parent delete, child running | C/L/L | **C/C/C** |
| Parent delete, child completed | C/L/L | **C/C/C** |
| Archive | C/L/L | **C/C/C** |
| Subagent yielded on its hand-off | kept | kept (`paused`, count 1; exit resumes it) |
| Main chat: completion / abort / failure | L/L/L | unchanged by design |

A `setsid` double fork stays untracked on macOS, unchanged (follow-up).

**Real model** (`openai/gpt-6.2-sol`, this branch): a hidden subagent started a `background:true` HTTP server and a `nohup` process and was then killed. Both processes were gone afterwards, and the child row went from count 2 to no count.

**Control UI**, screenshot taken 12 s after the kill without a reload (base used the scripted model):

| Before (base) | After (this branch) |
| --- | --- |
| ![Base: parent row still spinning after the worker was killed](https://github.com/user-attachments/assets/70a79031-46d9-40ff-87f3-de7b98bcec88) | ![Branch: parent row shows a static dot after the worker was killed](https://github.com/user-attachments/assets/bf5fb28d-4485-4869-8593-8148fbdc3870) |
| ![Still spinning highlighted](https://github.com/user-attachments/assets/9501efca-61a2-42be-8d9d-7e5f11b7f7ff) | ![Stopped highlighted](https://github.com/user-attachments/assets/a6947c14-1553-4798-8bb8-82729f8966b2) |

## Merge danger and blast radius

- Two-way door: no stored rows, schema, config or protocol change; a revert fully restores the old lifetime.
- Hidden subagents that start services meant to outlive them now lose them at task end. Archive stops a chat's dev server.
- The stop touches only an ended hidden child's scope, and its `assertCurrent` re-derives the condition, so a resumed child is not stopped. An unconfirmed stop is logged and retried on the next publication for that child; a publication never throws.
- Cost: one map lookup per changed run per registry publication.
- Size: production +134/−18. The design estimated about +60 of logic; the rest is import formatting, the hoisted archive key list and the review fix that bounds the stop by the task's end time (a reset child key keeps its later processes). Tests: +376/−4.

## Left for later

PR 2: group kill for adopted survivors, the relay on macOS without the marker, a required `scopeKey` with a single factory and a teardown census, cron run sessions, `canStop: false` on killed children. PR 3: crash recovery for adopted survivors (needs approval) and Linux `cgroup.kill`.

Co-authored-by: Ayaan Zaidi <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…stage 2)

Catches the pure continuation candidate bc7e568 up to openclaw/openclaw
main 41bdde2 (fetched 2026-11-19T14:32:59Z),
2,996 upstream commits past the old merge base 401a1de. Merge commit only;
rerere disabled, so every resolution was made here.

80 conflicted paths (77 content, 3 modify/delete), each recorded with base,
ours and theirs blobs and its reason in the lane's stage2-conflicts.md:
- 8 take upstream whole: the openclaw#197153 pg16-smoke cherry-pick (6909b64) now
  ships upstream (ci.yml, ci-build-manifest, ci-workflow-planning test), the
  Control UI settings child moved onto runDistArtifactChild, the canary
  worker target and two active-facts migration tests.
- 3 deleted with upstream: session-fork and update-candidate-canary suites
  whose production paths upstream removed; cwd-split folded away (openclaw#198916),
  its one continuation case rehomed to attempt.continuation-tools.test.ts.
- One-owner cutovers where upstream now owns a fork extraction: the
  requester-origin projection and replacement-text helpers (openclaw#200533) replace
  the fork's byte-identical copies in user-turn-transcript.metadata.ts.
- Ports into fork-extracted owners: removalReason in the queued-start plan
  and collector-group sweep (openclaw#199868), the async prepared-pricing usage
  diagnostic, the announce flow types, and the session-delivery codec, which
  gains upstream's mediaCandidate kind, reviewedTaskId and their schemas
  (openclaw#198227), importing its retention type from the leaf types module.
- Transcript repair (openclaw#201304, post-b894): upstream's payload-free adapter
  kernel carries the fork's continue_delegate attachment redaction through a
  payload-adapter-only fact and a withBlock update.
- Reset cleanup: upstream's process and retained-send stops (openclaw#199079,
  openclaw#200326) with the fork's continuation-aware reason as the single input;
  the chat reset's retention adapter wraps upstream's stopSessionResetWork,
  the Gateway preemption keeps stopSessionResetSubagents as upstream does.
- Schema: upstream owns agent 42 (tool usage) and 43 (pending-input
  endings) and is at 43; 44 is unused upstream. Continuation's recipient
  authority moves 42 -> 44: version constants, step order, historical
  schemas, witness additive table and version set, backup scope, PostgreSQL
  ladder (V43 = current minus the authority table) and port descriptor.
  package.json schemaVersions state 40, agent 44.
- Generated outputs regenerated, never hand-merged: config baseline,
  gateway validators, postgres schema catalogs, worker-access inventory.
- Compile follow-through for upstream's delivery-union narrowing and its
  readSessionDelivery callers.

Refs openclaw#129388
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…pinner (#201157)

Related: #199079

## What Problem This Solves

When a hidden subagent finishes, fails, times out or is stopped, the servers and `nohup … &` processes it started keep running, with nothing left to manage them. Its parent's sidebar row keeps spinning, because the leftover processes still count on the dead child. Archiving a chat had the same gap. On 2026-11-18 a stopped worker left an isolated Gateway, a mock server and an HTTP server running until someone killed them by hand. The process-lifetime audit reproduced this on every subagent end path and on archive.

## User Impact

- A hidden subagent's `yieldMs` commands, `background: true` services and leftover processes (`cmd &`, `nohup`) stop when its task ends: it finishes, fails, times out or is stopped. A subagent waiting in `sessions_yield` keeps the command it waits on, and that command's exit still wakes it.
- Archiving a chat stops its processes, as reset and delete already do. If the stop cannot be confirmed, the archive fails with a retryable error and the chat stays unarchived.
- The parent row and the agent header stop spinning once the child's own run ends. A child's processes still show on its own row.
- **Behavior change:** to keep a service after a subagent ends, use `durable: true` or start it from the parent. Main chats, visible spawned sessions and the one-shot `agent --local` hand-off are unchanged.

## Why This Change Was Made

The chat stays the only owner of its processes (#199079, #200097), and `stopSessionExecProcesses` stays the only stop. Two chat ends never called it:
- **Subagent task end:** one subscriber on the registry's persistence publication derives "task ended" from the stored rows. All rows ended; none yielded, steer-restart or a visible session. It then stops the child's scope keys (key and session id, the same keys the row counts). Every end path writes its terminal row through that bus, so a new end path is covered automatically.
- **Archive:** calls the same stop after the lifecycle drain.
- **Sidebar:** one helper, `childShowsParentWorking`, replaces the two duplicated fold rules (session tree and team header). A child folds into its parent only while its run is visible, or while it is a yielded subagent waiting on its own command. No protocol change.
- **Text:** the `background` exec description and the background-process and subagent docs.

## Evidence

- **Contract table** (`subagent-task-end-processes.lifecycle.test.ts`, real processes: a service, a hand-off and a survivor per row). Complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5, the branch passes. The yielded child and the visible-session child keep their processes on both. About 20 s of test time.
- **Archive** (`server.sessions.archive-lifecycle.test.ts -t "archive stops the chat"`): both processes stop; an unconfirmed stop returns retryable `UNAVAILABLE` and does not archive. Base fails, the branch passes.
- **Sidebar** (`app-sidebar-session-tree.test.ts`): a `historical` child with processes does not spin its parent or the team header; `paused` and `active` children do. Base fails, the branch passes.
- tsgo core/ui/core-test, oxlint, format and `agent-tools.prefix-stability.test.ts`: green.

**Fault matrix rerun** (isolated Gateways, `env -i`, service marker set, scripted model; base `c8da4b7fbc40` → this branch). R2 = `yieldMs`, R3 = `background:true`, R4 = `nohup &`. L = alive and counted, C = clean.

| Cell | Base R2/R3/R4 | Head R2/R3/R4 |
|---|---|---|
| Subagent normal completion | L/L/L | **C/C/C** |
| Subagent model failure (400) | L/L/L | **C/C/C** |
| Subagent kill | C/L/L | **C/C/C** |
| Parent delete, child running | C/L/L | **C/C/C** |
| Parent delete, child completed | C/L/L | **C/C/C** |
| Archive | C/L/L | **C/C/C** |
| Subagent yielded on its hand-off | kept | kept (`paused`, count 1; exit resumes it) |
| Main chat: completion / abort / failure | L/L/L | unchanged by design |

A `setsid` double fork stays untracked on macOS, unchanged (follow-up).

**Real model** (`openai/gpt-6.2-sol`, this branch): a hidden subagent started a `background:true` HTTP server and a `nohup` process and was then killed. Both processes were gone afterwards, and the child row went from count 2 to no count.

**Control UI**, screenshot taken 12 s after the kill without a reload (base used the scripted model):

| Before (base) | After (this branch) |
| --- | --- |
| ![Base: parent row still spinning after the worker was killed](https://github.com/user-attachments/assets/70a79031-46d9-40ff-87f3-de7b98bcec88) | ![Branch: parent row shows a static dot after the worker was killed](https://github.com/user-attachments/assets/bf5fb28d-4485-4869-8593-8148fbdc3870) |
| ![Still spinning highlighted](https://github.com/user-attachments/assets/9501efca-61a2-42be-8d9d-7e5f11b7f7ff) | ![Stopped highlighted](https://github.com/user-attachments/assets/a6947c14-1553-4798-8bb8-82729f8966b2) |

## Merge danger and blast radius

- Two-way door: no stored rows, schema, config or protocol change; a revert fully restores the old lifetime.
- Hidden subagents that start services meant to outlive them now lose them at task end. Archive stops a chat's dev server.
- The stop touches only an ended hidden child's scope, and its `assertCurrent` re-derives the condition, so a resumed child is not stopped. An unconfirmed stop is logged and retried on the next publication for that child; a publication never throws.
- Cost: one map lookup per changed run per registry publication.
- Size: production +134/−18. The design estimated about +60 of logic; the rest is import formatting, the hoisted archive key list and the review fix that bounds the stop by the task's end time (a reset child key keeps its later processes). Tests: +376/−4.

## Left for later

PR 2: group kill for adopted survivors, the relay on macOS without the marker, a required `scopeKey` with a single factory and a teardown census, cron run sessions, `canStop: false` on killed children. PR 3: crash recovery for adopted survivors (needs approval) and Linux `cgroup.kill`.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit cf21361)

Release adaptation: Preserve stable process capacity and receipt documentation. The acquired archive drain fences the captured process scope without adding turn-time authority rechecks.
Companion audit: #199079 and #200097 process owners are present. 8d21848 is archive fixture isolation only, 0a26c24 changes unrelated sidebar semantics, and later retained-work/worker changes are independent.

Co-authored-by: RomneyDa <[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 docs Improvements or additions to documentation 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. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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