Repository navigation
Background shell jobs: shell_background runs a command as a job, with a real kill - #610
Conversation
… 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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
PasClaw/src/pkg/agent/PasClaw.Agent.SubagentBg.pas
Lines 1163 to 1164 in 47c3a2f
With subagents_enabled=false, ResolveSubagentSpecs returns an empty array and this guard skips the entire coordinator, including shell_background and its status/wait/cancel tools. That setting is documented as disabling model fan-out, while a local background shell does not require a subagent or provider; users who opt out of subagents unexpectedly lose the newly documented shell feature. Register the shell job tools independently of whether any subagent specs exist.
ℹ️ 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".
| P.Terminate; | ||
| Break; | ||
| end; | ||
| FStateLock.Enter; | ||
| try Cancelled := FState = bjCancelled; finally FStateLock.Leave; end; | ||
| if Cancelled then begin P.Terminate; Break; end; |
There was a problem hiding this comment.
Terminate the entire background process tree
When a command starts child processes, both timeout and cancellation call Terminate only on the /bin/sh or cmd.exe wrapper. Descendants such as compiler workers or commands launched with & can therefore continue modifying files and consuming resources after spawn_cancel reports that the job was killed. Start each local job in an isolated process group/job object and terminate that group for cancellation, timeout, and output-limit exits.
Useful? React with 👍 / 👎.
| GBackgroundDoneHook := nil; | ||
| TUIInst.Free; |
There was a problem hiding this comment.
Synchronize hook teardown with in-flight callbacks
If a background job finishes while the TUI is closing, clearing the global method pointer does not wait for a worker that has already passed the Assigned(GBackgroundDoneHook) check. That worker can enter TUIInst.BackgroundDone after this code frees TUIInst and its FBgFlashLock, causing a use-after-free during normal shutdown. Hook removal needs synchronization with callback dispatch or a lifetime-stable intermediary.
Useful? React with 👍 / 👎.
| {$ELSE} | ||
| { The FPC build is a line REPL with no footer; a line will do. } | ||
| WriteLn('[' + S + ']'); | ||
| {$ENDIF} |
There was a problem hiding this comment.
Drain completion notifications in the FPC TUI
In the FPC build, BackgroundDone only stores the message in FBgFlashPending, but DrainBackgroundFlash is called solely from the Delphi positioned-TUI loop. The FPC Run loop never invokes it, so this WriteLn branch is unreachable and background completions produce no operator notification despite the documented line-REPL behavior.
Useful? React with 👍 / 👎.
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
Four conflicts, all from both sides touching the same lines: Makefile / docs/configuration.md -- this branch's new rows and target sit where #608's tree-kill rewording landed. Kept both. PasClaw.Config.pas -- ApplyConfigGlobals: main renamed the shell timeout setter to SetShellToolTimeoutMs, this branch added the permission-rule wiring right beside it. Kept both. PasClaw.TUI.pas -- TTUI.Destroy. #610 moved FBgFlashLock.Free to the end (after the thread hand-off) and this branch had added the ask state's Free beside it at the top. Resolved by not freeing the ask lock or event at all: a worker parked in AskPermission leaves it within a poll slice of FQuit, but the bounded wait hands the thread to FreeOnTerminate after the same 250 ms, so Destroy cannot know it has left -- the same reasoning the file already records for FToolActivityLock. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U
#609 has merged, so this now targets
maindirectly withmainmerged in. Its diff is only the background-jobs work: nothing from B.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 ansh-<hex>handle immediately. The job runs the command on the local backend throughTStdioProcess, polling for output, the shell timeout and the cancelled state; on a non-local backend (docker) it goes throughExeclikeshell_execand cancel stays advisory. Same denylist and cwd rules asshell_exec.[background shell results]block, beside the subagent block.spawn_statusshows the command,spawn_waitreturns the full output,spawn_cancelkills a local shell job and everything it started.TProcessis not thread-safe, and aTerminateracing the owner's poll is a double reap, which is exactly the access violation the first cut produced under-O2.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 abackground_donedesktop 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
P1 — the kill took only the shell. All three exits of the job loop (cancel, timeout, output cap) signalled the
/bin/sh(orcmd.exe) wrapper alone, so compiler workers, amake -jand anything launched with&kept running afterspawn_cancelreported the job killed. They now go throughTerminateProcessTree, the callPasClaw.Platform's own one-shot timeouts already use.Not the isolated process group the review asked for, because there is no portable way to get one here: FPC's
TProcesshas no POSIX process-group option (poNewProcessGroupis Windows-only) andsetsidis 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 istaskkill /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, inRunOneShot,RunOneShotWithEnvandRunArgvCapture. Worse than it reads, because the orphaned flooder keeps writing into a pipe nobody reads any more andRunOneShotnever 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 theTTUIobject 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 behindSetBackgroundDoneHook/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 leaksFToolActivityLock— a worker handed to the OS byFreeOnTerminatemay still be on its way in. With teardown now ordered,TTUI.DestroyfreesFBgFlashLockproperly, at the end rather than before the thread joins.P2 — the FPC TUI never showed a completion.
BackgroundDoneparked the line, butDrainBackgroundFlashwas only called from the Delphi frame loop, so the FPC branch of it was dead code. 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. That branch also usesPrintLnrather thanWriteLnnow, like the rest of the surface.Not in the review: the Delphi build of this branch did not compile. A stray
if S <> '' then Flash(S); end;sat at the top level ofPasClaw.TUI.pas, left behind when a routine header was deleted. It is inside the file's large{$IFNDEF FPC}block, so FPC never parsed it andmake testwas green — only dcc64 would ever have seen it. Deleted, andscripts/check-pascal-shape.py(whichmake testalready runs throughtest-desktop) gained the rule that catches it: after a line that is exactlyend;in column 0, the next line of code must start a new declaration in column 0, not an indented statement. Clean across every.pasand.dprin the tree; the rule stays narrow because that script's own notes record a begin/end balance check tried there and removed for crying wolf.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 jobsspawn_waitalready collected.Added with the review fixes, each negative-verified by reverting the fix:
shell_timeout_tests:yesfloods past 1 MiB with a grandchild recorded. Reverting that one does not fail, it hangs, which is the second half of the bug.TTUI.Runbodies are checked to call the drain, since neither loop can be driven from a test (one positions a console, the other blocks inReadLn). The check strips comments first — its first cut passed on a body that only mentioned draining in a comment.Full
make test: green, 0 make errors.Docs
docs/tools.md,docs/configuration.md(background_jobs_max),docs/agent-features.md.🤖 Generated with Claude Code
https://claude.ai/code/session_01KYD1zZPD7GuM8pF1btwi2U