diff --git a/plugins/phased-delivery/.claude-plugin/plugin.json b/plugins/phased-delivery/.claude-plugin/plugin.json index ca02453..b16e2bb 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.16.0", + "version": "0.17.0", "description": "Plan work as self-contained phases, then implement it phase by phase.", "author": { "name": "Bryan" diff --git a/plugins/phased-delivery/scripts/build-check.py b/plugins/phased-delivery/scripts/build-check.py index f58d488..3187c2b 100755 --- a/plugins/phased-delivery/scripts/build-check.py +++ b/plugins/phased-delivery/scripts/build-check.py @@ -24,9 +24,12 @@ re-rendered from the records. --repo defaults to the current directory. start validates phase.json and the stage files and writes HEAD and the - paths already modified into phase.json's record (kept as is when - set: resume). Exit 1 on invalid JSON or a stage's file already - modified. + paths already modified into phase.json's record. On resume (HEAD + already set) it adds the paths modified since, other than stage + files and the plan's, so the driver never restores them. Exit 5 + when the only problem is a brief changed without a higher + revision; exit 1 on other invalid JSON or, on the first start, a + stage's file already modified. can-try exit 1 when the stage already has a non-error attempt on the pair at the brief's current revision. record logs an attempt and gates a build: no uncommitted path outside the @@ -35,7 +38,10 @@ accepted; 1 failed; 3 budget stop (build exit 8); 4 error (any other build exit: not a try of the pair). Exit 2, nothing logged, for --model orchestrator on a stage that is not session_only. - Stages "review" and "revise" are logged for spend only. + Stages "review" and "revise" are logged for spend only. --live + streams each check to stderr as it runs: "[check-] $ ", + each output line (stdout and stderr merged) and "[check-] + exit N". reject marks the stage's accepted, uncommitted attempt rejected. commit commits the stage's changed files with the stage trailers (an empty commit for a session-only or reopened stage with none), @@ -220,8 +226,20 @@ def outside_paths(top, plan_dir, pj, stages, sid): if p not in allowed and not is_cache(p) and not in_dir(p, rel(top, plan_dir))] -def run_checks(top, commands): - return [{"cmd": c, "exit": subprocess.run(["sh", "-c", c], cwd=top, capture_output=True).returncode} +def run_live(top, stage, cmd): + tag = f"[check-{stage}]" + print(f"{tag} $ {cmd}", file=sys.stderr, flush=True) + with subprocess.Popen(["sh", "-c", cmd], cwd=top, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p: + for raw in p.stdout: + line = raw.decode(errors="replace").rstrip("\r\n") + print(f"{tag} {line}", file=sys.stderr, flush=True) + print(f"{tag} exit {p.returncode}", file=sys.stderr, flush=True) + return p.returncode + + +def run_checks(top, commands, live_stage=None): + return [{"cmd": c, "exit": run_live(top, live_stage, c) if live_stage + else subprocess.run(["sh", "-c", c], cwd=top, capture_output=True).returncode} for c in commands] @@ -236,15 +254,21 @@ def count(x): # ---- subcommands def cmd_start(a): - pdir, _ = phase_paths(a.phase_dir) + pdir, plan_dir = phase_paths(a.phase_dir) name = os.path.basename(pdir) pj, stages, problems = checked_phase(pdir) if problems: - return report(problems) - if pj["record"].get("start_commit"): - return 0 + return 5 if report(problems) and all(p["kind"] == "revision" for p in problems) else 1 top = toplevel(a.repo) now = changed_paths(top) + if pj["record"].get("start_commit"): + # resume: keep paths changed since the last run, so a restore never deletes or reverts them + known = set(pj["record"]["preexisting"]) | {p for s in stages.values() for p in brief_files(s)} + new = [p for p in now if p not in known and not is_cache(p) and not in_dir(p, rel(top, plan_dir))] + if new: + save(os.path.join(pdir, "phase.json"), + with_record(pj, preexisting=pj["record"]["preexisting"] + new)) + return 0 dirty = [{"file": f"{name}/{sid}.json", "where": sid, "msg": f"stage file already modified: {p}"} for sid, s in stages.items() for p in brief_files(s) if p in now] if dirty: @@ -285,7 +309,7 @@ def cmd_record(a): top = toplevel(a.repo) same = [x for x in attempts_of(s) if x["fix"] == a.fix and x["result"] != "error" and not x["commit"]] outside = outside_paths(top, plan_dir, pj, stages, a.stage) - checks = [] if a.exit_code or outside else run_checks(top, s["brief"]["checks"]) + checks = [] if a.exit_code or outside else run_checks(top, s["brief"]["checks"], a.stage if a.live else None) if a.exit_code == 8: outcome, code = {"result": "stopped", "why": "budget reached"}, 3 elif a.exit_code != 0: @@ -437,6 +461,7 @@ def parse_args(argv): s.add_argument("--tool-calls", type=number) s.add_argument("--premium", action="store_true") s.add_argument("--fix", action="store_true") + s.add_argument("--live", action="store_true") s.add_argument("--repo", default=".") s = sub.add_parser("reject") for k in ("phase_dir", "stage", "why"): diff --git a/plugins/phased-delivery/scripts/run-phase.py b/plugins/phased-delivery/scripts/run-phase.py index f0595ad..494c6dd 100755 --- a/plugins/phased-delivery/scripts/run-phase.py +++ b/plugins/phased-delivery/scripts/run-phase.py @@ -108,6 +108,10 @@ def py(script, *args): return sh(sys.executable, os.path.join(HERE, script), *args) +def say(text): + print(f"[driver] {text}", file=sys.stderr, flush=True) + + def feed(label, event): """The live lines for one stream event: thinking, text, tool calls, failed tool results, the result.""" def short(text, n=300): @@ -271,9 +275,33 @@ def call(c, label, guide, inputs, pair, keep_briefs, what, *flags): def record(c, what, pair, res, *flags): - return py("build-check.py", "record", c.pdir, what, "--tool", "claude-code", "--model", pair["model"], - "--effort", pair["effort"], "--exit", res["exit"], "--tokens", res["tokens"], "--cost", res["cost"], - "--cap", pair["cap_usd"], *(["--premium"] if pair["premium"] else []), *flags, "--repo", c.top) + """build-check.py record --live: its [check-] lines go to stderr as it writes them; the result keeps the rest.""" + stage = what not in ("review", "revise") + cmd = [sys.executable, os.path.join(HERE, "build-check.py"), "record", c.pdir, what, "--tool", "claude-code", + "--model", pair["model"], "--effort", pair["effort"], "--exit", res["exit"], "--tokens", res["tokens"], + "--cost", res["cost"], "--cap", pair["cap_usd"], *(["--premium"] if pair["premium"] else []), *flags, + "--repo", c.top, "--live"] + # bytes, not text=True: universal newlines would split a check's '\r' progress into lines without [check- + with subprocess.Popen([str(x) for x in cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p: + kept, checking = [], False + for line in (raw.decode() for raw in p.stderr): + if line.startswith("[check-"): + if not checking: # only record knows whether checks run (not after a failed build or outside paths) + say(f"stage {what}: checks") + checking = True + print(line, end="", file=sys.stderr, flush=True) + else: + kept.append(line) + out = p.stdout.read().decode() # one JSON line, written after the checks + if stage and p.returncode in (0, 1, 3, 4): + logged = json.loads(last(out)) + say(f"stage {what}: {logged['result']}" + (f", outside: {', '.join(logged['outside'])}" if logged["outside"] else "")) + return subprocess.CompletedProcess(p.args, p.returncode, out, "".join(kept)) + + +def reject(c, sid, why): + must(py("build-check.py", "reject", c.pdir, sid, why), "reject") + say(f"stage {sid}: rejected: {why}") def stage_pair(c, brief, *steps): @@ -335,11 +363,13 @@ 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.""" + started = py("build-check.py", "start", c.pdir, "--repo", c.top) # every run: a resume adds new user edits + if started.returncode == 5: + raise Halt("brief-changed", started.stdout.strip()) + if started.returncode: + raise Halt("revise-failed", (started.stdout + started.stderr).strip()) runs = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"].get("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()) current = py("select-models.py", "check", os.path.join(c.plan_dir, "models.md"), *c.profiles) if current.returncode: raise Halt("models-stale", last(current.stdout + current.stderr)) @@ -357,6 +387,7 @@ def failed(c, sid, times, unchanged, why): restore(c) if times >= MAX_REVISIONS: raise Halt("revise-capped", f"stage {sid} was revised {times} times for failures in this run; then: {why}") + say(f"stage {sid}: revising: {why}") if revise(c, f"stage {sid}: {why}") == "unchanged": raise Halt(unchanged, why) return "revised" @@ -382,6 +413,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)] + say(f"stage {sid}: build") 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: @@ -391,13 +423,12 @@ def build(c, sid, s, times): if stopped or (accepted and res["edited"]): why = "edited the plan" if not stopped else stopped.group(1) or "the builder stopped" if accepted: - must(py("build-check.py", "reject", c.pdir, sid, why), "reject") + reject(c, sid, why) return failed(c, sid, times, "builder-stopped", why) if stopped else "retry" if accepted: done = commit(c, sid) if done.returncode: # reject it first, so a rerun builds the stage again - must(py("build-check.py", "reject", c.pdir, sid, f"commit: {last(done.stderr) or last(done.stdout)}"), - "reject") + reject(c, sid, f"commit: {last(done.stderr) or last(done.stdout)}") must(done, "commit") return "built" restore(c, json.loads(last(logged.stdout))["outside"]) @@ -468,8 +499,11 @@ def load_review(c): def commit(c, sid): - return py("build-check.py", "commit", c.pdir, sid, "--subject-suffix", c.a.subject_suffix, *c.trailers, + done = py("build-check.py", "commit", c.pdir, sid, "--subject-suffix", c.a.subject_suffix, *c.trailers, "--repo", c.top) + if done.returncode == 0: + say(f"stage {sid}: committed {done.stdout.strip()}") + return done def fix(c, sid, s, f): @@ -487,7 +521,7 @@ def fix(c, sid, s, f): why = "the fix changed none of the stage's files" if why: if logged.returncode == 0: - must(py("build-check.py", "reject", c.pdir, sid, why), "reject") + reject(c, sid, why) raise Halt("fix-failed", why) @@ -499,8 +533,10 @@ def review_and_fix(c): """With every stage committed: review, fix what the review says to fix, ask the rest; returns when all is settled.""" stages = read_stages(c.pdir) if not os.path.isfile(os.path.join(c.pdir, "review.json")): + say("review: start") step("review", None, review, c, stages) findings = step("review", None, load_review, c) + say(f"review: {len(findings)} findings") known = {x["index"]: x["status"] for x in plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"].get("findings", [])} # asked on an earlier run: the session has handled them since @@ -509,6 +545,7 @@ def review_and_fix(c): is_fix = lambda f: f["action"] in ("remove", "fix") and f["stage"] in stages for i, f in enumerate(findings): if states[i] == "open" and is_fix(f): + say(f"fix {f['stage']}: finding {i}") try: fix(c, f["stage"], stages[f["stage"]], f) except Halt as h: @@ -518,6 +555,7 @@ def review_and_fix(c): ask = [i for i, f in enumerate(findings) if states[i] == "open" and not is_fix(f)] if ask: mark(c, ask, "asked") + say(f"review: asked {len(ask)} findings") gap = any(findings[i]["action"] == "plan-gap" for i in ask) raise Halt("plan-gap" if gap else "question", "\n".join(describe(findings[i], "asked") for i in ask), "review") @@ -565,15 +603,18 @@ def run(a): if rec.get("built"): # already built: report it and write nothing print("\n".join(report(c, None))) return 0 + say(f"phase {os.path.basename(pdir)}: start") try: pre_phase(c, read_stages(pdir)) stage_loop(c) review_and_fix(c) step("finish", None, finish, c) + say("finish: built") halt = None except Halt as h: halt = {"step": h.step, "stage": h.stage, "reason": h.reason, "detail": h.detail, "next": NEXT[h.reason]} set_halt(pdir, plan_dir, halt) + say(f"halted at {h.step}" + (f" {h.stage}" if h.stage else "") + f": {h.reason}") print("\n".join(report(c, halt))) return 10 if halt else 0 diff --git a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md index 89b1572..08669f4 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md +++ b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md @@ -54,7 +54,9 @@ works this way is in (built), 10 (halted) or 2 (bad usage: fix the command). Run it as a background shell: a phase outlasts a foreground command's time limit, and the user watches the live feed on its stderr (each call's thinking, - messages and tool calls) in the tool's view of that shell. Do not read + messages and tool calls, the driver's own steps as `[driver]` lines and + each stage check's command, output and exit as `[check-NN.n]` lines) in + the tool's view of that shell. Do not read the feed into your own context; wait for the exit and read the report. 2. **On exit 10, answer the halt.** Read `record.halt` in the phase's `phase.json` (the report prints it too): `step`, `stage`, `reason`, 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 65cf302..a02d635 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/build-guide.md +++ b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md @@ -19,7 +19,11 @@ outcome, the halt, that Codex is off and, for a built phase, `report.md` in a numbered folder (a temporary directory otherwise). While a call runs, the driver prints its feed to stderr, each line tagged with the call (`[build-01.2]`): its thinking summaries, messages, tool calls, failed -tool results and result. +tool results and result. It also prints a `[driver]` line for each step it +takes (stage build, checks, result, commit, reject, revise, review, fixes, +finish, halt) and passes through `[check-01.2]` lines for each check's +command, output and exit code, which it gets from `build-check.py record +--live`. ## The parts @@ -45,20 +49,24 @@ sets it already). ## Revise and start -On a phase with no revise run recorded, the driver: +Every run starts with `build-check.py start`, which validates the phase. +The first time it writes `start_commit` and the paths already modified +(`preexisting`); on a rerun it adds the paths modified since, other than +stage files and the plan's, so files the user added or edited between runs +are never restored. A brief changed without a higher revision halts +`brief-changed`; any other refusal halts `revise-failed`. -1. runs `build-check.py start`, which validates the phase and writes - `start_commit` and the paths already modified (`preexisting`); a refusal - halts `revise-failed`; -2. runs `select-models.py check /models.md`; a stale table halts +On a phase with no revise run recorded, the driver then: + +1. runs `select-models.py check /models.md`; a stale table halts `models-stale`; -3. gives [revise-guide.md](revise-guide.md) to a headless reviser at the +2. gives [revise-guide.md](revise-guide.md) to a headless reviser at the review pair (`route --review`), with "none" as the problem, and records the run. A report without `Result: revised` or `Result: unchanged` halts `escalated`; a revised plan that fails `plan-check.py` halts `revise-failed`. -On a rerun before any stage has an attempt it only runs `plan-check.py`. +On a rerun before any stage has an attempt it then only runs `plan-check.py`. ## Build each stage diff --git a/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md b/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md index 584aa77..c70cfba 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md +++ b/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md @@ -221,9 +221,9 @@ Never written by planning or revising: write `"record": {}` in reader of a built plan knows them. - `phase.json`: `start_commit`, the commit the build started from; - `preexisting`, the paths with edits present before the build; `runs`, - the revise and review attempts; `findings`, the review's findings by - `index` with a `status` (`open`, `fixed`, `asked`, `answered`); `halt`, + `preexisting`, the paths with edits present before the build or added + between runs; `runs`, the revise and review attempts; `findings`, the + review's findings by `index` with a `status` (`open`, `fixed`, `asked`, `answered`); `halt`, why the build stopped, or null; `built`, the commit that finished the phase, or null. - Stage file: `revisions`, the hash of the brief at each revision that was diff --git a/plugins/phased-delivery/tests/test_build_check.py b/plugins/phased-delivery/tests/test_build_check.py index f79984e..e137087 100644 --- a/plugins/phased-delivery/tests/test_build_check.py +++ b/plugins/phased-delivery/tests/test_build_check.py @@ -157,14 +157,22 @@ def test_failed_check_then_retry(repo): (repo / "src/a.txt").write_text("a2\n") first = record(repo, "01.1", "haiku", "high", 0, "500", "0.10") assert first.returncode == 1 - assert json.loads(first.stdout)["checks"] == [{"cmd": "test -f src/done.txt", "exit": 1}] + assert "[check-" not in first.stderr + live = record(repo, "01.1", "sonnet", "high", 0, "600", "0.20", "--live") + assert live.returncode == 1 + assert live.stderr.splitlines() == ["[check-01.1] $ test -f src/done.txt", "[check-01.1] exit 1"] + for run in (first, live): + assert len(run.stdout.splitlines()) == 1 + assert json.loads(run.stdout)["checks"] == [{"cmd": "test -f src/done.txt", "exit": 1}] (repo / "src/done.txt").write_text("done\n") second = record(repo, "01.1", "opus", "medium", 0, "900", "0.30") assert second.returncode == 0 + assert len(second.stdout.splitlines()) == 1 assert bc(repo, "commit", PHASE, "01.1").returncode == 0 msg = message(repo) - assert "Attempt: 2" in msg + assert "Attempt: 3" in msg assert "Earlier-Attempt: haiku high 500 check failed" in msg + assert "Earlier-Attempt: sonnet high 600 check failed" in msg def test_can_try_refuses_repeat(repo): diff --git a/plugins/phased-delivery/tests/test_run_phase.py b/plugins/phased-delivery/tests/test_run_phase.py index a27383c..5729cb2 100644 --- a/plugins/phased-delivery/tests/test_run_phase.py +++ b/plugins/phased-delivery/tests/test_run_phase.py @@ -32,13 +32,13 @@ "record": {}} -def stage(title, order, path, tests=()): +def stage(title, order, path, tests=(), check=None): return {"brief": {"revision": 1, "title": title, "order": order, "lines": "under 30", "files": [{"path": path, "action": "create", "role": "the file"}], "provides": [], "uses": [], "goal": title, "context": {"builds_on": [], "code_read": [], "design": []}, "behaviour": [], "external_inputs": [], "tests": list(tests), "done_when": ["it exists"], - "checks": [f"test -f {path}"], "out_of_scope": [], + "checks": [check or f"test -f {path}"], "out_of_scope": [], "model_basis": dict.fromkeys("JFRCKPVS", 0)}, "record": {}} @@ -46,7 +46,9 @@ def stage(title, order, path, tests=()): STAGES = { "01.1": stage("Write one", "first", "src/one.txt", [{"test": "src/one.txt", "kind": "outcome", "action": "writes", "proves": "one exists", - "outcome": "O1"}]), + "outcome": "O1"}], + # prints a stdout line then a stderr line, so the test sees the merged output streamed in order + "cat src/one.txt && echo warn >&2"), "01.2": stage("Write two", "after 01.1", "src/two.txt"), } @@ -139,6 +141,16 @@ def test_builds_phase(repo): # the live feed of each call, on stderr for line in ("[revise] thinking: fake thinking", "[build-01.1] Bash: true", "result: success, $0.01"): assert line in result.stderr, result.stderr + # the driver's steps and each check's command and exit, in the order they happen + lines = result.stderr.splitlines() + wanted = ["[driver] phase 01-demo: start", "[driver] stage 01.1: build", "[driver] stage 01.1: checks", + "[check-01.1] $ cat src/one.txt && echo warn >&2", "[check-01.1] one", "[check-01.1] warn", + "[check-01.1] exit 0", "[driver] stage 01.1: accepted", + "[driver] review: start", "[driver] review: 0 findings", "[driver] finish: built"] + assert all(x in lines for x in wanted), result.stderr + assert [lines.index(x) for x in wanted] == sorted(lines.index(x) for x in wanted), result.stderr + assert any(x.startswith("[driver] stage 01.1: committed ") for x in lines), result.stderr + assert "[check-01.2] $ test -f src/two.txt" in lines, result.stderr def test_plan_ignored_by_git(repo): @@ -201,6 +213,12 @@ def test_revise_then_halt(repo): assert two["brief"]["revision"] == 3 and not two["record"].get("commit") assert [x["result"] for x in two["record"]["attempts"]] == ["failed"] * 3 assert "Halt: revise-capped at build 01.2" in result.stdout + lines = result.stderr.splitlines() + assert "[driver] stage 01.2: failed" in lines, result.stderr + assert "[check-01.2] exit 1" in lines, result.stderr + revising = next(i for i, x in enumerate(lines) if x.startswith("[driver] stage 01.2: revising: ")) + assert lines[revising + 1].startswith("[revise] "), result.stderr + assert lines[-1] == "[driver] halted at build 01.2: revise-capped", result.stderr def test_resume_after_halt(repo): @@ -209,6 +227,10 @@ def test_resume_after_halt(repo): assert first.returncode == 10, first.stdout + first.stderr assert halt(repo) == ("build-error", "01.1") assert not (repo / "src/one.txt").exists() # restored, so the rerun starts from a clean tree + # files the user adds or edits between runs are theirs: no restore may delete or revert them + (repo / "notes/mine.txt").parent.mkdir() + (repo / "notes/mine.txt").write_text("mine\n") + (repo / "src/base.txt").write_text("edited\n") # the rerun does not revise again, builds 01.1 and halts at 01.2, before any review second = drive(repo, [BUILD_ONE, {**BUILD_TWO, "exit": 3}]) assert second.returncode == 10, second.stdout + second.stderr @@ -216,6 +238,9 @@ def test_resume_after_halt(repo): assert halt(repo) == ("build-error", "01.2") assert read(repo, "01.1.json")["record"]["commit"] assert not read(repo, "01.2.json")["record"].get("commit") + assert (repo / "notes/mine.txt").read_text() == "mine\n" + assert (repo / "src/base.txt").read_text() == "edited\n" + assert git(repo, "show", "--name-only", "--format=", "HEAD").split() == ["src/one.txt"] def test_refused_commit_rejects_attempt(repo):