graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Headless runs wait for their background work to report
justrachcd948c761506
diff --git a/docs/adr/0215-headless-runs-wait-until-idle.md b/docs/adr/0215-headless-runs-wait-until-idle.mdnew file mode 100644index 00000000..8d42be54--- /dev/null+++ b/docs/adr/0215-headless-runs-wait-until-idle.md@@ -0,0 +1,66 @@+# 0215. Headless runs wait until their background work reports++Status: accepted 2026-09-29++## Context++A long command moves to the background after the foreground wait (15 s under+lean `-p`, 120 s elsewhere), and a subagent can run in the background. Each+reports when it finishes: a job posts an exit notice (`job_notify.zig`) and a+subagent leaves a report. Interactive surfaces deliver that as an idle wake:+the TUI, the line REPL and ACP start a new turn with it (ADR 0118, ADR 0154).++Headless surfaces have no idle wake. `-p`, `--json` (the SDKs), `graff serve`+and piped stdin ended the run on the model's first reply without tool calls.+The tool results tell the model it is "notified on exit — do not poll", so it+ends with "the build is running; I will report when it finishes". That ended+the run, and the notice was never read. Under `-p` the process then exited.++The unreal-agent harness makes the opposite the rule for every run. Tool calls+are asynchronous and each result wakes a turn. Ending a turn with no tool+calls while calls are running sleeps until one finishes; ending it with+nothing running ends the session. A heartbeat wakes the model after ten silent+minutes.++## Decision++A headless root turn runs until idle (`run_idle.zig`).++- Where a plain final would end the root turn, after the empty-reply retry and+ after the one open-checklist reminder (ADR 0064), the run looks for live+ background work: a running shell job that will post an exit notice, and a+ background subagent the root started. A server never reports, so a job that+ is persistent, pinned, detached, or whose process group listens on a TCP port+ (lsof) does not count.+- With live work, the run waits. A queued exit notice or a finished subagent's+ report continues the turn, and the next request carries it. A notice that+ landed during the final model call is delivered the same way, so no result+ is lost at the end of a run.+- After `GRAFF_HEARTBEAT_SECS` (default 600, 0 turns it off) with no news, a+ heartbeat notice names the running work and wakes the model to check on it,+ stop it, or end its reply to keep waiting. Three heartbeats in a row with no+ result and no tool call end the wait.+- The wait ends early on cancel, when a `--json` client sends its next request+ (that request runs, and its first step boundary delivers whatever reported),+ or when the run budget cannot buy another request.+- A headless root also receives a finished background subagent's report at+ each step boundary, capped at 6 KB, as an interactive root does.+- The system prompt says so (the `background` segment, gated on local tools):+ background work reports back when it finishes, a reply that ends while it+ runs waits for the result, and a reply with nothing running ends the run.++Interactive surfaces are unchanged: their turn ends and the idle wake starts+the next one.++## Consequences++- A headless run lasts as long as its background work. The heartbeat, the+ quiet-heartbeat cap, the run budget (`--max-model-calls`) and the caller's+ own timeout bound it.+- A long-lived process the lsof check does not see as a server (no lsof on the+ host, or not listening yet) holds the run until it exits or the+ quiet-heartbeat cap ends the wait.+- A `--json` turn's terminal `turn` event arrives after its background work+ reports. SDK loops already wait for `turn` or `error`.+- Revisit if a caller needs a headless run that returns with work still+ running. That would be an opt-out flag, not a return to losing results.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex cab51b0d..217c34bc 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -241,6 +241,7 @@ record only when you need the evidence or the edge cases.| [0212](0212-build-time-is-analysis-bound.md) | A cold build is ~16 s of single-core semantic analysis; codegen and link are nearly free. No redundant files to cut. Keep the default backend: `-fllvm` is 2x slower, `-fincremental`/`--watch` do not help on Zig 0.17-dev, and `-fno-llvm -fno-lld` exhausts memory. Iterate with `-Dtest-filter` (44 s → 13 s). || [0213](0213-line-repl-paste-is-framed-and-typed.md) | Keep line-REPL paste framed through active turns; submit one draft on Enter, and stage or reject bounded image data URIs before text expansion. || [0214](0214-evals-are-mined-and-hillclimbed-on-a-held-out-split.md) | Mine live eval tasks from merged PRs, with graders validated red on the parent and green and stable on the merge, and a person approving each. Hill-climb on a fixed held-out split with measured noise: keep a change only when train beats the noise band and test improves. Model-guide advice enters as candidates, not edits. |+| [0215](0215-headless-runs-wait-until-idle.md) | Headless roots (`-p`, `--json`, `graff serve`, piped stdin) wait for their own background work to report before a plain final ends the run. Servers do not count, a 10-minute heartbeat wakes the model, and interactive surfaces keep their idle wake. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 7e501974..2d47f458 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -119,8 +119,8 @@{"args": ["--old"], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the isolated publication fixture and report its result.", "id": "publication-pending-ci-failure", "why": "#1179: pending exact-head branch CI is reread before deciding whether publication is ready.", "github_fixture": {"checks": "SUCCESS", "runs": "pending", "run_sequence": ["pending", "failure"], "review_files": ["notes.md"]}, "script": [{"tool": "shell", "arguments": {"command": "gh pr create --title fixture --body-file notes.md"}}, {"text": "Publication remains blocked by failed CI."}], "assert": [{"request_contains": {"text": "exact head SHA has a failed branch run"}}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('mutations.jsonl').exists()"]}{"id": "btw-advertised-tools-never-execute", "why": "ADR0011: cached tools remain advertised to /btw, but an unsolicited tool call must never dispatch or pollute the parent history.", "workspace_seed": {"sentinel.txt": "unchanged"}, "prompt": "Describe the current task briefly.", "controls_after_turn": [{"type": "btw", "text": "SIDE-QUESTION-SENTINEL"}], "second_prompt": "Continue the original discussion.", "script": [{"text": "Initial discussion."}, {"tool": "write_file", "arguments": {"path": "sentinel.txt", "content": "SIDE-EFFECT-SENTINEL"}}, {"text": "Original discussion continues."}], "assert": [{"event": {"type": "error", "message": "side question failed; the conversation is unchanged"}}, {"no_event": {"type": "tool_call"}}, {"file_equals": {"path": "sentinel.txt", "content": "unchanged"}}, {"request_contains": {"index": 1, "text": "\"tools\""}}, {"request_lacks": {"index": -1, "text": "SIDE-QUESTION-SENTINEL"}}, {"request_lacks": {"index": -1, "text": "SIDE-EFFECT-SENTINEL"}}, {"final_text_contains": "Original discussion continues."}]}{"id": "completion-result-keeps-evidence-and-limits", "why": "A result-only completion must deliver the full verified answer and remaining limitations without requiring duplicate assistant prose; this checks delivery, not model compliance with the wording.", "prompt": "Run the fixture verification command, then report the exact evidence and the remaining integration-test limitation.", "script": [{"tool": "shell", "arguments": {"command": "printf 'fixture verification: OK\\n'"}}, {"tool": "attempt_completion", "arguments": {"result": "Verified: fixture verification: OK.\nRemaining: integration tests were not run."}}], "assert": [{"event": {"type": "tool_result", "name": "shell", "is_error": false}}, {"final_text_contains": "Verified: fixture verification: OK."}, {"final_text_contains": "Remaining: integration tests were not run."}, {"events_at_most": {"match": {"type": "model_call_started"}, "count": 2}}]}-{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-pending-automatic", "why": "An unfinished shell receipt cannot satisfy same-batch completion; pending is not command failure.", "script": [{"tools": [{"tool": "shell", "arguments": {"command": "sleep 1; exit 0", "timeout": 1}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}], "assert": [{"event": {"type": "tool_call_finished", "name": "shell", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "Verification is still pending."}]}-{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-pending-explicit", "why": "An unfinished shell receipt cannot satisfy same-batch completion; pending is not command failure.", "script": [{"tools": [{"tool": "shell", "arguments": {"command": "sleep 0.2; exit 0", "run_in_background": true}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}], "assert": [{"event": {"type": "tool_call_finished", "name": "shell", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "Verification is still pending."}]}+{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-pending-automatic", "why": "An unfinished shell receipt cannot satisfy same-batch completion; pending is not command failure. The headless run then waits for the job and continues with its exit instead of ending.", "script": [{"tools": [{"tool": "shell", "arguments": {"command": "sleep 1; exit 0", "timeout": 1}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}, {"text": "Verification finished: the check exited 0."}], "assert": [{"event": {"type": "tool_call_finished", "name": "shell", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"request_contains": {"index": 2, "text": "exited 0: sleep 1; exit 0"}}, {"final_text_contains": "Verification finished: the check exited 0."}]}+{"args": ["--old"], "prompt": "Run the scripted verification fixture and report only observed results.", "id": "completion-pending-explicit", "why": "An unfinished shell receipt cannot satisfy same-batch completion; pending is not command failure. The headless run then waits for the job and continues with its exit instead of ending.", "script": [{"tools": [{"tool": "shell", "arguments": {"command": "sleep 0.2; exit 0", "run_in_background": true}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}, {"text": "Verification finished: the check exited 0."}], "assert": [{"event": {"type": "tool_call_finished", "name": "shell", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"request_contains": {"index": 2, "text": "exited 0: sleep 0.2; exit 0"}}, {"final_text_contains": "Verification finished: the check exited 0."}]}{"args":["--old"],"prompt":"Run the scripted verification fixture and report only observed results.","id":"completion-resumed-failure","why":"A resumed verification result admits completion only after a successful terminal exit.","script":[{"tool":"shell","arguments":{"command":"printf 'RESUMED_EXIT_SEVEN\\n'; exit 7","run_in_background":true}},{"tool":"shell","arguments":{"command":"sleep 0.3"}},{"tools":[{"tool":"shell","arguments":{"action":"output","id":4294967296,"wait_ms":1000}},{"tool":"attempt_completion","arguments":{"result":"FAILED_COMPLETION"}}]},{"text":"Verification failed; completion withheld."}],"assert":[{"event":{"type":"tool_call_finished","name":"attempt_completion","is_error":true}},{"no_event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"event":{"type":"tool_result","name":"shell","is_error":true,"text":"[job 4294967296: exited with code 7]\nRESUMED_EXIT_SEVEN\n","id":"call_3_0"}},{"request_contains":{"text":"exited with code 7"}}],"workspace_seed":{".codegraff/shell-id.lock":"shell-ids-v1\n",".codegraff/shell-id.counter":"4294967295\n"}}{"args":["--old"],"prompt":"Run the scripted verification fixture and report only observed results.","id":"completion-resumed-success","why":"A resumed verification result admits completion only after a successful terminal exit.","script":[{"tool":"shell","arguments":{"command":"printf 'RESUMED_EXIT_ZERO\\n'; exit 0","run_in_background":true}},{"tool":"shell","arguments":{"command":"sleep 0.3"}},{"tools":[{"tool":"shell","arguments":{"action":"output","id":4294967296,"wait_ms":1000}},{"tool":"attempt_completion","arguments":{"result":"VERIFIED_COMPLETION"}}]},{"text":"Verification failed; completion withheld."}],"assert":[{"event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"final_text_contains":"VERIFIED_COMPLETION"},{"event":{"type":"tool_result","name":"shell","is_error":false,"text":"[job 4294967296: exited with code 0]\nRESUMED_EXIT_ZERO\n","id":"call_3_0"}}],"workspace_seed":{".codegraff/shell-id.lock":"shell-ids-v1\n",".codegraff/shell-id.counter":"4294967295\n"}}{"id": "malformed-edit-batch-recovers", "why": "A string-valued edits field used to panic on unchecked union access; return a tool error without writing so the next model turn can retry a valid array and finish.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Create version.txt with alpha and beta, then update both lines using a batched edit. Correct any malformed arguments and verify the final file.", "script": [{"tool": "write_file", "arguments": {"path": "version.txt", "content": "alpha\nbeta\n"}}, {"tool": "edit_file", "arguments": {"path": "version.txt", "edits": "[{\"old_string\":\"alpha\",\"new_string\":\"ALPHA\"}]"}}, {"tool": "edit_file", "arguments": {"path": "version.txt", "edits": [{"old_string": "alpha", "new_string": "ALPHA"}, {"old_string": "beta", "new_string": "BETA"}]}}, {"tool": "bash", "arguments": {"command": "test \"$(cat version.txt)\" = \"$(printf 'ALPHA\\nBETA')\" && echo EDIT_BATCH_RECOVERED"}}, {"text": "The corrected batch landed and was verified."}], "assert": [{"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": true}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 1}}, {"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": false}}, {"request_contains": {"index": 2, "text": "edits must be an array"}}, {"event": {"type": "tool_result", "name": "bash", "text": "EDIT_BATCH_RECOVERED\n"}}, {"file_equals": {"path": "version.txt", "content": "ALPHA\nBETA\n"}}, {"final_text_contains": "The corrected batch landed and was verified."}]}@@ -130,7 +130,7 @@{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-ordered-edit-then-verification", "why": "A dependent verification sees the preceding edit within one RLM script.", "script": [{"tool": "rlm", "arguments": {"code": "e = edit_file(path=\"target.txt\", old_string=\"old\", new_string=\"new\")\nv = bash(\"test $(cat target.txt) = new && printf ORDER_VERIFIED\")\nprint(v)"}}, {"text": "Ordered verification passed."}], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": false}}, {"request_contains": {"index": 1, "text": "ORDER_VERIFIED"}}, {"file_equals": {"path": "target.txt", "content": "new"}}]}{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-failed-edit-blocks-tail", "why": "A failed native edit aborts dependent RLM commands without marker side effects.", "script": [{"tool": "rlm", "arguments": {"code": "e = edit_file(path=\"target.txt\", old_string=\"absent\", new_string=\"new\")\nv = bash(\"printf ran > marker\")\nprint(v)"}}, {"text": "The edit failed; the later command did not run."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": true}}, {"file_equals": {"path": "target.txt", "content": "old"}}]}{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-nested-shell-failure-status", "why": "A nested shell failure propagates error status and prevents later nested mutation.", "script": [{"tool": "rlm", "arguments": {"code": "print(bash(\"printf NESTED_FAILURE; exit 7\"), write_file(path=\"marker\", content=\"ran\"))"}}, {"text": "The nested command failed."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": true}}, {"request_contains": {"index": 1, "text": "NESTED_FAILURE"}}]}-{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-pending-host-blocks-tail-completion", "why": "Pending nested background work preserves pending status, stops later mutation and cannot satisfy same-batch completion.", "script": [{"tools": [{"tool": "rlm", "arguments": {"code": "print(bash(command=\"sleep 0.2; exit 0\", run_in_background=true), write_file(path=\"marker\", content=\"ran\"))"}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "Verification is still pending."}]}+{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-pending-host-blocks-tail-completion", "why": "Pending nested background work preserves pending status, stops later mutation and cannot satisfy same-batch completion. The headless run then waits for the job and continues with its exit instead of ending.", "script": [{"tools": [{"tool": "rlm", "arguments": {"code": "print(bash(command=\"sleep 0.2; exit 0\", run_in_background=true), write_file(path=\"marker\", content=\"ran\"))"}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}, {"text": "Verification finished: the check exited 0."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"request_contains": {"index": 2, "text": "exited 0: sleep 0.2; exit 0"}}, {"final_text_contains": "Verification finished: the check exited 0."}]}{"id": "rlm-indexed-print-refuses-and-recovers", "why": "Unsupported Python-style result indexing must report an error without pretending to execute the nested host or executing later side effects; the supported text binding form recovers.", "args": ["--lean"], "prompt": "Run the scripted checks and report only observed results.", "script": [{"tool": "rlm", "arguments": {"code": "print(bash(\"printf ran > nested-marker\")[\"stdout\"])\nx = write_file(path=\"tail-marker\", content=\"ran\")"}}, {"tool": "rlm", "arguments": {"code": "r = bash(\"printf VERIFIED\")\nprint(r)"}}, {"text": "Verified using the supported text result."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path(\"nested-marker\").exists(); assert not Path(\"tail-marker\").exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": true}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 1}}, {"request_contains": {"index": 1, "text": "host results are text"}}, {"event": {"type": "tool_result", "name": "rlm", "is_error": false, "text": "VERIFIED"}}, {"final_text_contains": "Verified using the supported text result."}]}{"id": "gateway-failure-usage-unknown", "why": "A typed gateway failure with no usage must preserve the provider diagnostic and label totals as incomplete instead of implying a free zero-token call.", "args": ["-p", "summarize the fixture"], "prompt": "summarize the fixture", "script": [{"text": "partial", "stream_error": {"type": "gateway_error", "code": "request_failed", "message": "fixture request failed"}}], "expected_exit": 1, "assert": [{"stderr_contains": "gateway_error request_failed"}, {"stderr_contains": "known subtotal: 0 api call(s)"}, {"stderr_contains": "1 failed request attempt(s) without usage (tokens and cost unknown)"}]}{"id": "gateway-retry-usage-remains-incomplete", "why": "A recovered retry retains known successful usage while the failed attempt remains explicitly unknown.", "prompt": "summarize the fixture", "script": [{"text": "partial", "stream_error": {"type": "api_error", "message": "Internal error during token parsing"}}, {"text": "recovered fixture"}], "assert": [{"event": {"type": "turn", "usage_complete": false, "unreported_failed_attempts": 1, "api_calls": 1}}, {"final_text_contains": "recovered fixture"}]}@@ -142,3 +142,6 @@{"id":"stream-reused-index-distinct-tool-ids","why":"A streamed tool index can restart with a fresh call ID. Guard the incomplete first call, execute the separate complete call once, and preserve both outcomes in model history.","args":["--old"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"prompt":"Run the scripted file operation and report the observed result.","script":[{"stream_deltas":[{"tool_calls":[{"index":0,"id":"old","type":"function","function":{"name":"write_file","arguments":"{\"path\":\"guard.txt\""}}]},{"tool_calls":[{"index":0,"id":"new","type":"function","function":{"name":"write_file","arguments":"{\"path\":\"result.txt\",\"content\":\"done\\n\"}"}}]}]},{"text":"The valid file operation completed."}],"verify_command":["python3","-c","from pathlib import Path; assert not Path('guard.txt').exists(); assert Path('result.txt').read_text() == 'done\\n'"],"assert":[{"request_count":2},{"event":{"type":"tool_call_finished","name":"write_file","is_error":true}},{"event":{"type":"tool_call_finished","name":"write_file","is_error":false}},{"events_at_most":{"match":{"type":"tool_call_finished","name":"write_file","is_error":false},"count":1}},{"request_contains":{"index":1,"text":"tool call arguments were truncated or not a JSON object"}},{"file_equals":{"path":"result.txt","content":"done\n"}},{"final_text_contains":"The valid file operation completed."}]}{"id":"jev-effort-only-rejects-judgment","why":"Jev is only an optional effort selector: the removed generic judgment call and an effort request on an ineligible route must both fail locally without changing session effort.","env":{"JEV_BACKEND":"mock"},"prompt":"Try the old judgment tool, then try effort selection here.","script":[{"tool":"jev_judge","arguments":{"state":"tests passed","question":"Did tests pass?","type":"noul"}},{"tool":"jev_effort","arguments":{"task":"a small read-only lookup"}},{"text":"Neither call changed effort."}],"assert":[{"event":{"type":"tool_result","name":"jev_judge","is_error":true,"text":"unknown tool: jev_judge"}},{"event":{"type":"tool_result","name":"jev_effort","is_error":true}},{"final_text_contains":"Neither call changed effort."}]}{"id":"stream-length-stop-cut-call","why":"A response that hits its output limit mid-batch must run the finished call and refuse the unfinished one with the cause (#1218), never run it as an empty call.","args":["--old"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"prompt":"Run the scripted file operations and report the observed result.","script":[{"stream_deltas":[{"tool_calls":[{"index":0,"id":"done","type":"function","function":{"name":"write_file","arguments":"{\"path\":\"result.txt\",\"content\":\"done\\n\"}"}}]},{"tool_calls":[{"index":1,"id":"cut","type":"function","function":{"name":"read_file"}}]}],"finish":"length"},{"text":"The finished call ran and the cut one was refused."}],"verify_command":["python3","-c","from pathlib import Path; assert Path('result.txt').read_text() == 'done\\n'"],"assert":[{"request_count":2},{"event":{"type":"tool_call_finished","name":"write_file","is_error":false}},{"event":{"type":"tool_call_finished","name":"read_file","is_error":true}},{"request_contains":{"index":1,"text":"the response ended before this call was complete"}},{"file_equals":{"path":"result.txt","content":"done\n"}},{"final_text_contains":"The finished call ran"}]}+{"id": "headless-waits-for-background-job", "why": "Run until idle: a --json turn that ends while its background job runs waits for the job and continues with its result, instead of ending with the result lost.", "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Start the background build, then report its result.", "script": [{"tool": "bash", "arguments": {"command": "sleep 0.5; echo BUILD_RESULT_READY", "run_in_background": true}}, {"text": "The build is running in the background; I will report when it finishes."}, {"text": "The build finished and printed BUILD_RESULT_READY."}], "assert": [{"request_count": 3}, {"request_contains": {"index": 2, "text": "BUILD_RESULT_READY"}}, {"events_at_most": {"match": {"type": "turn"}, "count": 1}}, {"final_text_contains": "The build finished and printed BUILD_RESULT_READY."}]}+{"id": "headless-heartbeat-checks-stuck-job", "why": "Run until idle: a waiting run wakes the model with a heartbeat after silence, naming the running job, so it can stop work that will not finish.", "env": {"GRAFF_NO_CODEDB_GUARD": "1", "GRAFF_HEARTBEAT_SECS": "1"}, "prompt": "Start the background watcher and handle it.", "script": [{"tool": "bash", "arguments": {"command": "sleep 30; echo NEVER_PRINTED", "run_in_background": true}}, {"text": "The watcher is running."}, {"tool": "bash_kill", "arguments": {"id": 4294967296}}, {"text": "Stopped the watcher; it was not going to finish."}], "assert": [{"request_count": 4}, {"request_contains": {"index": 2, "text": "[heartbeat: no news from background work"}}, {"request_contains": {"index": 2, "text": "sleep 30"}}, {"final_text_contains": "Stopped the watcher"}], "workspace_seed": {".codegraff/shell-id.lock": "shell-ids-v1\n", ".codegraff/shell-id.counter": "4294967295\n"}}+{"id": "headless-server-does-not-hold", "why": "Run until idle: a server never reports, so a turn that leaves one running in the background ends instead of waiting on it.", "env": {"GRAFF_NO_CODEDB_GUARD": "1", "GRAFF_HEARTBEAT_SECS": "1"}, "prompt": "Start the dev server in the background and confirm it launched.", "script": [{"tool": "bash", "arguments": {"command": "python3 -m http.server 0 --bind 127.0.0.1", "run_in_background": true}}, {"text": "The dev server is running."}], "assert": [{"request_count": 2}, {"final_text_contains": "The dev server is running."}]}diff --git a/src/agent_empty_completion.zig b/src/agent_empty_completion.zigindex abc79e57..f15233e4 100644--- a/src/agent_empty_completion.zig+++ b/src/agent_empty_completion.zig@@ -157,8 +157,11 @@ pub fn handle(self: *Agent, final_text: []const u8, hist_len: usize) !bool {/// Plain finals bypass attempt_completion's gate (#745). Keep the allowance/// on the runTurn stack: tool progress and compaction must not reset it.+/// Background work still running is live work too: after the reminder, a+/// headless run waits for it to report (run_idle.zig).pub const PendingWork = struct {nudged: bool = false,+ idle: @import("run_idle.zig").Hold = .{},pub const note = "Open-work reconciliation: your plain final reply would end root execution, but the current checklist is unfinished. " ++"If the user still wants this task done, continue actionable independent work now; collect required background results with agent_output/bash_output and wait_ms>0 when needed, rather than polling or promising future work. " ++@@ -185,8 +188,9 @@ pub const PendingWork = struct {pub fn finish(state: *PendingWork, self: *Agent, text: []const u8) !?[]const u8 {if (!self.sub and Agent.esc_cancel.load(.acquire)) return error.Interrupted;const count = open(self);- if (count == 0) return text;- if (!state.nudged and canRequest(self)) {+ // The reminder first, so independent work runs beside the background+ // work; the wait applies once the model stops again.+ if (count > 0 and !state.nudged and canRequest(self)) {state.nudged = true;const goals = @import("goal_state.zig");const body = try std.fmt.allocPrint(self.arena, "{s}\n\n{s}", .{ note, goals.renderTodos(self, goals.currentEpoch(self.goal)) });@@ -194,6 +198,8 @@ pub const PendingWork = struct {if (self.tracer) |tr| tr.note("pending_work", "plain final reconciled; one retry granted");return null;}+ if (canRequest(self) and try state.idle.wait(self)) return null;+ if (count == 0) return text;const footer = try std.fmt.allocPrint(self.arena, "\n\n[Root execution has stopped with {d} open checklist items; background jobs may still run.]", .{count});if (self.tracer) |tr| tr.note("pending_work", "plain final stopped with open work; retry or budget exhausted");// The answer may already have streamed, so surface the new suffix too.@@ -204,6 +210,10 @@ pub const PendingWork = struct {}};+test {+ _ = @import("run_idle.zig");+}+fn pendingFixture(arena: std.mem.Allocator) Agent {var self: Agent = undefined;self.arena = arena;diff --git a/src/job_notify.zig b/src/job_notify.zigindex d769f0bf..001c962a 100644--- a/src/job_notify.zig+++ b/src/job_notify.zig@@ -233,6 +233,13 @@ pub fn stillRunning(io: Io, id: u64, waited_ms: u64, unread: usize) void {tool_pulse.emitNotice(io, "· bash_output · job {d} still running · {s} · {d} unread byte(s)", .{ id, tool_pulse.formatElapsed(&ebuf, waited_ms), unread });}+/// A notice is queued for the next step boundary (run_idle.zig's wait).+pub fn pending(io: Io) bool {+ mu.lockUncancelable(io);+ defer mu.unlock(io);+ return count > 0;+}+/// Drain queued notices into `buf` (step boundary: everything). Null when/// nothing finished.pub fn takeWake(io: Io, buf: []u8) ?[]const u8 {diff --git a/src/json_inbox.zig b/src/json_inbox.zigindex dab0396a..5ce5b236 100644--- a/src/json_inbox.zig+++ b/src/json_inbox.zig@@ -81,6 +81,15 @@ pub fn endTurn() void {turn_active.store(false, .release);}+/// The client sent a line that waits for the current turn to end. A turn+/// waiting on background work hands the session back for it (run_idle.zig).+pub fn waiting() bool {+ const io = inbox_io orelse return false;+ mutex.lockUncancelable(io);+ defer mutex.unlock(io);+ return lines.items.len > 0;+}+/// Mainloop request read. In non-JSON modes the original reader remains owner.pub fn request(arena: Allocator, fallback: *Io.Reader) !?[]const u8 {return read(arena, fallback, false);diff --git a/src/mainloop.zig b/src/mainloop.zigindex 28a0f3c3..c08366fb 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -63,6 +63,9 @@ pub const Ctx = struct {pub fn run(ctx: *Ctx) !void {@import("subagent_interactive.zig").configure(ctx.interactive);defer @import("subagent_interactive.zig").configure(false);+ // --json, serve and piped stdin have no idle wake: a turn waits for its background work.+ @import("run_idle.zig").enabled = !ctx.interactive;+ defer @import("run_idle.zig").enabled = false;if (main_mod.json_mode) json_inbox.start(ctx.gpa, ctx.io, ctx.in);defer if (main_mod.json_mode) json_inbox.stop();var title_jobs: mainloop_title.Jobs = .{};diff --git a/src/prompt_golden.zig b/src/prompt_golden.zigindex ac610229..3fb7fd7d 100644--- a/src/prompt_golden.zig+++ b/src/prompt_golden.zig@@ -158,6 +158,12 @@ pub const full_prompt =\\When a named SPEC.md (or equivalent contract) is in the task, satisfy\\every clause — a green public test is not the whole spec.\\+ \\Long commands and background subagents keep running while you work, and+ \\each one reports back when it finishes: do not poll or sleep to wait for+ \\it. If your reply ends while such work is still running, the run waits for+ \\it and continues with its result. A reply that ends with nothing running+ \\ends the run, so end that way only when the task is done.+ \\\\Before a large chunk of work, give a one- or two-sentence heads-up on what\\you are about to do; on long tasks, drop a brief note as each phase lands.\\Put that text in the SAME response as the tool calls it introduces: adiff --git a/src/prompt_text.zig b/src/prompt_text.zigindex 67832097..c65ca95a 100644--- a/src/prompt_text.zig+++ b/src/prompt_text.zig@@ -224,6 +224,19 @@ pub const work_note =\\every clause — a green public test is not the whole spec.;+/// Gate: `caps.local_tools`. Run until idle (run_idle.zig): a reply that ends+/// while background work runs waits for its result, and only a reply with+/// nothing running ends the run.+pub const background_note =+ \\+ \\+ \\Long commands and background subagents keep running while you work, and+ \\each one reports back when it finishes: do not poll or sleep to wait for+ \\it. If your reply ends while such work is still running, the run waits for+ \\it and continues with its result. A reply that ends with nothing running+ \\ends the run, so end that way only when the task is done.+;+/// Always present: narration is a habit, not a capability. ADR 0061: the/// note used to say only THAT a heads-up is owed; a model that answers every/// step with bare function calls (Gemini flash: no text in any of 259@@ -388,6 +401,13 @@ pub const lean_work_note =\\— a green public test is not the whole spec.;+pub const lean_background_note =+ \\+ \\Background jobs and subagents report back when they finish; do not poll.+ \\Ending your reply while one runs waits for its result. Ending with nothing+ \\running ends the run.+;+pub const lean_closing_note =\\\\Write the final message as a short teammate update. Use existing evidence;@@ -407,6 +427,7 @@ pub fn leanSegment(name: []const u8, original: []const u8, is_lean: bool) ?[]conif (std.mem.eql(u8, name, "intro")) return lean_intro_note;if (std.mem.eql(u8, name, "local_tools")) return lean_local_tools_note;if (std.mem.eql(u8, name, "work")) return lean_work_note;+ if (std.mem.eql(u8, name, "background")) return lean_background_note;if (std.mem.eql(u8, name, "closing")) return lean_closing_note;return original;}diff --git a/src/prompts.zig b/src/prompts.zigindex b6ae035d..8f3c925b 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -39,9 +39,8 @@ const tool_gates = @import("tool_gates.zig"); // #352's additive gate — the otconst tool_surface = @import("tool_surface.zig");const session_index = @import("session_index.zig"); // #410: where the durable transcript lives-/// The prompt text itself lives next door; this file owns when each part-/// of it is sent. `parallel_tools_note` is re-exported because-/// `sub_system_prompt` composes it as a comptime whole.+/// The prompt text lives next door; this file owns when each part is sent.+/// `parallel_tools_note` is re-exported for `sub_system_prompt`'s comptime whole.pub const parallel_tools_note = text.parallel_tools_note;/// The capability a segment needs. `.always` is what survives every gate.@@ -66,6 +65,7 @@ pub const segments = [_]Segment{.{ .name = "git_authoring", .text = text.git_authoring_note, .gate = .git_repo },.{ .name = "git_safety", .text = text.git_safety_note, .gate = .always },.{ .name = "work", .text = text.work_note, .gate = .always },+ .{ .name = "background", .text = text.background_note, .gate = .local_tools },.{ .name = "headsup", .text = text.headsup_note, .gate = .always },.{ .name = "todo_progress", .text = text.todo_progress_note, .gate = .todos },.{ .name = "root_cause", .text = text.root_cause_note, .gate = .always },diff --git a/src/run_idle.zig b/src/run_idle.zignew file mode 100644index 00000000..b6209d93--- /dev/null+++ b/src/run_idle.zig@@ -0,0 +1,329 @@+//! Run until idle. A root reply that would end the run while work it started+//! in the background is still running does not end it: the run waits for that+//! work to report, then continues with the result. Only a reply with nothing+//! running ends the run.+//!+//! Headless surfaces only: `-p`, and the non-interactive mainloop behind+//! `--json`, `graff serve` and piped stdin. Nothing else wakes those sessions+//! again, so a background build's exit notice used to die with the process.+//! The TUI, the line REPL and ACP start a new turn when background work+//! reports (idle_wake_sources.zig), so they end the turn instead.+//!+//! Live work is a running shell job that will post an exit notice, and a+//! background subagent the root started. A server never reports, so a job+//! that is persistent, pinned, detached or listening on a TCP port does not+//! count. While waiting, a heartbeat wakes the model after `heartbeat_ms`+//! without news so it can check on work that may be stuck; after+//! `max_quiet_beats` heartbeats in a row with no result and no tool call, the+//! run stops waiting.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const jobs = @import("jobs.zig");+const subagent = @import("subagent.zig");+const job_notify = @import("job_notify.zig");+const session_wake = @import("session_wake.zig");+const tool_pulse = @import("tool_pulse.zig");+const util = @import("util.zig");++/// Set by the headless entry points (session_run.runOneshotPrompt, mainloop.run).+pub var enabled: bool = false;++/// Silence before a heartbeat. GRAFF_HEARTBEAT_SECS overrides; 0 turns it off.+pub var heartbeat_ms: u64 = 10 * std.time.ms_per_min;++/// Heartbeats in a row with no result and no tool call before the run stops+/// waiting: the model has looked that many times and only chose to wait.+const max_quiet_beats: u8 = 3;+const poll_ms = 200;+/// A finished subagent's report rides its wake up to this size.+const report_cap: usize = 6 * 1024;++/// Seconds; unparseable values are ignored, 0 disables, a week is the cap.+pub fn applyEnv(environ_map: anytype) void {+ const v = environ_map.get("GRAFF_HEARTBEAT_SECS") orelse return;+ const secs = std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10) catch return;+ heartbeat_ms = @min(secs, 7 * 24 * 3600) * std.time.ms_per_s;+}++/// The run's state across the waits of one root turn.+pub const Hold = struct {+ quiet_beats: u8 = 0,+ calls_at_beat: u64 = 0,++ /// Where a final reply would end the root turn. True continues the turn:+ /// a result or a heartbeat is queued for the next request.+ pub fn wait(self: *Hold, agent: *Agent) !bool {+ if (!enabled or agent.sub or agent.review_mode or agent.text_only or agent.completed != null) return false;+ const io = agent.io;+ if (agent.tool_calls_this_turn != self.calls_at_beat) self.quiet_beats = 0; // it acted since the last beat+ var scratch = std.heap.ArenaAllocator.init(agent.gpa);+ defer scratch.deinit();+ const a = scratch.allocator();+ const work = try Work.snapshot(agent.gpa, io, a);+ var since: ?i64 = null;+ while (true) {+ if (Agent.esc_cancel.load(.acquire)) return error.Interrupted;+ // The client sent its next request: the turn ends and that request+ // runs; its first step boundary delivers whatever has reported.+ if (@import("json_inbox.zig").waiting()) return false;+ // Read before the notices: work that ends after this read is caught+ // on the next pass, and work that ended before it already queued its+ // notice (done and the notice share the jobs lock).+ const live = work.live(io);+ if (job_notify.pending(io) or try deliver(agent)) {+ self.quiet_beats = 0;+ return true;+ }+ if (!live) return false;+ const now = util.unixMs(io);+ const started = since orelse blk: {+ if (self.quiet_beats >= max_quiet_beats) {+ try agent.say("[stopped waiting: background work is still running after {d} heartbeats with no news]\n", .{max_quiet_beats});+ if (agent.tracer) |t| t.note("run_idle", "quiet cap");+ return false;+ }+ try agent.say("[waiting for background work to report: {s}]\n", .{try work.describe(io, a)});+ if (agent.tracer) |t| t.note("run_idle", "waiting");+ since = now;+ break :blk now;+ };+ if (heartbeat_ms > 0 and now - started >= @as(i64, @intCast(heartbeat_ms))) {+ self.quiet_beats += 1;+ self.calls_at_beat = agent.tool_calls_this_turn;+ session_wake.inject(agent, try heartbeatText(a, @intCast(now - started), try work.describe(io, a)));+ if (agent.tracer) |t| t.note("run_idle", "heartbeat");+ return true;+ }+ io.sleep(.fromMilliseconds(poll_ms), .awake) catch return false;+ }+ }+};++/// Step boundary (turn_inbox) and the wait: a finished background subagent+/// the root started wakes the run with its report. Interactive roots own+/// their children and get subagent_interactive's wake instead.+pub fn deliver(agent: *Agent) !bool {+ if (!enabled or agent.sub) return false;+ var texts: std.ArrayList([]u8) = .empty;+ defer {+ for (texts.items) |t| agent.gpa.free(t);+ texts.deinit(agent.gpa);+ }+ try takeReports(agent.gpa, agent.io, &texts);+ for (texts.items) |t| session_wake.inject(agent, t);+ return texts.items.len > 0;+}++/// Unread reports of finished root children, marked read. `agent_output`+/// still returns a report in full after this.+fn takeReports(gpa: Allocator, io: Io, texts: *std.ArrayList([]u8)) !void {+ const reg = &subagent.g_agent_jobs;+ reg.mutex.lockUncancelable(io);+ defer reg.mutex.unlock(io);+ for (reg.list.items) |job| {+ if (!rootChild(job) or !job.done or job.notified) continue;+ const status = try subagent.agentStatusText(gpa, job.id, true, job.is_error, job.usage, job.result);+ defer gpa.free(status);+ try texts.ensureUnusedCapacity(gpa, 1);+ texts.appendAssumeCapacity(try reportWake(gpa, job.id, status));+ job.notified = true;+ }+}++fn reportWake(gpa: Allocator, id: u32, status: []const u8) ![]u8 {+ if (status.len <= report_cap)+ return std.fmt.allocPrint(gpa, "{s}\nContinue the task from this result.", .{status});+ return std.fmt.allocPrint(gpa, "{s}\n[report cut at {d} bytes; agent_output id {d} returns all of it]\nContinue the task from this result.", .{ util.utf8Prefix(status, report_cap), report_cap, id });+}++/// A background child of a headless root: interactive roots set `owner`,+/// and a child's own children belong to it.+fn rootChild(job: *const subagent.AgentJob) bool {+ return job.owner == null and !job.ctx.from_sub;+}++fn heartbeatText(a: Allocator, silent_ms: u64, running: []const u8) ![]const u8 {+ var ebuf: [16]u8 = undefined;+ return std.fmt.allocPrint(a, "[heartbeat: no news from background work for {s}. Still running: {s}. Check on anything that may be stuck (action=output or agent_output for a snapshot, action=kill to stop a job), or end your reply to keep waiting.]", .{ tool_pulse.formatElapsed(&ebuf, silent_ms), running });+}++/// The background work a run waits on, captured when it starts waiting.+const Work = struct {+ jobs: std.ArrayList(JobRef) = .empty,+ agents: std.ArrayList(AgentRef) = .empty,++ const JobRef = struct { id: u64, cmd: []const u8, started_ms: i64 };+ const AgentRef = struct { id: u32, label: []const u8 };++ fn snapshot(gpa: Allocator, io: Io, a: Allocator) !Work {+ var w: Work = .{};+ var candidates: std.ArrayList(struct { ref: JobRef, pid: i32 }) = .empty;+ {+ const reg = &jobs.g_jobs;+ reg.mutex.lockUncancelable(io);+ defer reg.mutex.unlock(io);+ for (reg.list.items) |job| {+ // quiet: still in its foreground wait, the tool call is live.+ if (job.done or job.quiet or job.persistent or job.pinned or job.detach) continue;+ try candidates.append(a, .{ .ref = .{ .id = job.id, .cmd = try a.dupe(u8, job.cmd), .started_ms = job.started_ms }, .pid = job.group_pid });+ }+ }+ // lsof runs outside the lock. A listening process group is a server.+ for (candidates.items) |c| {+ if (c.pid != 0 and @import("job_registry.zig").listenPorts(gpa, io, a, c.pid).len > 0) continue;+ try w.jobs.append(a, c.ref);+ }+ const reg = &subagent.g_agent_jobs;+ reg.mutex.lockUncancelable(io);+ defer reg.mutex.unlock(io);+ for (reg.list.items) |job| {+ if (rootChild(job) and !job.done) try w.agents.append(a, .{ .id = job.id, .label = try a.dupe(u8, job.label) });+ }+ return w;+ }++ fn live(w: Work, io: Io) bool {+ {+ const reg = &jobs.g_jobs;+ reg.mutex.lockUncancelable(io);+ defer reg.mutex.unlock(io);+ for (w.jobs.items) |ref| {+ for (reg.list.items) |job| if (job.id == ref.id and !job.done) return true;+ }+ }+ const reg = &subagent.g_agent_jobs;+ reg.mutex.lockUncancelable(io);+ defer reg.mutex.unlock(io);+ for (w.agents.items) |ref| if (reg.find(ref.id)) |job| if (!job.done) return true;+ return false;+ }++ /// `job 3 (zig build test, 12m)` style, for the waiting line and the heartbeat.+ fn describe(w: Work, io: Io, a: Allocator) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(a);+ const now = util.unixMs(io);+ for (w.jobs.items, 0..) |ref, i| {+ var ebuf: [16]u8 = undefined;+ const age: u64 = @intCast(@max(0, now - ref.started_ms));+ try aw.writer.print("{s}job {d} ({s}, {s})", .{ if (i == 0) "" else ", ", ref.id, util.utf8Prefix(ref.cmd, 48), tool_pulse.formatElapsed(&ebuf, age) });+ }+ for (w.agents.items, 0..) |ref, i| {+ try aw.writer.print("{s}agent {d} ({s})", .{ if (i == 0 and w.jobs.items.len == 0) "" else ", ", ref.id, util.utf8Prefix(ref.label, 48) });+ }+ return aw.written();+ }+};++test "GRAFF_HEARTBEAT_SECS: seconds, 0 turns it off, junk is ignored" {+ const saved = heartbeat_ms;+ defer heartbeat_ms = saved;+ const Env = struct {+ v: ?[]const u8,+ pub fn get(self: @This(), name: []const u8) ?[]const u8 {+ return if (std.mem.eql(u8, name, "GRAFF_HEARTBEAT_SECS")) self.v else null;+ }+ };+ applyEnv(Env{ .v = "90" });+ try std.testing.expectEqual(@as(u64, 90_000), heartbeat_ms);+ applyEnv(Env{ .v = "junk" });+ try std.testing.expectEqual(@as(u64, 90_000), heartbeat_ms);+ applyEnv(Env{ .v = "0" });+ try std.testing.expectEqual(@as(u64, 0), heartbeat_ms);+}++test "a running background job is live work until it ends, and then its notice is queued" {+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ jobs.g_jobs = .{};+ defer jobs.jobsReap(gpa, io);+ var buf: [4096]u8 = undefined;+ while (job_notify.takeWake(io, &buf) != null) {}+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const id = (try jobs.spawnJob(gpa, io, "sleep 0.3; echo run-idle-done")).id;+ const work = try Work.snapshot(gpa, io, scratch.allocator());+ try std.testing.expectEqual(@as(usize, 1), work.jobs.items.len);+ try std.testing.expect(work.live(io));+ const line = try work.describe(io, scratch.allocator());+ try std.testing.expect(std.mem.indexOf(u8, line, "sleep 0.3") != null);+ var waited: u32 = 0;+ while (work.live(io) and waited < 100) : (waited += 1) io.sleep(.fromMilliseconds(50), .awake) catch {};+ try std.testing.expect(!work.live(io));+ try std.testing.expect(job_notify.pending(io));+ const wake = job_notify.takeWake(io, &buf).?;+ try std.testing.expect(std.mem.indexOf(u8, wake, "run-idle-done") != null);+ _ = id;+}++test "only the root's own background children are waited on and reported" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ const saved = subagent.g_agent_jobs;+ subagent.g_agent_jobs = .{};+ defer {+ subagent.g_agent_jobs.list.deinit(gpa);+ subagent.g_agent_jobs = saved;+ }+ var label = "review parser".*;+ const ctx: @import("tools.zig").ToolCtx = .{ .gpa = gpa, .io = io, .client = undefined, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null };+ var mine: subagent.AgentJob = .{ .id = 1, .label = &label, .prompt = &label, .niche = &label, .isolation = .shared_cwd, .isolation_fallback = false, .ctx = ctx };+ var nested_ctx = ctx;+ nested_ctx.from_sub = true;+ var nested: subagent.AgentJob = .{ .id = 2, .label = &label, .prompt = &label, .niche = &label, .isolation = .shared_cwd, .isolation_fallback = false, .ctx = nested_ctx };+ var owned: subagent.AgentJob = .{ .id = 3, .label = &label, .prompt = &label, .niche = &label, .isolation = .shared_cwd, .isolation_fallback = false, .ctx = ctx, .owner = "tui-session" };+ try subagent.g_agent_jobs.list.appendSlice(gpa, &.{ &mine, &nested, &owned });++ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const work = try Work.snapshot(gpa, io, scratch.allocator());+ try std.testing.expectEqual(@as(usize, 1), work.agents.items.len);+ try std.testing.expectEqual(@as(u32, 1), work.agents.items[0].id);+ try std.testing.expect(work.live(io));++ var result = "PARSER_OK".*;+ for ([_]*subagent.AgentJob{ &mine, &nested, &owned }) |job| {+ job.done = true;+ job.result = &result;+ }+ try std.testing.expect(!work.live(io));+ var texts: std.ArrayList([]u8) = .empty;+ defer {+ for (texts.items) |t| gpa.free(t);+ texts.deinit(gpa);+ }+ try takeReports(gpa, io, &texts);+ try std.testing.expectEqual(@as(usize, 1), texts.items.len);+ try std.testing.expect(std.mem.indexOf(u8, texts.items[0], "[agent 1: completed") != null);+ try std.testing.expect(std.mem.indexOf(u8, texts.items[0], "PARSER_OK") != null);+ try std.testing.expect(mine.notified and !nested.notified and !owned.notified);+ for (texts.items) |t| gpa.free(t);+ texts.clearRetainingCapacity();+ try takeReports(gpa, io, &texts); // read once+ try std.testing.expectEqual(@as(usize, 0), texts.items.len);+}++test "a long report is cut at the cap and points at agent_output" {+ const gpa = std.testing.allocator;+ const long = try gpa.alloc(u8, report_cap + 100);+ defer gpa.free(long);+ @memset(long, 'x');+ const text = try reportWake(gpa, 9, long);+ defer gpa.free(text);+ try std.testing.expect(std.mem.indexOf(u8, text, "agent_output id 9 returns all of it") != null);+ try std.testing.expect(text.len < report_cap + 200);+}++test "the heartbeat names the silence, the work and both ways forward" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const text = try heartbeatText(arena.allocator(), 10 * std.time.ms_per_min, "job 3 (zig build test, 12m)");+ try std.testing.expect(std.mem.indexOf(u8, text, "10m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "job 3 (zig build test, 12m)") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "action=kill") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "keep waiting") != null);+}diff --git a/src/session_run.zig b/src/session_run.zigindex f963a230..db519d72 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -151,6 +151,7 @@ pub fn runFrontendCommands(gpa: Allocator, io: Io, environ_map: anytype, root: *pub fn runOneshotPrompt(gpa: Allocator, io: Io, arena: Allocator, root: *agent_mod.Agent, keys: *provider_mod.Keys, tracer: *trace.Tracer, out: *Io.Writer, prompt_text: []const u8) !void {if (@import("goal_pacing.zig").oneshotSlashRefusal(prompt_text)) |why| std.process.fatal("{s}", .{why}); // usage error, not a promptmain_mod.unattended = true;+ @import("run_idle.zig").enabled = true; // nothing wakes a finished one-shot: wait for its background work@import("named_work.zig").rememberOn(root, prompt_text);root.in = null; // gate: deny instead of prompt; ask_user: self-decideroot.out = null; // tool progress → stderr; stdout carries only the answerdiff --git a/src/session_settings.zig b/src/session_settings.zigindex 33e16a1d..5b169d8f 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -72,6 +72,7 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {jev_tool.configure(environ_map);main_mod.g_codedb_guard = environ_map.get("GRAFF_NO_CODEDB_GUARD") == null; // issue #626 guard, opt-out via envjob_idle.applyEnv(environ_map); // #199: background-job idle warn/stop, minutes (0 = off)+ @import("run_idle.zig").applyEnv(environ_map); // GRAFF_HEARTBEAT_SECS: a waiting run's heartbeat (0 = off)main_mod.g_force_stall_once = environ_map.get("GRAFF_FORCE_STALL_ONCE") != null; // #134 test seamif (environ_map.get("GRAFF_PUBLISH_PENDING_WAIT_MS")) |v| @import("publish_gate.zig").pending_wait_ms = std.fmt.parseInt(i64, v, 10) catch 60_000; // #1189 fixture seammain_mod.g_force_drop_once = environ_map.get("GRAFF_FORCE_DROP_ONCE") != null; // #132/#133 test seamdiff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zigindex df933ab5..7d2934b1 100644--- a/src/session_settings_tests.zig+++ b/src/session_settings_tests.zig@@ -64,6 +64,7 @@ const knobs = [_]Knob{.{ .name = "GRAFF_XAI_X_SEARCH", .value = "0" },.{ .name = "GRAFF_JOB_IDLE_WARN_MINS", .value = "3" },.{ .name = "GRAFF_JOB_IDLE_STOP_MINS", .value = "0" },+ .{ .name = "GRAFF_HEARTBEAT_SECS", .value = "600" },};/// A stand-in for the process environment that records which names were askeddiff --git a/src/turn_inbox.zig b/src/turn_inbox.zigindex fe60d97d..bf94c082 100644--- a/src/turn_inbox.zig+++ b/src/turn_inbox.zig@@ -14,6 +14,7 @@ pub fn deliver(self: *Agent) !void {@import("peer_channel.zig").deliverInbound(self);try @import("subagent_feedback.zig").deliverToAgent(self);@import("job_notify.zig").deliver(self);+ _ = try @import("run_idle.zig").deliver(self); // headless roots: finished background subagents@import("schedule.zig").deliver(self);@import("channel_worker.zig").deliver(self);@import("hot_context.zig").deliver(self); // #1333: changed ambient keys, before the prompt