Skip to content

Background shell jobs, onto main: shell_background runs a command as a job, with a real kill - #619

Merged
FMXExpress merged 5 commits into
mainfrom
claude/opencode2-c-async-shell
Oct 23, 2026
Merged

FMXExpress merged 5 commits into
mainfrom
claude/opencode2-c-async-shell

Conversation

@FMXExpress

@FMXExpress FMXExpress commented Oct 23, 2026 •

Copy link
Copy Markdown
Owner

Re-opens #610 against main. #610 was merged into #609's branch rather than main, so its work landed in claude/opencode2-b-codemode (four commits ahead of main) and never reached main; GitHub will not change the base of a merged pull request, hence a new number. Same branch, same head — main is merged in and the diff below is only the background-jobs work, nothing from #609.

What

A build or a test suite that takes minutes should not block the turn, and it should be killable. PasClaw had background subagents with handles, status, wait, cancel and the loop-top drain; a shell command is the cheaper thing that was missing, so it reuses all of that rather than growing a second coordinator.

  • shell_background(command, cwd?, timeout_sec?) returns an sh-<hex> handle immediately. The job runs the command on the local backend through TStdioProcess, polling for output, the shell timeout and the cancelled state; on a non-local backend (docker) it goes through Exec like shell_exec and cancel stays advisory. Same denylist and cwd rules as shell_exec.
  • When it finishes, its output (exit code on line 1) reaches the model at the top of its next turn as a [background shell results] block, beside the subagent block. spawn_status shows the command, spawn_wait returns the full output, spawn_cancel kills a local shell job and everything it started.
  • shell_background is a shell tool, not a subagent one: it and the three handle verbs register whatever subagents_enabled says. Only spawn_background needs a subagent.
  • The job's own thread does the kill: TProcess is not thread-safe, and a Terminate racing the owner's poll is a double reap, which is exactly the access violation the first cut produced under -O2.
  • Operator notification: a job's completion goes through FireBackgroundDone (the TUI parks it and flashes it in the footer on the next frame; the FPC line REPL prints it as a line) and publishes a background_done desktop event for the web UI. The model needs neither: the drain at the top of its next turn delivers the result.
  • background_jobs_max (default 6) caps subagent and shell jobs together per coordinator, replacing the compile-time 4.

Review fixes on this PR

P1 — the descendant walk was Linux-only. TerminateProcessTree found descendants by enumerating /proc and reading /proc/<pid>/stat. macOS and the BSDs have no /proc, so the snapshot came back empty, only the shell pid was signalled, and a cancelled, timed-out or output-capped command left its children running while PasClaw reported it stopped. That affected every caller, not just background jobs — shell_exec's timeout and the output cap too.

The walk now reads /proc when it is there (no subprocess, and the only source in a stripped container with no ps) and falls back to ps -axo pid=,ppid= when it is not — the trailing = suppresses headers on BSD and procps alike, /bin/ps tried before the bare name. A thread-local guard stops the fallback recurring into itself, since RunArgvCapture kills a timed-out child through TerminateProcessTree.

Process-group isolation, the other option the review offered, is the better mechanism and is not reachable from here: FPC's TProcess has no POSIX process-group option (poNewProcessGroup is Windows-only) and setsid is not a binary to count on, so a group would need our own fork/setpgid/exec wrapper on every spawn path plus a Windows job-object equivalent. The parent-link walk catches every descendant that has not deliberately re-parented itself, which is what the leak was made of.

P2 — subagents_enabled:false took the background shell with it. Every caller resolved the subagent specs first and skipped the whole registration when the list was empty, so turning off LLM subagents silently removed shell_background, spawn_status, spawn_wait and spawn_cancel. Only spawn_background is gated on specs now — in RegisterBackgroundSpawnTools, RegisterSubagentTools (serve / gateway), the CLI's MaybeRegisterBackgroundSpawnTools, and Cmd_TUI_Run.

Review fixes (carried over from #610)

P1 — the kill took only the shell. All three exits of the job loop (cancel, timeout, output cap) signalled the /bin/sh (or cmd.exe) wrapper alone, so compiler workers, a make -j and anything launched with & kept running after spawn_cancel reported the job killed. They now go through TerminateProcessTree, the call PasClaw.Platform's own one-shot timeouts already use.

While there: PasClaw.Platform's own output-cap exits had the same leak — #608 fixed the timeout exit and left the cap signalling the shell alone, in RunOneShot, RunOneShotWithEnv and RunArgvCapture. Worse than it reads, because the orphaned flooder keeps writing into a pipe nobody reads any more and RunOneShot never returns.

P2 — clearing the completion hook did not wait for a callback in flight. if Assigned(hook) then hook(...) has a window between the test and the call; the TUI installs a method of the TTUI object and clears the hook on its way to freeing that object, so a job finishing during an ordinary shutdown could run a method of freed memory. The hook now lives behind SetBackgroundDoneHook / FireBackgroundDone, which take one lock: clearing it blocks until a running handler returns and no new one can start. The lock is nilled but never freed at finalization, for the same reason the TUI leaks FToolActivityLock. With teardown now ordered, TTUI.Destroy frees FBgFlashLock properly, at the end rather than before the thread joins.

P2 — the FPC TUI never showed a completion. BackgroundDone parked the line, but DrainBackgroundFlash was only called from the Delphi frame loop, so the FPC branch of it was dead code. The line REPL now drains before printing its prompt and right after the operator's Enter, through PrintLn like the rest of that surface.

Not in the review: the Delphi build did not compile. A stray if S <> '' then Flash(S); end; sat at the top level of PasClaw.TUI.pas, inside the file's large {$IFNDEF FPC} block, so FPC never parsed it and make test was green. Deleted, and scripts/check-pascal-shape.py (run by make test through test-desktop) gained the narrow rule that catches it: after a column-0 end;, the next line of code must start a declaration in column 0. Clean across every .pas and .dpr in the tree.

Not in this PR

Moving a running foreground turn to the background (/bg). The TUI runs one loop thread per process, and detaching it means a second loop on the same session, which is a larger change than the shell jobs deserve to carry. Noted in the plan.

Tests

subagent_bg_tests: a job runs and delivers exit + output, status names the command, the done hook fires with the handle and the drain key, the denylist refuses, a 1 s timeout kills a 30 s sleep with exit 124 promptly, cancel kills a running sleep within a poll, the drain delivers uncollected jobs once under the shell header and skips jobs spawn_wait already collected.

Added with the review fixes, each negative-verified by reverting the fix:

  • no /proc (shell_timeout_tests): the grandchild fixture run again with the procfs root pointed at a path that does not exist — the only way to take the ps branch on a box that has /proc. SetProcFSRootForTests exists for that and is a no-op on Windows. Reverting the fallback leaves the grandchild alive. The case skips itself when /bin/ps is missing. Its first run failed on a real bug in my own parse (a nested routine cleared the caller's accumulator, which — a const string being passed by reference — cleared its own argument), fixed with a note.
  • subagents off: with an empty spec array, shell_background and the three handle verbs register and a job runs end to end, while spawn_background does not. Reverting the split fails.
  • cancel and timeout: a grandchild records its pid and sleeps 45 s; both exits must leave it dead. Reverting the tree kill fails on the cancel case.
  • hook teardown: a handler that sleeps 600 ms, caught mid-call, then the clear is timed. Reverting the lock fails.
  • the output cap: yes floods past 1 MiB with a grandchild recorded. Reverting that one does not fail, it hangs, which is the second half of the bug.
  • both TTUI.Run bodies are checked to call the drain (comments stripped first), since neither loop can be driven from a test.

Docs

docs/tools.md (and that shell_background does not depend on subagents_enabled), docs/configuration.md (background_jobs_max), docs/agent-features.md, docs/security.md (the tree kill covers cancel and the output cap, and how descendants are found per platform).

After this merges

claude/opencode2-b-codemode is ahead of main only because #610 landed there; once this is in, that branch holds nothing main lacks and can be deleted. #611 (permissions) is based on this branch and I will retarget it to main as soon as this merges — its diff is then only the permissions work.


🤖 Generated with Claude Code

https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U

… a real kill

PR C of docs/opencode2-plan.md. A build or a test suite that takes
minutes should not block the turn, and it should be killable. PasClaw
had background subagents with handles, status, wait, cancel and the
loop-top drain; a shell command is the cheaper thing that was missing,
so it reuses all of that rather than growing a second coordinator.

shell_background(command, cwd?, timeout_sec?) returns an sh-<hex>
handle immediately. The job runs the command on the local backend
through TStdioProcess, polling for output, the shell timeout and the
cancelled state; on a non-local backend (docker) it goes through
Exec like shell_exec and cancel stays advisory. Same denylist and cwd
rules as shell_exec. When it finishes, its output (exit code on line 1)
reaches the model at the top of its next turn as a [background shell
results] block, beside the subagent block; spawn_status shows the
command, spawn_wait returns the full output, and spawn_cancel kills a
local shell job -- the job's own thread does the kill, because
TProcess is not thread-safe and a Terminate racing the owner's poll is
a double reap, which is exactly the access violation the first cut
produced under -O2.

Completions are visible to the operator too: a job calls
GBackgroundDoneHook (the TUI parks it and flashes it in the footer on
the next frame; the FPC line REPL prints it) and publishes a
background_done desktop event for the web UI. The model needs neither:
the drain at the top of its next turn delivers the result, so the
"wake an idle parent" problem is a notification problem, not a
steering one. Moving a running foreground turn to the background (/bg)
is not in this PR: the TUI runs one loop thread per process, and
detaching it means a second loop on the same session, which is a
larger change than the shell jobs deserve to carry.

background_jobs_max (default 6) caps subagent and shell jobs together
per coordinator, replacing the compile-time 4.

Tested in subagent_bg_tests: a job runs and delivers exit + output,
status names the command, the done hook fires with the handle and the
drain key, the denylist refuses, a 1 s timeout kills a 30 s sleep with
exit 124 promptly, cancel kills a running sleep within a poll, the
drain delivers uncollected jobs once under the shell header and skips
jobs spawn_wait already collected. The suite was run three times in a
row at -O2 after the fix.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
docs/configuration.md and docs/tools.md conflicted: both sides touched
the shell_timeout_sec row and the shell_exec timeout paragraph -- #608's
tree-kill wording in main against this branch's background-jobs rows.
Kept both, with the tree-kill wording, and said that cancelling a
background job kills the tree too (which the next commit implements).

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
…fe to tear down

Three review findings on the background-jobs PR, plus a Delphi build
break the review did not mention.

**The Delphi build of this branch did not compile.** A stray `if S <> ''
then Flash(S); end;` sat at the top level of PasClaw.TUI.pas, left behind
when a routine header was deleted. It is inside the file's big
{$IFNDEF FPC} block, so FPC never parsed it and `make test` was green;
only dcc64 would ever have seen it. Deleted, and
scripts/check-pascal-shape.py (which `make test` already runs through
test-desktop) gained the rule that would have caught it: after a line
that is exactly `end;` in column 0, the next line of code must start a
new declaration in column 0, not an indented statement. Clean across
every .pas and .dpr in the tree; the rule stays narrow because this
file's own notes record that a begin/end balance check was tried here and
removed for crying wolf.

**Cancel and timeout killed only the shell wrapper.** Everything the
command had started -- compiler workers, a `make -j`, anything launched
with `&` -- kept running after spawn_cancel reported the job killed,
still writing files with nothing holding a handle to them. All three
exits of the job loop (cancel, timeout, output cap) now go through
TerminateProcessTree, the same call PasClaw.Platform's own one-shot
timeouts use.

Codex asked for an isolated process group instead. There is no portable
way to get one here: FPC's TProcess has no POSIX process-group option
(poNewProcessGroup is Windows-only) and `setsid` is not a binary to count
on (util-linux ships one, macOS does not). The parent-link walk catches
every descendant that has not deliberately re-parented itself, and on
Windows is `taskkill /T /F`.

While there: PasClaw.Platform's own output-cap exits had the same leak --
#608 fixed the timeout exit and left the cap signalling the shell alone,
in RunOneShot, RunOneShotWithEnv and RunArgvCapture. Worse than it looks,
because the orphaned flooder keeps writing into a pipe nobody reads any
more and RunOneShot never returns.

**Clearing the completion hook did not wait for a callback in flight.**
`if Assigned(GBackgroundDoneHook) then GBackgroundDoneHook(...)` has a
window between the test and the call. The TUI installs a method of the
TTUI object and clears the hook on its way to freeing that object, so a
job finishing during an ordinary shutdown could run a method of freed
memory. The hook now lives behind SetBackgroundDoneHook /
FireBackgroundDone, which take the same lock: clearing it blocks until a
running handler returns and no new one can start. The lock is nilled but
never freed at finalization, for the same reason the TUI leaks
FToolActivityLock -- a worker handed to the OS by FreeOnTerminate may
still be on its way in. With the teardown now ordered, TTUI.Destroy can
free FBgFlashLock properly, at the end rather than before the thread
joins.

**The FPC TUI never showed a completion.** BackgroundDone parked the
line, but DrainBackgroundFlash was only called from the Delphi frame
loop, so the FPC branch of it was dead code and the operator was told
nothing. The line REPL now drains at the two moments it is looking at the
prompt: before printing it, and right after the operator's Enter.

Tested (test-subagent-bg, test-shell-timeout), each fix negative-verified
by reverting it:

  - cancel and timeout: a grandchild records its pid and sleeps 45 s;
    both exits must leave it dead. Reverting the tree kill fails on the
    cancel case.
  - hook teardown: a handler that sleeps 600 ms, caught mid-call, then
    the clear is timed. Reverting the lock fails -- the clear returns
    while the handler is still running.
  - the output cap, in shell_timeout_tests: `yes` floods past 1 MiB with
    a grandchild recorded. Reverting this one does not fail, it HANGS,
    which is the second half of the bug.
  - both TTUI.Run bodies are checked to call the drain, since neither
    loop can be driven from a test (one positions a console, the other
    blocks in ReadLn). The check strips comments first -- its first cut
    passed on a body that only mentioned draining in a comment.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T05:05:22.370175Z d2aaaef PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d2aaaefae0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +420 to +421
TerminateProcessTree(P.ProcessId);
if P.Running then try P.Terminate; except end;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use a portable tree-kill mechanism for background shells

On supported macOS/BSD builds, cancelling, timing out, or output-capping a local background command with child processes leaves those descendants running. This call relies on TerminateProcessTree, but its POSIX implementation discovers descendants exclusively through /proc/*, which these systems do not provide, so it only signals the shell PID before reporting the job stopped. Use process-group isolation or a platform-specific descendant enumeration method rather than the Linux-only /proc walk.

Useful? React with 👍 / 👎.

T.Category := tcMutating;
Reg.Register(T);

T.Name := 'shell_background';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Register shell_background when subagents are disabled

With subagents_enabled:false, every caller supplies an empty Specs array and this registration routine exits before reaching the new shell_background definition, so disabling LLM subagents also silently removes the unrelated background-shell feature. The documentation exposes shell_background as a shell tool without this dependency; create the coordinator and register the shell/status/wait/cancel tools independently of whether subagent specs exist.

Useful? React with 👍 / 👎.

…subagent feature

Two review findings on the background-jobs PR.

**P1: the descendant walk was Linux-only.** TerminateProcessTree found
descendants by enumerating /proc and reading /proc/<pid>/stat. macOS and
the BSDs have no /proc, so the snapshot came back empty, only the shell
pid was signalled, and a cancelled, timed-out or output-capped command
left its compiler workers and `&` children running while PasClaw
reported the job stopped. Every caller was affected, not just the
background jobs: shell_exec's timeout and the 1 MiB cap too.

The walk now takes its process table from /proc when it is there -- no
subprocess, and the only source in a stripped container with no `ps` --
and from `ps -axo pid=,ppid=` when it is not. The trailing `=` suppresses
headers on BSD and procps alike, and /bin/ps is tried before the bare
name. A thread-local guard stops the fallback recurring into itself:
RunArgvCapture kills a timed-out child through TerminateProcessTree,
which lands back in the walk.

Codex offered process-group isolation as the alternative. It is the
better mechanism and it is not reachable from here: FPC's TProcess has
no POSIX process-group option (poNewProcessGroup is Windows-only) and
`setsid` is not a binary to count on, so a group would need our own
fork/setpgid/exec wrapper on every spawn path and a Windows job-object
equivalent. The parent-link walk catches every descendant that has not
deliberately re-parented itself, which is what the leak was made of.

**P2: subagents_enabled:false took the background shell with it.** Every
caller resolved the subagent specs first and skipped the whole
registration when the list was empty, so turning off LLM subagents
silently removed shell_background, spawn_status, spawn_wait and
spawn_cancel -- tools the docs describe as shell features with no such
dependency. Only spawn_background actually needs a subagent to spawn, so
it is now the only one the specs gate; the coordinator and the rest
register regardless, in RegisterBackgroundSpawnTools, RegisterSubagentTools,
MaybeRegisterBackgroundSpawnTools (CLI) and Cmd_TUI_Run.

Tested, each fix negative-verified by reverting it:

  - shell_timeout_tests: the existing grandchild fixture run again with
    the procfs root pointed at a path that does not exist, which is the
    only way to take the `ps` branch on a box that has /proc. New
    SetProcFSRootForTests exists for that and is a no-op on Windows.
    Reverting the fallback leaves the grandchild alive. The case skips
    itself when /bin/ps is missing rather than failing.
  - subagent_bg_tests: with an empty spec array, shell_background and the
    three handle verbs register and a job runs end to end, while
    spawn_background does not register. Reverting the split fails on the
    coordinator never being created.

The `ps` parse was wrong on the first cut and the test caught it: a
nested routine cleared the caller's accumulator, which -- a `const`
string parameter being passed by reference -- cleared its own argument
with it, so nothing parsed. Its locals are its own now, with a note.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
@FMXExpress
FMXExpress merged commit 0a19c38 into main Oct 23, 2026
FMXExpress pushed a commit that referenced this pull request Oct 23, 2026
…lag, and refuse before touching the repo

This branch now targets main. It brings in the updated #611 branch,
which carries main -- #609 code mode and #619 background jobs, both
merged -- so the PR's diff against main is permissions plus worktrees
until #611 lands, then worktrees alone. Worktrees depend on #611: they
add resource mappings to PasClaw.Permissions, the file #611 creates.

Three conflicts:

  docs/configuration.md -- this branch's worktree rows sat where main
  reworded shell_timeout_sec. Kept both, and said that
  worktree.enabled:false takes the spawn argument away too.

  PasClaw.Permissions.pas, ResourceOf -- this branch added
  worktree_remove/worktree_create cases to the old name list that #611
  replaced with a generic path/url/command fall-through. worktree_remove
  takes a `path`, which the fall-through already reads; worktree_create
  is named by its `branch`, which no generic field covers, so it keeps a
  named case.

  PasClaw.Agent.SubagentBg.pas, the spawn_background registration --
  #619 put it inside `if Length(Specs) > 0` so the shell tools survive
  subagents being off; this branch added a `worktree` schema property.
  Kept #619's structure; the property is now conditional (below).

And the two review findings, both P2, both real:

**worktree.enabled:false only took away one door of three.** Callers
dropped the worktree_* tools, but spawn and spawn_background still
advertised a `worktree` argument and still created a branch and a
checkout when it was passed. WorktreeArgEnabled (a nil Cfg reads as the
documented default, on) now gates both handlers, which refuse the
argument with a message saying how to proceed, and both schemas, which
stop offering it.

**spawn_background created the worktree before checking the job cap.**
A spawn the cap was always going to refuse still made a branch and a
checkout on disk, then returned the capacity error. Checking first is
not enough by itself -- two spawns in one parallel batch would both pass
and both create -- so the slot is reserved under the lock (FReserved,
counted by SlotsInUse alongside running jobs, and shell_background's cap
check counts it too), the slow git work runs outside the lock, and the
reservation becomes the job or is handed back on failure.

spawn had the same shape with its cheap checks: an unknown agent or an
empty prompt made a worktree on its way to being refused. EnsureWorktree
now runs after every check that can reject the call.

Tested (test-worktree), each fix negative-verified by reverting it:

  - with worktree.enabled:false, neither spawn nor spawn_background
    offers the property, both refuse it, and no directory or branch
    appears; with it on, spawn offers it again. Reverting the gate fails
    on the schema assertion.
  - spawn with an unknown agent or no prompt, and spawn_background at a
    cap of 1 held by a running shell job, each leave no worktree
    directory and no branch. Reverting the reservation fails on the cap
    case. Reverting spawn's ordering fails too -- on the flag test first,
    since the reverted order also runs ahead of the flag check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants