From 819cfeab25cbfc72e307c0c284780b7792cb897e Mon Sep 17 00:00:00 2001 From: Bryan <28662377+bryanwieg@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:29:24 +0000 Subject: [PATCH 1/2] Record stalled calls, so their cap counts in the premium spend Each stalled call is recorded with exit 7 after its edits are undone: a stage's as an error attempt (not a try of the pair), a revise or review as a run. A stalled revise does not count as the phase's revise. Co-Authored-By: Claude Opus 5.5 --- plugins/phased-delivery/scripts/run-phase.py | 19 ++++++++++++------- .../skills/implement-in-phases/build-guide.md | 6 ++++-- .../phased-delivery/tests/test_run_phase.py | 17 +++++++++++++++-- 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/plugins/phased-delivery/scripts/run-phase.py b/plugins/phased-delivery/scripts/run-phase.py index 2f6f6be..f0595ad 100755 --- a/plugins/phased-delivery/scripts/run-phase.py +++ b/plugins/phased-delivery/scripts/run-phase.py @@ -226,8 +226,10 @@ def route(c, *options): return json.loads(r.stdout) -def call(c, label, guide, inputs, pair, keep_briefs): - """One model call through claude-build.sh: {exit, tokens, cost, line (the report's last), stderr, edited}.""" +def call(c, label, guide, inputs, pair, keep_briefs, what, *flags): + """One model call through claude-build.sh: {exit, tokens, cost, line (the report's last), stderr, edited}. + + WHAT and FLAGS record a stalled try (build-check.py record), so its cap counts in the premium spend.""" out = os.path.join(c.work, f"{len(os.listdir(c.work)) + 1:02d}-{label}") os.makedirs(out) prompt = os.path.join(out, "prompt.md") @@ -251,6 +253,9 @@ def call(c, label, guide, inputs, pair, keep_briefs): build_check.save(p, doc) restore(c, [build_check.rel(c.top, p) for p in sorted(plan_files(c.plan_dir) - present)]) restore(c) + # recorded after the undo, which puts the plan's files back as they were + must(record(c, what, pair, {"exit": 7, "tokens": "unknown", "cost": "unknown"}, *flags), "record", (0, 4)) + before = plan_docs(c.plan_dir) # the guard's baseline now holds that record else: raise Halt("stalled", f"the {label} call stalled twice: {last(r.stderr)}") records, briefs = guard(before, keep_briefs) @@ -317,7 +322,7 @@ def revise(c, problem): f"- The plugin's guides (absolute paths): `{os.path.join(SKILLS, 'plan-in-phases')}` holds " f"revising.md and the field guides; plan-check.py is `{os.path.join(HERE, 'plan-check.py')}`; " f"the repository is `{c.top}`"] - res = call(c, "revise", REVISE_GUIDE, inputs, pair, False) + res = call(c, "revise", REVISE_GUIDE, inputs, pair, False, "revise") if res["exit"] not in (0, 8): raise Halt("build-error", res["stderr"]) must(record(c, "revise", pair, res), "record") @@ -331,7 +336,7 @@ def revise(c, problem): def pre_phase(c, stages): """Revise and start a phase not yet revised; check the plan while no stage has an attempt.""" runs = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"].get("runs", []) - if not any(x["stage"] == "revise" for x in runs): + if not any(x["stage"] == "revise" and x["exit"] != 7 for x in runs): # a stalled revise is not one started = py("build-check.py", "start", c.pdir, "--repo", c.top) if started.returncode: raise Halt("revise-failed", (started.stdout + started.stderr).strip()) @@ -377,7 +382,7 @@ def build(c, sid, s, times): "against the brief in the packet"] if fix else [] inputs = [c.instructions, "- Anything else the brief links to: none", *earlier, "- Stage packet:", "", plan_check.packet(c.plan_dir, sid)] - res = call(c, f"build-{sid}", STAGE_BUILDER, inputs, pair, True) + res = call(c, f"build-{sid}", STAGE_BUILDER, inputs, pair, True, sid, *(["--fix"] if fix else [])) logged = record(c, sid, pair, res, *(["--fix"] if fix else [])) if logged.returncode == 4: raise Halt("build-error", res["stderr"]) @@ -441,7 +446,7 @@ def review(c, stages): + (", ".join(f"`{p}`" for p in rec["preexisting"]) or "none"), c.instructions, f"- Review file to write: `{path}`", "- Stages with no check commands, which only this review checks: " + (", ".join(unchecked) or "none")] - res = call(c, "review", PHASE_REVIEWER, inputs, pair, False) + res = call(c, "review", PHASE_REVIEWER, inputs, pair, False, "review") if res["exit"] and os.path.isfile(path): os.remove(path) # a review cut short is not a review; the rerun reviews again if res["exit"] not in (0, 8): @@ -473,7 +478,7 @@ def fix(c, sid, s, f): inputs = [c.instructions, f"- Finding: `{f['type']}` at `{f['file']}:{f['line']}`", f" - Evidence: {f['evidence']}", f" - Action: {f['action']}", "- Stage packet:", "", plan_check.packet(c.plan_dir, sid)] - res = call(c, f"fix-{sid}", STAGE_BUILDER, inputs, pair, True) + res = call(c, f"fix-{sid}", STAGE_BUILDER, inputs, pair, True, sid, "--fix") logged = must(record(c, sid, pair, res, "--fix"), "record", (0, 1, 3, 4)) stopped = re.match(r"Result: stopped:?\s*(.*)", res["line"]) why = ((stopped.group(1) or "the builder stopped") if stopped else "edited the plan" if res["edited"] diff --git a/plugins/phased-delivery/skills/implement-in-phases/build-guide.md b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md index a4cb7c0..65cf302 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/build-guide.md +++ b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md @@ -87,8 +87,10 @@ parallel is not built in parallel. For each: the stage is routed again; - stalled (`claude-build.sh` exit 7: no output for `CLAUDE_BUILD_STALL` seconds): the call's edits are undone and it runs once more, not as a - try of the pair; a second stall halts `stalled`. This holds for every - model call, not only builds; + try of the pair; a second stall halts `stalled`. Each stalled call is + recorded with exit 7 (for a stage, as an error attempt), so its cap + counts in the premium spend; a stalled revise does not count as the + phase's revise. This holds for every model call, not only builds; - error (a build exit other than 0, 7 and 8; not a try of the pair): halt `build-error`; - the builder's report ends `Result: stopped`: the attempt is rejected diff --git a/plugins/phased-delivery/tests/test_run_phase.py b/plugins/phased-delivery/tests/test_run_phase.py index 6fb7102..a27383c 100644 --- a/plugins/phased-delivery/tests/test_run_phase.py +++ b/plugins/phased-delivery/tests/test_run_phase.py @@ -247,7 +247,10 @@ def test_stalled_call_is_undone_and_run_again(repo): result = drive(repo, [REVISED_NOTHING, {**BUILD_ONE, "sleep": 6}, BUILD_ONE, BUILD_TWO, REVIEW], stall=2) assert result.returncode == 0, result.stdout + result.stderr assert calls(repo) == 5 - assert len(read(repo, "01.1.json")["record"]["attempts"]) == 1 # the stall is not a try of the pair + # the stall is recorded as an error, not a try of the pair, at its cap for the premium spend + stall, built = read(repo, "01.1.json")["record"]["attempts"] + assert (stall["result"], stall["exit"], stall["cost"], stall["cap"]) == ("error", 7, None, 0.75) + assert built["result"] == "accepted" def test_second_stall_halts(repo): @@ -256,4 +259,14 @@ def test_second_stall_halts(repo): assert result.returncode == 10, result.stdout + result.stderr assert halt(repo) == ("stalled", "01.1") assert not (repo / "src/one.txt").exists() - assert not read(repo, "01.1.json")["record"].get("attempts") + assert [x["exit"] for x in read(repo, "01.1.json")["record"]["attempts"]] == [7, 7] + + +def test_stalled_revise_runs_again(repo): + stalled = {**REVISED_NOTHING, "sleep": 6} + assert drive(repo, [stalled, stalled], stall=2).returncode == 10 + runs = read(repo, "phase.json")["record"]["runs"] + assert [(x["stage"], x["exit"]) for x in runs] == [("revise", 7), ("revise", 7)] + result = drive(repo, [REVISED_NOTHING, BUILD_ONE, BUILD_TWO, REVIEW]) + assert result.returncode == 0, result.stdout + result.stderr + assert calls(repo) == 4 # the revise ran again From 7e3a6fa20870a78f24fb311c96e4086061bef445 Mon Sep 17 00:00:00 2001 From: Bryan <28662377+bryanwieg@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:29:24 +0000 Subject: [PATCH 2/2] Stop what a model call started when it ends (0.15.3) claude runs in its own process group (setsid), and the group is stopped when the call stalls or finishes, so no test run or shell it started is left behind. Co-Authored-By: Claude Opus 5.5 --- .../.claude-plugin/plugin.json | 2 +- .../phased-delivery/scripts/claude-build.sh | 13 +++++++++---- .../tests/test_claude_build.py | 19 ++++++++++++++++--- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/plugins/phased-delivery/.claude-plugin/plugin.json b/plugins/phased-delivery/.claude-plugin/plugin.json index 52f4e0e..ad6f5ff 100644 --- a/plugins/phased-delivery/.claude-plugin/plugin.json +++ b/plugins/phased-delivery/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "phased-delivery", - "version": "0.15.2", + "version": "0.15.3", "description": "Plan work as self-contained phases, then implement it phase by phase.", "author": { "name": "Bryan" diff --git a/plugins/phased-delivery/scripts/claude-build.sh b/plugins/phased-delivery/scripts/claude-build.sh index 8ec6379..6ca10d8 100755 --- a/plugins/phased-delivery/scripts/claude-build.sh +++ b/plugins/phased-delivery/scripts/claude-build.sh @@ -16,7 +16,8 @@ # sandbox image does). # CLAUDE_BUILD_STALL (seconds, default 900) stops the call when stream.jsonl # gains no line for that long: a hung call, not a slow one (the longest -# silence in 39 recorded runs was 130 s). +# silence in 39 recorded runs was 130 s). Claude runs in its own process +# group (with setsid), so whatever it started is stopped with it, stalled or not. # Prints "Tokens: N" (input, output, cache read and cache creation, from # modelUsage, else usage) and # "Cost: X.XX" (USD), or unknown, for the stage commit. @@ -25,7 +26,7 @@ # seconds without output); 8 the budget was reached; other non-zero: the # claude exit status. Never commits; the orchestrator does. set -u -[ $# -eq 6 ] || { sed -n '2,26p' "$0" >&2; exit 2; } +[ $# -eq 6 ] || { sed -n '2,27p' "$0" >&2; exit 2; } REPO=$1; PROMPT=$2; MODEL=$3; EFFORT=$4; BUDGET=$5; OUT=$6 MODE=${CLAUDE_BUILD_PERMISSIONS:-acceptEdits} case "$MODE" in @@ -42,7 +43,10 @@ TEXT=$(cat "$PROMPT") || exit 2 # this claude knows it (it then rejects the invalid value here, naming the option; otherwise --version runs) THINK= claude --thinking-display check --version < /dev/null 2>&1 | grep -q -- --thinking-display && THINK=summarized -(cd "$REPO" && exec claude -p "$TEXT" --model "$MODEL" --effort "$EFFORT" \ +# its own process group (setsid, where there is one), so the processes it starts are stopped with it +GROUP= +command -v setsid > /dev/null && GROUP="setsid -w" +(cd "$REPO" && exec $GROUP claude -p "$TEXT" --model "$MODEL" --effort "$EFFORT" \ --max-budget-usd "$BUDGET" \ --settings '{"enabledPlugins":{"phased-delivery@ai-coding-plugins":false}}' \ ${THINK:+--thinking-display "$THINK"} \ @@ -56,12 +60,13 @@ rm -f "$OUT/stalled" while sleep 1; do now=$(wc -c < "$OUT/stream.jsonl") if [ "$now" = "$size" ]; then quiet=$((quiet + 1)); else size=$now; quiet=0; fi - [ $quiet -lt "$STALL" ] || { : > "$OUT/stalled"; kill $pid; exit; } + [ $quiet -lt "$STALL" ] || { : > "$OUT/stalled"; kill -TERM "-$pid" 2>/dev/null || kill $pid; exit; } done) > /dev/null 2>&1 & watch=$! wait $pid status=$? kill $watch 2>/dev/null +[ -z "$GROUP" ] || kill -TERM "-$pid" 2>/dev/null # what the call left running if [ -e "$OUT/stalled" ]; then : > "$OUT/report.md" printf 'Tokens: unknown\nCost: unknown\n' diff --git a/plugins/phased-delivery/tests/test_claude_build.py b/plugins/phased-delivery/tests/test_claude_build.py index 0b63575..7cdab7a 100644 --- a/plugins/phased-delivery/tests/test_claude_build.py +++ b/plugins/phased-delivery/tests/test_claude_build.py @@ -2,6 +2,7 @@ import os from pathlib import Path import subprocess +import time import pytest @@ -20,10 +21,11 @@ "cacheCreationInputTokens": 9070}}} -def run(tmp_path, events, code=0, permissions=None, pause=0, stall=None, thinking=True): +def run(tmp_path, events, code=0, permissions=None, pause=0, stall=None, thinking=True, child=False): """Run the script with a stub `claude` that records its arguments and prints EVENTS. - THINKING: whether the stub knows --thinking-display (claude-build.sh probes it first).""" + THINKING: whether the stub knows --thinking-display (claude-build.sh probes it first). + CHILD: the stub leaves a process running, its pid in child.pid.""" bin_dir = tmp_path / "bin" bin_dir.mkdir() (tmp_path / "events.jsonl").write_text("not json\n" + "".join(json.dumps(e) + "\n" for e in events)) @@ -33,7 +35,8 @@ def run(tmp_path, events, code=0, permissions=None, pause=0, stall=None, thinkin if thinking else "echo 2.1.330; exit 0") stub.write_text(f'#!/bin/sh\ncase " $* " in *" --version "*) {probe};; esac\n' f'printf "%s\\n" "$@" > "{tmp_path / "args.txt"}"\n' - f'echo "claude failed" >&2\ncat "{tmp_path / "events.jsonl"}"\nsleep {pause}\nexit {code}\n') + + (f'sleep 300 > /dev/null 2>&1 & echo $! > "{tmp_path / "child.pid"}"\n' if child else "") + + f'echo "claude failed" >&2\ncat "{tmp_path / "events.jsonl"}"\nsleep {pause}\nexit {code}\n') stub.chmod(0o755) env = {**os.environ, "PATH": f"{bin_dir}:{os.environ['PATH']}"} env.pop("CLAUDE_BUILD_PERMISSIONS", None) @@ -93,6 +96,16 @@ def test_stall_stops_the_call(tmp_path): assert run(other, [BUILT], stall="soon").returncode == 2 +@pytest.mark.parametrize("pause, stall, code", [(30, "2", 7), (0, None, 0)]) +def test_processes_left_by_the_call_are_stopped(tmp_path, pause, stall, code): + # stalled or finished, nothing the call started outlives it + assert run(tmp_path, [BUILT], pause=pause, stall=stall, child=True).returncode == code + pid = int((tmp_path / "child.pid").read_text()) + time.sleep(0.3) + with pytest.raises(ProcessLookupError): + os.kill(pid, 0) + + def test_thinking_display_left_out_when_unknown(tmp_path): # a claude without the undocumented option would fail the call on it assert run(tmp_path, [BUILT], thinking=False).returncode == 0