diff --git a/README.md b/README.md index 11552da..277177e 100644 --- a/README.md +++ b/README.md @@ -145,8 +145,22 @@ premium spend for routing, and makes each stage, fix and phase commit with its trailers. Every attempt goes into the stage file's `record`, and `phase.md`'s status is rendered from the records, so a resumed session picks up where it stopped. The phase reviewer writes `review.json` in the -phase folder with a closed list of finding types. SKILL.md is a -short outline; each step's directions are in its own guide. +phase folder with a closed list of finding types. + +### The phase driver + +implement-in-phases does not run the phase loop itself: for every phase it +runs `plugins/phased-delivery/scripts/run-phase.py `, which +revises the phase, routes, builds, gates and commits each stage, runs the +review and its fixes and finishes the phase. Every step is a headless +`claude` at the model, thinking level and cost cap the routing gives, and a +builder sees only its own stage's packet. When a step cannot go on (a brief +that cannot be built, a review question, a sign-in or service failure) the +driver writes a halt into `phase.json` and exits 10; the session does what +the halt's `next` says, asking you where the skill says to, and reruns it, +which resumes from the records. The session itself builds only a stage +marked `session_only`. Version 1 builds with Claude only: Codex routing +(below) is not used by the driver yet. Some tools, Codex among them, let subagents use a different model only when the user asks. To allow it, add to the project's `AGENTS.md` or `CLAUDE.md`: diff --git a/plugins/phased-delivery/.claude-plugin/plugin.json b/plugins/phased-delivery/.claude-plugin/plugin.json index 46b0796..c63d771 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.12.0", + "version": "0.13.0", "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 98db8f9..7defbed 100755 --- a/plugins/phased-delivery/scripts/claude-build.sh +++ b/plugins/phased-delivery/scripts/claude-build.sh @@ -11,20 +11,28 @@ # file edits work and commands follow the project's allow rules). A session # already in a sandbox container sets it to bypassPermissions (the ai-coding # 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). # 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. # -# Exit: 0 built; 2 usage; 8 the budget was reached; other non-zero: the +# Exit: 0 built; 2 usage; 7 stalled (stopped after CLAUDE_BUILD_STALL +# 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,17p' "$0" >&2; exit 2; } +[ $# -eq 6 ] || { sed -n '2,23p' "$0" >&2; exit 2; } REPO=$1; PROMPT=$2; MODEL=$3; EFFORT=$4; BUDGET=$5; OUT=$6 MODE=${CLAUDE_BUILD_PERMISSIONS:-acceptEdits} case "$MODE" in acceptEdits|bypassPermissions) ;; *) echo "CLAUDE_BUILD_PERMISSIONS must be unset or bypassPermissions, not '$MODE'" >&2; exit 2 ;; esac +STALL=${CLAUDE_BUILD_STALL:-900} +case "$STALL" in + ''|*[!0-9]*|0) echo "CLAUDE_BUILD_STALL must be a whole number of seconds, not '$STALL'" >&2; exit 2 ;; +esac mkdir -p "$OUT" TEXT=$(cat "$PROMPT") || exit 2 (cd "$REPO" && exec claude -p "$TEXT" --model "$MODEL" --effort "$EFFORT" \ @@ -32,8 +40,26 @@ TEXT=$(cat "$PROMPT") || exit 2 --settings '{"enabledPlugins":{"phased-delivery@ai-coding-plugins":false}}' \ --permission-mode "$MODE" --no-session-persistence \ --output-format stream-json --verbose) \ - < /dev/null > "$OUT/stream.jsonl" 2> "$OUT/stderr.txt" + < /dev/null > "$OUT/stream.jsonl" 2> "$OUT/stderr.txt" & +pid=$! +rm -f "$OUT/stalled" +# the watchdog: stops claude after STALL seconds without a new stream line +(size=-1; quiet=0 + 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; } + done) > /dev/null 2>&1 & +watch=$! +wait $pid status=$? +kill $watch 2>/dev/null +if [ -e "$OUT/stalled" ]; then + : > "$OUT/report.md" + printf 'Tokens: unknown\nCost: unknown\n' + echo "No output for $STALL s; the call was stopped as stalled" >&2 + exit 7 +fi # Exits 0 for a successful result, 8 when the budget was reached, 9 for another # error result, 1 without one. python3 - "$OUT/stream.jsonl" "$OUT/report.md" <<'PY' diff --git a/plugins/phased-delivery/scripts/plan-check.py b/plugins/phased-delivery/scripts/plan-check.py index 51214ee..538ca38 100644 --- a/plugins/phased-delivery/scripts/plan-check.py +++ b/plugins/phased-delivery/scripts/plan-check.py @@ -3,6 +3,7 @@ Usage: plan-check.py PLAN_DIR [--repo DIR] [--spec FILE] [--design FILE] [--outline] [--phase NN] + plan-check.py PLAN_DIR --packet NN.n The plan is PLAN_DIR/plan.json (plan.schema.json: outcomes, cross-phase decisions, existing interfaces, phases) and, per phase, a folder NN-name @@ -19,6 +20,10 @@ ones; --phase NN limits them to that phase. A brief that changed since an attempt built it needs a higher `revision`. +--packet prints the stage packet, the only plan text a builder is given: the +phase's role, why, how, before, after and test budget, then the stage's +brief as phase.md shows it. It checks and renders nothing; exit 2 for an unknown stage. + --spec and --design default to the paths plan.json names in `docs`, relative to --repo, which defaults to the current directory. @@ -51,20 +56,26 @@ # ---- a small JSON Schema subset (the plugin's scripts use the standard library only) +TYPES = {"object": dict, "array": list, "string": str, "boolean": bool, "null": type(None), + "integer": int, "number": (int, float)} + + +def is_type(data, name): + # a bool is an int in Python, not in JSON + return isinstance(data, TYPES[name]) and (name == "boolean" or not isinstance(data, bool)) + + def validate(data, schema, root=None, path=""): root = root or schema if "$ref" in schema: schema = root["definitions"][schema["$ref"].split("/")[-1]] out = [] t = schema.get("type") - types = {"object": dict, "array": list, "string": str, "boolean": bool} - if t == "integer": - if not isinstance(data, int) or isinstance(data, bool): - return [(path, f"must be an integer, got {type(data).__name__}")] - if data < schema.get("minimum", data) or data > schema.get("maximum", data): - out.append((path, f"{data} is outside {schema.get('minimum')}..{schema.get('maximum')}")) - elif t and not isinstance(data, types[t]): - return [(path, f"must be {t}, got {type(data).__name__}")] + if t and not any(is_type(data, name) for name in ([t] if isinstance(t, str) else t)): + wanted = "an integer" if t == "integer" else t if isinstance(t, str) else " or ".join(t) + return [(path, f"must be {wanted}, got {type(data).__name__}")] + if is_type(data, "number") and (data < schema.get("minimum", data) or data > schema.get("maximum", data)): + out.append((path, f"{data} is outside {schema.get('minimum')}..{schema.get('maximum')}")) if "enum" in schema and data not in schema["enum"]: out.append((path, f"{data!r} is not one of {schema['enum']}")) if "pattern" in schema and isinstance(data, str) and not re.search(schema["pattern"], data): @@ -74,11 +85,14 @@ def validate(data, schema, root=None, path=""): for k in schema.get("required", []): if k not in data: out.append((path, f"missing {k!r}")) + extra = schema.get("additionalProperties") for k, v in data.items(): if k in props: out += validate(v, props[k], root, f"{path}/{k}") - elif schema.get("additionalProperties") is False: + elif extra is False: out.append((path, f"unknown field {k!r}")) + elif isinstance(extra, dict): + out += validate(v, extra, root, f"{path}/{k}") if isinstance(data, list): if len(data) < schema.get("minItems", 0): out.append((path, f"needs at least {schema['minItems']} items")) @@ -399,11 +413,42 @@ def contract_lines(sid, brief, contracts, existing): return mine + used or ["none"] +def phase_rows(found, stages): + return [t for t in outcome_rows(stages) if t["written_in"] in found or t["passes_from"] in found] + + +def render_stage(sid, s, plan, stages, proves): + # the stage's section of phase.md, also the body of its packet + b = s["brief"] + c = b["context"] + L = ["", f"## {sid} {b['title']}".rstrip(), "", f"Goal: {b['goal']}", "", "Context:"] + ctx = [f"- Builds on {x['source']}: {x['what']}" for x in c["builds_on"]] + ctx += [f"- `{x['where']}`: {x['fact']}" for x in c["code_read"]] + ctx += [f"- {x['doc'].capitalize()}, {x['section']}: \"{x['quote']}\"" for x in c["design"]] + L += ctx or ["none"] + L += ["", "Contracts:"] + contract_lines(sid, b, registry(stages), plan["existing"]) + L += ["", "Files:"] + bullets(b["files"], lambda x: f"`{x['path']}` ({x['action']}): {x['role']}") + L += ["", "Behaviour:"] + bullets(b["behaviour"], lambda x: + f"Given {x['given']}, when {x['when']}, then {x['then'].rstrip('.')}.") + L += ["", "External inputs:"] + bullets(b["external_inputs"], lambda x: + f"{x['source']}: {x['check']}; on failure, {x['on_failure']}") + L += ["", "Tests:"] + bullets(b["tests"], lambda x: + f"{x['action']} `{x['test'].strip('`')}` ({x['kind']}): " + + (proves.get(x["test"].strip("`"), x["proves"]) if x["kind"] == "outcome" else x["proves"]) + + (f" (unit because: {x['why_unit']})" if x.get("why_unit") else "")) + L += ["", "Done when:"] + bullets(b["done_when"], str) + L += ["", "Checks:"] + bullets(b["checks"], lambda x: f"`{x}`") + L += ["", "Out of scope:"] + bullets(b["out_of_scope"], str) + total, t, why = tier(b["model_basis"]) + L += ["", "Model basis: " + " ".join(f"{m}{b['model_basis'][m]}" for m in MEASURES) + + f" = {total} -> {t}" + (f" (override: {why})" if why else "")] + return L + + def render_phase(ph, pj, found, plan, stages): num, d = ph["phase"], pj["brief"] outcomes = {x["id"]: x["observable"] for x in plan["outcomes"]} - contracts = registry(stages) - rows = [t for t in outcome_rows(stages) if t["written_in"] in found or t["passes_from"] in found] + rows = phase_rows(found, stages) proves = {t["test"]: outcomes.get(t["outcome"], t["outcome"]) for t in rows} L = [f"# Phase {num}: {ph['name']}", "", "Implement with the implement-in-phases skill; do not build from this file", @@ -420,29 +465,7 @@ def render_phase(ph, pj, found, plan, stages): L += [f"| {sid} | {s['brief']['goal']} | {tier(s['brief']['model_basis'])[1]} | {s['brief']['order']} | " f"{stage_status(s)} |" for sid, s in found.items()] for sid, s in found.items(): - b = s["brief"] - c = b["context"] - L += ["", f"## {sid} {b['title']}".rstrip(), "", f"Goal: {b['goal']}", "", "Context:"] - ctx = [f"- Builds on {x['source']}: {x['what']}" for x in c["builds_on"]] - ctx += [f"- `{x['where']}`: {x['fact']}" for x in c["code_read"]] - ctx += [f"- {x['doc'].capitalize()}, {x['section']}: \"{x['quote']}\"" for x in c["design"]] - L += ctx or ["none"] - L += ["", "Contracts:"] + contract_lines(sid, b, contracts, plan["existing"]) - L += ["", "Files:"] + bullets(b["files"], lambda x: f"`{x['path']}` ({x['action']}): {x['role']}") - L += ["", "Behaviour:"] + bullets(b["behaviour"], lambda x: - f"Given {x['given']}, when {x['when']}, then {x['then'].rstrip('.')}.") - L += ["", "External inputs:"] + bullets(b["external_inputs"], lambda x: - f"{x['source']}: {x['check']}; on failure, {x['on_failure']}") - L += ["", "Tests:"] + bullets(b["tests"], lambda x: - f"{x['action']} `{x['test'].strip('`')}` ({x['kind']}): " - + (proves.get(x["test"].strip("`"), x["proves"]) if x["kind"] == "outcome" else x["proves"]) - + (f" (unit because: {x['why_unit']})" if x.get("why_unit") else "")) - L += ["", "Done when:"] + bullets(b["done_when"], str) - L += ["", "Checks:"] + bullets(b["checks"], lambda x: f"`{x}`") - L += ["", "Out of scope:"] + bullets(b["out_of_scope"], str) - total, t, why = tier(b["model_basis"]) - L += ["", "Model basis: " + " ".join(f"{m}{b['model_basis'][m]}" for m in MEASURES) - + f" = {total} -> {t}" + (f" (override: {why})" if why else "")] + L += render_stage(sid, s, plan, stages, proves) notes = list(d["notes"]) for x in plan["decisions"]: if "all" in x["phases"] or num in x["phases"]: @@ -487,12 +510,32 @@ def write(plan_dir, plan, phases, nums): return list(texts) +def read_plan(plan_dir): + # (plan.json, [(its phase entry, phase.json, {stage id: stage file})]) as they are, without checks + plan = read_json(os.path.join(plan_dir, "plan.json")) + return plan, [(ph, read_json(os.path.join(plan_dir, ph["dir"], "phase.json")), + {n[:-5]: read_json(os.path.join(plan_dir, ph["dir"], n)) + for n in stage_files(os.path.join(plan_dir, ph["dir"]))}) for ph in plan["phases"]] + + +def packet(plan_dir, sid): + """The stage packet, the only plan text a builder is given, or None for an unknown stage.""" + plan, phases = read_plan(plan_dir) + stages = flatten(phases) + for _, pj, found in phases: + if sid in found: + d = pj["brief"] + outcomes = {x["id"]: x["observable"] for x in plan["outcomes"]} + proves = {t["test"]: outcomes.get(t["outcome"], t["outcome"]) for t in phase_rows(found, stages)} + head = [f"Role: {d['role']}", f"Why: {d['why']}", f"How: {d['how']}", + f"Before: {d['before']}", f"After: {d['after']}", f"Test budget: {d['test_budget']}"] + return "\n".join(head + render_stage(sid, found[sid], plan, stages, proves)) + "\n" + return None + + def render_plan(plan_dir): """Re-render plan.md and every phase.md from the JSON as it is, without checks; returns the paths written.""" - plan = read_json(os.path.join(plan_dir, "plan.json")) - phases = [(ph, read_json(os.path.join(plan_dir, ph["dir"], "phase.json")), - {n[:-5]: read_json(os.path.join(plan_dir, ph["dir"], n)) - for n in stage_files(os.path.join(plan_dir, ph["dir"]))}) for ph in plan["phases"]] + plan, phases = read_plan(plan_dir) return [os.path.join(plan_dir, n) for n in write(plan_dir, plan, phases, [ph["phase"] for ph in plan["phases"]])] @@ -546,7 +589,7 @@ def load_phase(plan_dir, ph, outline, stage_schema, r): def main(argv): - args, opts = [], {"--repo": ".", "--spec": None, "--design": None, "--phase": None} + args, opts = [], {"--repo": ".", "--spec": None, "--design": None, "--phase": None, "--packet": None} outline, i = False, 0 while i < len(argv): if argv[i] in opts and i + 1 < len(argv): @@ -561,6 +604,17 @@ def main(argv): print(__doc__, file=sys.stderr) return 2 plan_dir, repo, scope = args[0], opts["--repo"], opts["--phase"] + if opts["--packet"] is not None: + try: + text = packet(plan_dir, opts["--packet"]) + except (OSError, ValueError) as e: + print(e, file=sys.stderr) + return 2 + if text is None: + print(f"--packet {opts['--packet']} is not a stage of the plan", file=sys.stderr) + return 2 + print(text, end="") + return 0 r = Report() plan_path = os.path.join(plan_dir, "plan.json") if not os.path.exists(plan_path): diff --git a/plugins/phased-delivery/scripts/run-phase.py b/plugins/phased-delivery/scripts/run-phase.py new file mode 100755 index 0000000..38e4d72 --- /dev/null +++ b/plugins/phased-delivery/scripts/run-phase.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +"""Run one phase of a plan end to end: revise, build each stage, review, finish. + +Usage: + run-phase.py PHASE_DIR [--repo DIR] [--profiles PATH] [--work DIR] + [--instructions PATH]... [--subject-suffix TEXT] + [--extra-trailer LINE]... + +PHASE_DIR is a plan's phase folder NN-name, holding phase.json and one stage +file per stage. The driver prints a report: each stage and its result, the +review findings and their outcome, the halt if any, that Codex is off and, +for a finished phase, stage-stats.sh's table. + +When a step cannot go on, the driver writes a halt into phase.json's record, +{step, stage, reason, detail, next}, re-renders the plan and stops. `next` +says what the session does before rerunning; a rerun clears the halt and +resumes from the records. + +Exit codes: 0 built; 10 halted (the halt is in phase.json's record); 2 usage. +""" + +import argparse +import importlib.util +import json +import os +import re +import subprocess +import sys +import tempfile +from types import SimpleNamespace + +HERE = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("plan_check", os.path.join(HERE, "plan-check.py")) +plan_check = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(plan_check) +_spec = importlib.util.spec_from_file_location("build_check", os.path.join(HERE, "build-check.py")) +build_check = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(build_check) + +# What the session does about each halt before rerunning the driver. +NEXT = { + "revise-failed": "Read the detail (the reviser's report and plan-check.py's errors, or build-check.py " + "start's refusal), correct the stage files by revising.md " + "or clean the working tree, then rerun.", + "escalated": "The reviser says the problem is above this phase: settle it with the user in the spec, the " + "design or the plan, revise the stage files to match, then rerun.", + "revise-capped": "The stage was revised twice for failures in this run, or the reviser found nothing to " + "change after a used-up ladder: go through its attempts and its brief with the user, revise " + "the brief and raise its revision, then rerun.", + "builder-stopped": "Read the builder's report: correct the brief it could not build and raise its " + "revision, then rerun.", + "brief-changed": "A brief changed without a higher revision: raise the stage's revision or restore the " + "brief, then rerun.", + "record-changed": "A model call changed a record, which only the scripts write; the driver has already " + "restored it. Check that step's directions, named in the detail, with the user, then rerun.", + "models-stale": "Refresh the model profiles as model-selection.md says, then rerun.", + "session-only": "Build, record and commit the stage in the session before rerunning: a rerun restores " + "uncommitted stage files.", + "build-error": "The build failed for a reason that is not the model's (sign-in, service): clear the " + "cause in the detail, then rerun.", + "stalled": "A model call gave no output for the stall limit twice and its edits were undone: check " + "that the claude service and sign-in work, then rerun.", + "review-capped": "The review call stopped at its cost cap, so there is no usable review.json: tell the " + "user, and rerun when they agree; the review runs again.", + "review-invalid": "review.json does not match review.schema.json: delete it, then rerun so the phase is " + "reviewed again.", + "plan-gap": "A review finding is a gap in the plan: revise the stage files by revising.md to cover it, " + "then rerun.", + "question": "A review finding is a question: answer it with the user, revise the plan by revising.md " + "if the answer needs it, then rerun; the driver marks the finding answered.", + "fix-failed": "The fix for a review finding failed: revise the stage's brief and raise its revision so " + "the driver rebuilds it, or settle the finding with the user, then rerun.", +} + + +def set_halt(pdir, plan_dir, halt): + """Write the halt (None clears it) into phase.json's record and re-render the plan.""" + path = os.path.join(pdir, "phase.json") + pj = plan_check.read_json(path) + build_check.save(path, {**pj, "record": {**pj["record"], "halt": halt}}) + plan_check.render_plan(plan_dir) + + +SKILLS = os.path.join(os.path.dirname(HERE), "skills") +REVISE_GUIDE = os.path.join(SKILLS, "implement-in-phases", "revise-guide.md") +STAGE_BUILDER = os.path.join(SKILLS, "implement-in-phases", "stage-builder.md") +PHASE_REVIEWER = os.path.join(SKILLS, "implement-in-phases", "phase-reviewer.md") +MAX_REVISIONS = 2 # failure-driven revisions of one stage in a run before the user is asked + + +class Halt(Exception): + """A step cannot go on: the reason (a key of NEXT), the detail, and where it happened.""" + + def __init__(self, reason, detail, step="revise", stage=None): + super().__init__(reason, detail) + self.reason, self.detail, self.step, self.stage = reason, detail, step, stage + + +# ---- tools + +def sh(*cmd): + return subprocess.run([str(x) for x in cmd], capture_output=True, text=True) + + +def py(script, *args): + return sh(sys.executable, os.path.join(HERE, script), *args) + + +def last(text): + lines = [x for x in text.splitlines() if x.strip()] + return lines[-1].strip() if lines else "" + + +def must(r, what, ok=(0,)): + """The finished command, or a halt: brief-changed for exit 5, build-error for any other exit not in OK.""" + if r.returncode == 5: + raise Halt("brief-changed", r.stdout.strip() or last(r.stderr)) + if r.returncode not in ok: + raise Halt("build-error", f"{what}: {last(r.stderr) or last(r.stdout)}") + return r + + +def restore(c, paths=None): + """Put PATHS back as HEAD has them; by default every uncommitted path but the plan's and the preexisting ones.""" + if paths is None: + kept = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"].get("preexisting", []) + plan_rel = build_check.rel(c.top, c.plan_dir) + paths = [p for p in build_check.changed_paths(c.top) if p not in kept + and not build_check.is_cache(p) and not build_check.in_dir(p, plan_rel)] + for p in paths: + if sh("git", "-C", c.top, "cat-file", "-e", f"HEAD:{p}").returncode == 0: + build_check.git(c.top, "restore", "--source=HEAD", "--staged", "--worktree", "--", p) + else: + build_check.git(c.top, "rm", "-q", "--cached", "--ignore-unmatch", "--", p) + if os.path.lexists(os.path.join(c.top, p)): + os.remove(os.path.join(c.top, p)) + + +def plan_docs(plan_dir): + """{path: content} of every phase.json and stage file of the plan.""" + dirs = [os.path.join(plan_dir, ph["dir"]) for ph in plan_check.read_json(os.path.join(plan_dir, "plan.json"))["phases"]] + return {os.path.join(d, n): plan_check.read_json(os.path.join(d, n)) + for d in dirs for n in ["phase.json"] + plan_check.stage_files(d)} + + +def plan_files(plan_dir): + """Every file under the plan folder.""" + return {os.path.join(d, n) for d, _, names in os.walk(plan_dir) for n in names} + + +def guard(before, keep_briefs): + """Undo what a model call may not change in the plan: (a record changed, a brief changed and was restored).""" + def now(path): + try: + doc = plan_check.read_json(path) + except (OSError, ValueError): + return None + return doc if isinstance(doc, dict) else None + after = {p: now(p) for p in before} + for p, old in before.items(): + new = after[p] + right = old if new is None or keep_briefs else {**new, "record": old["record"]} + if right != new: + build_check.save(p, right) + records = any(after[p] is None or after[p].get("record") != old["record"] for p, old in before.items()) + briefs = keep_briefs and any(after[p] is not None and after[p].get("brief") != old["brief"] + for p, old in before.items()) + return records, briefs + + +def route(c, *options): + r = must(py("select-models.py", "route", c.available, *c.profiles, *options), "route") + 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}.""" + 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") + with open(guide) as g, open(prompt, "w") as f: + f.write(g.read() + "\n## Inputs\n\n" + "\n".join(inputs) + "\n") + before = plan_docs(c.plan_dir) + present = plan_files(c.plan_dir) + for _ in range(2): # a stalled call is undone and run once more + r = sh("sh", os.path.join(HERE, "claude-build.sh"), c.top, prompt, pair["model"], pair["effort"], + pair["cap_usd"], out) + if r.returncode != 7: + break + for p, doc in before.items(): + 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) + else: + raise Halt("stalled", f"the {label} call stalled twice: {last(r.stderr)}") + records, briefs = guard(before, keep_briefs) + added = sorted(plan_files(c.plan_dir) - present) if keep_briefs else [] # the reviser may add stage files + restore(c, [build_check.rel(c.top, p) for p in added]) + if records: + raise Halt("record-changed", f"the {label} call changed a record; its directions: {guide}") + printed = dict(re.findall(r"^(Tokens|Cost): (\S+)$", r.stdout, re.MULTILINE)) + report_path = os.path.join(out, "report.md") + text = open(report_path).read() if os.path.isfile(report_path) else "" + return {"exit": r.returncode, "tokens": printed.get("Tokens", "unknown"), "cost": printed.get("Cost", "unknown"), + "line": last(text), "stderr": last(r.stderr), "edited": briefs or bool(added)} + + +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) + + +def stage_pair(c, brief, *steps): + """The stage's routed pair, from its brief's scores and the premium spend.""" + spent = must(py("build-check.py", "spend", c.pdir), "spend").stdout.strip() + scores = "".join(f"{k}{brief['model_basis'][k]}" for k in "JFRCKPVS") + return route(c, "--scores", scores, "--premium-spent", spent, *steps) + + +def set_findings(c, findings): + path = os.path.join(c.pdir, "phase.json") + build_check.save(path, build_check.with_record(plan_check.read_json(path), findings=findings)) + + +def mark(c, indexes, status): + """Give the findings at INDEXES a new status in phase.json's record.""" + old = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"]["findings"] + set_findings(c, [{**x, "status": status} if x["index"] in indexes else x for x in old]) + + +def step(name, stage, fn, *args): + """Run one step; a halt in it is reported at that step and stage.""" + try: + return fn(*args) + except Halt as h: + raise Halt(h.reason, h.detail, name, stage) from None + + +# ---- steps. A step that cannot go on raises Halt. + +def check_plan(c): + number = next(ph["phase"] for ph in plan_check.read_json(os.path.join(c.plan_dir, "plan.json"))["phases"] + if ph["dir"] == os.path.basename(c.pdir)) + r = py("plan-check.py", c.plan_dir, "--repo", c.top, "--phase", number) + if r.returncode: + raise Halt("revise-failed", (r.stdout + r.stderr).strip()) + + +def revise(c, problem): + """Run the reviser on the phase and check its plan: 'revised' or 'unchanged'.""" + pair = route(c, "--scores", "J0F0R0C0K0P0V0S0", "--review") + inputs = [f"- Phase folder: `{c.pdir}`", f"- Problem: {problem}", c.instructions, + 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) + if res["exit"] not in (0, 8): + raise Halt("build-error", res["stderr"]) + must(record(c, "revise", pair, res), "record") + word = re.fullmatch(r"Result: (revised|unchanged)", res["line"]) + if not word: # an escalate line, or none + raise Halt("escalated", res["line"] or "the reviser's report has no result line") + check_plan(c) + return word.group(1) + + +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): + 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)) + revise(c, "none") + elif not any(s["record"].get("attempts") for s in stages.values()): + check_plan(c) + + +def read_stages(pdir): + return {n[:-5]: plan_check.read_json(os.path.join(pdir, n)) for n in plan_check.stage_files(pdir)} + + +def failed(c, sid, times, unchanged, why): + """A stage that cannot be built on its revision: clean the tree and revise the phase for it.""" + restore(c) + if times >= MAX_REVISIONS: + raise Halt("revise-capped", f"stage {sid} was revised {times} times for failures in this run; then: {why}") + if revise(c, f"stage {sid}: {why}") == "unchanged": + raise Halt(unchanged, why) + return "revised" + + +def build(c, sid, s, times): + """One step on a stage, read from its record: a build ('built' or 'retry'), or a revision ('revised').""" + brief, rec = s["brief"], s["record"] + if brief.get("session_only"): + raise Halt("session-only", f"stage {sid} is built in the session") + tried = [x for x in rec.get("attempts", []) if x["revision"] == brief["revision"]] + up = sum(x["result"] in ("failed", "rejected") for x in tried) + down = sum(x["result"] == "stopped" for x in tried) + if up and down: + return failed(c, sid, times, "revise-capped", "its builds both failed and reached their budget") + pair = stage_pair(c, brief, *(["--up", up] if up else ["--down", down] if down else [])) + # a ladder moved fewer steps than asked lands on a pair already tried, so can-try covers that too + if must(py("build-check.py", "can-try", c.pdir, sid, pair["model"], pair["effort"]), "can-try", (0, 1)).returncode: + return failed(c, sid, times, "revise-capped", + f"every model pair of its ladder was tried; the last attempt: {tried[-1]['why'] if tried else ''}") + fix = bool(rec.get("commit")) # reopened: rebuilt against the new brief as a fix + earlier = [f"- Earlier commit: `{rec['commit']}` built this stage from an earlier brief; rebuild it " + "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) + logged = record(c, sid, pair, res, *(["--fix"] if fix else [])) + if logged.returncode == 4: + raise Halt("build-error", res["stderr"]) + accepted = must(logged, "record", (0, 1, 3)).returncode == 0 + stopped = re.match(r"Result: stopped:?\s*(.*)", res["line"]) + 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") + 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") + must(done, "commit") + return "built" + restore(c, json.loads(last(logged.stdout))["outside"]) + return "retry" + + +def shelve_review(c): + """Before a build: put an earlier review aside, so the phase is reviewed again after it.""" + path = os.path.join(c.pdir, "review.json") + if os.path.isfile(path): + n = len([x for x in os.listdir(c.pdir) if re.fullmatch(r"review-\d+\.json", x)]) + 1 + os.rename(path, os.path.join(c.pdir, f"review-{n}.json")) + set_findings(c, []) + + +def stage_loop(c): + """Build the stages not done, in id order.""" + revisions = {} + while True: + stages = read_stages(c.pdir) + todo = [sid for sid, s in stages.items() if plan_check.stage_status(s) != "done"] + if not todo: + return + sid = todo[0] + shelve_review(c) + try: + result = build(c, sid, stages[sid], revisions.get(sid, 0)) + except Halt as h: + restore(c) # a rerun starts from a clean tree + raise Halt(h.reason, h.detail, "build", sid) from None + if result == "revised": + revisions = {**revisions, sid: revisions.get(sid, 0) + 1} + + +def review(c, stages): + """Run the reviewer, which writes review.json.""" + path = os.path.join(c.pdir, "review.json") + rec = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"] + unchecked = [sid for sid, s in stages.items() if not s["brief"]["checks"]] + pair = route(c, "--scores", "J0F0R0C0K0P0V0S0", "--review") + inputs = [f"- Phase folder: `{c.pdir}`", f"- Diff of the phase: `git diff {rec['start_commit']}`", + "- Edits that were present before the phase and are not part of it: " + + (", ".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) + 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): + raise Halt("build-error", res["stderr"]) + must(record(c, "review", pair, res), "record") + if res["exit"] == 8: + raise Halt("review-capped", "the review call reached its cost cap") + + +def load_review(c): + """review.json's findings, checked against its schema.""" + path = os.path.join(c.pdir, "review.json") + if not os.path.isfile(path): + raise Halt("review-invalid", "the review wrote no review.json") + doc, problems = build_check.load_checked(path, "review.schema.json", "review") + if problems: + raise Halt("review-invalid", "; ".join(f"{p['where']}: {p['msg']}" for p in problems)) + return doc["findings"] + + +def commit(c, sid): + return py("build-check.py", "commit", c.pdir, sid, "--subject-suffix", c.a.subject_suffix, *c.trailers, + "--repo", c.top) + + +def fix(c, sid, s, f): + """One fix build of the stage for the finding, committed; any failure halts fix-failed.""" + pair = stage_pair(c, s["brief"]) + 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) + 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"] + else "" if logged.returncode == 0 else res["stderr"] if logged.returncode == 4 else last(logged.stdout)) + if not why and commit(c, sid).returncode: + 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") + raise Halt("fix-failed", why) + + +def describe(f, status): + return f"{status}: {f['action']} `{f['type']}` in {f['stage']} at {f['file']}:{f['line']}: {f['evidence']}" + + +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")): + step("review", None, review, c, stages) + findings = step("review", None, load_review, c) + 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 + states = [known.get(i, "open").replace("asked", "answered") for i in range(len(findings))] + set_findings(c, [{"index": i, "status": x} for i, x in enumerate(states)]) + 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): + try: + fix(c, f["stage"], stages[f["stage"]], f) + except Halt as h: + restore(c) # a rerun starts from a clean tree + raise Halt(h.reason, h.detail, "fix", f["stage"]) from None + mark(c, [i], "fixed") + ask = [i for i, f in enumerate(findings) if states[i] == "open" and not is_fix(f)] + if ask: + mark(c, ask, "asked") + 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") + + +def finish(c): + must(py("build-check.py", "finish", c.pdir, *c.trailers, "--repo", c.top), "finish") + + +def report(c, halt): + """The report's lines, read from the phase's files.""" + listed = lambda items: [f"- {x}" for x in items] or ["none"] + rec = plan_check.read_json(os.path.join(c.pdir, "phase.json"))["record"] + marks = rec.get("findings", []) + # the record has findings only for a review.json that passed its schema + findings = plan_check.read_json(os.path.join(c.pdir, "review.json"))["findings"] if marks else [] + lines = [f"Phase {os.path.basename(c.pdir)}", "Stages:"] + lines += listed(f"{sid}: {plan_check.stage_status(s)}" for sid, s in read_stages(c.pdir).items()) + lines += ["Review findings:"] + listed(describe(findings[x["index"]], x["status"]) for x in marks) + if halt: + lines += [f"Halt: {halt['reason']} at {halt['step']}" + (f" {halt['stage']}" if halt["stage"] else ""), + f" {halt['detail']}", f" Next: {halt['next']}"] + else: + lines += ["Halt: none"] + stats = [] if halt else ["", subprocess.run(["sh", os.path.join(HERE, "stage-stats.sh"), f"{rec['start_commit']}..HEAD"], + cwd=c.top, capture_output=True, text=True).stdout] + return lines + ["Codex: off (driver version 1)"] + stats + + +def run(a): + pdir = os.path.realpath(a.phase_dir) + plan_dir = os.path.dirname(pdir) + rec = plan_check.read_json(os.path.join(pdir, "phase.json"))["record"] + # a rerun means the session has handled the halt; resuming reads the records only + if rec.get("halt") and not rec.get("built"): + set_halt(pdir, plan_dir, None) + work = a.work or tempfile.mkdtemp(prefix="run-phase-") + os.makedirs(work, exist_ok=True) + c = SimpleNamespace( + a=a, pdir=pdir, plan_dir=plan_dir, top=build_check.toplevel(a.repo), work=work, + available=os.path.join(plan_dir, "models-available.json"), + profiles=["--profiles", a.profiles] if a.profiles else [], + trailers=[x for line in a.extra_trailer for x in ("--extra-trailer", line)], + instructions="- Project instructions: " + + (", ".join(f"`{os.path.abspath(p)}`" for p in a.instructions) or "none")) + if rec.get("built"): # already built: report it and write nothing + print("\n".join(report(c, None))) + return 0 + try: + pre_phase(c, read_stages(pdir)) + stage_loop(c) + review_and_fix(c) + step("finish", None, finish, c) + 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) + print("\n".join(report(c, halt))) + return 10 if halt else 0 + + +def parse_args(argv): + p = argparse.ArgumentParser(prog="run-phase.py", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("phase_dir") + p.add_argument("--repo", default=".") + p.add_argument("--profiles") + p.add_argument("--work") + p.add_argument("--instructions", action="append", default=[]) + p.add_argument("--subject-suffix", default="") + p.add_argument("--extra-trailer", action="append", default=[]) + a = p.parse_args(argv) + if not os.path.isfile(os.path.join(a.phase_dir, "phase.json")): + p.error(f"not a phase folder (no phase.json): {a.phase_dir}") + return a + + +if __name__ == "__main__": + sys.exit(run(parse_args(sys.argv[1:]))) diff --git a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md index 77c796d..a7f6e62 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md +++ b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md @@ -1,6 +1,6 @@ --- name: implement-in-phases -description: "Build a written phased plan one phase at a time: revise the next phase's stage files against the repository, hand its stage briefs to agents in the planned order, review the actual diff, make one local commit per stage (with model, effort and token trailers), then stop and report. Use whenever the user asks to implement, build, execute, start, continue or resume a phased plan or a numbered phase (\"implement phase 2\", \"build the next phase\", \"continue the plan\", \"start on the plan\"), or when a plan directory of NN-name phase folders (phase.json and stage files) exists and the user wants it built. Requires a complete plan; if phase folders or stage briefs are missing, use plan-in-phases first. Use proactively, without being asked, whenever the work at hand is described by a plan's phase.md files (their header says \"Implement with the implement-in-phases skill\"); never build them without this skill. Never pushes unless asked." +description: "Build a written phased plan one phase at a time: run the phase driver (run-phase.py), which revises the next phase's stage files against the repository, hands its stage briefs to headless builders, reviews the actual diff and makes one local commit per stage (with model, effort and token trailers); answer each halt it reports, then stop and report. Use whenever the user asks to implement, build, execute, start, continue or resume a phased plan or a numbered phase (\"implement phase 2\", \"build the next phase\", \"continue the plan\", \"start on the plan\"), or when a plan directory of NN-name phase folders (phase.json and stage files) exists and the user wants it built. Requires a complete plan; if phase folders or stage briefs are missing, use plan-in-phases first. Use proactively, without being asked, whenever the work at hand is described by a plan's phase.md files (their header says \"Implement with the implement-in-phases skill\"); never build them without this skill. Never pushes unless asked." --- # Implement in phases @@ -14,12 +14,14 @@ from them; never edit a rendered file or a `record` by hand. The implementer owns how each stage's code works inside its brief. The planner's simplicity rules apply unchanged. -Each step below has its own guide; read it when you reach the step. -`scripts/build-check.py` (in this plugin, two directories above this -skill's directory) decides what needs no judgment: whether a build stayed -in its files and passed its checks, which model and thinking level pairs -were already tried, the premium spend, and every commit with its trailers. -Do not count, sum or write those by hand. Why it works this way is in +`scripts/run-phase.py` (the driver, in this plugin, two directories above +this skill's directory) builds a phase: it revises the phase, routes, +dispatches, gates and commits every stage, runs the review and its fixes +and finishes the phase, each model call a headless `claude`. The session +runs the driver and answers its halts; it does not dispatch, gate or commit +a stage itself, except a stage whose brief sets `session_only`. What the +driver does at each step is in [build-guide.md](build-guide.md); why it +works this way is in [structured-implementation-notes.md](structured-implementation-notes.md). ## Before the first phase @@ -31,61 +33,91 @@ Do not count, sum or write those by hand. Why it works this way is in 3. Note the starting git state and any edits already present, so they are not mistaken for this work. The commit the plan's work starts from is the first phase's `record.start_commit` in its `phase.json`, written by - `build-check.py start`; the work report counts from it. On resume, find - where the phase left off from `phase.md`'s status line and stage table, - which are rendered from the records. + the driver; the work report counts from it. On resume, rerun the driver: + it finds where the phase left off from the records. 4. Project rules (testing, size limits, what may be run) apply throughout. Writing code gives no permission to run it, and delegating to another agent does not lift any rule. ## Each phase -1. **Revise.** Read [revise-guide.md](revise-guide.md) and follow it with - no problem: check the phase's stage files against the repository, edit - the stale briefs, raise their revisions and run `plan-check.py` until - clean. Then run `build-check.py start ` until it exits 0. -2. **Build.** Read [build-guide.md](build-guide.md) and follow it for every - stage: route, `can-try`, dispatch, `record` (the gate), and `commit`. - Only a stage `record` accepted may be committed, and only a stage whose - brief sets `session_only` may be built by the session itself. -3. **Review.** Hand the review to a new agent that built none of the phase, - with [phase-reviewer.md](phase-reviewer.md) unchanged and its inputs - filled in, written to a prompt file outside the repository. Run `route - --review` and `scripts/claude-build.sh` with its `model`, `effort` and - `cap_usd`, and record the run with `build-check.py record - review ... --premium`. A review never drops a step: if it stops at its cap - (claude-build.sh exit 8), report that to the user. While Codex is on, check - the routing rule first; when it sends the review to Codex, run - `scripts/codex-build.sh` with the pair `route --review` prints for - `models-available-codex.json`. The reviewer writes - `review.json` in the phase folder with only the finding types phase-reviewer.md - lists. Read the diff yourself and decide on each finding by its action: - - `remove` and `fix`: make the change, `record ... --fix` and `commit` - it against the stage it changes (build-guide.md, "Commit each stage"); - - `plan-gap`: revise the plan before any code changes, following - [revise-guide.md](revise-guide.md) with the finding as the problem; a - built stage it reopens is rebuilt with `record ... --fix`; - - `question`: put it to the user in the report. -4. **Finish.** Update the phase's `notes` in `phase.json`, then run - `build-check.py finish `: it checks `review.json` and that - every stage has a commit and none is reopened, records the built commit, - re-renders `phase.md` and `plan.md` and commits the plan directory with a - `Phase:` trailer. Never push or publish unless asked. - -Then stop and report to the user: - -- each stage: done or not, and where to see it; -- deviations from the briefs, or "none"; -- what was verified by running something versus only by reading code, and what - could not be verified; +1. **Run the driver** from the repository, for every phase: + + ``` + python3 scripts/run-phase.py [--instructions ]... \ + [--subject-suffix "[skip ci]"] [--extra-trailer "Co-Authored-By: ..."]... + ``` + + Pass each project instruction file (CLAUDE.md, AGENTS.md) with + `--instructions`, and the project's required commit subject annotation + and trailers with the other two options. It prints a report and exits 0 + (built), 10 (halted) or 2 (bad usage: fix the command). +2. **On exit 10, answer the halt.** Read `record.halt` in the phase's + `phase.json` (the report prints it too): `step`, `stage`, `reason`, + `detail` and `next`. Do what `next` says, as the table below expands it, + then rerun the same command; the rerun clears the halt and resumes from + the records. Repeat until it exits 0. Never edit a `record`, and never + build, record or commit a stage that is not `session_only` to get past a + halt. +3. **On exit 0, report** (below). Never push or publish unless asked. + +"Revise" below means: follow [revise-guide.md](revise-guide.md) yourself, +with the halt's detail as the problem; edit the briefs, raise the +`revision` of each changed brief and run `plan-check.py` until clean. A +change that guide does not allow (another phase, `plan.json`, the +specification or the design) is settled with the user first. + +| Reason | What happened | What the session does, then reruns | +| --- | --- | --- | +| `revise-failed` | The revised plan fails `plan-check.py`, or `build-check.py start` refused (a stage's file was already modified). | Revise to clear the errors in the detail, or clean the working tree. | +| `escalated` | The reviser says the problem is above this phase. | **Ask the user**; settle it in the specification, the design or the plan, then revise the stage files to match. | +| `revise-capped` | A stage was revised twice for failures in this run, or its model pairs are used up and the reviser changed nothing. | **Ask the user**: go through the stage's attempts and brief with them, then revise the brief and raise its revision. | +| `builder-stopped` | The builder reported the brief cannot be built, and the reviser changed nothing. | Read the detail; revise the brief and raise its revision. | +| `brief-changed` | A brief changed without a higher revision. | Raise the stage's revision, or restore the brief. | +| `record-changed` | A model call changed a record; the driver restored it. | Check the directions named in the detail with the user. | +| `models-stale` | `models.md` no longer matches the model profiles. | Refresh as [model-selection.md](../plan-in-phases/model-selection.md) says ("Handle what the script reports"). | +| `session-only` | The stage's brief sets `session_only`. | Build, record and commit it yourself ("A session-only stage", below). | +| `build-error` | A call failed for a reason that is not the model's (sign-in, service, usage limit, a script error). | Clear the cause in the detail yourself; ask the user only when you cannot. | +| `stalled` | A model call gave no output for `CLAUDE_BUILD_STALL` seconds (default 900), twice; the driver undid its edits each time. | Check that `claude` works (sign-in, service), then rerun. | +| `review-capped` | The review stopped at its cost cap; there is no review. | Tell the user; rerun when they agree. | +| `review-invalid` | `review.json` is missing or does not match `review.schema.json`. | Delete `review.json`. | +| `plan-gap` | A review finding is a gap in the plan. | Revise the stage files to cover it; a built stage whose revision is raised is rebuilt by the driver. | +| `question` | A review finding is a question. | **Ask the user**; revise if the answer needs it. | +| `fix-failed` | The fix for a review finding failed. | Revise the stage's brief and raise its revision so the driver rebuilds it, or settle the finding with the user. | + +### A session-only stage + +The one stage the session builds. On the `session-only` halt, for the stage +it names: + +1. Print its packet: `python3 scripts/plan-check.py --packet + `. Build from the packet alone, under + [stage-builder.md](stage-builder.md), like a headless builder. +2. Gate it: `build-check.py record --tool claude-code + --model orchestrator --effort default --exit 0 --tokens unknown --cost + unknown` (add `--fix` when the stage already has a commit). Exit 1 + names the files outside the stage or the failing checks: correct the + work and record again. +3. Commit it: `build-check.py commit ` with the same + subject suffix and trailers as the driver's. Commit before rerunning: a + rerun restores uncommitted stage files. + +## The phase report + +When the driver exits 0, stop and report to the user: + +- the driver's report: each stage and where to see it, the review findings + and their outcome, and the models' work in this phase (the table from + `scripts/stage-stats.sh`); +- every halt of the phase and how it was answered; +- what was verified by running something versus only by reading code, and + what could not be verified; - plan adjustments made, as recorded in the phase's `notes`; -- the models' work in this phase: the table from - `scripts/stage-stats.sh ..HEAD`; -- whether Codex was on or off this phase, and why; +- that Codex was off (the driver, version 1, builds with Claude only); - questions, and the next phase. -A routing stop follows build-guide.md, "Stopping mid-phase"; report it the -same way, adding the stages left and both usage scripts' output lines. +A phase left halted for the user is reported the same way, with the halt +and the stages left. Continue to the next phase only when the user says so; a user stop wins. 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 2d6b0f1..cd5848d 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/build-guide.md +++ b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md @@ -1,164 +1,157 @@ -# Build the stages: guide - -How to route, dispatch, gate and commit each stage of a phase. The routing -rules are in [model-selection.md](../plan-in-phases/model-selection.md); -`scripts/build-check.py` reads each stage's brief from its stage file -(`/NN.n.json`), keeps the attempts in the stage file's `record`, -gates each build and makes the commits, so nothing here is counted or -written by hand. - -## Order and builders - -Follow the stage table's order. Hand each stage to a new builder with -[stage-builder.md](stage-builder.md) unchanged and its inputs filled in; run -stages marked parallel together. Only a stage whose brief sets -`session_only` is built by the session itself, under the same directions; -`record` refuses any other stage built by the orchestrator. Delegation keeps -each agent's context focused on its brief. - -## Models - -Before the phase's first dispatch, run `scripts/select-models.py check -/models.md`. Only on exit 1, or when a dispatch fails because a model -is unavailable, refresh the plan's `models-available.json` from the running -tool, rerun the selector to regenerate `models.md` and note the change in -the phase's `notes` (`phase.json`); exit 3 means the fallback, as model-selection.md -describes. - -## Route and dispatch each stage - -1. Take the stage's scores from its brief's `model_basis`, written without - spaces (`J1F1R0C0K0P0V0S0`). -2. Run `scripts/select-models.py route /models-available.json - --scores --premium-spent $(scripts/build-check.py spend )` ("Route each stage" in model-selection.md). -3. Run `build-check.py can-try `. Exit - 1 means the pair was already tried for this stage at its brief's current - revision: do not dispatch it; revise the plan (model-selection.md, - "Adjust while working"). A raised revision starts the pairs afresh. Exit - 5, from `can-try` or `record`, means the brief changed without a higher - `revision`: raise it ([revise-guide.md](revise-guide.md)) and rerun - `plan-check.py`. -4. Build a Claude stage headless: write stage-builder.md and its filled-in - inputs to a prompt file outside the repository and run - `scripts/claude-build.sh - ` with route's `model`, `effort` and `cap_usd`. Read the - builder's report from `/report.md`; the script prints `Tokens:` - and `Cost:`. Accept it exactly as a subagent's work. - -`CLAUDE_BUILD_PERMISSIONS` unset gives the builder `acceptEdits`: file -edits, and commands the project's allow rules permit. A session already in -a sandbox container may set it to `bypassPermissions` (the ai-coding -sandbox sets it already). - -## Gate each build - -After every build, record it: +# What the driver does: reference + +`scripts/run-phase.py` builds one phase. This file describes what it does +at each step, so a halt can be understood; it gives the session nothing to +do. What the session does is in [SKILL.md](SKILL.md): run the driver, +answer its halts, and build a `session_only` stage. The routing rules are in +[model-selection.md](../plan-in-phases/model-selection.md). ``` -build-check.py record --tool claude-code --model --effort \ - --exit --tokens --cost --cap [--tool-calls N] [--premium] +run-phase.py PHASE_DIR [--repo DIR] [--profiles PATH] [--work DIR] + [--instructions PATH]... [--subject-suffix TEXT] [--extra-trailer LINE]... ``` -Pass `--premium` when route printed `"premium": true`. `--tool-calls` comes -from the tool's own usage report (an in-session subagent's completion -notice); leave it out when there is none. Tokens and cost are `unknown` -when the tool gives none, never the builder's own claim. - -It prints one JSON line and exits: - -- **0, accepted:** no changed file outside the scope rule (the brief's - `files`), and every command in the brief's `checks` passed. Read the - builder's report and the diff; when the work is wrong in - a way the checks miss, run `build-check.py reject - ""` and treat it as a failed "Done when". The orchestrator can - reject a passing build, never accept a failing one. -- **1, failed:** a changed file outside the stage (`outside`) or a failing - check (`checks`). Restore the `outside` paths (`git restore` them, or - delete them when HEAD lacks them), then rerun with `route --up 1`, one - step further on each further failure. When it fails because the brief is - wrong, revise it instead: follow [revise-guide.md](revise-guide.md) with - the failure as the problem. -- **3, budget reached** (build exit 8): restore the `outside` paths, then - retry with `route --down 1`, one step further on each further stop. -- **4, error** (any other build exit): not a try of the pair. Apply that - tool's rule: for `claude-build.sh` (2: bad arguments or permissions; - otherwise claude's own status, such as a sign-in or service failure), - report stderr's last line to the user and stop; for a failed Codex build, - follow model-selection.md ("After a failed build"). - -A stage that has both hit its cap and failed its checks goes back to -planning; never net `--down` against `--up`. - -For a `small` stage, never take the builder's report as evidence: the -checks are rerun by `record`, and read its diff before committing. +Exit 0: built. Exit 10: halted, with `{step, stage, reason, detail, next}` +in `record.halt` of the phase's `phase.json`. Exit 2: bad usage. Each run +prints a report: every stage and its status, the review findings and their +outcome, the halt, that Codex is off and, for a built phase, +`stage-stats.sh`'s table. `--work` keeps each call's prompt, output and +`report.md` in a numbered folder (a temporary directory otherwise). + +## The parts + +- The driver reads each stage's brief from its stage file + (`/NN.n.json`) and resumes from the records alone: a rerun + clears the halt and continues with the first step not yet recorded. A + phase already built is only reported. +- Every model call is a headless `claude` through `scripts/claude-build.sh`, + at the model, thinking level and cost cap `select-models.py route` + prints. Version 1 builds with Claude only, as if Codex were off. +- `scripts/build-check.py` keeps the attempts, gates each build, sums the + premium spend and makes the commits, so nothing is counted or written by + hand. +- After every model call the driver restores what the call may not change + in the plan: any `record` (halt `record-changed`), and for a builder or + fixer also the briefs and any file it added to the plan folder. Only the + reviser may edit briefs. + +`CLAUDE_BUILD_PERMISSIONS` unset gives each call `acceptEdits`: file edits, +and commands the project's allow rules permit. A session already in a +sandbox container may set it to `bypassPermissions` (the ai-coding sandbox +sets it already). + +## Revise and start + +On a phase with no revise run recorded, the driver: + +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 + `models-stale`; +3. 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`. + +## Build each stage + +The stages not done are built one at a time in id order; a stage marked +parallel is not built in parallel. For each: + +1. A `session_only` stage halts `session-only`: the session builds it + (SKILL.md, "A session-only stage"). +2. **Route.** `route` with the brief's `model_basis` scores and + `build-check.py spend` as `--premium-spent`, moved `--up` one step per + failed or rejected attempt at the brief's current revision, or `--down` + one step per budget stop. From $10 of premium spend, builds get no + premium pair (route does this). +3. **`can-try`.** A pair already tried at this revision, or a stage that has + both failed and hit its cap, is not dispatched: the stage is revised + (below). +4. **Dispatch.** [stage-builder.md](stage-builder.md) unchanged, then the + project instructions and the stage packet (`plan-check.py --packet`), the + only plan text a builder is given. A reopened stage (committed, then its + brief's revision raised) is rebuilt the same way as a fix, with its + earlier commit named. +5. **Gate.** `build-check.py record` with the call's exit, tokens and cost: + - accepted (no changed file outside the brief's `files`, every command + in its `checks` passed): `build-check.py commit`; + - failed or budget stop: the paths outside the stage are restored and + 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; + - 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 + and the stage revised. A builder that edited the plan is rejected and + the stage routed again. +6. **Commit.** Only the stage's changed files, with the subject `NN.n + ` and the trailers `stage-stats.sh` reads (Stage, Plan, Tier, + Tool, Model, Effort, Attempt, Tokens, Cost, Tool-Calls, and an + Earlier-Attempt per failed, stopped or rejected try, over every + revision), plus `--subject-suffix` and each `--extra-trailer`. The + commit goes into the stage file's `record` and `phase.md` is + re-rendered, where the stage then shows as done (in the working tree; + `finish` commits the plan directory). + +**Revising a stage that cannot be built.** The driver restores the working +tree and runs the reviser with the failure as the problem. `revised`: the +raised revision starts the pairs afresh and the stage is built again. +`unchanged`: halt `builder-stopped` when the builder stopped, otherwise +`revise-capped`. A stage revised twice for failures in one run halts +`revise-capped` instead of a third revision. A brief changed without a +higher revision (exit 5 of any `build-check.py` call) halts +`brief-changed`. + +A halt during a build restores every uncommitted path but the plan's and +the preexisting ones, so a rerun starts from a clean tree. Any build puts +an earlier `review.json` aside as `review-N.json`, so the phase is reviewed +again. + +## Review and fix + +With every stage committed and no `review.json`, the driver gives +[phase-reviewer.md](phase-reviewer.md) to a new headless reviewer at the +review pair, with the phase's diff from `start_commit`, the preexisting +edits and the stages that have no check commands, and records the run. A +review stopped at its cap halts `review-capped`; a missing `review.json` or +one that does not match `review.schema.json` halts `review-invalid`. + +Each finding's status is kept in `record.findings` of `phase.json`: + +- `remove` and `fix` on a stage of the phase: one fix build of that stage + at its routed pair, with the finding as the assignment (stage-builder.md, + "Fixing one review finding"), recorded with `--fix` and committed with + `Fixes-Stage:`. A fix that fails its gate, stops, edits the plan or + changes none of the stage's files halts `fix-failed`. +- every other finding is marked `asked` and halts `plan-gap` (when one of + them is a plan gap) or `question`; on the rerun they count as answered. + A stage the session reopened to answer one is rebuilt first, and the + phase reviewed again. + +## Finish + +`build-check.py finish` checks `review.json` and that every stage has a +commit and none is reopened, records the built commit, re-renders +`phase.md` and `plan.md` and commits the plan directory with a `Phase:` +trailer and each `--extra-trailer`. Its refusal halts `build-error`. ## Premium spend `build-check.py spend <phase dir>` prints the phase's premium spend: the cost of every attempt recorded with `--premium`, its cap when the cost is -unknown. Pass `--premium` for every `claude-build.sh` run of a premium pair -and for every phase review run through `claude-build.sh`. From $10, builds -get no premium pair (route does this). Codex runs are never `--premium` and -their `route` calls pass no `--premium-spent`. - -## Commit each stage +unknown. The driver passes `--premium` for every run of a pair route marks +premium, the revise and review runs included. -When a stage is accepted, run: - -``` -build-check.py commit <phase dir> <stage> [--subject-suffix "[skip ci]"] [--extra-trailer "Co-Authored-By: ..."] -``` - -It commits only the stage's changed files, with the subject `NN.n <title>` -and the trailers `stage-stats.sh` reads (Stage, Plan, Tier, Tool, Model, -Effort, Attempt, Tokens, Cost, Tool-Calls, and an Earlier-Attempt per -failed, stopped or rejected try, over every revision), writes the commit -into the stage file's `record` and re-renders `phase.md`, where the stage -then shows as done (in the working tree; `finish` commits the plan -directory). -Add the project's required subject annotations and trailers with the two -options. Stages built in parallel are committed one by one. +## Session-only stages A `session_only` stage, built by the session, is recorded with `--model orchestrator --effort default --tokens unknown --cost unknown`; `record` exits 2 for that model on any other stage. When it changed no file in the repository, `commit` makes an empty commit with its trailers. - -A later change to fix a committed stage, from the phase review or later -work, is recorded with `record ... --fix` and committed the same way; its -commit carries `Fixes-Stage:` with the fixer's Model, Effort and Tokens. -A committed stage whose brief's revision was raised shows as `reopened`: it -is rebuilt against the new brief the same way, with `--fix`, and is done -again once that fix is committed, even when the rebuild changed no file. - -## Codex - -When the plan has `models-codex.md` and the session is not Codex, take -Codex availability from the daily check in "Builders in another tool" in -model-selection.md: off when the session was told at start that Codex is -off today, otherwise what `scripts/codex-usage.py` answers from its daily -cache before the phase's first dispatch. When Codex is off, skip the rest -of this section and record why in the phase's `notes`. - -While Codex is on, refresh `models-codex.md` the same way as `models.md`, -then before each dispatch run `scripts/claude-usage.py` and -`scripts/codex-usage.py` and route the stage by the routing table there. A -Codex dispatch runs alone (stages marked parallel run one after another -when one goes to Codex) and starts with the snapshot of REPO; follow the -rules there for failed Codex builds. For a Codex build, write -stage-builder.md and its filled-in inputs to a prompt file outside the -repository and run `scripts/codex-build.sh <repo> <prompt> <model> <effort> -<outdir>`, with the model and effort `route` prints for -`models-available-codex.json` (Codex builds have no cap), and record it -with `--tool codex`. Read its report from `<outdir>/report.md`; it prints -the token count. - -## Stopping mid-phase - -When the routing rule stops the phase (both tools nearly out), commit the -stage in progress, then run `build-check.py finish <phase dir> --stopped` -to commit the plan directory (the JSON with its records, and the rendered -files). After a stop at the check before the review, every stage shows as -done and the phase is not built; resuming starts with the review, after -checking availability and the routing rule again. diff --git a/plugins/phased-delivery/skills/implement-in-phases/stage-builder.md b/plugins/phased-delivery/skills/implement-in-phases/stage-builder.md index d0b323a..6e779e7 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/stage-builder.md +++ b/plugins/phased-delivery/skills/implement-in-phases/stage-builder.md @@ -1,28 +1,31 @@ # Stage builder directions Give this file, unchanged, to each builder of a stage, followed by the -inputs below: through `scripts/claude-build.sh` or `scripts/codex-build.sh`, +inputs below (for a fix of one review finding, the inputs under "Fixing one +review finding" instead): through `scripts/claude-build.sh` or `scripts/codex-build.sh`, at the model and thinking level `select-models.py route` prints (see "Route -each stage" in [model-selection.md](../plan-in-phases/model-selection.md)). The orchestrator -follows these rules too when it builds a stage directly. +each stage" in [model-selection.md](../plan-in-phases/model-selection.md)). The session +follows these rules too for a `session_only` stage. Inputs the orchestrator fills in: -- Phase file: `<path>` -- Stage: `<NN.n>` - Project instructions: `<paths, such as CLAUDE.md or AGENTS.md>` - Anything else the brief links to: `<paths>` +- Stage packet: the output of `plan-check.py PLAN_DIR --packet NN.n`, pasted + in full --- -You are building one stage of a phased plan. The stage brief in the phase -file is your whole assignment. The structure and contracts are decided; how +You are building one stage of a phased plan. The stage packet pasted under +the inputs is your whole assignment: the phase's role, why, how, before and +after, then your stage brief. It is the only plan text you are given; do not +read the plan folder or any JSON of the plan. The structure and contracts are decided; how the code works inside the brief is yours. ## Before writing code -1. Read the project instructions, the whole phase file, your stage brief and - everything the brief links to. +1. Read the project instructions, the whole stage packet and everything + the brief links to. 2. Read the code the brief names in Context, Contracts and Files, as it is now. Earlier stages may have changed it. Do not rely on memory or on the brief's description of the code; check it. @@ -42,8 +45,8 @@ the code works inside the brief is yours. artifacts, branches and procedures follow their own requirements. - Write the tests the brief's Tests line names, and remove the expected-fail marks it says to. Add no others: if the goal seems to need - another test, stop and report. Keep tests deterministic and within the - phase file's Outcome tests budget. + another test, stop and report. Keep tests deterministic, fast and + within the test budget the stage packet gives. - Follow the project's rules for testing, size limits and what may be run. Writing code gives no permission to run it. - Do not commit; the orchestrator commits each stage. @@ -68,3 +71,30 @@ it. what you could not verify. - Deviations from the brief, or "none". - Stops and questions, or "none". +- Last line, exactly one of: + - `Result: done` + - `Result: stopped: <why>` when you stopped and reported instead of + finishing (the brief is wrong or cannot be built). + +## Fixing one review finding + +When the inputs are these, you are fixing one finding of the phase review, +not building the stage: + +- Project instructions: `<paths, such as CLAUDE.md or AGENTS.md>` +- Finding: `<type>` at `<file>:<line>` + - Evidence: `<what the review saw>` + - Action: `<what to change>` +- Stage packet: the output of `plan-check.py PLAN_DIR --packet NN.n` for the + stage the finding belongs to, pasted in full + +Everything above applies, with these changes: + +- The finding is your whole assignment; the packet says what the code is + for and which files are the stage's. +- Change only what the finding names, and only inside the stage's files. +- Write no test the brief does not name. +- If the finding is wrong, or cannot be fixed inside the stage's files, + stop and report. +- Report as above, with "the finding's action" in place of the "Done when" + items, and end with the same result line. diff --git a/plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md b/plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md index 22f581e..0cf9863 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md +++ b/plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md @@ -1,7 +1,7 @@ # Why implementation uses stage files, a script gate and closed review types -Background for maintainers of this skill; the orchestrator and the reviewer -do not need it. Changed 2026-11-24 (plugin 0.11.0). +Background for maintainers of this skill; the session and the reviewer +do not need it. Changed 2026-11-24 (plugin 0.11.0; the driver in 0.13.0, below). ## What changed @@ -71,7 +71,8 @@ and `build-check.py` takes a phase folder and reads each stage file directly: headless reviser follow the same rules. The sections above and below describe 0.11.0 where they name the revision -JSON or the ledger. +JSON or the ledger, and the time before the driver where the orchestrator +dispatches, records or commits. ## Decisions worth keeping @@ -85,26 +86,42 @@ JSON or the ledger. committed: parallel stages work, and a committed stage cannot change unseen. -## Later: a driver script - -Investigate, not built. The `plan-phase-driver` branch holds an unreviewed -draft plan (2026-11-22) for a Python driver that owns the whole phase loop -and calls `claude -p` for each step (revise, build, review, triage), with -the orchestrator LLM only handling halts. - -- **What it would add:** rules that hold every time (no step skipped), no - orchestrator tokens, clean halts and resume on usage limits, and the - whole loop testable offline with a fake `claude`. -- **What it would cost:** a larger build than this one; the draft predates - `claude-build.sh`, `route`, the premium budget and this script, so it - needs re-planning on top of `build-check.py`. While both paths exist, - the loop's rules live in prose and Python. Codex routing was deferred in - the draft, and every case the rules do not cover becomes a halt for the - user. -- **What to measure first:** with this version in use, how often the - orchestrator skips or misapplies a step the script does not gate, and - how much of a phase's usage the orchestrator itself spends. If both are - small, the driver is not worth it. +## The driver (0.13.0) + +Built. Until 0.12.x the session ran +the phase loop itself from SKILL.md and build-guide.md: revise, route, +dispatch, gate, commit, review, finish. `scripts/run-phase.py` now owns +that loop and the session only runs it and answers its halts. + +- **Every step is a headless `claude`** through `claude-build.sh`: the + reviser (revise-guide.md), each builder and fixer (stage-builder.md) and + the reviewer (phase-reviewer.md), at the pair and cap `route` prints. + The session spends no tokens on the loop, and no step can be skipped. +- **A halt is data.** When a step cannot go on, the driver writes + `{step, stage, reason, detail, next}` into `phase.json`'s record and + exits 10. The reasons are a closed list, each with a fixed `next`; + SKILL.md's table says what the session does for each and which ones go + to the user. A rerun clears the halt and resumes from the records, so a + usage limit or a crash loses nothing recorded. +- **A builder is given only the stage packet** (`plan-check.py --packet`): + the phase's role and the stage's brief, nothing of other stages or of any + record. A session-only stage is built from the same packet. +- **Model calls cannot change what is not theirs.** After each call the + driver restores every record, and for builders and fixers the briefs + too; a changed record is a halt. +- **Failures revise, twice at most.** A stage whose pairs are used up, or + whose builder stopped, goes to the reviser with the failure as the + problem; after two such revisions in one run the user is asked. +- **Review findings are settled by the driver**: `remove` and `fix` get one + fix build each; plan gaps and questions halt for the session. +- **Only a session-only stage is built by the session**, and SKILL.md and + build-guide.md give it no other way to dispatch, gate or commit. +- **The loop is tested offline** with a fake `claude` + (`tests/test_run_phase.py`). + +Not built: Codex routing. Version 1 builds with Claude only, as if Codex +were off, and says so in its report; the Codex rules in model-selection.md +wait for a later plan. Stages marked parallel are built one after another. ## Measured @@ -133,3 +150,63 @@ git copy of the eval repository. built the stage itself), a failing build, a retry or a budget stop (the stage passed first time), Codex, and check commands that run long; the open question on check timeouts stays open. + +### Driver run on lower models (0.13.0) + +One run, 2026-11-24: `run-phase.py` on the same task, `p2-multistep`, +written as a one-phase, one-stage plan in the new layout in a git copy of +the eval repository, with only Opus and Haiku offered and the eval's +project rules (git state and `plan/` closed to builders). + +- **Result:** the driver exited 0 on its first run with no halt; the + task's files, copied onto a fresh eval repository, pass the hidden check + (`RESULT pass`). Cost $0.70: revise on Opus high $0.38 (285k tokens, + `Result: unchanged`), the stage on Haiku high $0.01 as claude reported + (188k tokens, accepted on the first try), the review on Opus high $0.31 + (300k tokens, no findings). +- **What it showed:** the session ran one command and wrote nothing. The + driver routed, built from the stage packet, gated, committed with the + usual trailers (`Stage`, `Plan`, `Tier`, `Model`, `Effort`, `Attempt`, + `Tokens`, `Cost`) and finished the phase (`Phase:` commit); the + stage-stats table came out of the report. Unlike the 0.11.0 run, nothing + was built or capped by the orchestrator. +- **Not exercised:** a failing build, the ladder, the reviser after a + failure, a halt and rerun, review findings and fix builds, premium + routing. The tests cover these with a fake claude; the real-routing run + is still to come. + +### Driver run with the real routing (0.13.0) + +One run, 2026-11-24, on real work rather than an eval task: none of the +eval tasks scores above `small`. The work was a one-stage plan to rewrite +the parts of `model-selection.md` that still described the session-run +loop, built in a clone of the branch, with the plan's model list but Fable +offered at low and medium only (the user's quota limit; with Fable at low +alone, `middle+` and `top` route to Opus high, which scores within the tie +margin and costs less, so no premium pair would run). + +- **Result:** built after two halts, each answered as SKILL.md says, with + exit 0 on the third run. The guide change, with a new guide test, was + taken onto the branch. Cost $3.60, of which $2.55 premium (all Fable + low; Fable medium never routed). +- **Run 1 (exit 10, `plan-gap`):** the pre-phase reviser on Fable low + ($0.77) raised the brief to revision 2, adding three citations it found + in the guide. The stage built on Opus high and passed first time ($0.42). + The review on Fable low ($0.94) found a bug, which the driver fixed with + a fix build on its own ($0.19, a `Fixes-Stage` commit), and two findings + for the session: two more sentences still had the session routing, and a + `models-stale` halt with no profiles gave advice that only halts again. +- **Answer and run 2 (exit 10, `plan-gap`):** the session revised the brief + to revision 3, re-citing the guide as built (a reopened stage's + citations describe the code its earlier build changed). The driver + rebuilt the reopened stage as a fix build ($0.44), archived the old + review and reviewed again ($0.84): ready, with one finding, that + revision 3 had no line in the phase's Notes. +- **Answer and run 3 (exit 0):** the session added the note; the driver + marked the finding answered and finished the phase. +- **What it showed:** premium routing and spend, the reviser before a + phase, review findings turned into fix builds, two halts and reruns, and + a reopened stage rebuilt on a new revision all ran on real models. + Every halt's `next` was enough to answer it. +- **Not exercised:** a failing build and the ladder, a budget stop, and the + revise cap. diff --git a/plugins/phased-delivery/skills/plan-in-phases/model-selection.md b/plugins/phased-delivery/skills/plan-in-phases/model-selection.md index 1914657..07c6359 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/model-selection.md +++ b/plugins/phased-delivery/skills/plan-in-phases/model-selection.md @@ -1,9 +1,10 @@ # Choosing a model and effort Used by plan-in-phases, which scores every stage and records a tier and -effort, and by implement-in-phases, which re-scores each stage and routes -it to a model and thinking level with `select-models.py route` when it -dispatches a builder. Score from the brief and the code as read now, not +effort, and by `run-phase.py`, the driver, which routes each stage to a +model and thinking level with `select-models.py route` from the scores its +brief holds when it dispatches a builder. Scores change only when the brief +is revised (see "Adjust while working"). Score from the brief and the code as read now, not from how small the task looks, from memory or from habit. ## Score the task @@ -151,17 +152,20 @@ rerun the script. what the script printed; if nothing is selectable, use the fallback. - **No Python available:** use the fallback. -At the start of each phase, the implementer runs +At the start of each phase, `run-phase.py` runs ``` python3 scripts/select-models.py check <plan>/models.md ``` -Exit 0: `models.md` is current, reuse it. Exit 1: its Profiles line differs -or is missing; refresh `models-available.json` from the tool, rerun the -selector and record the change in the phase's Notes. Do the same when a -dispatch fails because a model is unavailable. Exit 3: profiles missing, -use the fallback. A plan built in a different tool from the one it was +and goes on when `models.md` is current. Otherwise it halts `models-stale` +with the check's last line. The session then refreshes as this guide says: +when the Profiles line differs or is missing, refresh +`models-available.json` from the tool, rerun the selector, record the +change in the phase's Notes and rerun the driver. Do the same when a +dispatch fails because a model is unavailable. When the model profiles +are missing, tell the user: the driver cannot route without profiles, so +the phase waits until they exist. A plan built in a different tool from the one it was planned in is redone the same way; briefs record tiers and scores, so nothing else changes. @@ -171,21 +175,22 @@ called for. ## Route each stage -Before every stage build and the phase review, the implementer runs +The driver, `scripts/run-phase.py`, is the one that routes: before every +stage build, fix, revision and the phase review it runs ``` python3 scripts/select-models.py route <plan>/models-available.json --scores J1F1R1C1K0P0V1S0 [--down N | --up N] [--premium-spent USD] [--review] ``` -`--scores` is the stage's `Model basis` scores, re-scored at dispatch, -written without spaces. It prints one JSON line: `model`, `effort`, `tier`, +`--scores` is the stage's `model_basis` scores as its brief holds them, +written without spaces. The session routes nothing itself; the driver, +version 1, routes to Claude only, as if Codex were off. It prints one JSON line: `model`, `effort`, `tier`, `premium`, `score`, `cap_tokens`, `cap_usd` and `why` (the rules that shaped the pick). Exit codes: 0 printed; 2 bad input (fix it from the -message); 3 profiles missing; 4 no selectable pair. On 3, or without -Python, dispatch the tier's pair from `models.md` (or the fallback) as an -in-session subagent with no cap, and say so in the phase's Notes. On 4, -stop and report to the user: falling back would get around the premium -budget and the cap. +message); 3 profiles missing; 4 no selectable pair. The driver halts +`build-error` on any exit but 0, with route's message; it never falls back +to a pair of its own, which would get around the premium budget and the +cap. What `route` does, in this order: @@ -218,9 +223,9 @@ at the top of the script. there. A paid calibration run is still to set the caps. - **Budget stop:** a build that `claude-build.sh` stops at its cap (exit 8) is retried one step down the frontier (see "Adjust while working"). -- **Premium budget, $10 per phase:** the implementer records each +- **Premium budget, $10 per phase:** the driver records each `claude-build.sh` run of a pair `route` printed with `"premium": true`, - and every phase review it runs, with `build-check.py record ... + and every phase review, with `build-check.py record ... --premium`, and passes `build-check.py spend <phase dir>` (the runs' `Cost:`, or `cap_usd` when the cost is `unknown`) to `route` as `--premium-spent`. Once it reaches $10, builds get no premium pair for @@ -263,8 +268,8 @@ sets it already). Any other value exits 2. Write the scores in each stage brief's `Model basis` line, for example `J1 F1 R1 C1 K0 P0 V1 S0 = 5 -> middle`, and name any override applied. -Reviewers check the scores against the code; the implementer re-scores at -dispatch. +Reviewers check the scores against the code. Scores change only when the +brief is revised; the driver routes from them (see "Adjust while working"). ## Examples @@ -375,7 +380,9 @@ the cause, the user runs `codex-usage.py --recheck`. ### The routing rule -Only while Codex is on. Checked before **every** stage dispatch and before +Codex is off in driver version 1: `run-phase.py` routes every stage and +the review to Claude. This rule is kept as reference for when Codex +returns. Only while Codex is on. Checked before **every** stage dispatch and before the phase review. Run `scripts/claude-usage.py` (Claude level) and `scripts/codex-usage.py` (exit 0 or 2 means room; exit 1 means no room; exit 3, 4 or 5 is handled by the availability table first). No usage data @@ -386,7 +393,7 @@ hit the limit reports exit 7. | --- | --- | --- | | on pace (0) or no data (3) | narrow stages (F = 0, R = 0) to Codex | build in session | | ahead of pace (1) | stages with F <= 1 and R <= 1 to Codex | build in session | -| nearly out (2) | every build stage **and** the phase review to Codex | stop and report | +| nearly out (2) | every build stage **and** the phase review to Codex | decided when Codex returns | Width caps what goes to Codex until Claude is nearly out, because Codex models lose track across many files and large amounts of data; only when @@ -398,20 +405,11 @@ the session cannot continue does sparing its quota outweigh that. `models-available-codex.json`, with no cap; a Codex review uses `route --review` on it, through `scripts/codex-build.sh` with phase-reviewer.md as the prompt file. -- **Stop and report:** finish and commit the stage in progress, update the - phase status line and Notes, commit them, and stop. Report the stages - done and left and both scripts' output lines (usage and reset times). - When the stop comes at the check before the phase review, set - `Status: in progress (stages done: all; review pending)`; resuming - starts with the review, after checking availability and the rule again. -- At level 2, Codex turning off or failing a build (exit 3, 5, 6 or 7) - means "Codex has no room": the failed - stage is not rebuilt in the session; restore it as above, leave it - `planned`, stop and report, with the cause. -- **Session-only stages** (those that must write outside the repository, - or whose brief says it is built in the session or by the orchestrator) - are built in the session at every level, including level 2; the rule - never sends them to Codex. +- **Session-only stages** (those that must write outside the repository; + their brief sets `session_only`) are built in the session at every + level, including level 2; the rule never sends them to Codex. The driver + halts at one for the session to build, and `build-check.py record` + refuses a session build of any other stage. - Planning, plan revision, plan-review rounds and the orchestrator's own work stay in the session at every level; only stage builds and the phase review are routed (`codex-build.sh` can write only the repository and @@ -423,24 +421,26 @@ the session cannot continue does sparing its quota outweigh that. ## Adjust while working -- At dispatch, re-score against the brief as revised and the code as it now - is. If a score changes, update `Model basis` and record why in the Notes; - `route` reads the new scores. -- If `claude-build.sh` stops a build at its cap (exit 8), retry it with - `route --down 1`, and one step further on each further stop (`--down 2`, - and so on). Each stopped attempt becomes an Earlier-Attempt (`build-check.py`). When - `why` says it moved fewer pairs than asked, or `route` prints a pair - already tried for this stage, the stage is too big for its cap: revise - the plan. -- If a builder fails its "Done when", stops because the stage was harder - than its scores showed, or produces work the review rejects for reasoning - errors, rerun it with `route --up 1` instead of retrying the same pair - (one step further on each further failure), and note which measure was - under-scored. Where the model is inherited, `route` moves only its - thinking level. When `why` says it moved fewer pairs than asked, or - `route` prints a pair already tried for this stage, the brief or the - plan is the problem: go back to planning. A stage that has both hit its - cap and failed its checks also goes back to planning; never net `--down` - against `--up`, which would re-dispatch a pair already tried. -- If a builder stops because the brief is wrong, a higher tier is not the - fix; revise the plan. +`run-phase.py` steps the ladder; the session does not re-score or route at +dispatch. + +- The driver routes each stage from its brief's `Model basis`. A score + changes only when the brief is revised: the reviser updates `Model basis` + and records why in the Notes, and `route` reads the new scores. +- The driver counts a stage's attempts per revision of its brief. After + builds that `claude-build.sh` stopped at their cap (exit 8), it routes + the next with `route --down N`, N the stopped attempts. After builds that + failed their checks or that the driver rejected (the build edited the + plan, or its commit failed), it routes with `route --up N`, N those + failures. A review finding does not step the ladder: its fix is built at + the stage's routed pair, and a failed fix halts `fix-failed`. Where the + model is inherited, `route` moves only its thinking level. +- The ladder is used up when one revision has both stopped and failed + attempts (never net `--down` against `--up`), or when `route` lands on a + pair already tried. The driver then calls the reviser, which revises the + brief, re-scoring a measure that was under-scored, or leaves it + unchanged. A builder that stops because the brief is wrong also goes to + the reviser; a higher tier is not the fix. +- The session answers the halts: `revise-capped` (the reviser left the + brief unchanged, or the stage was revised too often in one run) and + `builder-stopped`. Revise the plan, then rerun the driver. diff --git a/plugins/phased-delivery/skills/plan-in-phases/phase.schema.json b/plugins/phased-delivery/skills/plan-in-phases/phase.schema.json index 9cb04a5..ec38ee7 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/phase.schema.json +++ b/plugins/phased-delivery/skills/plan-in-phases/phase.schema.json @@ -16,12 +16,29 @@ "properties": { "start_commit": {"type": "string"}, "preexisting": {"type": "array", "items": {"type": "string"}}, - "runs": {"type": "array", "items": {"type": "object"}}, + "runs": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["stage", "n", "fix", "tool", "model", "effort", "exit", "tokens", "cost", "cap", + "tool_calls", "premium", "result", "why", "commit"], + "properties": { + "stage": {"enum": ["review", "revise"]}, "n": {"type": "integer", "minimum": 0}, + "fix": {"type": "boolean"}, "tool": {"type": "string"}, "model": {"type": "string"}, + "effort": {"type": "string"}, "exit": {"type": "integer"}, + "tokens": {"type": ["number", "null"]}, "cost": {"type": ["number", "null"]}, + "cap": {"type": ["number", "null"]}, "tool_calls": {"type": ["number", "null"]}, + "premium": {"type": "boolean"}, "result": {"enum": ["review", "revise"]}, + "why": {"type": "string"}, "commit": {"type": "string"}}}}, "findings": {"type": "array", "items": {"type": "object", "additionalProperties": false, "required": ["index", "status"], "properties": {"index": {"type": "integer", "minimum": 0}, "status": {"enum": ["open", "fixed", "asked", "answered"]}}}}, - "halt": {}, - "built": {}}} + "halt": {"type": ["object", "null"], "additionalProperties": false, + "required": ["step", "stage", "reason", "detail", "next"], + "properties": { + "step": {"type": "string"}, "stage": {"type": ["string", "null"]}, + "reason": {"enum": ["revise-failed", "escalated", "revise-capped", "builder-stopped", "brief-changed", + "record-changed", "models-stale", "session-only", "build-error", "stalled", "review-capped", + "review-invalid", "plan-gap", "question", "fix-failed"]}, + "detail": {"type": "string"}, "next": {"type": "string"}}}, + "built": {"type": ["string", "null"]}}} } } diff --git a/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json b/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json index 949fcd6..ab2ce4e 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json +++ b/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json @@ -56,7 +56,7 @@ "session_only": {"type": "boolean"}}}, "record": {"type": "object", "additionalProperties": false, "properties": { - "revisions": {"type": "object"}, + "revisions": {"type": "object", "additionalProperties": {"type": "string", "pattern": "^[0-9a-f]{64}$"}}, "attempts": {"type": "array", "items": {"type": "object", "additionalProperties": false, "required": ["revision", "n", "fix", "tool", "model", "effort", "exit", "tokens", "cost", "cap", "tool_calls", "premium", "result", "why", "commit"], @@ -64,7 +64,8 @@ "revision": {"type": "integer", "minimum": 1}, "n": {"type": "integer", "minimum": 0}, "fix": {"type": "boolean"}, "tool": {"type": "string"}, "model": {"type": "string"}, "effort": {"type": "string"}, "exit": {"type": "integer"}, - "tokens": {}, "cost": {}, "cap": {}, "tool_calls": {}, + "tokens": {"type": ["number", "null"]}, "cost": {"type": ["number", "null"]}, + "cap": {"type": ["number", "null"]}, "tool_calls": {"type": ["number", "null"]}, "premium": {"type": "boolean"}, "result": {"enum": ["accepted", "failed", "stopped", "error", "rejected"]}, "why": {"type": "string"}, "commit": {"type": "string"}}}}, diff --git a/plugins/phased-delivery/tests/fake-claude.sh b/plugins/phased-delivery/tests/fake-claude.sh new file mode 100644 index 0000000..f427507 --- /dev/null +++ b/plugins/phased-delivery/tests/fake-claude.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# fake-claude.sh: stands in for `claude` on PATH in the driver's tests. +# +# FAKE_CLAUDE_PLAN is a file holding a JSON list of steps; each call takes the +# next one, counted by the lines of "$FAKE_CLAUDE_PLAN.calls" (one line of the +# call's arguments, as JSON, is added per call). A step, every field optional: +# {"files": {PATH: TEXT}, files to write +# "brief": {STAGE_FILE: {FIELD: VALUE}}, fields to set in that stage +# file's brief; its record is kept +# "report": TEXT, the final message (report.md) +# "sleep": SECONDS, silence after the edits, before the result +# "exit": N, the exit status (default 0) +# "cost": USD} total_cost_usd (default 0.01) +# Paths are relative to the directory claude runs in, the repository. It +# prints the result event claude-build.sh parses. A call past the last step +# exits 1 with a message on stderr and nothing printed. +exec python3 - "$@" <<'PY' +import json, os, sys, time + +plan = os.environ["FAKE_CLAUDE_PLAN"] +steps = json.load(open(plan)) +with open(plan + ".calls", "a+") as calls: + calls.seek(0) + index = len(calls.readlines()) + calls.write(json.dumps(sys.argv[1:]) + "\n") +if index >= len(steps): + sys.exit(f"fake claude: call {index + 1} but the plan has {len(steps)} steps") +step = steps[index] +for path, text in step.get("files", {}).items(): + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + with open(path, "w") as f: + f.write(text) +for path, fields in step.get("brief", {}).items(): + stage = json.load(open(path)) + with open(path, "w") as f: + json.dump({**stage, "brief": {**stage["brief"], **fields}}, f, indent=1) + f.write("\n") +time.sleep(step.get("sleep", 0)) +usage = {"input_tokens": 100, "output_tokens": 5, "cache_read_input_tokens": 1000, + "cache_creation_input_tokens": 20} +print(json.dumps({"type": "result", "subtype": "success", "result": step.get("report", ""), "usage": usage, + "total_cost_usd": step.get("cost", 0.01)})) +sys.exit(step.get("exit", 0)) +PY diff --git a/plugins/phased-delivery/tests/test_claude_build.py b/plugins/phased-delivery/tests/test_claude_build.py index 505abe9..afda5df 100644 --- a/plugins/phased-delivery/tests/test_claude_build.py +++ b/plugins/phased-delivery/tests/test_claude_build.py @@ -20,7 +20,7 @@ "cacheCreationInputTokens": 9070}}} -def run(tmp_path, events, code=0, permissions=None): +def run(tmp_path, events, code=0, permissions=None, pause=0, stall=None): """Run the script with a stub `claude` that records its arguments and prints EVENTS.""" bin_dir = tmp_path / "bin" bin_dir.mkdir() @@ -28,12 +28,14 @@ def run(tmp_path, events, code=0, permissions=None): (tmp_path / "prompt.md").write_text("Build stage 03.1.") stub = bin_dir / "claude" stub.write_text(f'#!/bin/sh\nprintf "%s\\n" "$@" > "{tmp_path / "args.txt"}"\n' - f'echo "claude failed" >&2\ncat "{tmp_path / "events.jsonl"}"\nexit {code}\n') + 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) if permissions: env["CLAUDE_BUILD_PERMISSIONS"] = permissions + if stall: + env["CLAUDE_BUILD_STALL"] = stall return subprocess.run( ["sh", SCRIPT, str(tmp_path), str(tmp_path / "prompt.md"), "opus", "high", "2.5", str(tmp_path / "out")], env=env, capture_output=True, text=True, @@ -74,3 +76,12 @@ def test_permissions_setting(tmp_path): other.mkdir() assert run(other, [BUILT], permissions="default").returncode == 2 assert not (other / "args.txt").exists() # refused before running claude + + +def test_stall_stops_the_call(tmp_path): + result = run(tmp_path, [{"type": "system"}], pause=30, stall="2") + assert result.returncode == 7 + assert "Tokens: unknown" in result.stdout and "stalled" in result.stderr + other = tmp_path / "other" + other.mkdir() + assert run(other, [BUILT], stall="soon").returncode == 2 diff --git a/plugins/phased-delivery/tests/test_guides.py b/plugins/phased-delivery/tests/test_guides.py new file mode 100644 index 0000000..b38a260 --- /dev/null +++ b/plugins/phased-delivery/tests/test_guides.py @@ -0,0 +1,17 @@ +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +GUIDE = ROOT / "skills" / "plan-in-phases" / "model-selection.md" +DRIVER = ROOT / "scripts" / "run-phase.py" + + +def test_model_selection_leaves_the_loop_to_the_driver(): + text = " ".join(GUIDE.read_text().split()) + session_loop = ["the implementer runs", "re-scores at", "At dispatch, re-score", + "retry it with `route --down", "rerun it with `route --up", + "**Stop and report:**", "stop and report, with the cause", "review pending"] + assert [p for p in session_loop if p in text] == [] + named = set(re.findall(r"`([a-z]+-[a-z-]+)`", text)) & {"models-stale", "revise-capped", "builder-stopped"} + halts = set(re.findall(r'"([a-z]+-[a-z-]+)"', DRIVER.read_text())) + assert named == {"models-stale", "revise-capped", "builder-stopped"} <= halts diff --git a/plugins/phased-delivery/tests/test_run_phase.py b/plugins/phased-delivery/tests/test_run_phase.py new file mode 100644 index 0000000..dbf37c3 --- /dev/null +++ b/plugins/phased-delivery/tests/test_run_phase.py @@ -0,0 +1,218 @@ +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest + + +TESTS = Path(__file__).resolve().parent +SCRIPTS = TESTS.parent / "scripts" +PROFILES = TESTS / "fixtures" / "profiles.json" +PLAN_DIR = "docs/plan" +PHASE = PLAN_DIR + "/01-demo" +GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.invalid", + "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@example.invalid", + "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"} + +# One pair only, so a stage's ladder is used up by its first failed build. +AVAILABLE = {"tool": "claude-code", "subagent_model_choice": "allowed", + "models": [{"id": "gpt-9-sol", "efforts": ["high"]}]} + +PLAN = {"description": "Demo", "goal": "one and two exist.", "why": "w", + "size": {"verdict": "full", "evidence": ["two stages"]}, + "outcomes": [{"id": "O1", "title": "one", "observable": "one exists", "how_to_check": "read it", + "sources": [{"doc": "spec", "section": "Goals", "quote": "one and two exist"}]}], + "decisions": [], "existing": [], + "phases": [{"phase": "01", "dir": "01-demo", "name": "Demo", "kind": "behaviour"}]} + +PHASE_JSON = {"brief": {"role": "r", "why": "w", "how": "h", "before": "nothing.", + "after": "one and two exist.", "assumptions": [], "test_budget": "1 s", "notes": []}, + "record": {}} + + +def stage(title, order, path, tests=()): + 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": [], + "model_basis": dict.fromkeys("JFRCKPVS", 0)}, + "record": {}} + + +STAGES = { + "01.1": stage("Write one", "first", "src/one.txt", + [{"test": "src/one.txt", "kind": "outcome", "action": "writes", "proves": "one exists", + "outcome": "O1"}]), + "01.2": stage("Write two", "after 01.1", "src/two.txt"), +} + +# fake claude steps +REVISED_NOTHING = {"report": "Nothing to change.\nResult: unchanged"} +BUILD_ONE = {"files": {"src/one.txt": "one\n"}, "report": "Wrote one.\nResult: done"} +BUILD_TWO = {"files": {"src/two.txt": "two\n"}, "report": "Wrote two.\nResult: done"} +FAILED_TWO = {"report": "Wrote two."} # writes nothing, so the stage's check fails +REVIEW = {"files": {PHASE + "/review.json": json.dumps({"findings": [], "verdict": "ready"})}, + "report": "Reviewed."} + + +def raise_two(revision): + return {"brief": {PHASE + "/01.2.json": {"revision": revision}}, "report": "Revised 01.2.\nResult: revised"} + + +def git(repo, *args): + return subprocess.run(["git", "-C", str(repo), *args], env={**os.environ, **GIT_ENV}, + capture_output=True, text=True, check=True).stdout + + +@pytest.fixture +def repo(tmp_path): + """A git repository with one commit: a plan with one phase of two stages, each creating a file.""" + r = tmp_path / "repo" + (r / "src").mkdir(parents=True) + (r / PHASE).mkdir(parents=True) + (r / "src/base.txt").write_text("base\n") + (r / "spec.md").write_text("Goals: one and two exist.\n") + files = {"plan.json": {**PLAN, "docs": {"spec": "spec.md"}}, "models-available.json": AVAILABLE, + "01-demo/phase.json": PHASE_JSON, **{f"01-demo/{sid}.json": s for sid, s in STAGES.items()}} + for name, data in files.items(): + (r / PLAN_DIR / name).write_text(json.dumps(data)) + subprocess.run([sys.executable, SCRIPTS / "select-models.py", r / PLAN_DIR / "models-available.json", + "--profiles", PROFILES, "--out", r / PLAN_DIR / "models.md"], check=True, capture_output=True) + subprocess.run([sys.executable, SCRIPTS / "plan-check.py", r / PLAN_DIR, "--repo", r], check=True, + capture_output=True) + git(r, "init", "-q") + git(r, "add", ".") + git(r, "commit", "-q", "-m", "base") + return r + + +def drive(repo, steps, stall=None): + """Run the driver on the phase with a fake claude that takes STEPS in order (a new list per run).""" + tmp = repo.parent + bin_dir = tmp / "bin" + bin_dir.mkdir(exist_ok=True) + stub = bin_dir / "claude" + stub.write_text(f'#!/bin/sh\nexec sh "{TESTS / "fake-claude.sh"}" "$@"\n') + stub.chmod(0o755) + plan = tmp / "steps.json" + plan.write_text(json.dumps(steps)) + Path(f"{plan}.calls").unlink(missing_ok=True) + env = {**os.environ, **GIT_ENV, "PATH": f"{bin_dir}:{os.environ['PATH']}", "FAKE_CLAUDE_PLAN": str(plan)} + if stall: + env["CLAUDE_BUILD_STALL"] = str(stall) + return subprocess.run([sys.executable, SCRIPTS / "run-phase.py", PHASE, "--profiles", PROFILES, + "--work", tmp / "work"], cwd=repo, env=env, capture_output=True, text=True) + + +def calls(repo): + """How many times the last drive called claude.""" + path = repo.parent / "steps.json.calls" + return len(path.read_text().splitlines()) if path.exists() else 0 + + +def read(repo, name): + return json.loads((repo / PHASE / name).read_text()) + + +def halt(repo): + found = read(repo, "phase.json")["record"].get("halt") or {} + return found.get("reason"), found.get("stage") + + +def subjects(repo): + return git(repo, "log", "--format=%s").splitlines() + + +def test_builds_phase(repo): + result = drive(repo, [REVISED_NOTHING, BUILD_ONE, BUILD_TWO, REVIEW]) + assert result.returncode == 0, result.stdout + result.stderr + assert calls(repo) == 4 + assert "Status: built" in (repo / PHASE / "phase.md").read_text() + assert any(s.startswith("01.1 Write one") for s in subjects(repo)) + assert any(s.startswith("01.2 Write two") for s in subjects(repo)) + assert git(repo, "status", "--porcelain") == "" + assert "Codex: off (driver version 1)" in result.stdout + + +def test_rerun_of_built_phase(repo): + drive(repo, [REVISED_NOTHING, BUILD_ONE, BUILD_TWO, REVIEW]) + head = git(repo, "rev-parse", "HEAD") + result = drive(repo, []) + assert result.returncode == 0, result.stdout + result.stderr + assert calls(repo) == 0 + assert git(repo, "rev-parse", "HEAD") == head + assert git(repo, "status", "--porcelain") == "" + assert "Halt: none" in result.stdout + + +def test_revise_then_halt(repo): + steps = [REVISED_NOTHING, BUILD_ONE, FAILED_TWO, raise_two(2), FAILED_TWO, raise_two(3), FAILED_TWO] + result = drive(repo, steps) + assert result.returncode == 10, result.stdout + result.stderr + assert calls(repo) == len(steps) + assert halt(repo) == ("revise-capped", "01.2") + assert read(repo, "01.1.json")["record"]["commit"] + two = read(repo, "01.2.json") + 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 + + +def test_resume_after_halt(repo): + # claude exits 3 after writing the file: an error that is not the model's + first = drive(repo, [REVISED_NOTHING, {**BUILD_ONE, "exit": 3}]) + 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 + # 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 + assert calls(repo) == 2 + 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") + + +def test_refused_commit_rejects_attempt(repo): + # 01.1 edits a committed one.txt to what it already holds, so the commit finds no changed files + (repo / "src/one.txt").write_text("one\n") + one = read(repo, "01.1.json") + one["brief"]["files"][0]["action"] = "edit" + (repo / PHASE / "01.1.json").write_text(json.dumps(one)) + git(repo, "add", ".") + git(repo, "commit", "-q", "-m", "one") + result = drive(repo, [REVISED_NOTHING, BUILD_ONE]) + assert result.returncode == 10, result.stdout + result.stderr + assert halt(repo) == ("build-error", "01.1") + attempt = read(repo, "01.1.json")["record"]["attempts"][-1] + assert attempt["result"] == "rejected" and "no changed files" in attempt["why"] + + +def test_build_adding_plan_file_is_undone(repo): + added = {**BUILD_ONE["files"], PHASE + "/01.3.json": "{}"} + result = drive(repo, [REVISED_NOTHING, {**BUILD_ONE, "files": added}, REVISED_NOTHING]) + assert result.returncode == 10, result.stdout + result.stderr + assert not (repo / PHASE / "01.3.json").exists() + assert halt(repo) == ("revise-capped", "01.1") # the retry's only pair is used up, so it revises + attempt = read(repo, "01.1.json")["record"]["attempts"][-1] + assert (attempt["result"], attempt["why"]) == ("rejected", "edited the plan") + + +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 + + +def test_second_stall_halts(repo): + stalled = {**BUILD_ONE, "sleep": 6} + result = drive(repo, [REVISED_NOTHING, stalled, stalled], stall=2) + 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")