Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugins/phased-delivery/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
13 changes: 9 additions & 4 deletions plugins/phased-delivery/scripts/claude-build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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"} \
Expand All @@ -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'
Expand Down
19 changes: 12 additions & 7 deletions plugins/phased-delivery/scripts/run-phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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)
Expand Down Expand Up @@ -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")
Expand All @@ -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())
Expand Down Expand Up @@ -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"])
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 16 additions & 3 deletions plugins/phased-delivery/tests/test_claude_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
from pathlib import Path
import subprocess
import time

import pytest

Expand All @@ -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))
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
17 changes: 15 additions & 2 deletions plugins/phased-delivery/tests/test_run_phase.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
Loading