diff --git a/README.md b/README.md index 5917ed5..11552da 100644 --- a/README.md +++ b/README.md @@ -118,29 +118,34 @@ calibration cases and their results. ### Plan checks -plan-in-phases writes the plan as JSON in a `.plan/` folder while planning: -`plan.json` (outcomes, cross-phase decisions, a contract registry, outcome -tests, phases and stages) and one `NN.json` per phase. Field guides in the -skill say what goes in each field, down to the interface level and no -further. `plugins/phased-delivery/scripts/plan-check.py` checks what needs no +plan-in-phases writes the plan as JSON and keeps it for the plan's whole +life: `plan.json` (outcomes, cross-phase decisions, a contract registry, +outcome tests, phases) and, per phase, a folder `NN-name` holding +`phase.json` and one stage file `NN.n.json` per stage. Each of those has a +`brief`, written by planning and revising, and a `record`, written only by +the build scripts. Field guides in the skill say what goes in each field, +down to the interface level and no further. `plugins/phased-delivery/scripts/plan-check.py` checks what needs no judgment (each contract listed by its provider and users, build order, files, outcome coverage, tiers, spec and design quotes, code citations, no code in -briefs) and renders the `NN-name.md` phase files, which are the plan once it -is reported. The plan reviewer reports only a closed list of finding types. -It uses only the Python standard library; without Python, the planner writes -the phase files directly and checks by reading. +briefs) and renders `plan.md` and each phase folder's `phase.md` for +reading; the rendered files are never edited. The plan reviewer reports only a closed list of finding types. +It uses only the Python standard library; without Python, the planner +checks by reading. ### Build checks -implement-in-phases follows the same pattern. Revising a phase ends in -`.build/NN-revision.json` (each stage's files, check commands and scores), -and `plugins/phased-delivery/scripts/build-check.py` does the bookkeeping: -it gates each build (no changed file outside the stage, every check -passes), refuses a model and thinking level already tried for the stage, -sums the premium spend for routing, and makes each stage, fix and phase -commit with its trailers. A ledger in `.build/` keeps every attempt, so a -resumed session picks up where it stopped. The phase reviewer writes -`.build/NN-review.json` with a closed list of finding types. SKILL.md is a +implement-in-phases builds from the same files. Revising a phase edits its +stage files and raises the `revision` of each changed brief, and +`plugins/phased-delivery/scripts/build-check.py` does the bookkeeping from +a phase folder: it gates each build with the stage file's files and check +commands, refuses a model and thinking level already tried for the stage at +its current revision (a brief changed without a higher revision is an +error), lets the session build only a stage marked `session_only`, sums the +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. Some tools, Codex among them, let subagents use a different model only when the diff --git a/plugins/phased-delivery/.claude-plugin/plugin.json b/plugins/phased-delivery/.claude-plugin/plugin.json index 165aef5..46b0796 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.11.0", + "version": "0.12.0", "description": "Plan work as self-contained phases, then implement it phase by phase.", "author": { "name": "Bryan" diff --git a/plugins/phased-delivery/hooks/session-start.sh b/plugins/phased-delivery/hooks/session-start.sh index 59fecca..95a0f0e 100644 --- a/plugins/phased-delivery/hooks/session-start.sh +++ b/plugins/phased-delivery/hooks/session-start.sh @@ -12,7 +12,7 @@ json_escape() { unfinished="" if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then unfinished=$(git grep -l --untracked -F "$marker" -- '*.md' 2>/dev/null | - grep -E '(^|/)[0-9][0-9]-[^/]*\.md$' | head -50 | + grep -E '(^|/)[0-9][0-9]-[^/]*(/phase)?\.md$' | head -50 | while IFS= read -r f; do status=$(grep -m1 '^Status:' "$f" | sed 's/^Status:[[:space:]]*//') case "$status" in diff --git a/plugins/phased-delivery/scripts/build-check.py b/plugins/phased-delivery/scripts/build-check.py index 4ebc867..497f2eb 100755 --- a/plugins/phased-delivery/scripts/build-check.py +++ b/plugins/phased-delivery/scripts/build-check.py @@ -2,45 +2,60 @@ """Gate, record and commit the stages of a phase for implement-in-phases. Usage: - build-check.py start PHASE_FILE [--repo DIR] - build-check.py can-try PHASE_FILE STAGE MODEL EFFORT - build-check.py record PHASE_FILE STAGE|review --tool T --model M --effort E - --exit N --tokens X --cost Y [--cap USD] [--tool-calls N] - [--premium] [--fix] [--repo DIR] - build-check.py reject PHASE_FILE STAGE WHY - build-check.py commit PHASE_FILE STAGE [--subject-suffix TEXT] + build-check.py start PHASE_DIR [--repo DIR] + build-check.py can-try PHASE_DIR STAGE MODEL EFFORT + build-check.py record PHASE_DIR STAGE|review|revise --tool T --model M + --effort E --exit N --tokens X --cost Y [--cap USD] + [--tool-calls N] [--premium] [--fix] [--repo DIR] + build-check.py reject PHASE_DIR STAGE WHY + build-check.py commit PHASE_DIR STAGE [--subject-suffix TEXT] [--extra-trailer LINE]... [--repo DIR] - build-check.py spend PHASE_FILE - build-check.py finish PHASE_FILE [--stopped] [--extra-trailer LINE]... + build-check.py spend PHASE_DIR + build-check.py finish PHASE_DIR [--stopped] [--extra-trailer LINE]... [--repo DIR] -PHASE_FILE is a plan's NN-name.md. The script keeps its files next to it in -.build/: NN-revision.json (written by the orchestrator, revision.schema.json -in skills/implement-in-phases), NN-review.json (written by the phase -reviewer, review.schema.json) and NN-ledger.json (written here: the start -state and every attempt). --repo defaults to the current directory. - -start validates the revision and writes the ledger with HEAD and the - paths already modified (kept as is when it exists: resume). Exit 1 - on an invalid revision or a stage file already modified. -can-try exit 1 when the stage already has a non-error attempt on the pair. +PHASE_DIR is a plan's phase folder NN-name: phase.json, one stage file +NN.n.json per stage (phase.schema.json and stage.schema.json in +skills/plan-in-phases) and review.json (written by the phase reviewer, +review.schema.json in skills/implement-in-phases). The script reads the +briefs and writes only the records: the start state, review and revise runs +and the built commit in phase.json, and each stage's revisions, attempts and +commit in its stage file. Status is never edited: phase.md and plan.md are +re-rendered from the records. --repo defaults to the current directory. + +start validates phase.json and the stage files and writes HEAD and the + paths already modified into phase.json's record (kept as is when + set: resume). Exit 1 on invalid JSON or a stage's file already + modified. +can-try exit 1 when the stage already has a non-error attempt on the pair + at the brief's current revision. record logs an attempt and gates a build: no uncommitted path outside the scope rule, and every check command of the stage passes. Prints one JSON line {stage, attempt, result, outside, checks}. Exit 0 accepted; 1 failed; 3 budget stop (build exit 8); 4 error (any - other build exit: not a try of the pair). Stage "review" is logged - for spend only. + other build exit: not a try of the pair). Exit 2, nothing logged, + for --model orchestrator on a stage that is not session_only. + Stages "review" and "revise" are logged for spend only. reject marks the stage's accepted, uncommitted attempt rejected. -commit commits the stage's changed files with the stage trailers and - marks the stage done in the phase file (working tree only). +commit commits the stage's changed files with the stage trailers (an + empty commit for a session-only or reopened stage with none), + writes the commit into the stage's record and re-renders. spend prints the premium spend: costs of --premium attempts (cap when the cost is unknown), as a bare number. -finish validates the review, sets "Status: built " and commits - the phase file's directory with a Phase: trailer. --stopped skips - the review and status and only commits the directory. +finish refuses while a stage has no commit or is reopened, validates the + review, sets the record's built commit, re-renders and commits the + plan directory with a Phase: trailer. --stopped only commits. + +can-try and record store the hash of the stage's brief under its revision; +every subcommand but start exits 5, nothing changed, when a brief changed +since its revision was stored or the revision is lower than a stored one: +raise the revision. Every subcommand validates phase.json and the stage +files as start does; but for start, another problem is exit 2, one JSON +line each. +record exits 2, nothing logged, for a stage with a commit without --fix. Exit codes not listed: 0 done; 1 refused (one JSON line per problem for -invalid JSON); 2 bad usage or a missing file. +invalid JSON); 2 bad usage, a missing file, or start has not run. """ import argparse @@ -61,14 +76,18 @@ class Usage(Exception): pass -def paths(phase_file): - if not os.path.isfile(phase_file): - raise Usage(f"no phase file: {phase_file}") - num = os.path.basename(phase_file)[:2] - if not num.isdigit(): - raise Usage(f"phase file must be named NN-name.md: {phase_file}") - build = os.path.join(os.path.dirname(os.path.realpath(phase_file)), ".build") - return {k: os.path.join(build, f"{num}-{k}.json") for k in ("revision", "review", "ledger")} +class Invalid(Exception): + """(problems, exit code): the phase failed validation; main prints the problems as JSON lines.""" + + +def phase_paths(phase_dir): + """(the phase folder, its plan directory), both real paths.""" + pdir = os.path.realpath(phase_dir) + if not os.path.basename(pdir)[:2].isdigit(): + raise Usage(f"phase folder must be named NN-name: {phase_dir}") + if not os.path.isfile(os.path.join(pdir, "phase.json")): + raise Usage(f"missing {os.path.join(phase_dir, 'phase.json')}") + return pdir, os.path.dirname(pdir) def load_checked(path, schema_name, label): @@ -84,13 +103,29 @@ def load_checked(path, schema_name, label): return (None if errs else data), [{"file": label, "where": w or "/", "msg": m} for w, m in errs] +def checked_phase(pdir): + """(phase.json, {stage id: stage file}, problems): the schemas, then the revision check.""" + name, r = os.path.basename(pdir), plan_check.Report() + pj = plan_check.load(os.path.join(pdir, "phase.json"), plan_check.schema_for("phase.schema.json"), r, + f"{name}/phase.json") + schema = plan_check.schema_for("stage.schema.json") + loaded = {n[:-5]: plan_check.load(os.path.join(pdir, n), schema, r, f"{name}/{n}") + for n in plan_check.stage_files(pdir)} + stages = {sid: s for sid, s in loaded.items() if s is not None} + if not loaded: + r.add(f"{name}/phase.json", "-", "missing", f"no stage files in {name}") + for sid, s in stages.items(): + plan_check.check_revision(sid, {**s, "file": f"{name}/{sid}.json"}, r) + return pj, stages, r.items + + def report(problems): for p in problems: print(json.dumps(p)) return 1 if problems else 0 -# ---- repository and ledger +# ---- repository and records def git(repo, *args, check=True): r = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True) @@ -132,36 +167,57 @@ def is_cache(path): return "__pycache__" in parts or ".pytest_cache" in parts or path.endswith(".pyc") -def load(path): - return json.load(open(path)) - - def save(path, data): with open(path, "w") as f: json.dump(data, f, indent=1) f.write("\n") -def stage_files(revision, stage): - for s in revision["stages"]: - if s["id"] == stage: - return [f["path"] for f in s["files"]] - raise Usage(f"stage {stage} is not in the revision") +def read_phase(phase_dir): + """(phase folder, plan directory, phase.json, {stage id: stage file}) of a started phase.""" + pdir, plan_dir = phase_paths(phase_dir) + pj, stages, problems = checked_phase(pdir) + if problems: + # a brief edited without a higher revision keeps exit 5; any other problem is exit 2 + raise Invalid(problems, 5 if all(p["kind"] == "revision" for p in problems) else 2) + if not pj["record"].get("start_commit"): + raise Usage(f"{phase_dir} has no start_commit: run start first") + return pdir, plan_dir, pj, stages + + +def stage_of(stages, sid): + if sid not in stages: + raise Usage(f"stage {sid} has no stage file") + return stages[sid] + + +def with_record(doc, **fields): + return {**doc, "record": {**doc["record"], **fields}} + + +def attempts_of(s): + return s["record"].get("attempts", []) -def committed_stages(ledger): - return {a["stage"] for a in ledger["attempts"] if a["result"] == "accepted" and a["commit"] and not a["fix"]} +def brief_files(s): + return [f["path"] for f in s["brief"]["files"]] -def outside_paths(top, phase_file, revision, ledger, stage): - plan_dir = rel(top, os.path.dirname(os.path.realpath(phase_file))) - done = committed_stages(ledger) - allowed = set(stage_files(revision, stage)) | set(ledger["preexisting"]) - for s in revision["stages"]: - if s["id"] not in done: - allowed |= {f["path"] for f in s["files"]} +def pinned(pdir, sid, s): + """The stage with its brief's hash stored under its revision, saved; read_phase has run the revision check.""" + revs, rev = s["record"].get("revisions", {}), str(s["brief"]["revision"]) + if rev in revs: + return s + new = with_record(s, revisions={**revs, rev: plan_check.brief_hash(s["brief"])}) + save(os.path.join(pdir, f"{sid}.json"), new) + return new + + +def outside_paths(top, plan_dir, pj, stages, sid): + uncommitted = {p for s in stages.values() if not s["record"].get("commit") for p in brief_files(s)} + allowed = set(brief_files(stages[sid])) | set(pj["record"]["preexisting"]) | uncommitted return [p for p in changed_paths(top) - if p not in allowed and not is_cache(p) and not in_dir(p, plan_dir)] + if p not in allowed and not is_cache(p) and not in_dir(p, rel(top, plan_dir))] def run_checks(top, commands): @@ -180,173 +236,170 @@ def count(x): # ---- subcommands def cmd_start(a): - f = paths(a.phase_file) - revision, problems = load_checked(f["revision"], "revision.schema.json", "revision") + pdir, _ = phase_paths(a.phase_dir) + name = os.path.basename(pdir) + pj, stages, problems = checked_phase(pdir) if problems: return report(problems) - if os.path.exists(f["ledger"]): + if pj["record"].get("start_commit"): return 0 top = toplevel(a.repo) now = changed_paths(top) - dirty = [{"file": "revision", "where": s["id"], "msg": f"stage file already modified: {p}"} - for s in revision["stages"] for p in stage_files(revision, s["id"]) if p in now] + dirty = [{"file": f"{name}/{sid}.json", "where": sid, "msg": f"stage file already modified: {p}"} + for sid, s in stages.items() for p in brief_files(s) if p in now] if dirty: return report(dirty) - save(f["ledger"], {"start_commit": git(top, "rev-parse", "HEAD").strip(), "preexisting": now, "attempts": []}) + save(os.path.join(pdir, "phase.json"), + with_record(pj, start_commit=git(top, "rev-parse", "HEAD").strip(), preexisting=now)) return 0 -def ledger_of(f): - if not os.path.exists(f["ledger"]): - raise Usage(f"missing {f['ledger']}: run start first") - return load(f["ledger"]) - - def cmd_can_try(a): - ledger = ledger_of(paths(a.phase_file)) - for x in ledger["attempts"]: - if (x["stage"], x["model"], x["effort"]) == (a.stage, a.model, a.effort) and x["result"] != "error": + pdir, _, _, stages = read_phase(a.phase_dir) + s = pinned(pdir, a.stage, stage_of(stages, a.stage)) + for x in attempts_of(s): + if ((x["model"], x["effort"], x["revision"]) == (a.model, a.effort, s["brief"]["revision"]) + and x["result"] != "error"): print(json.dumps(x)) return 1 return 0 def cmd_record(a): - f = paths(a.phase_file) - ledger = ledger_of(f) - attempt = {"stage": a.stage, "n": 0, "fix": a.fix, "tool": a.tool, "model": a.model, "effort": a.effort, - "exit": a.exit_code, "tokens": a.tokens, "cost": a.cost, "cap": a.cap, - "tool_calls": a.tool_calls, "premium": a.premium, "result": "review", "why": "", "commit": ""} - outside, checks, code = [], [], 0 - if a.stage != "review": - revision = load(f["revision"]) - top = toplevel(a.repo) - same = [x for x in ledger["attempts"] if x["stage"] == a.stage and x["fix"] == a.fix - and x["result"] != "error" and not x["commit"]] - attempt["n"] = len(same) + 1 - outside = outside_paths(top, a.phase_file, revision, ledger, a.stage) - if a.exit_code == 8: - attempt.update(result="stopped", why="budget reached") - code = 3 - elif a.exit_code != 0: - attempt.update(result="error", why=f"build exit {a.exit_code}", n=0) - code = 4 - elif outside: - attempt.update(result="failed", why="changed files outside the stage") - code = 1 - else: - checks = run_checks(top, next(s["checks"] for s in revision["stages"] if s["id"] == a.stage)) - failed = any(c["exit"] for c in checks) - attempt.update(result="failed" if failed else "accepted", why="check failed" if failed else "") - code = 1 if failed else 0 - ledger["attempts"].append(attempt) - save(f["ledger"], ledger) + pdir, plan_dir, pj, stages = read_phase(a.phase_dir) + base = {"n": 0, "fix": a.fix, "tool": a.tool, "model": a.model, "effort": a.effort, + "exit": a.exit_code, "tokens": a.tokens, "cost": a.cost, "cap": a.cap, + "tool_calls": a.tool_calls, "premium": a.premium, "why": "", "commit": ""} + if a.stage in ("review", "revise"): + run = {"stage": a.stage, **base, "result": a.stage} + save(os.path.join(pdir, "phase.json"), with_record(pj, runs=pj["record"].get("runs", []) + [run])) + print(json.dumps({"stage": a.stage, "attempt": 0, "result": a.stage, "outside": [], "checks": []})) + return 0 + if a.model == "orchestrator" and not stage_of(stages, a.stage)["brief"].get("session_only"): + print(f"stage {a.stage} is not session_only: the orchestrator may not build it", file=sys.stderr) + return 2 + if stage_of(stages, a.stage)["record"].get("commit") and not a.fix: + print(f"stage {a.stage} already has a commit: pass --fix to record its rebuild", file=sys.stderr) + return 2 + s = pinned(pdir, a.stage, stages[a.stage]) + top = toplevel(a.repo) + same = [x for x in attempts_of(s) if x["fix"] == a.fix and x["result"] != "error" and not x["commit"]] + outside = outside_paths(top, plan_dir, pj, stages, a.stage) + checks = [] if a.exit_code or outside else run_checks(top, s["brief"]["checks"]) + if a.exit_code == 8: + outcome, code = {"result": "stopped", "why": "budget reached"}, 3 + elif a.exit_code != 0: + outcome, code = {"result": "error", "why": f"build exit {a.exit_code}", "n": 0}, 4 + elif outside: + outcome, code = {"result": "failed", "why": "changed files outside the stage"}, 1 + elif any(c["exit"] for c in checks): + outcome, code = {"result": "failed", "why": "check failed"}, 1 + else: + outcome, code = {"result": "accepted"}, 0 + attempt = {"revision": s["brief"]["revision"], **base, "n": len(same) + 1, **outcome} + save(os.path.join(pdir, f"{a.stage}.json"), with_record(s, attempts=attempts_of(s) + [attempt])) print(json.dumps({"stage": a.stage, "attempt": attempt["n"], "result": attempt["result"], "outside": outside, "checks": checks})) return code -def open_attempt(ledger, stage): - for x in reversed(ledger["attempts"]): - if x["stage"] == stage and x["result"] == "accepted" and not x["commit"]: +def open_attempt(s): + for x in reversed(attempts_of(s)): + if x["result"] == "accepted" and not x["commit"]: return x return None +def replaced(s, marked, **fields): + """The stage's attempts with `fields` set on the ones in `marked`.""" + return [{**y, **fields} if any(y is m for m in marked) else y for y in attempts_of(s)] + + def cmd_reject(a): - f = paths(a.phase_file) - ledger = ledger_of(f) - x = open_attempt(ledger, a.stage) + pdir, _, _, stages = read_phase(a.phase_dir) + s = stage_of(stages, a.stage) + x = open_attempt(s) if x is None: print(f"no accepted, uncommitted attempt for {a.stage}", file=sys.stderr) return 1 - x.update(result="rejected", why=a.why) - save(f["ledger"], ledger) + save(os.path.join(pdir, f"{a.stage}.json"), + with_record(s, attempts=replaced(s, [x], result="rejected", why=a.why))) return 0 def git_commit(top, files, subject, trailers): - git(top, "add", "-A", "--", *files) body = "\n".join(trailers) - git(top, "commit", "-q", "-m", subject, "-m", body, "--", *files) + if files: + # a deletion is left to commit's pathspec: git add fails on one already staged (git rm) + present = [p for p in files if os.path.lexists(os.path.join(top, p))] + if present: + git(top, "add", "-A", "--", *present) + git(top, "commit", "-q", "-m", subject, "-m", body, "--", *files) + else: + # an empty commit made from HEAD's tree, so that paths staged by someone else stay out of it + new = git(top, "commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", subject, "-m", body).strip() + git(top, "update-ref", "HEAD", new) return git(top, "rev-parse", "--short", "HEAD").strip() -def mark_done(phase_file, done): - """Set the done stages' table cells and the Status line in the working tree.""" - lines = open(phase_file).read().split("\n") - for i, line in enumerate(lines): - cells = line.split("|") - if len(cells) > 6 and cells[1].strip() in done: - cells[-2] = " done " - lines[i] = "|".join(cells) - elif line.startswith("Status:"): - lines[i] = f"Status: in progress (stages done: {', '.join(sorted(done))})" - open(phase_file, "w").write("\n".join(lines)) - - def cmd_commit(a): - f = paths(a.phase_file) - ledger, revision = ledger_of(f), load(f["revision"]) - x = open_attempt(ledger, a.stage) + pdir, plan_dir, pj, stages = read_phase(a.phase_dir) + s = stage_of(stages, a.stage) + x = open_attempt(s) if x is None: print(f"no accepted, uncommitted attempt for {a.stage}", file=sys.stderr) return 1 top = toplevel(a.repo) - now = set(changed_paths(top)) - set(ledger["preexisting"]) - files = [p for p in stage_files(revision, a.stage) if p in now] - if not files: + now = set(changed_paths(top)) - set(pj["record"]["preexisting"]) + files = [p for p in brief_files(s) if p in now] + if not files and not (s["brief"].get("session_only") or plan_check.stage_status(s) == "reopened"): print(f"no changed files for {a.stage}", file=sys.stderr) return 1 - earlier = [y for y in ledger["attempts"] if y["stage"] == a.stage and y["fix"] == x["fix"] + earlier = [y for y in attempts_of(s) if y["fix"] == x["fix"] and y["result"] in ("failed", "stopped", "rejected") and not y["commit"]] - stage = next(s for s in revision["stages"] if s["id"] == a.stage) trailers = [f"{'Fixes-Stage' if x['fix'] else 'Stage'}: {a.stage}", - f"Plan: {rel(top, a.phase_file)}", - f"Tier: {stage['tier']}", f"Tool: {x['tool']}", f"Model: {x['model']}", - f"Effort: {x['effort']}", f"Attempt: {len(earlier) + 1}", f"Tokens: {count(x['tokens'])}", - f"Cost: {amount(x['cost'])}", f"Tool-Calls: {count(x['tool_calls'])}"] - trailers += [f"Earlier-Attempt: {y['model']} {y['effort']} {count(y['tokens'])} {' '.join(y['why'].split())}" for y in earlier] - subject = f"{a.stage} {stage['title']}" + (f" {a.subject_suffix}" if a.subject_suffix else "") - sha = git_commit(top, files, subject, trailers + a.extra_trailer) - for y in earlier + [x]: - y["commit"] = sha - save(f["ledger"], ledger) - if not x["fix"]: - mark_done(a.phase_file, committed_stages(ledger)) + f"Plan: {rel(top, pdir)}", + f"Tier: {plan_check.tier(s['brief']['model_basis'])[1]}", f"Tool: {x['tool']}", + f"Model: {x['model']}", f"Effort: {x['effort']}", f"Attempt: {len(earlier) + 1}", + f"Tokens: {count(x['tokens'])}", f"Cost: {amount(x['cost'])}", + f"Tool-Calls: {count(x['tool_calls'])}"] + earlier_lines = [f"Earlier-Attempt: {y['model']} {y['effort']} {count(y['tokens'])} {' '.join(y['why'].split())}" + for y in earlier] + subject = f"{a.stage} {s['brief']['title']}" + (f" {a.subject_suffix}" if a.subject_suffix else "") + sha = git_commit(top, files, subject, trailers + earlier_lines + a.extra_trailer) + save(os.path.join(pdir, f"{a.stage}.json"), + with_record(s, attempts=replaced(s, earlier + [x], commit=sha), commit=sha)) + plan_check.render_plan(plan_dir) print(sha) return 0 def cmd_spend(a): - ledger = ledger_of(paths(a.phase_file)) - total = sum((x["cost"] if x["cost"] is not None else x["cap"] or 0) for x in ledger["attempts"] if x["premium"]) + _, _, pj, stages = read_phase(a.phase_dir) + spent = pj["record"].get("runs", []) + [x for s in stages.values() for x in attempts_of(s)] + total = sum((x["cost"] if x["cost"] is not None else x["cap"] or 0) for x in spent if x["premium"]) print(f"{total:.2f}") return 0 def cmd_finish(a): - f = paths(a.phase_file) - ledger, revision = ledger_of(f), load(f["revision"]) + pdir, plan_dir, pj, stages = read_phase(a.phase_dir) + top = toplevel(a.repo) if not a.stopped: - _, problems = load_checked(f["review"], "review.schema.json", "review") - missing = [s["id"] for s in revision["stages"] if s["id"] not in committed_stages(ledger)] - problems += [{"file": "ledger", "where": s, "msg": "stage has no commit"} for s in missing] - if problems: - return report(problems) - top = toplevel(a.repo) - ours = {x["commit"] for x in ledger["attempts"] if x["result"] == "accepted" and x["commit"]} - log = git(top, "log", "--format=%h", "--abbrev=7", f"{ledger['start_commit']}..HEAD").split() + _, review_problems = load_checked(os.path.join(pdir, "review.json"), "review.schema.json", "review") + states = {sid: plan_check.stage_status(s) for sid, s in stages.items()} + unbuilt = [{"file": f"{sid}.json", "where": sid, + "msg": "stage is reopened" if state == "reopened" else "stage has no commit"} + for sid, state in states.items() if state != "done"] + if review_problems or unbuilt: + return report(review_problems + unbuilt) + ours = {s["record"]["commit"] for s in stages.values()} + log = git(top, "log", "--format=%h", "--abbrev=7", f"{pj['record']['start_commit']}..HEAD").split() last = next(h for h in log if any(c.startswith(h) or h.startswith(c) for c in ours)) - mark_done(a.phase_file, committed_stages(ledger)) - text = open(a.phase_file).read().split("\n") - text = [f"Status: built {last}" if line.startswith("Status:") else line for line in text] - open(a.phase_file, "w").write("\n".join(text)) - top = toplevel(a.repo) - plan_dir = rel(top, os.path.dirname(os.path.realpath(a.phase_file))) - phase = rel(top, a.phase_file) - subject = f"Phase {os.path.basename(a.phase_file)[:2]} {'stopped' if a.stopped else 'built'}: status and notes" - print(git_commit(top, [plan_dir], subject, [f"Phase: {phase}"] + a.extra_trailer)) + save(os.path.join(pdir, "phase.json"), with_record(pj, built=last)) + plan_check.render_plan(plan_dir) + subject = f"Phase {os.path.basename(pdir)[:2]} {'stopped' if a.stopped else 'built'}: status and notes" + print(git_commit(top, [rel(top, plan_dir)], subject, [f"Phase: {rel(top, pdir)}"] + a.extra_trailer)) return 0 @@ -364,13 +417,13 @@ def parse_args(argv): formatter_class=argparse.RawDescriptionHelpFormatter) sub = p.add_subparsers(dest="cmd", required=True) s = sub.add_parser("start") - s.add_argument("phase_file") + s.add_argument("phase_dir") s.add_argument("--repo", default=".") s = sub.add_parser("can-try") - for k in ("phase_file", "stage", "model", "effort"): + for k in ("phase_dir", "stage", "model", "effort"): s.add_argument(k) s = sub.add_parser("record") - s.add_argument("phase_file") + s.add_argument("phase_dir") s.add_argument("stage") for k in ("--tool", "--model", "--effort"): s.add_argument(k, required=True) @@ -383,18 +436,18 @@ def parse_args(argv): s.add_argument("--fix", action="store_true") s.add_argument("--repo", default=".") s = sub.add_parser("reject") - for k in ("phase_file", "stage", "why"): + for k in ("phase_dir", "stage", "why"): s.add_argument(k) s = sub.add_parser("commit") - s.add_argument("phase_file") + s.add_argument("phase_dir") s.add_argument("stage") s.add_argument("--subject-suffix", default="") s.add_argument("--extra-trailer", action="append", default=[]) s.add_argument("--repo", default=".") s = sub.add_parser("spend") - s.add_argument("phase_file") + s.add_argument("phase_dir") s = sub.add_parser("finish") - s.add_argument("phase_file") + s.add_argument("phase_dir") s.add_argument("--stopped", action="store_true") s.add_argument("--extra-trailer", action="append", default=[]) s.add_argument("--repo", default=".") @@ -409,6 +462,9 @@ def main(argv): a = parse_args(argv) try: return COMMANDS[a.cmd](a) + except Invalid as e: + report(e.args[0]) + return e.args[1] except (Usage, OSError, ValueError) as e: print(e, file=sys.stderr) return 2 diff --git a/plugins/phased-delivery/scripts/plan-check.py b/plugins/phased-delivery/scripts/plan-check.py index 3e4af2f..51214ee 100644 --- a/plugins/phased-delivery/scripts/plan-check.py +++ b/plugins/phased-delivery/scripts/plan-check.py @@ -1,20 +1,26 @@ #!/usr/bin/env python3 -"""Check a phased plan written as JSON and render its phase files. +"""Check a phased plan written as JSON and render its plan.md and phase.md files. Usage: - plan-check.py PLAN_DIR [--repo DIR] [--spec FILE] [--design FILE] [--outline] - -The planner writes PLAN_DIR/.plan/plan.json (plan.schema.json: outcomes, -cross-phase decisions, the contract registry, outcome tests, phases and -stages) and one PLAN_DIR/.plan/NN.json per phase (phase.schema.json: the -stage briefs). The field guides in skills/plan-in-phases say how to fill -them. This script checks what can be checked without judgment and renders -each phase whose JSON is clean to PLAN_DIR/NN-name.md in the phase file -layout. --outline checks plan.json only (before the phase JSON exists). - ---spec and --design default to the paths a plan names in its sources and -must be given when quotes are to be checked; --repo defaults to the current -directory. + plan-check.py PLAN_DIR [--repo DIR] [--spec FILE] [--design FILE] [--outline] [--phase NN] + +The plan is PLAN_DIR/plan.json (plan.schema.json: outcomes, cross-phase +decisions, existing interfaces, phases) and, per phase, a folder NN-name +holding phase.json (phase.schema.json) and one NN.n.json per stage +(stage.schema.json). Each of those has a `brief`, written by planning and +revising, and a `record`, written by the build scripts. The field guides in +skills/plan-in-phases say how to fill them. This script checks what can be +checked without judgment and renders PLAN_DIR/plan.md and, for each phase +whose JSON is clean, NN-name/phase.md. --outline checks plan.json and the +outline fields of the stage files only, and renders nothing. + +The checks that compare a brief with the repository apply to stages still to +build: file actions to stages with no commit, code citations also to reopened +ones; --phase NN limits them to that phase. A brief that changed since an +attempt built it needs a higher `revision`. + +--spec and --design default to the paths plan.json names in `docs`, relative +to --repo, which defaults to the current directory. Output: one JSON line per problem, {"file", "where", "kind", "msg", "level"}, then a summary line. level "error" must be fixed; "warning" is reported for @@ -22,6 +28,7 @@ missing or unreadable file. """ +import hashlib import json import os import re @@ -33,7 +40,8 @@ "event": 300, "cli": 300, "format": 400, "route": 500, "other": 200} LIMITS = {"behaviour": 8, "done_when": 6, "out_of_scope": 5} CODE_READ_MAX, DESIGN_MAX, GOAL_MAX, SENTENCES_MAX = 8, 4, 250, 6 -STAGE_ID = re.compile(r"^\d\d\.\d+$") +STAGE_FILE = re.compile(r"^\d\d\.\d+\.json$") +OUTLINE = ["revision", "title", "order", "lines", "files", "provides", "uses"] TESTY = re.compile(r"(^|/)tests?/|(^|/)test_|\.test\.|::test_") CODEY = re.compile(r"```|`[^`\n]*(?:==|!=|\bis (?:not )?None\b|\breturn\b|\.get\(|\bfor \w+ in\b|\bif\b|\belse\b|\+=)[^`\n]*`") WHERE = re.compile(r"(?:\./)?([\w./-]+):(\d+)(?:-(\d+))?") @@ -113,20 +121,69 @@ def strings(x, path=""): yield from strings(v, f"{path}/{i}") -def build_positions(plan): +def brief_hash(brief): + return hashlib.sha256(json.dumps(brief, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def stage_files(pdir): + return sorted((n for n in os.listdir(pdir) if STAGE_FILE.match(n)), + key=lambda n: [int(x) for x in n[:-5].split(".")]) + + +def flatten(phases): + # every stage of the plan in build order: id -> its file's content, phase number and file name + return {sid: {**s, "phase": ph["phase"], "file": f"{ph['dir']}/{sid}.json"} + for ph, _, found in phases for sid, s in found.items()} + + +def build_positions(stages): # global build position per stage; a parallel stage shares its partner's position pos, n = {}, 0 - for ph in plan["phases"]: - for s in ph["stages"]: - m = re.match(r"parallel with (\d\d\.\d+)", s["order"]) - if m and m.group(1) in pos: - pos[s["id"]] = pos[m.group(1)] - else: - n += 1 - pos[s["id"]] = n + for sid, s in stages.items(): + m = re.match(r"parallel with (\d\d\.\d+)", s["brief"]["order"]) + if m and m.group(1) in pos: + pos[sid] = pos[m.group(1)] + else: + n += 1 + pos[sid] = n return pos +def registry(stages): + # the contracts the stages provide, each with its provider and the stages whose `uses` name it + return [{**c, "provided_by": sid, "users": [u for u, x in stages.items() if c["name"] in x["brief"]["uses"]]} + for sid, s in stages.items() for c in s["brief"]["provides"]] + + +def outcome_rows(stages): + tests = [(sid, t) for sid, s in stages.items() for t in s["brief"].get("tests", []) if t["kind"] == "outcome"] + turned_on = {t["test"].strip("`"): sid for sid, t in tests if t["action"] == "turns on"} + return [{"outcome": t["outcome"], "test": t["test"].strip("`"), "written_in": sid, + "passes_from": turned_on.get(t["test"].strip("`"), sid)} + for sid, t in tests if t["action"] == "writes" and "outcome" in t] + + +def stage_status(s): + rec = s["record"] + attempts = rec.get("attempts", []) + if not rec.get("commit"): + return "in progress" if attempts else "planned" + built = max((a["revision"] for a in attempts if a["commit"] == rec["commit"]), default=s["brief"]["revision"]) + return "reopened" if s["brief"]["revision"] > built else "done" + + +def phase_status(record, stages): + if record.get("built"): + return f"built {record['built']}" + halt = record.get("halt") + if halt: + return f"halted: {halt['reason']}" + states = {sid: stage_status(s) for sid, s in stages.items()} + if all(x == "planned" for x in states.values()): + return "planned" + return f"in progress (stages done: {', '.join(k for k, x in states.items() if x == 'done') or 'none'})" + + class Report: def __init__(self): self.items = [] @@ -135,17 +192,15 @@ def add(self, file, where, kind, msg): self.items.append({"file": file, "where": where, "kind": kind, "msg": msg, "level": "warning" if kind in WARNINGS else "error"}) - def errors(self, file=None): - return [x for x in self.items if x["level"] == "error" and (file is None or x["file"] == file)] + def errors(self, prefix=""): + return [x for x in self.items if x["level"] == "error" and x["file"].startswith(prefix)] -# ---- plan.json +# ---- the whole plan: plan.json and what the stage files say to each other -def check_plan(plan, repo, docs, r): +def check_plan(plan, stages, repo, docs, scope, outline, r): F = "plan.json" - stages = {s["id"]: (ph, s) for ph in plan["phases"] for s in ph["stages"]} - contracts = {c["id"]: c for c in plan["contracts"]} - pos = build_positions(plan) + pos = build_positions(stages) for group, prefix in (("outcomes", "O"), ("decisions", "D")): ids = [x["id"] for x in plan[group]] if ids != [f"{prefix}{i}" for i in range(1, len(ids) + 1)]: @@ -154,15 +209,8 @@ def check_plan(plan, repo, docs, r): if nums != [f"{i:02d}" for i in range(1, len(nums) + 1)]: r.add(F, "phases", "id", f"phases must be numbered 01..{len(nums):02d} in build order, got {nums}") for ph in plan["phases"]: - if not ph["file"].startswith(ph["phase"] + "-"): - r.add(F, ph["phase"], "id", f"file {ph['file']} does not start with {ph['phase']}-") - for s in ph["stages"]: - if not s["id"].startswith(ph["phase"] + "."): - r.add(F, s["id"], "id", f"stage {s['id']} is listed in phase {ph['phase']}") - if len(stages) != sum(len(ph["stages"]) for ph in plan["phases"]): - r.add(F, "stages", "id", "duplicate stage ids") - if len(contracts) != len(plan["contracts"]): - r.add(F, "contracts", "id", "duplicate contract ids") + if not ph["dir"].startswith(ph["phase"] + "-"): + r.add(F, ph["phase"], "id", f"dir {ph['dir']} does not start with {ph['phase']}-") for x in plan["outcomes"]: for s in x["sources"]: check_quote(F, x["id"], s, docs, r) @@ -175,86 +223,78 @@ def check_plan(plan, repo, docs, r): if p != "all" and p not in nums: r.add(F, x["id"], "ref", f"names phase {p}, which does not exist") created = {} - for ph in plan["phases"]: - for s in ph["stages"]: - for f in s["files"]: - if f["action"] == "create": - created.setdefault(f["path"], s["id"]) - for c in plan["contracts"]: - w, prov = c["id"], c["provided_by"] - if prov.startswith("existing:"): - path = prov[len("existing:"):].split("::")[0] - m = WHERE.fullmatch(path) - path = m.group(1) if m else path - if not os.path.exists(os.path.join(repo, path)): - r.add(F, w, "ref", f"{c['name']}: existing path {path} not found") - elif prov not in stages: - r.add(F, w, "ref", f"{c['name']}: provided_by {prov} is not a stage or existing:") - elif w not in stages[prov][1]["provides"]: - r.add(F, w, "registry", f"{c['name']}: stage {prov} does not list {w} in provides") - if not [u for u in c["used_by"] if c["kind"] == "test-helper" or not TESTY.search(u)]: - r.add(F, w, "internal", f"{c['name']}: used only by tests; that is internal: leave it out and state " - "what tests observe as behaviour") - for u in c["used_by"]: - if not STAGE_ID.match(u): - continue - if u not in stages: - r.add(F, w, "ref", f"{c['name']}: used_by {u} is not a stage") - continue - if w not in stages[u][1]["uses"]: - r.add(F, w, "registry", f"{c['name']}: used_by {u}, but {u} does not list {w} in uses") - if prov in pos and pos[prov] >= pos[u]: - r.add(F, w, "order", f"{c['name']}: provided by {prov}, used by {u}, which is not built after it") + for sid, s in stages.items(): + for f in s["brief"]["files"]: + if f["action"] == "create": + created.setdefault(f["path"], sid) + contracts = registry(stages) + names = [c["name"] for c in contracts] + [e["name"] for e in plan["existing"]] + for name in sorted({n for n in names if names.count(n) > 1}): + r.add(F, name, "registry", f"{name}: more than one provider; a name in uses must resolve to exactly one " + "stage's provides or one existing entry") + for e in plan["existing"]: + m = WHERE.fullmatch(e["path"]) + path = m.group(1) if m else e["path"] + if not os.path.exists(os.path.join(repo, path)): + r.add(F, e["name"], "ref", f"{e['name']}: existing path {path} not found") + for c in contracts: + w, G = c["provided_by"], stages[c["provided_by"]]["file"] + if not c["users"] and not [u for u in c["used_by"] if c["kind"] == "test-helper" or not TESTY.search(u)]: + r.add(G, w, "internal", f"{c['name']}: no stage uses it and no user outside the plan other than tests; " + "that is internal: leave it out and state what tests observe as behaviour") + for u in c["users"]: + if pos[w] >= pos[u]: + r.add(G, w, "order", f"{c['name']}: provided by {w}, used by {u}, which is not built after it") if len(c["shape"]) > SHAPE_MAX[c["kind"]]: - r.add(F, w, "shape", f"{c['name']}: shape is {len(c['shape'])} chars > {SHAPE_MAX[c['kind']]} for {c['kind']}") + r.add(G, w, "shape", f"{c['name']}: shape is {len(c['shape'])} chars > {SHAPE_MAX[c['kind']]} for {c['kind']}") if c["kind"] == "other": - r.add(F, w, "other", f"{c['name']}: kind other" + ("" if c.get("other_reason") else " without other_reason")) - for sid, (ph, s) in stages.items(): - for cid in s["provides"] + s["uses"]: - if cid not in contracts: - r.add(F, sid, "ref", f"lists unknown contract {cid}") - for cid in s["provides"]: - if cid in contracts and contracts[cid]["provided_by"] != sid: - r.add(F, sid, "registry", f"provides {cid}, but the registry says {contracts[cid]['provided_by']}") - for cid in s["uses"]: - if cid in contracts and sid not in contracts[cid]["used_by"]: - r.add(F, sid, "registry", f"uses {cid}, but {sid} is not in its used_by") - for f in s["files"]: - exists = os.path.exists(os.path.join(repo, f["path"])) - if f["action"] == "create" and exists: - r.add(F, sid, "files", f"creates {f['path']}, which already exists") - if f["action"] != "create" and not exists and not ( - f["path"] in created and pos[created[f["path"]]] < pos[sid]): - r.add(F, sid, "files", f"{f['action']}s {f['path']}, which does not exist and no earlier stage creates") - m = re.match(r"(?:after|parallel with) (\d\d\.\d+)", s["order"]) - listed = list(stages) + r.add(G, w, "other", f"{c['name']}: kind other" + ("" if c.get("other_reason") else " without other_reason")) + listed = list(stages) + written = {t["test"].strip("`") for s in stages.values() for t in s["brief"].get("tests", []) + if t["kind"] == "outcome" and t["action"] == "writes"} + for sid, s in stages.items(): + b, G = s["brief"], s["file"] + paths = {f["path"] for f in b["files"]} + for name in b["uses"]: + if name not in names: + r.add(G, sid, "ref", f"uses {name!r}, which no stage provides and existing does not list") + if not s["record"].get("commit") and scope in (None, s["phase"]): + for f in b["files"]: + exists = os.path.exists(os.path.join(repo, f["path"])) + if f["action"] == "create" and exists: + r.add(G, sid, "files", f"creates {f['path']}, which already exists") + if f["action"] != "create" and not exists and not ( + f["path"] in created and pos[created[f["path"]]] < pos[sid]): + r.add(G, sid, "files", f"{f['action']}s {f['path']}, which does not exist and no earlier stage creates") + m = re.match(r"(?:after|parallel with) (\d\d\.\d+)", b["order"]) if m and m.group(1) not in stages: - r.add(F, sid, "order", f"order names {m.group(1)}, which is not a stage") + r.add(G, sid, "order", f"order names {m.group(1)}, which is not a stage") elif m and listed.index(m.group(1)) > listed.index(sid): - r.add(F, sid, "order", f"order names {m.group(1)}, which is listed after {sid}; list stages in build order") - elif m and s["order"].startswith("after"): - dep = stages[m.group(1)][1] - if not set(dep["provides"]) & set(s["uses"]) and not ( - {f["path"] for f in dep["files"]} & {f["path"] for f in s["files"]}): - r.add(F, sid, "order-hint", f"ordered after {m.group(1)} but uses none of its contracts and shares " + r.add(G, sid, "order", f"order names {m.group(1)}, which is built after {sid}") + elif m: + dep = stages[m.group(1)]["brief"] + shared = paths & {f["path"] for f in dep["files"]} + if b["order"].startswith("parallel") and shared: + r.add(G, sid, "parallel", f"shares {sorted(shared)} with parallel stage {m.group(1)}") + if b["order"].startswith("after") and not shared and not {c["name"] for c in dep["provides"]} & set(b["uses"]): + r.add(G, sid, "order-hint", f"ordered after {m.group(1)} but uses none of its contracts and shares " "no file; if nothing else needs it first, order it after the stage it does depend on or in parallel") - if m and m.group(1) in stages and s["order"].startswith("parallel"): - shared = {f["path"] for f in s["files"]} & {f["path"] for f in stages[m.group(1)][1]["files"]} - if shared: - r.add(F, sid, "parallel", f"shares {sorted(shared)} with parallel stage {m.group(1)}") - have = {t["outcome"] for t in plan["outcome_tests"]} - for x in plan["outcomes"]: - if x["id"] not in have: - r.add(F, x["id"], "coverage", f"outcome {x['id']} has no outcome test") + for t in b.get("tests", []): + if t["kind"] == "outcome" and t["action"] == "writes" and "outcome" not in t: + r.add(G, sid, "tests", f"outcome test {t['test']} needs the id of its outcome in `outcome`") + if t["kind"] == "outcome" and t["action"] == "turns on" and t["test"].strip("`") not in written: + r.add(G, sid, "ref", f"turns on {t['test']}, which no stage writes") + rows = outcome_rows(stages) known = {x["id"] for x in plan["outcomes"]} - for t in plan["outcome_tests"]: + if not outline: # tests are not an outline field + for x in sorted(known - {t["outcome"] for t in rows}): + r.add(F, x, "coverage", f"outcome {x} has no outcome test") + for t in rows: + G = stages[t["written_in"]]["file"] if t["outcome"] not in known: - r.add(F, t["test"], "ref", f"outcome {t['outcome']} is not in outcomes") - for k in ("written_in", "passes_from"): - if t[k] not in stages: - r.add(F, t["test"], "ref", f"{k} {t[k]} is not a stage") - if t["written_in"] in pos and t["passes_from"] in pos and pos[t["written_in"]] > pos[t["passes_from"]]: - r.add(F, t["test"], "order", f"written in {t['written_in']}, after it must pass ({t['passes_from']})") + r.add(G, t["test"], "ref", f"outcome {t['outcome']} is not in outcomes") + if pos[t["written_in"]] > pos[t["passes_from"]]: + r.add(G, t["test"], "order", f"written in {t['written_in']}, after it must pass ({t['passes_from']})") for path, text in strings({k: plan[k] for k in ("size", "decisions", "outcomes")}): if CODEY.search(text): r.add(F, path, "code", CODEY.search(text).group(0)[:80]) @@ -287,128 +327,121 @@ def check_cite(file, where, cite, shows, repo, r): r.add(file, where, "cite", f"{cite} does not show {shows!r}; cite the lines that do") -# ---- NN.json - -def check_phase(num, d, plan, repo, docs, r): - F = f"{num}.json" - ph = next(p for p in plan["phases"] if p["phase"] == num) - want = {s["id"]: s for s in ph["stages"]} - got = {s["id"]: s for s in d["stages"]} - if list(want) != [s["id"] for s in d["stages"]]: - r.add(F, "stages", "plan", f"stages are {list(got)}, plan.json gives {list(want)} in that order") - contracts = {c["id"]: c for c in plan["contracts"]} - ids = set(contracts) | {x["id"] for x in plan["decisions"]} - table = {(t["test"].strip("`"), s) for t in plan["outcome_tests"] for s in (t["written_in"], t["passes_from"])} - for sid, s in got.items(): - where = lambda field: f"{sid}{field}" - if sid in want: - wf = {f["path"]: f["action"] for f in want[sid]["files"]} - gf = {f["path"]: f["action"] for f in s["files"]} - if wf != gf: - r.add(F, sid, "plan", f"files differ from plan.json: missing {sorted(set(wf) - set(gf))}, " - f"extra {sorted(set(gf) - set(wf))}, or a different action") - provided = " ".join(c["name"] + " " + c["shape"] for c in s["contracts"] if c["direction"] == "provides").lower() - for cid in want[sid]["provides"]: - if cid in contracts and norm(contracts[cid]["name"]) not in norm(provided): - r.add(F, sid, "plan", f"does not provide `{contracts[cid]['name']}`, which plan.json gives it") - if len(s["goal"]) > GOAL_MAX: - r.add(F, sid, "length", f"goal is {len(s['goal'])} chars > {GOAL_MAX}") - for f, n in LIMITS.items(): - if len(s[f]) > n: - r.add(F, sid, "length", f"{f} has {len(s[f])} items > {n}") - if len(s["context"]["code_read"]) > CODE_READ_MAX: - r.add(F, sid, "length", f"code_read has {len(s['context']['code_read'])} items > {CODE_READ_MAX}") - if len(s["context"]["design"]) > DESIGN_MAX: - r.add(F, sid, "length", f"design has {len(s['context']['design'])} items > {DESIGN_MAX}") - for c in s["contracts"]: - others = [x for x in c["counterparts"] if x != sid] - if c["kind"] != "test-helper": - others = [x for x in others if not TESTY.search(x)] - if not others: - r.add(F, sid, "internal", f"contract {c['name']}: no counterpart outside {sid} other than tests; " - "internal: leave it out and state what tests observe as behaviour") - if len(c["shape"]) > SHAPE_MAX[c["kind"]]: - r.add(F, sid, "shape", f"contract {c['name']}: shape is {len(c['shape'])} chars > {SHAPE_MAX[c['kind']]} for {c['kind']}") - if c["kind"] == "other": - r.add(F, sid, "other", f"contract {c['name']} is kind other" + ("" if c.get("other_reason") else " without other_reason")) - for t in s["tests"]: - if t["kind"] == "unit" and not t.get("why_unit"): - r.add(F, sid, "tests", f"unit test {t['test']} needs why_unit") - if (t["test"].strip("`"), sid) in table: - r.add(F, sid, "tests", f"{t['test']} is an outcome test of this stage in plan.json; the rendered brief lists it") - for x in s["context"]["design"]: - check_quote(F, where("/context/design"), x, docs, r) - for x in s["context"]["code_read"]: - check_cite(F, where("/context/code_read"), x["where"], x["shows"], repo, r) - for path, text in strings(s): - if not path.startswith("/contracts") or not path.endswith("/shape"): - if CODEY.search(text): - r.add(F, where(path), "code", CODEY.search(text).group(0)[:80]) - for path, text in strings(d): +# ---- phase.json and the stage files + +def check_revision(sid, s, r): + revs, rev = s["record"].get("revisions", {}), s["brief"]["revision"] + bad = [n for n in revs if not n.isdecimal()] + if bad: + r.add(s["file"], sid, "revision", f"stage {sid}: revisions keys {bad} are not revision numbers") + if str(rev) in revs and revs[str(rev)] != brief_hash(s["brief"]): + r.add(s["file"], sid, "revision", f"stage {sid}: the brief changed since revision {rev} was built; raise revision") + elif any(int(n) > rev for n in revs if n.isdecimal()): + r.add(s["file"], sid, "revision", f"stage {sid}: revision {rev} is lower than a revision already built") + + +def check_standalone(F, where, data, ids, r): + for path, text in strings(data): m = next((m for m in PLAN_IDS.finditer(text) if m.group(0) in ids), None) if m: - r.add(F, path, "standalone", f"uses the plan.json id {m.group(0)}, which the phase file does not define; " - "name the contract or decision instead") + r.add(F, where + path, "standalone", f"uses the plan.json id {m.group(0)}, which the phase file does not " + "define; name the decision instead") if ".plan/" in text: - r.add(F, path, "standalone", "cites the .plan folder; the phase file must stand alone") + r.add(F, where + path, "standalone", "cites the .plan folder; the phase file must stand alone") + + +def check_phase(F, brief, ids, r): + check_standalone(F, "", brief, ids, r) for k in ("before", "after"): - n = len(re.findall(r"[.!?](?:\s|$)", d[k])) + n = len(re.findall(r"[.!?](?:\s|$)", brief[k])) if n > SENTENCES_MAX: r.add(F, k, "length", f"{k} has {n} sentences > {SENTENCES_MAX}") +def check_stage(sid, s, ids, repo, docs, scope, r): + b, F = s["brief"], s["file"] + if len(b["goal"]) > GOAL_MAX: + r.add(F, sid, "length", f"goal is {len(b['goal'])} chars > {GOAL_MAX}") + for f, n in LIMITS.items(): + if len(b[f]) > n: + r.add(F, sid, "length", f"{f} has {len(b[f])} items > {n}") + if len(b["context"]["code_read"]) > CODE_READ_MAX: + r.add(F, sid, "length", f"code_read has {len(b['context']['code_read'])} items > {CODE_READ_MAX}") + if len(b["context"]["design"]) > DESIGN_MAX: + r.add(F, sid, "length", f"design has {len(b['context']['design'])} items > {DESIGN_MAX}") + for t in b["tests"]: + if t["kind"] == "unit" and not t.get("why_unit"): + r.add(F, sid, "tests", f"unit test {t['test']} needs why_unit") + for x in b["context"]["design"]: + check_quote(F, f"{sid}/context/design", x, docs, r) + if stage_status(s) != "done" and scope in (None, s["phase"]): + for x in b["context"]["code_read"]: + check_cite(F, f"{sid}/context/code_read", x["where"], x["shows"], repo, r) + for path, text in strings({k: v for k, v in b.items() if k != "checks"}): + if not (path.startswith("/provides") and path.endswith("/shape")) and CODEY.search(text): + r.add(F, sid + path, "code", CODEY.search(text).group(0)[:80]) + check_standalone(F, sid, b, ids, r) + + # ---- rendering def bullets(items, fmt): return [f"- {fmt(x)}" for x in items] or ["none"] -def render(num, d, plan): - ph = next(p for p in plan["phases"] if p["phase"] == num) - order = {s["id"]: s["order"] for s in ph["stages"]} - titles = {s["id"]: s["title"] for s in ph["stages"]} - sids = set(order) - outcomes = {x["id"]: x for x in plan["outcomes"]} - rows = [t for t in plan["outcome_tests"] if t["written_in"] in sids or t["passes_from"] in sids] +def contract_lines(sid, brief, contracts, existing): + mine = [f"- {c['kind']} `{c['name']}` (provides; {', '.join(c['users'] + c['used_by'])}): {c['shape']}" + for c in contracts if c["provided_by"] == sid] + sources = {**{e["name"]: {**e, "provided_by": f"existing, `{e['path']}`"} for e in existing}, + **{c["name"]: c for c in contracts}} + used = [f"- {c['kind']} `{c['name']}` (uses; {c['provided_by']}): {c['shape']}" + for c in (sources[n] for n in brief["uses"] if n in sources)] + return mine + used or ["none"] + + +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] + 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", - "without it. Model tiers map to models in [models.md](models.md).", - "Status: planned", f"Before: {d['before']}", f"After: {d['after']}", "", "## Assumptions"] + "without it. Model tiers map to models in [models.md](../models.md).", + f"Status: {phase_status(pj['record'], found)}", f"Before: {d['before']}", f"After: {d['after']}", "", + f"Role: {d['role']}", f"Why: {d['why']}", f"How: {d['how']}", "", "## Assumptions"] L += bullets(d["assumptions"], lambda a: f"{a['status'].capitalize()}: {a['text']} ({a['evidence']})") if plan["size"]["verdict"] == "quick": L += ["", "## Size", "", "Quick plan:"] + bullets(plan["size"]["evidence"], str) L += ["", "## Outcome tests", f"Budget: {d['test_budget']}", "", "| Outcome | Test | Written in | Passes from |", "| --- | --- | --- | --- |"] - L += [f"| {outcomes[t['outcome']]['observable'] if t['outcome'] in outcomes else t['outcome']} | " - f"`{t['test'].strip('`')}` | {t['written_in']} | {t['passes_from']} |" for t in rows] + L += [f"| {proves[t['test']]} | `{t['test']}` | {t['written_in']} | {t['passes_from']} |" for t in rows] L += ["", "## Stages", "", "| Stage | Goal | Tier | Order | Status |", "| --- | --- | --- | --- | --- |"] - L += [f"| {s['id']} | {s['goal']} | {tier(s['model_basis'])[1]} | {order.get(s['id'], '?')} | planned |" - for s in d["stages"]] - for s in d["stages"]: - c = s["context"] - L += ["", f"## {s['id']} {titles.get(s['id'], '')}".rstrip(), "", f"Goal: {s['goal']}", "", "Context:"] + 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:"] + bullets(s["contracts"], lambda x: - f"{x['kind']} `{x['name']}` ({x['direction']}; {', '.join(x['counterparts'])}): {x['shape']}") - L += ["", "Files:"] + bullets(s["files"], lambda x: f"`{x['path']}` ({x['action']}): {x['role']}") - L += ["", "Behaviour:"] + bullets(s["behaviour"], lambda x: + 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(s["external_inputs"], lambda x: + L += ["", "External inputs:"] + bullets(b["external_inputs"], lambda x: f"{x['source']}: {x['check']}; on failure, {x['on_failure']}") - tests = [f"- writes `{t['test'].strip('`')}` (outcome): {outcomes.get(t['outcome'], {}).get('observable', t['outcome'])}" - for t in rows if t["written_in"] == s["id"]] - tests += [f"- turns on `{t['test'].strip('`')}` (outcome): {outcomes.get(t['outcome'], {}).get('observable', t['outcome'])}" - for t in rows if t["passes_from"] == s["id"] and t["written_in"] != s["id"]] - tests += [f"- {x['action']} `{x['test'].strip('`')}` ({x['kind']}): {x['proves']}" - + (f" (unit because: {x['why_unit']})" if x.get("why_unit") else "") for x in s["tests"]] - L += ["", "Tests:"] + (tests or ["none"]) - L += ["", "Done when:"] + bullets(s["done_when"], str) - L += ["", "Out of scope:"] + bullets(s["out_of_scope"], str) - total, t, why = tier(s["model_basis"]) - L += ["", "Model basis: " + " ".join(f"{m}{s['model_basis'][m]}" for m in MEASURES) + 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 "")] notes = list(d["notes"]) for x in plan["decisions"]: @@ -423,70 +456,147 @@ def render(num, d, plan): return "\n".join(L) + "\n" +def render_overview(plan, phases, stages): + L = [f"# Plan: {plan['description']}", "", + "Rendered by plan-check.py from plan.json and the stage files; never edited by hand.", "", + f"Goal: {plan['goal']}", f"Why: {plan['why']}", "", "## Outcomes"] + L += bullets(plan["outcomes"], lambda x: f"{x['id']} {x['title']}: {x['observable']} Check: {x['how_to_check']}") + L += ["", "## Decisions"] + bullets(plan["decisions"], lambda x: + f"{x['id']} (phases {', '.join(x['phases'])}): {x['text']} Reason: {x['reason']}") + L += ["", "## Contracts"] + bullets(registry(stages), lambda c: + f"{c['kind']} `{c['name']}` (provided by {c['provided_by']}; used by " + f"{', '.join(c['users'] + c['used_by']) or 'none'}): {c['shape']}") + L += ["", "## Existing interfaces"] + bullets(plan["existing"], lambda e: + f"{e['kind']} `{e['name']}` (`{e['path']}`; used by " + f"{', '.join(u for u, s in stages.items() if e['name'] in s['brief']['uses']) or 'none'}): {e['shape']}") + L += ["", "## Phases", "", "| Phase | Kind | Status |", "| --- | --- | --- |"] + L += [f"| [{ph['phase']} {ph['name']}]({ph['dir']}/phase.md) | {ph['kind']} | " + f"{phase_status((pj or {}).get('record', {}), found)} |" for ph, pj, found in phases] + return "\n".join(L) + "\n" + + +def write(plan_dir, plan, phases, nums): + # writes phase.md for the phases in nums, then plan.md; returns the names written, relative to plan_dir + stages = flatten(phases) + texts = {f"{ph['dir']}/phase.md": render_phase(ph, pj, found, plan, stages) + for ph, pj, found in phases if ph["phase"] in nums} + texts["plan.md"] = render_overview(plan, phases, stages) + for name, text in texts.items(): + with open(os.path.join(plan_dir, name), "w") as f: + f.write(text) + return list(texts) + + +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"]] + return [os.path.join(plan_dir, n) for n in write(plan_dir, plan, phases, [ph["phase"] for ph in plan["phases"]])] + + # ---- main -def load(path, schema_name, r, file): +def read_json(path): + with open(path) as f: + return json.load(f) + + +def schema_for(name, outline=False): + schema = read_json(os.path.join(SKILL, name)) + if not outline: + return schema + brief = {**schema["properties"]["brief"], "required": OUTLINE} + return {**schema, "properties": {**schema["properties"], "brief": brief}} + + +def load(path, schema, r, file): try: - data = json.load(open(path)) + data = read_json(path) except OSError: + r.add(file, "-", "missing", "not written yet") return None except ValueError as e: r.add(file, "-", "json", f"not valid JSON: {e}") return None - errs = validate(data, json.load(open(os.path.join(SKILL, schema_name)))) + errs = validate(data, schema) for where, msg in errs: r.add(file, where or "/", "schema", msg) return None if errs else data +def load_phase(plan_dir, ph, outline, stage_schema, r): + # (phase.json or None, {stage id: stage file}); outline mode reads the stage files only + pdir, num = os.path.join(plan_dir, ph["dir"]), ph["phase"] + if not os.path.isdir(pdir): + r.add(f"{ph['dir']}/phase.json", "-", "missing", f"phase folder {ph['dir']} not written yet") + return None, {} + pj = None if outline else load(os.path.join(pdir, "phase.json"), schema_for("phase.schema.json"), r, + f"{ph['dir']}/phase.json") + names = stage_files(pdir) + if not names: + r.add(f"{ph['dir']}/phase.json", "-", "missing", f"no stage files in {ph['dir']}") + for n in names: + if not n.startswith(num + "."): + r.add(f"{ph['dir']}/{n}", n[:-5], "id", f"stage {n[:-5]} is in the folder of phase {num}") + loaded = {n[:-5]: load(os.path.join(pdir, n), stage_schema, r, f"{ph['dir']}/{n}") + for n in names if n.startswith(num + ".")} + return pj, {sid: s for sid, s in loaded.items() if s is not None} + + def main(argv): - args, opts = [], {"--repo": ".", "--spec": None, "--design": None} - outline_only, i = False, 0 + args, opts = [], {"--repo": ".", "--spec": None, "--design": None, "--phase": None} + outline, i = False, 0 while i < len(argv): if argv[i] in opts and i + 1 < len(argv): opts[argv[i]] = argv[i + 1] i += 2 elif argv[i] == "--outline": - outline_only, i = True, i + 1 + outline, i = True, i + 1 else: args.append(argv[i]) i += 1 if len(args) != 1: print(__doc__, file=sys.stderr) return 2 - plan_dir, repo = args[0], opts["--repo"] - docs = {} - for k in ("spec", "design"): - if opts[f"--{k}"]: - try: - docs[k] = norm(open(opts[f"--{k}"]).read()) - except OSError as e: - print(f"cannot read --{k}: {e}", file=sys.stderr) - return 2 + plan_dir, repo, scope = args[0], opts["--repo"], opts["--phase"] r = Report() - plan_path = os.path.join(plan_dir, ".plan", "plan.json") + plan_path = os.path.join(plan_dir, "plan.json") if not os.path.exists(plan_path): print(f"missing {plan_path}", file=sys.stderr) return 2 - plan = load(plan_path, "plan.schema.json", r, "plan.json") - rendered, missing = [], [] + plan = load(plan_path, schema_for("plan.schema.json"), r, "plan.json") + if plan and scope is not None and scope not in [ph["phase"] for ph in plan["phases"]]: + print(f"--phase {scope} is not a phase of the plan", file=sys.stderr) + return 2 + named = {k: os.path.join(repo, v) for k, v in (plan or {}).get("docs", {}).items()} + paths = {k: opts[f"--{k}"] or named.get(k) for k in ("spec", "design")} + docs = {} + for k, path in paths.items(): + if path: + try: + docs[k] = norm(open(path).read()) + except OSError as e: + print(f"cannot read the {k}: {e}", file=sys.stderr) + return 2 + rendered = [] if plan: - check_plan(plan, repo, docs, r) - if not outline_only: - for ph in plan["phases"]: - num, f = ph["phase"], f"{ph['phase']}.json" - path = os.path.join(plan_dir, ".plan", f) - if not os.path.exists(path): - missing.append(f) - r.add(f, "-", "missing", "phase JSON not written yet") - continue - d = load(path, "phase.schema.json", r, f) - if d is None: - continue - check_phase(num, d, plan, repo, docs, r) - if not r.errors(f) and not r.errors("plan.json"): - open(os.path.join(plan_dir, ph["file"]), "w").write(render(num, d, plan)) - rendered.append(ph["file"]) + stage_schema = schema_for("stage.schema.json", outline) + phases = [(ph, *load_phase(plan_dir, ph, outline, stage_schema, r)) for ph in plan["phases"]] + stages = flatten(phases) + check_plan(plan, stages, repo, docs, scope, outline, r) + ids = {x["id"] for x in plan["decisions"]} + for sid, s in stages.items(): + check_revision(sid, s, r) + if not outline: + check_stage(sid, s, ids, repo, docs, scope, r) + for ph, pj, _ in phases: + if pj: + check_phase(f"{ph['dir']}/phase.json", pj["brief"], ids, r) + clean = [ph["phase"] for ph, pj, _ in phases if pj and not r.errors(ph["dir"] + "/")] + if clean and not r.errors("plan.json"): + rendered = write(plan_dir, plan, phases, clean) for x in r.items: print(json.dumps(x)) print(json.dumps({"summary": {"errors": len(r.errors()), "warnings": len(r.items) - len(r.errors()), diff --git a/plugins/phased-delivery/scripts/plan-mode.py b/plugins/phased-delivery/scripts/plan-mode.py index bd12ff4..0d5893b 100755 --- a/plugins/phased-delivery/scripts/plan-mode.py +++ b/plugins/phased-delivery/scripts/plan-mode.py @@ -36,14 +36,14 @@ already written is always full; anything the estimate could not find (unresolved) makes it at least quick. -`rescore` re-scores a quick plan from PLAN_DIR/.plan/plan.json alone, so the -planner's own view of the estimate does not decide it: one part per stage, -with its files and `lines`; a stage providing a contract that existing -code, the user or disk uses, or editing the file of an existing contract, -is an interface part; a stage that only creates files is new; others are -internal. Reach is the contracts' outside users plus a search for their -names. More than one phase, or more than 3 stages, is full whatever the -score. +`rescore` re-scores a quick plan from PLAN_DIR/plan.json and its stage +files, so the planner's own view of the estimate does not decide it: one +part per stage, with its files and `lines`; a stage providing a contract +that existing code, the user or disk uses, or editing the file of an +existing contract, is an interface part; a stage that only creates files +is new; others are internal. Reach is the contracts' outside users plus a +search for their names. More than one phase, or more than 3 stages, is +full whatever the score. Output: one JSON line per problem, {"where", "kind", "msg", "level"}, then a summary line. level "error" must be fixed; "warning" is for the agent to @@ -115,7 +115,7 @@ def repo_files(repo): def texts(repo, skip=None): """Text files of the repository, except the input file and plan folders (phase files and their model tables mention every name and are not users of it).""" - out, plan_dirs = [], set() + out, plan_dirs, plan_trees = [], set(), set() for f in repo_files(repo): p = os.path.join(repo, f) if skip and os.path.abspath(p) == skip: @@ -131,9 +131,13 @@ def texts(repo, skip=None): continue text = data.decode("utf-8", "replace") if text.startswith("# Phase ") and PHASE_MARK in text[:500]: - plan_dirs.add(os.path.dirname(f)) + if os.path.basename(f) == "phase.md": # new layout /NN-name/phase.md: drop all of / + plan_trees.add(os.path.dirname(os.path.dirname(f)) + "/") + else: + plan_dirs.add(os.path.dirname(f)) out.append((f, text)) - return [(f, t) for f, t in out if os.path.dirname(f) not in plan_dirs] + return [(f, t) for f, t in out + if os.path.dirname(f) not in plan_dirs and not any(f.startswith(d) for d in plan_trees)] def mentions(corpus, needle, ignore_case): @@ -239,41 +243,32 @@ def bounds(form, parts): return {"mode": mode, "low": lo, "high": hi, "parts": rows, "reasons": reasons} -def plan_parts(plan): - """Parts for rescore: one per stage, kind and names from the contract registry.""" - contracts = {c["id"]: c for c in plan["contracts"]} - stage_ids = {s["id"] for ph in plan["phases"] for s in ph["stages"]} +def plan_parts(plan, phases): + """Parts for rescore: one per stage, kind and names from its provides and the existing interfaces.""" parts = [] - for ph in plan["phases"]: - for st in ph["stages"]: - paths = {f["path"] for f in st["files"]} - names, outside = [], set() - for cid in st["provides"]: - c = contracts.get(cid) - users = [u for u in (c["used_by"] if c else []) if u not in stage_ids] - if users: - names.append(c["name"]) - outside |= set(users) - for c in plan["contracts"]: - src = c["provided_by"] - if src.startswith("existing:") and src[len("existing:"):] in paths: - names.append(c["name"]) - outside |= {u for u in c["used_by"] if u not in stage_ids} + for stages in phases: + for sid, st in stages.items(): + b = st["brief"] + paths = {f["path"] for f in b["files"]} + outside = [c for c in b["provides"] if c["used_by"]] + names = [c["name"] for c in outside] + [e["name"] for e in plan["existing"] if e["path"] in paths] + listed = {u for c in outside for u in c["used_by"]} if names: kind = "interface" - elif all(f["action"] == "create" for f in st["files"]): + elif all(f["action"] == "create" for f in b["files"]): kind = "new" else: kind = "internal" - parts.append({"title": f"{st['id']} {st['title']}", "kind": kind, "files": st["files"], - "lines": st["lines"], "changes": names, "listed": outside - paths}) + parts.append({"title": f"{sid} {b['title']}", "kind": kind, "files": b["files"], + "lines": b["lines"], "changes": names, "listed": listed - paths}) return parts def rescore(plan_dir, repo): - with open(os.path.join(plan_dir, ".plan", "plan.json")) as fh: - plan = json.load(fh) - parts = plan_parts(plan) + plan = plan_check.read_json(os.path.join(plan_dir, "plan.json")) + dirs = [os.path.join(plan_dir, ph["dir"]) for ph in plan["phases"]] + phases = [{n[:-5]: plan_check.read_json(os.path.join(d, n)) for n in plan_check.stage_files(d)} for d in dirs] + parts = plan_parts(plan, phases) corpus = texts(repo) plan_abs = os.path.abspath(plan_dir) for p in parts: @@ -285,9 +280,9 @@ def rescore(plan_dir, repo): users = found | p.pop("listed") p["reach"], p["reach_files"] = sorted(users), len(users) mode, total, rows, reasons = score(parts, [], []) - stages = max(len(ph["stages"]) for ph in plan["phases"]) - if len(plan["phases"]) > 1 or stages > 3: - reasons.append(f"{len(plan['phases'])} phases, up to {stages} stages: more than one phase of 3 stages -> full") + stages = max(len(ph) for ph in phases) + if len(phases) > 1 or stages > 3: + reasons.append(f"{len(phases)} phases, up to {stages} stages: more than one phase of 3 stages -> full") mode = "full" for r, p in zip(rows, parts): r["kind"], r["reach_files"] = p["kind"], p["reach"][:MAX_FILES_PER_TERM] diff --git a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md index 0a82c7f..77c796d 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md +++ b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md @@ -1,14 +1,18 @@ --- name: implement-in-phases -description: "Build a written phased plan one phase at a time: revise the next phase file 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.md phase files exists and the user wants it built. Requires a complete plan; if phase files or stage briefs are missing, use plan-in-phases first. Use proactively, without being asked, whenever the work at hand is described by phase 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: 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." --- # Implement in phases -Companion to [plan-in-phases](../plan-in-phases/SKILL.md). The plan's phase -files hold the structure, contracts and stage briefs; the implementer owns how -each stage's code works inside its brief. The planner's simplicity rules apply -unchanged. +Companion to [plan-in-phases](../plan-in-phases/SKILL.md). The plan is its +JSON: `plan.json` and, per phase, a folder `NN-name` with `phase.json` and +one stage file `NN.n.json` per stage. Each has a `brief` (the structure, +contracts and stage briefs, written by planning and revising) and a `record` +(written only by the scripts). `plan.md` and each `phase.md` are rendered +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 @@ -20,48 +24,53 @@ Do not count, sum or write those by hand. Why it works this way is in ## Before the first phase -1. Read the project instructions, specification, design and every phase file. -2. Check that all phase files exist with complete stage briefs. If not, stop +1. Read the project instructions, specification, design and every `phase.md`. +2. Check that all phase folders exist with complete stage briefs. If not, stop and complete the plan with plan-in-phases first; implementation never fills planning gaps. 3. Note the starting git state and any edits already present, so they are not - mistaken for this work. Record the commit the plan's work starts from in - the first phase's Notes as `Plan start: `; the work report counts - from it. On resume, find where the phase left off from its status line, - stage table and `.build/NN-ledger.json`. + 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. 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: check - the phase file against the repository, write `.build/NN-revision.json`, - and run `build-check.py start ` until it exits 0. +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. + 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 + `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 - `.build/NN-review.json` with only the finding types phase-reviewer.md + `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 through plan-in-phases' revision rules - ([revising.md](../plan-in-phases/revising.md)) before any code changes; + - `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, then run `build-check.py finish - `: it checks the review JSON and that every stage has a - commit, sets `Status: built ` and commits the plan directory - with a `Phase:` trailer. Never push or publish unless asked. +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: @@ -69,7 +78,7 @@ Then stop and report to the user: - deviations from the briefs, or "none"; - what was verified by running something versus only by reading code, and what could not be verified; -- plan adjustments made in the Notes; +- 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; 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 afba66f..2d6b0f1 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/build-guide.md +++ b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md @@ -2,16 +2,19 @@ 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` keeps the attempts, gates each build and makes the -commits, so nothing here is counted or written by hand. +`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. Small or tightly coupled stages may be -built directly, under the same directions; record that in the Notes. -Delegation keeps each agent's context focused on its brief. +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 @@ -19,18 +22,23 @@ 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; exit 3 means the fallback, as model-selection.md +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 the revision JSON. +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: do not dispatch it; - revise the plan (model-selection.md, "Adjust while working"). + dir>)` ("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 @@ -48,7 +56,7 @@ sandbox sets it already). After every build, record it: ``` -build-check.py record --tool claude-code --model --effort \ +build-check.py record --tool claude-code --model --effort \ --exit --tokens --cost --cap [--tool-calls N] [--premium] ``` @@ -59,16 +67,18 @@ 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, and every check - 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 +- **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 the plan instead. + 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 @@ -85,7 +95,7 @@ checks are rerun by `record`, and read its diff before committing. ## Premium spend -`build-check.py spend ` prints the phase's premium spend: the +`build-check.py spend ` 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 @@ -97,23 +107,30 @@ their `route` calls pass no `--premium-spent`. When a stage is accepted, run: ``` -build-check.py commit [--subject-suffix "[skip ci]"] [--extra-trailer "Co-Authored-By: ..."] +build-check.py commit [--subject-suffix "[skip ci]"] [--extra-trailer "Co-Authored-By: ..."] ``` It commits 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), and marks the stage done in the phase -file's table and status line (in the working tree; `finish` commits them). +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. -A stage built directly by the orchestrator is recorded with `--model -orchestrator --effort default --tokens unknown --cost unknown`. +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 @@ -122,7 +139,7 @@ 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 Notes. +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 @@ -140,8 +157,8 @@ 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 file> --stopped` -to commit the plan directory (phase file, Notes and `.build/`). A stop at -the check before the review first sets the phase file's status line to -`Status: in progress (stages done: all; review pending)`; resuming starts -with the review, after checking availability and the routing rule again. +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/phase-reviewer.md b/plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md index 76a5b16..e370f4b 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md +++ b/plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md @@ -8,11 +8,11 @@ to Codex. It must not be an agent that built any stage of the phase. Inputs the orchestrator fills in: -- Phase file: `<path>` +- Phase folder: `<plan>/NN-name` (read its `phase.md`; the stage files `NN.n.json` hold each brief's `files` and `checks`) - Diff of the phase: `<command or base commit, for example git diff <base>>` - Edits that were present before the phase and are not part of it: `<list or "none">` - Project instructions: `<paths, such as CLAUDE.md or AGENTS.md>` -- Review file to write: `<plan>/.build/NN-review.json` +- Review file to write: `<plan>/NN-name/review.json` --- @@ -40,7 +40,7 @@ judgment. - **Done:** each stage's "Done when" is met, and the phase's "After" holds. Say which you confirmed by running something and which only by reading. - **Tests:** the tests each brief names exist, check what a user would - observe, and pass; the outcome tests the phase file says pass from this + observe, and pass; the outcome tests `phase.md` says pass from this phase have no expected-fail mark left. - **Assumptions:** the phase's assumptions still hold in the built code. - **Rules:** project rules and limits are kept. @@ -51,7 +51,7 @@ judgment. | Type | Report it when | Not this | | --- | --- | --- | -| `untraced-change` | a changed line maps to no stage brief, including a change in the plan directory that the phase's Notes do not record (revisions, re-scores and regenerated model files are recorded there; status, stage table, `.build` files and `work-report.md` need no note) | a line the brief's goal plainly needs | +| `untraced-change` | a changed line maps to no stage brief, including a change in the plan directory that the phase's Notes do not record (revisions, re-scores and regenerated model files are recorded there; the `record` parts of the JSON, the rendered `plan.md` and `phase.md`, `review.json` and `work-report.md` need no note) | a line the brief's goal plainly needs | | `internal-check` | a validation or error check on data this code produced or received through a settled contract | a check at an external input a brief lists | | `bug` | the code does something a brief's goal, contract or behaviour rule says it must not, or breaks a caller or another stage's contract; shown by a run or a cited line | behaviour the brief leaves to the builder | | `not-done` | a "Done when" item or the phase's "After" does not hold | an item you could only check by reading and have no reason to doubt | diff --git a/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md b/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md index 425d526..ca0e409 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md +++ b/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md @@ -1,68 +1,114 @@ # Revise the phase: guide -Before building a phase, check its file against what actually exists and -write the result as `<plan>/.build/NN-revision.json` in -[revision.schema.json](revision.schema.json). `scripts/build-check.py -start` checks it, and every later gate reads it: the files a stage may -change and the commands that show it is done come from this file, not -from the phase file's prose. - -## Check the phase file against the repository - -Earlier phases may have changed names, paths or details. Read the code each -stage touches as it is now, and update the phase file's context, contracts -and briefs so each stage is correct for the repository as it is. Record each -adjustment in the phase's Notes. - -Check each open assumption in the phase's Assumptions section against the -code now: mark it verified with where it was checked, or, if it is wrong, -revise the plan through plan-in-phases' revision rules -([revising.md](../plan-in-phases/revising.md)) before building. - -For a quick plan (its `Size` section says so), check that the revision keeps -it one phase of at most 3 stages and adds no contract that existing code, -the user or disk uses; if not, the plan must become a full plan first. - -Planning-level changes inside the approved design need no approval. A change -to the specification or design, or work the design lacks, goes to the user -first. - -## The revision JSON, field by field - -### phase -The phase number, `NN`, as in the file name. - -### stages -Every stage in the stage table, in its order. -- `id` and `title`: as in the phase file. The title becomes the stage - commit's subject after the id. -- `files`: exactly the paths the revised brief's Files line allows, with - `create`, `edit` or `delete`. The gate fails any other changed path, - except the files of stages not yet committed, the plan directory, - edits present before `start`, and Python caches. -- `checks`: shell commands that show the brief's "Done when" holds. Each - runs with `sh -c` from the repository root and must exit 0. Use the - commands the brief names; turn "the tests pass" into the command that - runs them. A brief whose "Done when" can only be confirmed by reading - gets an empty list; the orchestrator then reads the diff itself before - committing. -- `scores`: the brief's `Model basis` measures re-scored against the - revised brief and the code as it is now, written without spaces - (`J1F1R0C0K0P0V0S0`). When a score changes, update the brief's Model - basis and say why in the Notes. -- `tier`: the tier those scores give (model-selection.md, "Pick the tier"). - -### assumptions -Each open assumption checked: `verdict` `verified` or `wrong`, and -`evidence`, the file and symbol or the command that settled it. - -### adjustments -One line per change made to the phase file, as recorded in its Notes. - -## Then - -Run `build-check.py start <phase file>`. Fix each problem it prints (one -JSON line each) and rerun until it exits 0. It also refuses to start when a -stage's file already has uncommitted edits: commit or set them aside first, -so they are not mistaken for the stage's work. On resume, `start` keeps the -existing ledger; edit the revision only for stages not yet committed. +Directions for revising one phase of a plan, before it is built or after a +problem in it. The session follows them itself, or gives this file, +unchanged, to a headless reviser, followed by the inputs below. + +Inputs: + +- Phase folder: `<plan>/NN-name` +- Problem: `<the failed stage and what failed, the review finding, or "none" before the phase is built>` +- Project instructions: `<paths, such as CLAUDE.md or AGENTS.md>` + +--- + +You are revising one phase of a phased plan. The plan is its JSON: the phase +folder holds `phase.json` and one stage file `NN.n.json` per stage, each +with a `brief` and a `record`. The revision rules are plan-in-phases' +[revising.md](../plan-in-phases/revising.md); apply them, within the limits +below. The field guides beside it say what goes in each field. + +## What you may change + +- The `brief` of this phase's stage files, and in this phase's `phase.json` + the `notes` and the status and evidence of its `assumptions`. +- Never a `record`: only the build scripts write those. +- Never `phase.md` or `plan.md`: `plan-check.py` renders them. +- Nothing in another phase, `plan.json`, the specification or the design, + and no code. When the fix needs one of those, escalate (below). +- No revision JSON or other side file: the stage files are what + `build-check.py` gates and routes from. + +## Check the phase against the repository + +Earlier phases and stages may have changed names, paths or details. Read +the code each stage still to build touches as it is now, and update those +briefs (context, contracts, files, behaviour, `checks`) so each stage is +correct for the repository as it is. With a problem, start from it: find +which brief is wrong, and separate the missing definition from any proposed +code fix. + +- `files`: exactly the paths the stage may change, with `create`, `edit` or + `delete`. The gate fails any other changed path. +- `checks`: shell commands that show the brief's `done_when` holds. Each + runs with `sh -c` from the repository root and must exit 0. A brief whose + `done_when` can only be confirmed by reading gets an empty list. +- `model_basis`: re-score the measures when the brief or the code it + touches changed (model-selection.md, "Pick the tier"). + +Check each open assumption of the phase against the code now: mark it +verified with where it was checked. A wrong assumption is a problem to +revise for, like any other. + +For a quick plan (`plan.json`'s `size` says so), check that the revision +keeps it one phase of at most 3 stages and adds no contract that existing +code, the user or disk uses; if not, escalate: the plan must become a full +plan first. + +## Built stages + +Rework of built code is planned by revising the built stage's brief in +place, not by a cleanup stage: a committed stage whose brief has a higher +`revision` than it was built at is reopened and rebuilt against the new +brief as a fix. Raise the revision of every built stage the change affects, +after bringing its brief in line with the change. Add a stage file only for +work that belongs to no existing stage, numbered after the phase's existing +ones. + +## Raise revisions and check + +1. Raise `revision` by one in the brief of every stage whose brief you + changed, whatever the change, prose included. A changed brief with an + unchanged revision is an error from `plan-check.py` and `build-check.py`; + a raised one lets every model pair be tried again. +2. Record each change and its reason in `phase.json`'s `notes`. +3. Run `scripts/plan-check.py <plan dir> --repo <repo> --phase NN` and fix + every error, until it is clean. A headless reviser runs it when the + project's rules allow it to; the driver runs it after the reviser anyway, + and a revision that fails it is not built. + +## Escalate instead of changing anything + +Change nothing, and say why, when: + +- the fix is above the phase: another phase, `plan.json` (a contract other + phases use, an outcome, the architecture); +- the fix contradicts the approved specification or design, or is work the + design lacks. + +In the session, the first goes through revising.md on the whole plan and the +second to the user. A headless reviser only reports it. + +## In the session, then + +Before building the phase, run `build-check.py start <phase dir>`. Fix each +problem it prints (one JSON line each) and rerun until it exits 0. It also +refuses to start when a stage's file already has uncommitted edits: commit +or set them aside first, so they are not mistaken for the stage's work. On +resume, `start` keeps the existing record. + +## Report + +- Each stage file changed or added: what changed and why, and its new + revision. +- Assumptions checked, with the evidence. +- Whether `plan-check.py` ran, and its summary line. + +End the report with exactly one of these as its last line; a missing line +counts as escalate: + +- `Result: revised`: stage files edited, revisions raised, `plan-check.py` + clean (or not run, and said so above). +- `Result: unchanged`: nothing needed to change. +- `Result: escalate <phase|spec|design>: <why>`: nothing was changed; + `phase` means the fix is above this phase. diff --git a/plugins/phased-delivery/skills/implement-in-phases/revision.schema.json b/plugins/phased-delivery/skills/implement-in-phases/revision.schema.json deleted file mode 100644 index a89f350..0000000 --- a/plugins/phased-delivery/skills/implement-in-phases/revision.schema.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "type": "object", - "additionalProperties": false, - "required": ["phase", "stages", "assumptions", "adjustments"], - "properties": { - "phase": {"type": "string", "pattern": "^\\d\\d$"}, - "stages": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "additionalProperties": false, - "required": ["id", "title", "files", "checks", "scores", "tier"], - "properties": { - "id": {"type": "string", "pattern": "^\\d\\d\\.\\d+$"}, - "title": {"type": "string"}, - "files": { - "type": "array", - "minItems": 1, - "items": { - "type": "object", - "additionalProperties": false, - "required": ["path", "action"], - "properties": { - "path": {"type": "string"}, - "action": {"enum": ["create", "edit", "delete"]} - } - } - }, - "checks": {"type": "array", "items": {"type": "string"}}, - "scores": {"type": "string", "pattern": "^J[0-2]F[0-2]R[0-2]C[0-2]K[0-2]P[0-2]V[0-2]S[0-2]$"}, - "tier": {"enum": ["small", "middle", "middle+", "top"]} - } - } - }, - "assumptions": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": false, - "required": ["text", "verdict", "evidence"], - "properties": { - "text": {"type": "string"}, - "verdict": {"enum": ["verified", "wrong"]}, - "evidence": {"type": "string"} - } - } - }, - "adjustments": {"type": "array", "items": {"type": "string"}} - } -} 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 83cf9c5..22f581e 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,8 +1,7 @@ -# Why implementation uses a revision JSON, a script gate and closed review types +# 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). The plan that built it -is `docs/plans/implement-structured/`. +do not need it. Changed 2026-11-24 (plugin 0.11.0). ## What changed @@ -37,13 +36,50 @@ stopped ratcheting. implement-in-phases now follows the same pattern: ask for more every round. Unneeded code (unused, unasked-for or duplicated) keeps the useful part. +## Why the revision JSON went away (0.12.0) + +History: until 0.11.x a revised phase had three homes for a stage: the +`NN-name.md` phase file, the `.build/NN-revision.json` the revise step wrote +from it, and a ledger of attempts beside it in `.build/`. The planning JSON +was deleted once the plan was reported, so a revision edited prose and then +restated it as JSON, and the two could drift apart. + +Now the plan's JSON is kept for its whole life (see +[structured-planning-notes.md](../plan-in-phases/structured-planning-notes.md)), +and `build-check.py` takes a phase folder and reads each stage file directly: + +- **Revise is an edit of the JSON.** A stage's `files`, `checks` and + `model_basis` are already in its brief, so the revision JSON and its + schema had nothing left to say. The reviser edits briefs, raises their + `revision` and reruns `plan-check.py`. +- **Records beside the briefs.** Each stage file is `{brief, record}`; + attempts go into the stage's `record`, review and revise runs into + `phase.json`'s. Only the scripts write a `record`, so two writers never + share a part of a file, and status in `phase.md` is rendered from the + records, never edited. +- **A brief's hash is kept per revision.** A brief edited without a higher + `revision` is an error (exit 5), and the pairs already tried are counted + per revision: a changed brief may be tried again on every pair. +- **A built stage can be reopened** by raising its brief's revision; it is + rebuilt as a fix commit. Freezing built briefs left facts about later + stages unmovable. +- **Only a `session_only` stage may be recorded as built by the + orchestrator.** The 0.11.0 validation run below built a stage itself to + save money; the script now refuses that. +- **One guide for every revision.** revise-guide.md takes the problem as an + input (none before a phase) and ends in a result line, so a session and a + headless reviser follow the same rules. + +The sections above and below describe 0.11.0 where they name the revision +JSON or the ledger. + ## Decisions worth keeping - A build exit other than 0 and 8 is `error`, not a try: sign-in, service and Codex availability failures say nothing about the model, so they neither block the pair nor count against it in the work report. -- Stage commits hold only the stage's files; the phase file, `.build/` and - regenerated plan files are committed by `finish`, so the orchestrator's +- Stage commits hold only the stage's files; the plan directory (the JSON + with its records, and the rendered files) is committed by `finish`, so plan edits mid-phase never fail a gate. - Files of other stages count as in scope only until those stages are committed: parallel stages work, and a committed stage cannot change diff --git a/plugins/phased-delivery/skills/plan-in-phases/SKILL.md b/plugins/phased-delivery/skills/plan-in-phases/SKILL.md index 47a07e4..2391d04 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/SKILL.md +++ b/plugins/phased-delivery/skills/plan-in-phases/SKILL.md @@ -1,15 +1,15 @@ --- name: plan-in-phases -description: "Turn an approved specification and design into a complete phased implementation plan: one self-contained NN-name.md file per phase, each split into stage briefs a fresh agent can build without deciding anything other stages, code or the user see. Planning only; writes no code. Use whenever the user asks to plan, break down, phase, stage or sequence a feature, migration, rewrite or other multi-step change (\"plan this\", \"break this into phases\", \"write the implementation plan\", \"how should we build this in stages\"), or to review, fix or rework an existing phased plan or revise a phase after implementation finds gaps. Use proactively, without being asked, before writing code for any change that may touch several files, a shared contract or the architecture: its first step is a capped estimate (at most 5 files read) that sends small changes straight back to direct work, so starting it costs little. Not for one-file edits that change no contract, and not for building the plan; that is implement-in-phases." +description: "Turn an approved specification and design into a complete phased implementation plan: JSON checked by a script and rendered to one self-contained phase.md per phase, each split into stage briefs a fresh agent can build without deciding anything other stages, code or the user see. Planning only; writes no code. Use whenever the user asks to plan, break down, phase, stage or sequence a feature, migration, rewrite or other multi-step change (\"plan this\", \"break this into phases\", \"write the implementation plan\", \"how should we build this in stages\"), or to review, fix or rework an existing phased plan or revise a phase after implementation finds gaps. Use proactively, without being asked, before writing code for any change that may touch several files, a shared contract or the architecture: its first step is a capped estimate (at most 5 files read) that sends small changes straight back to direct work, so starting it costs little. Not for one-file edits that change no contract, and not for building the plan; that is implement-in-phases." --- # Plan in phases Turn the approved specification and design into the complete plan in one pass: -one file per phase, every stage detailed enough to build. This skill writes -documents only; [implement-in-phases](../implement-in-phases/SKILL.md) builds them. +one folder per phase, every stage detailed enough to build. This skill writes +the plan only; [implement-in-phases](../implement-in-phases/SKILL.md) builds it. Anyone implementing the plan, agent or person, must use the -implement-in-phases skill; every phase file says so in its header. +implement-in-phases skill; every rendered `phase.md` says so in its header. The user approves the specification and the design. First estimate how much planning the change needs (below); a change that needs no plan leaves this @@ -34,11 +34,11 @@ prints, unless the user asked for a particular one: - **direct:** do not plan. Leave this skill and make the change in context: read the code it touches, make it, run the tests. When the work turns out bigger, re-score as mode-guide.md says. -- **quick:** grill, then write `plan.json` and one phase file, - `01-short-name.md`, through `plan-check.py` as below, with `size` set to - `quick` and the score in its evidence. It need not follow the +- **quick:** grill, then write `plan.json` and one phase folder, + `01-short-name/`, checked and rendered by `plan-check.py` as below, with + `size` set to `quick` and the score in its evidence. It need not follow the skeleton-to-cutover progression. No review subagent: the script's checks - stand in for it. When `plan.json` passes `--outline`, run + stand in for it. When `plan.json` and the stage files pass `--outline`, run `scripts/plan-mode.py rescore` on the plan (mode-guide.md, "Re-scoring"): on full, continue as a full plan; on direct, stop planning and make the change. @@ -104,13 +104,27 @@ assumptions to check, and when it is done. Read [test-planning.md](test-planning.md) and follow it before planning any phase's tests or writing any stage brief's Tests line. -## Write every phase file +## Write every phase -Name the files `NN-short-name.md` in the plan directory, numbered in build -order. There is no separate index: each file stands alone and carries its own -status. The shared files are `models.md`, the plan's model table, and the -`models-available.json` it is generated from. Write -them top-down: +The plan directory holds `plan.json` and one folder per phase, named +`NN-short-name` and numbered in build order: + +``` +<plan dir>/ + plan.json the plan: goal, outcomes, decisions, phase list + plan.md rendered from plan.json + models.md, models-available.json + NN-short-name/ + phase.json the phase: role, before and after, assumptions, notes + NN.n.json one per stage: its brief + phase.md rendered: the phase and every stage brief +``` + +The JSON is the plan for its whole life: planning writes it, revising and +building keep using it, and nothing deletes it. `plan.md` and each +`phase.md` are rendered from it for people and builders; never edit them by +hand. The shared files are `models.md`, the plan's model table, and the +`models-available.json` it is generated from. Write the plan top-down: 1. List the models the running tool offers now in `models-available.json` and generate `models.md` with the plugin's `scripts/select-models.py` @@ -118,7 +132,7 @@ them top-down: memory. When the session can also build with Codex, do the same for Codex in `models-available-codex.json` and `models-codex.md` (see "Builders in another tool" there). -2. Create all phase files with their role and what exists before and after. +2. Create every phase with its role and what exists before and after. 3. Define every stage of every phase by goal, files and contracts. 4. Fill in each stage brief completely. @@ -130,37 +144,40 @@ into one of them, including callers and consumers in other phases. ### Write the plan as JSON and let the script check and render it -Steps 2 to 4 are written as JSON in a `.plan/` folder inside the plan -directory, and `scripts/plan-check.py` (in this plugin, two directories above -this skill's directory) checks them and renders the phase files. The JSON is -a planning tool only: once the plan is reported, the rendered `NN-name.md` -files are the plan. - -1. Steps 2 and 3: read [plan-guide.md](plan-guide.md) and write - `.plan/plan.json` following it: the outcomes from the grill, the - decisions that span phases, the contract registry, the outcome tests, - and every phase with its stages, files, contracts and order. Run +Steps 2 to 4 are written as JSON, and `scripts/plan-check.py` (in this +plugin, two directories above this skill's directory) checks it and renders +`plan.md` and each `phase.md`. + +1. Steps 2 and 3: read [plan-guide.md](plan-guide.md) and write `plan.json` + following it: the outcomes from the grill, the decisions that span + phases, the existing interfaces the stages rely on, and the phase list. + Read [phase-guide.md](phase-guide.md) and write one stage file, + `NN-name/NN.n.json`, for every stage, with its seven outline fields: + revision, title, order, lines, files, and the contracts it provides + and uses. Run `python3 scripts/plan-check.py <plan dir> --outline --repo <repo> --spec <spec> --design <design>` and fix every error it reports before going on; judge each warning. -2. Step 4: read [phase-guide.md](phase-guide.md) and write - `.plan/NN.json` for every phase following it. Run the script without - `--outline`; it checks each phase against the guide and `plan.json`, - checks every spec and design quote and every code citation, and renders - each clean phase to `NN-name.md` in the layout of +2. Step 4: following [phase-guide.md](phase-guide.md), write each phase's + `phase.json` and fill in the rest of every stage file. Write only the + `brief` part of each; `record` belongs to the build scripts. Run the + script without `--outline`; it checks every file against its schema and + the others, checks every spec and design quote and every code citation, + and renders `plan.md` and each clean phase's `phase.md` in the layout of [phase-file-template.md](phase-file-template.md). Fix every error and rerun until it reports none. -3. Change the plan by editing the JSON and rerunning the script, never the - rendered files, until the plan is reported. Then delete `.plan/`. +3. Change the plan only by editing the JSON and rerunning the script, now + and for as long as the plan lives. Never edit `plan.md` or a `phase.md` + by hand: the next run overwrites them. -The script decides what can be checked without judgment: that each -contract is listed by its provider and every user, the build order, that +The script decides what can be checked without judgment: that every +contract a stage uses has a provider, the build order, that files exist or are created first, outcome coverage, tiers from the scores, quotes and citations, and the no-code and length rules. Do not re-check those by hand; spend the reading on what needs judgment. If Python is not -available, write the phase files directly in the layout of -[phase-file-template.md](phase-file-template.md), follow the two guides for -each field, and check each item above by reading. +available, write the JSON all the same, following the two guides for each +field, check each item above by reading, and tell the user that `plan.md` +and the `phase.md` files were not rendered. ## Plan for simple code @@ -184,8 +201,8 @@ each field, and check each item above by reading. ## Review the written plan -Full plans only; a quick plan has no review subagent. When all files are -written and the script reports no errors, review the plan, not any implementation. Use a fresh reviewing subagent each round, +Full plans only; a quick plan has no review subagent. When the whole plan is +written and the script reports no errors and has rendered every phase, review the plan, not any implementation. Use a fresh reviewing subagent each round, since it reads the files as an implementer will, without the planning session's context. Give it [plan-reviewer.md](plan-reviewer.md) unchanged, with its inputs filled in; that file holds what counts as a finding, where diff --git a/plugins/phased-delivery/skills/plan-in-phases/mode-guide.md b/plugins/phased-delivery/skills/plan-in-phases/mode-guide.md index f5fead0..b53caea 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/mode-guide.md +++ b/plugins/phased-delivery/skills/plan-in-phases/mode-guide.md @@ -10,7 +10,7 @@ unrelated web app to show form, not content. | Mode | What happens | | --- | --- | | direct | No plan file. Make the change in context: read the code first, run the tests after. | -| quick | One phase file, checked by `plan-check.py`; no review subagent. Re-score when it is written (below). | +| quick | `plan.json` and one phase folder, checked and rendered by `plan-check.py`; no review subagent. Re-score when it is written (below). | | full | The full process in SKILL.md. | ## The steps @@ -141,10 +141,12 @@ break it? ## Re-scoring The mode holds only while the estimate is true. -- **Quick plan:** when its `plan.json` passes `plan-check.py --outline`, +- **Quick plan:** when its `plan.json` and stage files + (`<plan dir>/01-name/01.n.json`) pass `plan-check.py --outline`, run `plan-mode.py rescore <plan dir> --repo .`. It scores the plan - itself, not your form: one part per stage from its files and `lines`, - the kind and reach from the contract registry, and full whenever the plan + itself, not your form: one part per stage from its stage file's `files` + and `lines`, the kind and reach from the contracts the stage provides and + `plan.json`'s `existing`, and full whenever the plan needs more than one phase or more than 3 stages. If it says full, continue as a full plan. If it says direct, stop planning and make the change directly. 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 d517fdc..1914657 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/model-selection.md +++ b/plugins/phased-delivery/skills/plan-in-phases/model-selection.md @@ -221,7 +221,7 @@ at the top of the script. - **Premium budget, $10 per phase:** the implementer 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 ... - --premium`, and passes `build-check.py spend <phase file>` (the runs' + --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 the rest of the phase. @@ -299,7 +299,7 @@ R = 2, check whether the stage should be split. - Never dispatch a pair below the one `route` prints for the stage's scores without a written reason in the phase's Notes; a `--down` retry after a budget stop is recorded by its Earlier-Attempt trailer, which - `build-check.py commit` writes from the ledger. + `build-check.py commit` writes from the stage file's record. ## Builders in another tool diff --git a/plugins/phased-delivery/skills/plan-in-phases/phase-file-template.md b/plugins/phased-delivery/skills/plan-in-phases/phase-file-template.md index 6112f74..8aceea6 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/phase-file-template.md +++ b/plugins/phased-delivery/skills/plan-in-phases/phase-file-template.md @@ -1,19 +1,66 @@ -# Phase file layout +# Rendered plan layout + +`scripts/plan-check.py` renders both files below from the plan's JSON: +`<plan>/plan.md` from `plan.json` and the stage files, and +`<plan>/NN-name/phase.md` from that folder's `phase.json` and stage files +(see [plan-guide.md](plan-guide.md) and [phase-guide.md](phase-guide.md), +which say what goes in each field). Neither is edited by hand: change the +JSON and run the script again. + +## plan.md + +``` +# Plan: <description> + +Rendered by plan-check.py from plan.json and the stage files; never edited by hand. + +Goal: what exists when every phase is built +Why: what the goal is for + +## Outcomes +- O1 <title>: <what a user can observe> Check: <the run that shows it> + +## Decisions +- D1 (phases 01, 02): <decision> Reason: <why> + +## Contracts +- <kind> `<name>` (provided by NN.n; used by NN.n, user): <shape> + +## Existing interfaces +- <kind> `<name>` (`<path>`; used by NN.n): <shape> + +## Phases + +| Phase | Kind | Status | +| --- | --- | --- | +| [01 <name>](01-<name>/phase.md) | skeleton | planned | +``` + +## phase.md ``` # Phase NN: <name> Implement with the implement-in-phases skill; do not build from this file -without it. Model tiers map to models in [models.md](models.md). -Status: planned | in progress (stages done: …) | built <commit> | reviewed by user +without it. Model tiers map to models in [models.md](../models.md). +Status: planned | in progress (stages done: …) | halted: <reason> | built <commit> Before: what exists when this phase starts After: what exists when it ends (what the user will inspect) +Role: the phase's part in the plan +Why: why the plan needs it, and why here +How: the approach in outline + ## Assumptions - Verified: <assumption> (checked in <file/symbol>) - Open: <assumption>, why it cannot be checked yet, how and when to check it, and what changes if it is wrong +## Size + +Quick plan: +- <the score's evidence; this section appears in a quick plan only> + ## Outcome tests Budget: <the project's, or ~1 min per stage, a few minutes for the suite> @@ -28,11 +75,12 @@ Budget: <the project's, or ~1 min per stage, a few minutes for the suite> | NN.1 | … | middle | first | planned | | NN.2 | … | small | parallel with NN.3 | planned | -## NN.1 <name> +## NN.1 <title> <stage brief> ## Notes -- Decision or adjustment, one line each, with its reason and date. +- Decision or adjustment, one line each, with its reason and date; then + the plan's cross-phase decisions that name this phase. ``` `Tier` comes from scoring the stage with @@ -41,13 +89,14 @@ shows the scores. Plans record tiers, never model names or effort levels; `models.md` maps each tier to a current model and thinking level, chosen from the benchmark report. The implementer re-scores and makes the final choice at dispatch. `Order` says what must come first and what may run in -parallel. The implementer updates the `Status` -columns and line; the planner keeps them `planned`. +parallel. The `Status` column and line come from each file's `record`, +which the build scripts write: a stage is `planned`, `in progress`, `done` +or `reopened` (its brief's `revision` was raised after it was built). ## Stage brief A stage is one focused piece of work that a fresh agent can complete with only -the phase file and the documents it links. Keep it small enough that an agent +`phase.md` and the documents it links. Keep it small enough that an agent holds all of it in mind: one purpose, a handful of files. Split a stage that holds independent responsibilities. @@ -58,7 +107,8 @@ Context: what earlier phases and stages built that this uses, the planning), and the spec and design words that apply, quoted Contracts: every interface, format or name it provides to or uses from something outside the stage, exactly, with who is on the - other side + other side: from its `provides` and `uses`, and the + providers' shapes Files: exact paths it may create, change or delete, each with what it holds afterwards; nothing else Behaviour: what other code, tests or the user can observe, as given / @@ -69,14 +119,13 @@ Tests: the outcome tests it writes or turns on, then any other kind (outcome, integration, unit) and what it proves; a unit test also says why a run-through cannot cover it Done when: observable properties of the changed files +Checks: the commands that show it is done Out of scope: nearby things it must not change Model basis: scores per model-selection.md, e.g. J1 F1 R1 C1 K0 P0 V1 S0 = 5 -> middle ``` -`scripts/plan-check.py` renders this layout from the plan's JSON (see -[plan-guide.md](plan-guide.md) and [phase-guide.md](phase-guide.md), which -say what goes in each field). Write decisions, not instructions to decide: +Write decisions, not instructions to decide: "Decide how X works" is unfinished planning when X is seen outside the stage. The brief settles everything another stage, existing code or the user sees; how the code works inside the stage is the builder's, and the diff --git a/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md b/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md index 77cdb32..584aa77 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md +++ b/plugins/phased-delivery/skills/plan-in-phases/phase-guide.md @@ -1,14 +1,21 @@ -# Phase JSON: field guide - -Each phase is written as `<plan>/.plan/NN.json` in -[phase.schema.json](phase.schema.json); `scripts/plan-check.py` checks it -against this guide and against `plan.json`, and renders it into -`NN-name.md` in the layout of [phase-file-template.md](phase-file-template.md). -Stage order, titles, the outcome-test rows and the cross-phase decisions -come from `plan.json`; the phase JSON does not repeat them. Each field -below has its directions, its limit and an example. The examples use an -unrelated feature (login rate limiting in a web app) so they show form, -not content. +# phase.json and the stage files: field guide + +Each phase is a folder `<plan>/NN-name/` holding `phase.json` in +[phase.schema.json](phase.schema.json) and one stage file per stage, +`NN.n.json` in [stage.schema.json](stage.schema.json). +`scripts/plan-check.py` checks them against this guide and against +`plan.json`, and renders the folder's `phase.md` in the layout of +[phase-file-template.md](phase-file-template.md). The JSON is the plan for +its whole life: it is kept, and `phase.md` is never edited by hand. Each +fact has one home: the cross-phase decisions and the existing interfaces +are in `plan.json`, and a stage's order, files, contracts and tests are in +its stage file only. Each field below has its directions, its limit and an +example. The examples use an unrelated feature (login rate limiting in a +web app) so they show form, not content. + +**Both kinds of file have two parts, `brief` and `record`.** Planning and +revising write only `brief`. The planner never writes `record`: it leaves +it `{}`, and only the build scripts fill it (see "record" at the end). **The one rule behind every field:** the plan names a thing only if something outside its stage uses it: another stage, a test, existing code, @@ -19,13 +26,22 @@ appear anywhere. The builder writes it. Write decisions, not instructions to decide: "decide how X works" is unfinished planning when X is seen outside the stage; when X is seen only inside it, leave it out entirely. -The phase file stands alone: never cite `.plan/` or the ids `plan.json` -uses (C1, D3); name the contract or decision instead. Cite the -repository's code, spec and design. +The rendered phase file stands alone: never cite the decision ids +`plan.json` uses (D3); name the decision instead. Cite the repository's +code, spec and design. No string holds code: no code blocks, and no expressions such as `a.get(b) or c`, `if x is None`, `return foo(bar)`. Names, signatures, -routes, keys and literal values in backticks are fine. +routes, keys and literal values in backticks are fine. `checks` holds +commands and a contract's `shape` holds signatures; both are exempt. + +# phase.json: brief + +## role, why, how +One or two sentences each. `role`: the phase's part in the plan, what it +adds to the phases before it. `why`: why the plan needs this phase, and +why here in the order. `how`: the approach in outline, as the stages take +it; no internals. ## before / after What exists when the phase starts and ends, as things the user can inspect. @@ -36,33 +52,58 @@ At most 6 sentences each. line by line. ## assumptions -One sentence each. `verified`: evidence is the file:line or symbol read. -`open`: evidence says why it cannot be checked yet, how and when to check -it, and what changes if it is wrong. +`text`: one sentence each. `status` `verified`: `evidence` is the +file:line or symbol read. `status` `open`: `evidence` says why it cannot +be checked yet, how and when to check it, and what changes if it is wrong. ## test_budget The project's test time budget for this phase (see test-planning.md). -## stages[].id and goal -`id` as in `plan.json`, in the same order. `goal`: one sentence, at most -250 characters: what is true when done. +## notes +Decisions and adjustments that affect only this phase, one line each, with +the reason and the date. Cross-phase decisions live in `plan.json` and are +added to every phase they name when rendered. -## stages[].context -- `builds_on`: what earlier stages or phases built that this one uses, one - line each, naming the contract. -- `code_read`: existing code this stage relies on, read while planning. - `where` is `path:line` or `path:start-end`; `shows` is a few words that - appear on those lines (a name, a key, a signature fragment), so the - script can confirm the citation; `fact` is one sentence of what is there - that matters. At most 8. -- `design`: spec or design sections that apply: `doc` (spec or design), - `section`, and `quote`, the words that matter copied exactly. The script - looks for the quote in the document; a paraphrase is not a quote, so - write it in `builds_on` or a behaviour rule instead. At most 4. +# Stage file: brief + +One file per stage, named by the stage's id: `NN.n.json` in the folder of +phase NN, numbered from 1 in build order. `--outline` checks the first +seven fields below (`revision` to `uses`) before the rest is written. + +## revision +A number. Planning starts every stage at 1. Every later change to a +brief, prose alone included, raises it by one; the script keeps a hash of +each brief that was built and reports a brief that changed without a +higher `revision`. + +## title +A few words; it heads the stage's brief in `phase.md`. + +## order +`first`, `after NN.n` or `parallel with NN.n`, naming a stage that comes +before it. Order a stage after the stage it depends on, not after the +previous one by habit; the script warns when a stage is ordered after one +it uses nothing from and shares no file with. + +## lines +Your estimate of lines added plus removed in the stage's non-test files: +`under 30`, `30-150` or `over 150`. A quick plan is re-scored from these +(mode-guide.md, "Re-scoring"). + +## files +Every path the stage may change, with `action` `create`, `edit` or +`delete`. Edit and delete paths must exist (or be created by an earlier +stage); create paths must not. Stages that run in parallel share no file. +`role` is one sentence naming the contracts the file holds afterwards. +- Good: `{"path": "app/ratelimit.py", "action": "create", "role": + "holds check_rate and the RateLimited error"}` +- Bad: a role listing the edits inside the file step by step. -## stages[].contracts -Every interface, format or name this stage provides to, or uses from, -something outside it. `shape` is the exact outside view, nothing more: +## provides +Every interface, format or name this stage builds that something outside +it uses. The contract lives here, with its provider, and nowhere else; the +script builds the registry in `plan.md` and each brief's Contracts lines +from these lists. `shape` is the exact outside view, nothing more: | kind | shape holds | | --- | --- | @@ -75,75 +116,120 @@ something outside it. `shape` is the exact outside view, nothing more: | test-helper | signature of a helper tests share | | other | anything else seen outside the stage; `other_reason` says what it is | -One contract per name: `A / B` is two contracts. `shape` limits, in -characters: function, class, error, test-helper 200; config, event, cli -300; format 400; route 500. A shape that needs more is describing -internals: move what others observe into `behaviour`, and drop the rest. -`other` is for a real interface no kind fits; the checker reports every use. -Every contract `plan.json` says this stage provides appears here under the -same name. - -`counterparts` must name who is on the other side: for `provides`, the -stage ids, existing non-test code, `user` or `disk` that use it; for -`uses`, the stage id or existing file that provides it. Tests do not count -as counterparts (except for `test-helper`): what a test observes goes in -`behaviour`, and the test in `tests`. A thing with no counterpart outside -this stage other than tests is internal: leave it out. A function's -decision rules are not a contract, even when tests check them; they are -`behaviour`. +One contract per `name`: `A / B` is two contracts, and no two stages +provide the same name. `shape` limits, in characters: function, class, +error, test-helper 200; config, event, cli 300; format 400; route 500. A +shape that needs more is describing internals: move what others observe +into `behaviour`, and drop the rest. `other` is for a real interface no +kind fits; the checker reports every use. + +`used_by` names only the users outside the plan's stages: existing +non-test files, `user` or `disk`. Stages that use the contract are not +listed here; they name it in their `uses`, and the script derives them. +Tests do not count as users (except for `test-helper`): what a test +observes goes in `behaviour`, and the test in `tests`. A thing no stage +uses and nothing in `used_by` uses other than tests is internal: leave it +out. A function's decision rules are not a contract, even when tests check +them; they are `behaviour`. - Good: `{"kind": "function", "name": "check_rate", "shape": "check_rate(addr: str, now: float) -> bool; True when the attempt is - allowed", "direction": "provides", "counterparts": ["02.1", "app/views.py"]}` + allowed", "used_by": ["app/views.py"]}` - Bad: a contract for `_prune_old(window)`, a private helper only `check_rate` calls; or a shape that says how `check_rate` loops over the timestamps. -## stages[].files -Exactly the paths and actions `plan.json` gives the stage. `role` is one -sentence naming the contracts the file holds afterwards. -- Good: `{"path": "app/ratelimit.py", "action": "create", "role": - "holds check_rate and the RateLimited error"}` -- Bad: a role listing the edits inside the file step by step. +## uses +The names of the contracts this stage relies on: each is a name in an +earlier stage's `provides` or in `plan.json`'s `existing`. The provider +stage is built before every stage that uses it; the script checks both. -## stages[].behaviour -The behavior other code, tests or the user can observe, as given / when / -then, edge cases included. At most 8 items. Each item is a rule a test -could check, not a step of the code. +## goal +One sentence, at most 250 characters: what is true when done. + +## context +- `builds_on`: what earlier stages or phases built that this one uses, one + entry each: `source` the stage id, `what` a line naming the contract. +- `code_read`: existing code this stage relies on, read while planning. + `where` is `path:line` or `path:start-end`; `shows` is a few words that + appear on those lines (a name, a key, a signature fragment), so the + script can confirm the citation; `fact` is one sentence of what is there + that matters. At most 8. +- `design`: spec or design sections that apply: `doc` (`spec` or + `design`), `section`, and `quote`, the words that matter copied exactly. + The script looks for the quote in the document; a paraphrase is not a + quote, so write it in `builds_on` or a behaviour rule instead. At most 4. + +## behaviour +The behavior other code, tests or the user can observe, as `given` / +`when` / `then`, edge cases included. At most 8 items. Each item is a rule +a test could check, not a step of the code. - Good: given 5 failed attempts from one address in the last 60 s, when a sixth arrives, then `check_rate` returns False and the login view answers 429. - Bad: "then iterate the deque, pop entries older than now - 60, compare len to 5". -## stages[].external_inputs +## external_inputs Trust boundaries this stage may check: data from something this code does not control. `source`, the `check`, and what happens `on_failure`. An empty list means no checks. Data from this code or a settled contract gets none. -## stages[].tests -Tests other than the stage's outcome tests, which the rendered brief lists -from `plan.json`: tests the stage must keep passing, deletes, or writes -beyond the outcome tests, each with its kind (outcome, integration, unit) -and what it proves. A unit test also says in `why_unit` why a run-through -cannot cover it. - -## stages[].done_when +## tests +Every test the stage writes, turns on, keeps passing or deletes: `test` as +`path::name` (see test-planning.md), `kind` (`outcome`, `integration`, +`unit`), `action` (`writes`, `turns on`, `keeps passing`, `deletes`) and +`proves`, what it proves. A unit test also says in `why_unit` why a +run-through cannot cover it. + +An outcome test is written once and made to pass once. The stage that +writes it sets `outcome` to the id of the outcome in `plan.json` it shows. +When a later stage makes it pass, that stage lists the same `test` with +action `turns on`; otherwise it passes from the stage that writes it. The +script builds each phase's outcome-test table from these entries and +reports an outcome with no test. + +## done_when Observable properties of the changed files: commands that pass, behavior a -test shows. At most 6. A command must exist in the project (a make target, -a script in the package file); cite where it is defined in `code_read`. +test shows. At most 6. -## stages[].out_of_scope -Nearby things the stage must not change. At most 5. +## checks +The commands that show the stage is done, one per entry, exactly as they +are run from the repository root. A command must exist in the project (a +make target, a script in the package file); cite where it is defined in +`code_read`. An empty list means nothing is run. -## stages[].model_basis -Scores 0–2 per model-selection.md; the script adds them up and picks the -tier with its overrides. For J in this format: internals are always the -builder's, so J is 1, unless the stage copies a near-identical example the -context names (0). A J of 2 means the brief leaves an approach or -something other code sees open: settle it in contracts and behaviour -instead. +## out_of_scope +Nearby things the stage must not change. At most 5. -## notes -Decisions and adjustments that affect only this phase, one line each, with -the reason and the date. Cross-phase decisions live in `plan.json` and are -added to every phase they name when rendered. +## model_basis +The scores `J`, `F`, `R`, `C`, `K`, `P`, `V` and `S`, each 0–2 per +model-selection.md; the script adds them up and picks the tier with its +overrides. For J in this format: internals are always the builder's, so J +is 1, unless the stage copies a near-identical example the context names +(0). A J of 2 means the brief leaves an approach or something other code +sees open: settle it in `provides` and `behaviour` instead. + +## session_only +Optional. `true` for a stage that must be built in the session (see +"Session-only stages" in model-selection.md), such as one that must write +outside the repository. Leave it out otherwise. + +# record + +Never written by planning or revising: write `"record": {}` in +`phase.json` and in every stage file. The fields are listed here so that a +reader of a built plan knows them. + +- `phase.json`: `start_commit`, the commit the build started from; + `preexisting`, the paths with edits present before the build; `runs`, + the revise and review attempts; `findings`, the review's findings by + `index` with a `status` (`open`, `fixed`, `asked`, `answered`); `halt`, + why the build stopped, or null; `built`, the commit that finished the + phase, or null. +- Stage file: `revisions`, the hash of the brief at each revision that was + built; `attempts`, one entry per build attempt with its `revision`, its + number `n`, whether it was a `fix`, the `tool`, `model` and `effort`, + the `exit` code, `tokens`, `cost`, `cap`, `tool_calls`, whether it was + `premium`, its `result` (`accepted`, `failed`, `stopped`, `error`, + `rejected`) and `why`, and its `commit`; `commit`, the latest accepted + commit of the stage. 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 dbc8efc..9cb04a5 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/phase.schema.json +++ b/plugins/phased-delivery/skills/plan-in-phases/phase.schema.json @@ -1,58 +1,27 @@ { "type": "object", "additionalProperties": false, - "required": ["before", "after", "assumptions", "test_budget", "stages", "notes"], + "required": ["brief", "record"], "properties": { - "before": {"type": "string"}, "after": {"type": "string"}, - "assumptions": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["status", "text", "evidence"], - "properties": {"status": {"enum": ["verified", "open"]}, "text": {"type": "string"}, "evidence": {"type": "string"}}}}, - "test_budget": {"type": "string"}, - "stages": {"type": "array", "minItems": 1, "items": {"type": "object", "additionalProperties": false, - "required": ["id", "goal", "context", "contracts", "files", "behaviour", "external_inputs", "tests", - "done_when", "out_of_scope", "model_basis"], + "brief": {"type": "object", "additionalProperties": false, + "required": ["role", "why", "how", "before", "after", "assumptions", "test_budget", "notes"], "properties": { - "id": {"type": "string", "pattern": "^\\d\\d\\.\\d+$"}, - "goal": {"type": "string"}, - "context": {"type": "object", "additionalProperties": false, "required": ["builds_on", "code_read", "design"], - "properties": { - "builds_on": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["source", "what"], "properties": {"source": {"type": "string"}, "what": {"type": "string"}}}}, - "code_read": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["where", "shows", "fact"], "properties": {"where": {"type": "string"}, - "shows": {"type": "string"}, "fact": {"type": "string"}}}}, - "design": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["doc", "section", "quote"], "properties": {"doc": {"enum": ["spec", "design"]}, - "section": {"type": "string"}, "quote": {"type": "string"}}}}}}, - "contracts": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["kind", "name", "shape", "direction", "counterparts"], - "properties": { - "kind": {"enum": ["function", "class", "route", "format", "config", "error", "event", "cli", "test-helper", "other"]}, - "name": {"type": "string"}, "shape": {"type": "string"}, - "direction": {"enum": ["provides", "uses"]}, - "counterparts": {"type": "array", "minItems": 1, "items": {"type": "string"}}, - "other_reason": {"type": "string"}}}}, - "files": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["path", "action", "role"], - "properties": {"path": {"type": "string"}, "action": {"enum": ["create", "edit", "delete"]}, "role": {"type": "string"}}}}, - "behaviour": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["given", "when", "then"], - "properties": {"given": {"type": "string"}, "when": {"type": "string"}, "then": {"type": "string"}}}}, - "external_inputs": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["source", "check", "on_failure"], - "properties": {"source": {"type": "string"}, "check": {"type": "string"}, "on_failure": {"type": "string"}}}}, - "tests": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["test", "kind", "action", "proves"], - "properties": {"test": {"type": "string"}, "kind": {"enum": ["outcome", "integration", "unit"]}, - "action": {"enum": ["writes", "turns on", "keeps passing", "deletes"]}, - "proves": {"type": "string"}, "why_unit": {"type": "string"}}}}, - "done_when": {"type": "array", "items": {"type": "string"}}, - "out_of_scope": {"type": "array", "items": {"type": "string"}}, - "model_basis": {"type": "object", "additionalProperties": false, - "required": ["J", "F", "R", "C", "K", "P", "V", "S"], - "properties": {"J": {"type": "integer", "minimum": 0, "maximum": 2}, "F": {"type": "integer", "minimum": 0, "maximum": 2}, - "R": {"type": "integer", "minimum": 0, "maximum": 2}, "C": {"type": "integer", "minimum": 0, "maximum": 2}, - "K": {"type": "integer", "minimum": 0, "maximum": 2}, "P": {"type": "integer", "minimum": 0, "maximum": 2}, - "V": {"type": "integer", "minimum": 0, "maximum": 2}, "S": {"type": "integer", "minimum": 0, "maximum": 2}}}}}}, - "notes": {"type": "array", "items": {"type": "string"}} + "role": {"type": "string"}, "why": {"type": "string"}, "how": {"type": "string"}, + "before": {"type": "string"}, "after": {"type": "string"}, + "assumptions": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["status", "text", "evidence"], + "properties": {"status": {"enum": ["verified", "open"]}, "text": {"type": "string"}, "evidence": {"type": "string"}}}}, + "test_budget": {"type": "string"}, + "notes": {"type": "array", "items": {"type": "string"}}}}, + "record": {"type": "object", "additionalProperties": false, + "properties": { + "start_commit": {"type": "string"}, + "preexisting": {"type": "array", "items": {"type": "string"}}, + "runs": {"type": "array", "items": {"type": "object"}}, + "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": {}}} } } diff --git a/plugins/phased-delivery/skills/plan-in-phases/plan-guide.md b/plugins/phased-delivery/skills/plan-in-phases/plan-guide.md index 477e8d7..3305eae 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/plan-guide.md +++ b/plugins/phased-delivery/skills/plan-in-phases/plan-guide.md @@ -1,18 +1,28 @@ # plan.json: field guide -The plan's shared layer is written as `<plan>/.plan/plan.json` in -[plan.schema.json](plan.schema.json): the outcomes from the grill, the -decisions that span phases, the contract registry, the outcome tests, and -the phases with their stages. `scripts/plan-check.py` checks it before any -phase JSON is written (`--outline`), and again with every phase. Examples -use an unrelated feature (login rate limiting) to show form, not content. +The plan's shared layer is written as `<plan>/plan.json` in +[plan.schema.json](plan.schema.json): what the plan is for, the outcomes +from the grill, the decisions that span phases, the existing interfaces +the stages rely on, and the list of phases. Everything about a stage is in +its stage file ([phase-guide.md](phase-guide.md)), nowhere else. +`scripts/plan-check.py` checks plan.json together with the outline fields +of the stage files (`--outline`) before the rest is written, and again +with every phase; it renders `plan.md` from it. The JSON is the plan for +its whole life: it is kept, and `plan.md` is never edited by hand. +plan.json has no `record`. Examples use an unrelated feature (login rate +limiting) to show form, not content. -**The rule behind every field** is the same as for phase files: the plan -names a thing only if something outside the stage that builds it uses it: -another stage, existing code, the user, or a file on disk. Those things are -given exactly. Internals (private functions, branches, statement order) -appear nowhere. No string holds code; names, signatures, routes, keys and -literal values in backticks are fine. +**The rule behind every field** is the same as for the stage files: the +plan names a thing only if something outside the stage that builds it uses +it: another stage, existing code, the user, or a file on disk. Those +things are given exactly. Internals (private functions, branches, +statement order) appear nowhere. No string holds code; names, signatures, +routes, keys and literal values in backticks are fine. + +## description, goal, why +`description`: a few words naming the plan; it is `plan.md`'s title. +`goal`: one or two sentences on what exists when every phase is built. +`why`: one or two sentences on what the goal is for. ## size `verdict` `quick` or `full`, the mode `scripts/plan-mode.py score` @@ -20,72 +30,58 @@ printed (see mode-guide.md); `evidence` its total and one line per part with its score, and any re-score. ## outcomes -The outcomes the grill settled (see grill.md), O1.. in order. +The outcomes the grill settled (see grill.md), `id` O1.. in order. +- `title`: a few words naming the outcome. - `observable`: what a user can do or see afterwards, through which entry point (a command, a route, a page, a file), with the concrete values that show it. At most 3 sentences. - `how_to_check`: the run that shows it: the command, request or test client call and what its result must contain. If you cannot write it, the goal is not understood yet: go back to the grill. -- `sources`: the spec or design lines it comes from: `doc`, `section`, and - `quote`, the words copied exactly; the script looks for them. +- `sources`: the spec or design lines it comes from: `doc` (`spec` or + `design`), `section`, and `quote`, the words copied exactly; the script + looks for them. - Good: observable "six failed logins from one address within 60 s get HTTP 429 on the sixth"; how_to_check "test client POSTs /login six times with a wrong password from 10.0.0.1; the sixth answer is 429". - Bad: "rate limiting works well"; "the limiter uses a deque". +Every outcome needs at least one outcome test. The tests are not listed +here: the stage that writes one names the outcome in its `tests` (see +phase-guide.md), and the script builds the outcome-test tables from those. + ## decisions -Every decision that spans phases, D1.. in order: `text` the decision, +Every decision that spans phases, `id` D1.. in order: `text` the decision, `reason` why, `phases` the phase numbers it affects (or `all`); it is added to those phases' Notes when rendered. A departure from the spec or -design names the words it departs from in `departs_from` and sets -`user_answer`: `given` when the user agreed in the grill, `assumed` when -the user could not be asked. A decision that affects one phase only goes in -that phase's `notes`. +design names the words it departs from in `departs_from` (`doc`, +`section`, `quote`, as in an outcome's sources) and sets `user_answer`: +`given` when the user agreed in the grill, `assumed` when the user could +not be asked. A decision that affects one phase only goes in that phase's +`notes`. -## contracts -The registry: every interface one stage provides and another stage or -existing code uses, and every existing interface a stage relies on. -- `id` C1.., `kind` as in [phase-guide.md](phase-guide.md), `name` one - contract per name. -- `shape`: the exact outside view. Limits in characters: function, class, - error, test-helper 200; config, event, cli 300; format 400; route 500. - A longer shape is describing internals. -- `provided_by`: the stage id that builds it, or `existing:<path>` for code - already in the repository (the path must exist). -- `used_by`: stage ids, existing non-test files, `user` or `disk`. Tests do - not count, except for `test-helper`. Every stage listed here must list - the contract in its `uses`, and the other way round; the script checks - both directions and the build order (a provider stage comes before every - user). -- Good: `{"id": "C4", "kind": "function", "name": "check_rate", "shape": - "check_rate(addr: str, now: float) -> bool; True when allowed", - "provided_by": "02.1", "used_by": ["03.1"]}` -- Bad: a contract for a private helper; `used_by` naming only a test file. +## existing +Every interface that is already in the repository and that a stage relies +on, listed once. Interfaces the plan builds are not listed here: the stage +that builds one holds it in its `provides`. +- `kind` as in [phase-guide.md](phase-guide.md), `name` one interface per + name; no stage may provide the same name. +- `shape`: the exact outside view, within the limits phase-guide.md gives + per kind. +- `path`: the file that holds it, optionally `path:line`; it must exist. +- A stage that relies on it names it in its `uses`. +- Good: `{"kind": "route", "name": "login", "shape": "POST /login form + user, password; 302 to next on success, 401 on a wrong password", + "path": "app/views.py:40"}` +- Bad: an entry for a private helper; an entry no stage uses. -## outcome_tests -Every outcome with at least one row: `test` as `path::name` (see -test-planning.md), `written_in` and `passes_from` stage ids. A test is -written once and made to pass once; `written_in` is not after -`passes_from`. The rendered phase files list these rows; stage briefs do -not repeat them. +## docs +The paths of the `spec` and the `design`, relative to the repository, when +they exist. The script checks every quote against them. ## phases -In build order, numbered 01.. . `file` `NN-short-name.md`, `kind` per -phase-kinds.md (`behaviour` for a phase that is one behavior target). - -## phases[].stages -In build order within the phase. -- `id` NN.n, `title` a few words. -- `files`: every path the stage may change, with `create`, `edit` or - `delete`. Edit and delete paths must exist (or be created by an earlier - stage); create paths must not. Stages that run in parallel share no - file. -- `lines`: your estimate of lines added plus removed in the stage's - non-test files: `under 30`, `30-150` or `over 150`. A quick plan is - re-scored from these (mode-guide.md, "Re-scoring"). -- `provides` / `uses`: contract ids, matching the registry. -- `order`: `first`, `after NN.n` or `parallel with NN.n`, naming a stage - listed before it. Order a stage after the stage it depends on, not after - the previous one by habit; the script warns when a stage is ordered - after one it uses nothing from. +In build order: `phase` the number, 01.. ; `dir` the phase's folder, +`NN-short-name` in lower case, digits and hyphens, starting with that +number; `name` the phase's title; `kind` per phase-kinds.md (`behaviour` +for a phase that is one behavior target). Each folder holds the phase's +`phase.json` and one stage file per stage. diff --git a/plugins/phased-delivery/skills/plan-in-phases/plan-reviewer.md b/plugins/phased-delivery/skills/plan-in-phases/plan-reviewer.md index 76807e1..fb9916d 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/plan-reviewer.md +++ b/plugins/phased-delivery/skills/plan-in-phases/plan-reviewer.md @@ -6,7 +6,8 @@ from the plan's `models.md` (see [model-selection.md](model-selection.md)). Inputs the orchestrator fills in: -- Plan directory: `<path>` +- Plan directory: `<path>`, holding the rendered `plan.md` and one + `NN-name/phase.md` per phase, beside the JSON they are rendered from - Specification and design: `<paths or links>` - Project instructions: `<paths, such as CLAUDE.md or AGENTS.md>` - Round: `<n>`; for rounds after the first, the previous round's findings and @@ -24,8 +25,8 @@ need to be perfect. Report only the finding types listed under "What counts as a finding", each with evidence; anything else is not a finding, however true. Do not report wording or style. -`scripts/plan-check.py` has already checked what needs no judgment: each -contract is listed by its provider and every user, providers are built +`scripts/plan-check.py` has already checked what needs no judgment: every +contract a stage uses has a provider, providers are built before users, edited files exist or are created first, parallel stages share no file, every outcome has a test written before it must pass, tiers follow the scores, spec and design quotes appear in the documents, cited @@ -36,8 +37,10 @@ there. ## How to review -1. Read the project instructions, the specification, the design and every - phase file in full. +1. Read the project instructions, the specification, the design, `plan.md` + and every `phase.md` in full. They are rendered from the plan's JSON + (`plan.json`, each `phase.json` and the stage files) and show all of it + that is planned; open the JSON only to name a field in a finding. 2. Read the code. For every name, signature, path, format and behavior a brief takes from existing code, open that code and check it. Do not trust the plan's claims, its cited files or your own memory of the codebase. @@ -118,7 +121,7 @@ Examples (from an unrelated feature, login rate limiting): List findings, most serious first. For each: - **Type:** one of the types above. -- **Where:** phase file and stage. +- **Where:** phase folder and stage, or `plan.json`. - **Problem:** what is wrong or missing. - **Evidence:** the spec or design section with the words quoted, or `path:line` in the code, and the plan text that says otherwise. diff --git a/plugins/phased-delivery/skills/plan-in-phases/plan.schema.json b/plugins/phased-delivery/skills/plan-in-phases/plan.schema.json index 7642af2..3640dd8 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/plan.schema.json +++ b/plugins/phased-delivery/skills/plan-in-phases/plan.schema.json @@ -1,12 +1,13 @@ { "type": "object", "additionalProperties": false, - "required": ["size", "outcomes", "decisions", "contracts", "outcome_tests", "phases"], + "required": ["description", "goal", "why", "size", "outcomes", "decisions", "existing", "phases"], "definitions": { "source": {"type": "object", "additionalProperties": false, "required": ["doc", "section", "quote"], "properties": {"doc": {"enum": ["spec", "design"]}, "section": {"type": "string"}, "quote": {"type": "string"}}} }, "properties": { + "description": {"type": "string"}, "goal": {"type": "string"}, "why": {"type": "string"}, "size": {"type": "object", "additionalProperties": false, "required": ["verdict", "evidence"], "properties": {"verdict": {"enum": ["full", "quick"]}, "evidence": {"type": "array", "items": {"type": "string"}}}}, "outcomes": {"type": "array", "minItems": 1, "items": {"type": "object", "additionalProperties": false, @@ -21,33 +22,18 @@ "phases": {"type": "array", "minItems": 1, "items": {"type": "string", "pattern": "^(\\d\\d|all)$"}}, "user_answer": {"enum": ["given", "assumed"]}, "departs_from": {"$ref": "#/definitions/source"}}}}, - "contracts": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["id", "kind", "name", "shape", "provided_by", "used_by"], - "properties": {"id": {"type": "string", "pattern": "^C\\d+$"}, + "existing": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["kind", "name", "shape", "path"], + "properties": { "kind": {"enum": ["function", "class", "route", "format", "config", "error", "event", "cli", "test-helper", "other"]}, - "name": {"type": "string"}, "shape": {"type": "string"}, - "provided_by": {"type": "string"}, - "used_by": {"type": "array", "minItems": 1, "items": {"type": "string"}}, - "other_reason": {"type": "string"}}}}, - "outcome_tests": {"type": "array", "items": {"type": "object", "additionalProperties": false, - "required": ["outcome", "test", "written_in", "passes_from"], - "properties": {"outcome": {"type": "string", "pattern": "^O\\d+$"}, "test": {"type": "string"}, - "written_in": {"type": "string"}, "passes_from": {"type": "string"}}}}, + "name": {"type": "string"}, "shape": {"type": "string"}, "path": {"type": "string"}}}}, + "docs": {"type": "object", "additionalProperties": false, + "properties": {"spec": {"type": "string"}, "design": {"type": "string"}}}, "phases": {"type": "array", "minItems": 1, "items": {"type": "object", "additionalProperties": false, - "required": ["phase", "file", "name", "kind", "stages"], + "required": ["phase", "dir", "name", "kind"], "properties": {"phase": {"type": "string", "pattern": "^\\d\\d$"}, - "file": {"type": "string", "pattern": "^\\d\\d-[a-z0-9-]+\\.md$"}, + "dir": {"type": "string", "pattern": "^\\d\\d-[a-z0-9-]+$"}, "name": {"type": "string"}, - "kind": {"enum": ["skeleton", "interfaces", "internals", "integration", "behaviour"]}, - "stages": {"type": "array", "minItems": 1, "items": {"type": "object", "additionalProperties": false, - "required": ["id", "title", "files", "lines", "provides", "uses", "order"], - "properties": {"id": {"type": "string", "pattern": "^\\d\\d\\.\\d+$"}, "title": {"type": "string"}, - "files": {"type": "array", "minItems": 1, "items": {"type": "object", "additionalProperties": false, - "required": ["path", "action"], - "properties": {"path": {"type": "string"}, "action": {"enum": ["create", "edit", "delete"]}}}}, - "lines": {"enum": ["under 30", "30-150", "over 150"]}, - "provides": {"type": "array", "items": {"type": "string", "pattern": "^C\\d+$"}}, - "uses": {"type": "array", "items": {"type": "string", "pattern": "^C\\d+$"}}, - "order": {"type": "string", "pattern": "^(first|after \\d\\d\\.\\d+|parallel with \\d\\d\\.\\d+)$"}}}}}}} + "kind": {"enum": ["skeleton", "interfaces", "internals", "integration", "behaviour"]}}}} } } diff --git a/plugins/phased-delivery/skills/plan-in-phases/revising.md b/plugins/phased-delivery/skills/plan-in-phases/revising.md index 30f3fba..0c87d55 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/revising.md +++ b/plugins/phased-delivery/skills/plan-in-phases/revising.md @@ -5,7 +5,13 @@ implementation may show that an earlier decision, up to the architecture, is wrong. Then change it, alter it or drop it, however much of the plan that touches; do not build on a decision known to be wrong. -The implementer revises the next phase file before building it (see +The plan is its JSON: `plan.json`, each phase folder's `phase.json` and its +stage files. Every revision edits the `brief` parts of the JSON and reruns +`scripts/plan-check.py`, which checks the plan again against the code as it +now is and renders `plan.md` and each `phase.md`. Never edit the rendered +files, and never write a `record`; the build scripts own those. + +The implementer revises the next phase before building it (see implement-in-phases), rechecking that phase's open assumptions against the code as it now is. When a review or implementation finds work the plan does not cover or a decision that does not hold: @@ -16,13 +22,23 @@ not cover or a decision that does not hold: 3. Find the highest level affected and update the owning phase and its peers there; do not tack a cleanup stage onto the end when an earlier contract is what is wrong. -4. Recheck built stages the change affects, and plan the rework of built code - as stages in the affected phases. -5. When the change touches architecture or a contract other phases use, +4. Recheck built stages the change affects. Plan the rework of built code + by revising those stages' briefs in place, not by adding cleanup stages: + a built stage whose brief has a higher `revision` than the one it was + built at is reopened, and is rebuilt against the new brief as a fix. Add + a stage file, numbered after the phase's existing ones, only for work + that belongs to no existing stage. +5. Raise `revision` by one in the brief of every stage whose brief you + changed, whatever the change, prose included: `plan-check.py` reports a + brief that changed since it was built without a higher `revision`. +6. Rerun `plan-check.py <plan dir> --repo <repo>` (with `--phase NN` to + limit the repository checks to the phase about to be built) and fix + every error. +7. When the change touches architecture or a contract other phases use, review the affected phases again before building on them. -6. Never widen a stage to absorb the fix, or rewrite the plan to excuse +8. Never widen a stage to absorb the fix, or rewrite the plan to excuse unplanned edits. -7. If the change contradicts the approved spec or design, ask the user. +9. If the change contradicts the approved spec or design, ask the user. -Replace text that is no longer true; record why in the phase's Notes. Git holds -the history. +Replace text that is no longer true; record why in the phase's `notes` +(`phase.json`). Git holds the history. diff --git a/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json b/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json new file mode 100644 index 0000000..949fcd6 --- /dev/null +++ b/plugins/phased-delivery/skills/plan-in-phases/stage.schema.json @@ -0,0 +1,73 @@ +{ + "type": "object", "additionalProperties": false, + "required": ["brief", "record"], + "properties": { + "brief": {"type": "object", "additionalProperties": false, + "required": ["revision", "title", "order", "lines", "files", "provides", "uses", "goal", "context", + "behaviour", "external_inputs", "tests", "done_when", "checks", "out_of_scope", "model_basis"], + "properties": { + "revision": {"type": "integer", "minimum": 1}, + "title": {"type": "string"}, + "order": {"type": "string", "pattern": "^(first|after \\d\\d\\.\\d+|parallel with \\d\\d\\.\\d+)$"}, + "lines": {"enum": ["under 30", "30-150", "over 150"]}, + "files": {"type": "array", "minItems": 1, "items": {"type": "object", "additionalProperties": false, + "required": ["path", "action", "role"], + "properties": {"path": {"type": "string"}, "action": {"enum": ["create", "edit", "delete"]}, "role": {"type": "string"}}}}, + "provides": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["kind", "name", "shape", "used_by"], + "properties": { + "kind": {"enum": ["function", "class", "route", "format", "config", "error", "event", "cli", "test-helper", "other"]}, + "name": {"type": "string"}, "shape": {"type": "string"}, + "used_by": {"type": "array", "items": {"type": "string"}}, + "other_reason": {"type": "string"}}}}, + "uses": {"type": "array", "items": {"type": "string"}}, + "goal": {"type": "string"}, + "context": {"type": "object", "additionalProperties": false, "required": ["builds_on", "code_read", "design"], + "properties": { + "builds_on": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["source", "what"], "properties": {"source": {"type": "string"}, "what": {"type": "string"}}}}, + "code_read": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["where", "shows", "fact"], "properties": {"where": {"type": "string"}, + "shows": {"type": "string"}, "fact": {"type": "string"}}}}, + "design": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["doc", "section", "quote"], "properties": {"doc": {"enum": ["spec", "design"]}, + "section": {"type": "string"}, "quote": {"type": "string"}}}}}}, + "behaviour": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["given", "when", "then"], + "properties": {"given": {"type": "string"}, "when": {"type": "string"}, "then": {"type": "string"}}}}, + "external_inputs": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["source", "check", "on_failure"], + "properties": {"source": {"type": "string"}, "check": {"type": "string"}, "on_failure": {"type": "string"}}}}, + "tests": {"type": "array", "items": {"type": "object", "additionalProperties": false, + "required": ["test", "kind", "action", "proves"], + "properties": {"test": {"type": "string"}, "kind": {"enum": ["outcome", "integration", "unit"]}, + "action": {"enum": ["writes", "turns on", "keeps passing", "deletes"]}, + "proves": {"type": "string"}, "why_unit": {"type": "string"}, + "outcome": {"type": "string", "pattern": "^O\\d+$"}}}}, + "done_when": {"type": "array", "items": {"type": "string"}}, + "checks": {"type": "array", "items": {"type": "string"}}, + "out_of_scope": {"type": "array", "items": {"type": "string"}}, + "model_basis": {"type": "object", "additionalProperties": false, + "required": ["J", "F", "R", "C", "K", "P", "V", "S"], + "properties": {"J": {"type": "integer", "minimum": 0, "maximum": 2}, "F": {"type": "integer", "minimum": 0, "maximum": 2}, + "R": {"type": "integer", "minimum": 0, "maximum": 2}, "C": {"type": "integer", "minimum": 0, "maximum": 2}, + "K": {"type": "integer", "minimum": 0, "maximum": 2}, "P": {"type": "integer", "minimum": 0, "maximum": 2}, + "V": {"type": "integer", "minimum": 0, "maximum": 2}, "S": {"type": "integer", "minimum": 0, "maximum": 2}}}, + "session_only": {"type": "boolean"}}}, + "record": {"type": "object", "additionalProperties": false, + "properties": { + "revisions": {"type": "object"}, + "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"], + "properties": { + "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": {}, + "premium": {"type": "boolean"}, + "result": {"enum": ["accepted", "failed", "stopped", "error", "rejected"]}, + "why": {"type": "string"}, "commit": {"type": "string"}}}}, + "commit": {"type": "string"}}} + } +} diff --git a/plugins/phased-delivery/skills/plan-in-phases/structured-planning-notes.md b/plugins/phased-delivery/skills/plan-in-phases/structured-planning-notes.md index 253c92c..d6de15e 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/structured-planning-notes.md +++ b/plugins/phased-delivery/skills/plan-in-phases/structured-planning-notes.md @@ -178,3 +178,33 @@ plan-reviewer.md lost these two, since only full plans are reviewed now: criterion in plan-in-phases. Report any criterion that fails. | `size-wrong` | the plan claims to be small and a size criterion fails on re-measuring | | + +## The JSON is kept (2026-11-24) + +Until now the JSON lived in a `.plan/` folder (`.plan/plan.json` and one +`.plan/NN.json` per phase) that the planner deleted once the plan was +reported; the rendered `NN-name.md` files were then the plan, and revising +edited their text. That left two homes for each fact as soon as a script +needed one: the build scripts read stage tables and briefs back out of +Markdown, and a revision could change the prose a person reads without +changing what a script reads. + +Now the JSON is the plan's only source for its whole life: `plan.json`, +each phase folder's `phase.json` and one stage file per stage. +`plan-check.py` renders `plan.md` and each `phase.md`, which are never +edited by hand, and nothing deletes the JSON. Why: + +- **One home per fact.** The scripts and the people read the same stage, + so a revision cannot leave the two apart. Contracts live with the stage + that provides them; the registry and the stage and outcome-test tables + are built from the stage files instead of being repeated in `plan.json`. +- **Two writers never share a part of a file.** A stage file and + `phase.json` are `{brief, record}`: planning and revising write `brief`, + only the build scripts write `record`. +- **A changed brief is visible.** `record` keeps a hash of the brief each + attempt built, so a brief changed without a higher `revision` is an + error, and a built stage is reopened by revising its brief in place + instead of adding a cleanup stage. + +Plans in the old layout are not converted; the built ones keep their md +files as history. diff --git a/plugins/phased-delivery/tests/test_build_check.py b/plugins/phased-delivery/tests/test_build_check.py index 2482e32..f79984e 100644 --- a/plugins/phased-delivery/tests/test_build_check.py +++ b/plugins/phased-delivery/tests/test_build_check.py @@ -8,41 +8,42 @@ SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" SCRIPT = SCRIPTS / "build-check.py" -PHASE = "docs/plan/01-demo.md" +PLAN_DIR = "docs/plan" +PHASE = "docs/plan/01-demo" +PHASE_MD = PHASE + "/phase.md" 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"} -PHASE_TEXT = """# Phase 01: Demo - -Implement with the implement-in-phases skill; do not build from this file -without it. Model tiers map to models in [models.md](models.md). -Status: planned -Before: nothing. -After: a and b exist. - -## Stages - -| Stage | Goal | Tier | Order | Status | -| --- | --- | --- | --- | --- | -| 01.1 | Write a | middle | first | planned | -| 01.2 | Write b | small | after 01.1 | planned | - -## Notes -none -""" - -REVISION = { - "phase": "01", - "stages": [ - {"id": "01.1", "title": "Write a", "files": [{"path": "src/a.txt", "action": "edit"}, - {"path": "src/done.txt", "action": "create"}], - "checks": ["test -f src/done.txt"], "scores": "J1F1R0C0K0P0V0S0", "tier": "middle"}, - {"id": "01.2", "title": "Write b", "files": [{"path": "src/b.txt", "action": "edit"}], - "checks": [], "scores": "J0F0R0C0K0P0V0S0", "tier": "small"}, - ], - "assumptions": [], - "adjustments": [], +PLAN = {"description": "Demo", "goal": "a and b exist.", "why": "w", + "size": {"verdict": "full", "evidence": ["two stages"]}, + "outcomes": [{"id": "O1", "title": "a", "observable": "a exists", "how_to_check": "read it", + "sources": [{"doc": "spec", "section": "Goals", "quote": "a and b 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": "a and b exist.", + "assumptions": [], "test_budget": "1 s", "notes": []}, + "record": {}} + + +def stage(title, order, files, checks, basis, tests=()): + return {"brief": {"revision": 1, "title": title, "order": order, "lines": "under 30", "files": files, + "provides": [], "uses": [], "goal": title, + "context": {"builds_on": [], "code_read": [], "design": []}, + "behaviour": [], "external_inputs": [], "tests": list(tests), "done_when": ["it exists"], + "checks": checks, "out_of_scope": [], + "model_basis": {**dict.fromkeys("JFRCKPVS", 0), **basis}}, + "record": {}} + + +STAGES = { + "01.1": stage("Write a", "first", [{"path": "src/a.txt", "action": "edit", "role": "a"}, + {"path": "src/done.txt", "action": "create", "role": "done"}], + ["test -f src/done.txt"], {"J": 1, "F": 1}, + [{"test": "src/done.txt", "kind": "outcome", "action": "writes", "proves": "a exists", + "outcome": "O1"}]), + "01.2": stage("Write b", "after 01.1", [{"path": "src/b.txt", "action": "edit", "role": "b"}], [], {}), } REVIEW = {"findings": [], "verdict": "ready"} @@ -53,23 +54,38 @@ def git(repo, *args): capture_output=True, text=True, check=True).stdout +def write_json(path, data): + path.write_text(json.dumps(data)) + + @pytest.fixture def repo(tmp_path): - """A git repository with one commit holding a phase file, its revision JSON and two stage files.""" + """A git repository with one commit holding a plan with one phase folder of two stage files.""" r = tmp_path / "repo" (r / "src").mkdir(parents=True) - (r / "docs/plan/.build").mkdir(parents=True) + (r / PHASE).mkdir(parents=True) (r / "src/a.txt").write_text("a\n") (r / "src/b.txt").write_text("b\n") (r / "src/other.txt").write_text("other\n") - (r / PHASE).write_text(PHASE_TEXT) - (r / "docs/plan/.build/01-revision.json").write_text(json.dumps(REVISION)) + write_json(r / PLAN_DIR / "plan.json", PLAN) + write_json(r / PHASE / "phase.json", PHASE_JSON) + for sid, s in STAGES.items(): + write_json(r / PHASE / f"{sid}.json", s) git(r, "init", "-q") git(r, "add", ".") git(r, "commit", "-q", "-m", "base") return r +def stage_file(repo, sid): + return json.loads((repo / PHASE / f"{sid}.json").read_text()) + + +def edit_brief(repo, sid, **fields): + s = stage_file(repo, sid) + write_json(repo / PHASE / f"{sid}.json", {**s, "brief": {**s["brief"], **fields}}) + + def bc(repo, *args): return subprocess.run(["python3", str(SCRIPT), *args], cwd=repo, env={**os.environ, **GIT_ENV}, capture_output=True, text=True) @@ -98,12 +114,17 @@ def stats(repo): capture_output=True, text=True, check=True).stdout +def phase_md(repo): + return (repo / PHASE_MD).read_text() + + def test_accepted_stage_commit(repo): assert bc(repo, "start", PHASE).returncode == 0 build_a(repo) result = record(repo, "01.1", "opus", "high", 0, "1200", "0.40", "--tool-calls", "7") assert result.returncode == 0, result.stdout + result.stderr assert json.loads(result.stdout)["result"] == "accepted" + assert [x["result"] for x in stage_file(repo, "01.1")["record"]["attempts"]] == ["accepted"] done = bc(repo, "commit", PHASE, "01.1", "--extra-trailer", "Co-Authored-By: x <x@example.invalid>") assert done.returncode == 0, done.stderr assert sorted(changed(repo)) == ["src/a.txt", "src/done.txt"] @@ -114,7 +135,7 @@ def test_accepted_stage_commit(repo): "Co-Authored-By: x <x@example.invalid>"): assert line in msg assert "| opus | high | claude-code | 1 | 1/1 |" in stats(repo) - text = (repo / PHASE).read_text() + text = phase_md(repo) assert "| 01.1 | Write a | middle | first | done |" in text assert "Status: in progress (stages done: 01.1)" in text @@ -177,20 +198,20 @@ def test_preexisting_edits_left_alone(repo): def test_invalid_json_refused(repo): - bad = json.loads(json.dumps(REVISION)) - del bad["stages"][0]["checks"] - (repo / "docs/plan/.build/01-revision.json").write_text(json.dumps(bad)) + bad = stage_file(repo, "01.1") + del bad["brief"]["checks"] + write_json(repo / PHASE / "01.1.json", bad) result = bc(repo, "start", PHASE) assert result.returncode == 1 assert "checks" in result.stdout - assert not (repo / "docs/plan/.build/01-ledger.json").exists() + assert json.loads((repo / PHASE / "phase.json").read_text())["record"] == {} - (repo / "docs/plan/.build/01-revision.json").write_text(json.dumps(REVISION)) + write_json(repo / PHASE / "01.1.json", STAGES["01.1"]) assert bc(repo, "start", PHASE).returncode == 0 head = git(repo, "rev-parse", "HEAD") review = {"findings": [{"type": "style", "severity": "blocking", "stage": "01.1", "file": "src/a.txt", "line": 1, "evidence": "x", "action": "fix"}], "verdict": "not-ready"} - (repo / "docs/plan/.build/01-review.json").write_text(json.dumps(review)) + write_json(repo / PHASE / "review.json", review) result = bc(repo, "finish", PHASE) assert result.returncode == 1 assert "type" in result.stdout @@ -202,7 +223,7 @@ def test_finish_phase(repo): build_a(repo) record(repo, "01.1") bc(repo, "commit", PHASE, "01.1") - (repo / "docs/plan/.build/01-review.json").write_text(json.dumps(REVIEW)) + write_json(repo / PHASE / "review.json", REVIEW) assert bc(repo, "finish", PHASE).returncode == 1 # 01.2 has no commit (repo / "src/b.txt").write_text("b2\n") record(repo, "01.2", "haiku", "high") @@ -210,11 +231,12 @@ def test_finish_phase(repo): stage_commit = git(repo, "rev-parse", "--short", "HEAD").strip() result = bc(repo, "finish", PHASE) assert result.returncode == 0, result.stdout + result.stderr - text = (repo / PHASE).read_text() + text = phase_md(repo) assert f"Status: built {stage_commit}" in text assert "| 01.1 | Write a | middle | first | done |" in text and "| 01.2 | Write b | small | after 01.1 | done |" in text assert f"Phase: {PHASE}" in message(repo) - assert set(changed(repo)) >= {PHASE, "docs/plan/.build/01-ledger.json", "docs/plan/.build/01-review.json"} + assert set(changed(repo)) >= {PHASE_MD, f"{PHASE}/phase.json", f"{PHASE}/01.1.json", f"{PHASE}/review.json", + f"{PLAN_DIR}/plan.md"} assert git(repo, "status", "--porcelain") == "" @@ -229,6 +251,16 @@ def test_fix_commit(repo): msg = message(repo) assert "Fixes-Stage: 01.1" in msg and "Stage: 01.1\n" not in msg.replace("Fixes-Stage", "") assert "| opus | high | claude-code | 1 | 1/1 | 0/1 | 0 | 1 |" in stats(repo) + # a raised revision reopens the stage; its rebuild is a fix, with a changed file and then with none + for revision, content in ((2, "a4\n"), (3, None)): + edit_brief(repo, "01.1", revision=revision, goal=f"Write a, revision {revision}") + if content: + (repo / "src/a.txt").write_text(content) + assert record(repo, "01.1", "sonnet", "medium", 0, "300", "0.05", "--fix").returncode == 0 + assert bc(repo, "commit", PHASE, "01.1").returncode == 0 + assert "Fixes-Stage: 01.1" in message(repo) + assert changed(repo) == (["src/a.txt"] if content else []) + assert f"| 01.1 | Write a, revision {revision} | middle | first | done |" in phase_md(repo) def test_rename_from_outside_fails(repo): @@ -258,3 +290,74 @@ def test_reject_budget_stop_then_retry(repo): assert "Earlier-Attempt: haiku high 400 budget reached" in msg assert "Earlier-Attempt: sonnet high 1200 tests check nothing see diff" in msg assert "1 accepted stages" in stats(repo) + + +def test_revision_resets_ladder(repo): + def plan_check(): + result = subprocess.run(["python3", str(SCRIPTS / "plan-check.py"), PLAN_DIR], cwd=repo, + capture_output=True, text=True) + rows = [json.loads(x) for x in result.stdout.splitlines()[:-1]] + return result.returncode, [x["kind"] for x in rows if x["level"] == "error"] + + bc(repo, "start", PHASE) + (repo / "src/a.txt").write_text("a2\n") + assert record(repo, "01.1", "opus", "high").returncode == 1 + assert bc(repo, "can-try", PHASE, "01.1", "opus", "high").returncode == 1 + assert plan_check() == (0, []) + edit_brief(repo, "01.1", goal="Write a, edited") + assert plan_check() == (1, ["revision"]) + attempts = stage_file(repo, "01.1")["record"]["attempts"] + assert record(repo, "01.1", "sonnet", "high").returncode == 5 + assert stage_file(repo, "01.1")["record"]["attempts"] == attempts + edit_brief(repo, "01.1", revision=2) + assert plan_check() == (0, []) + assert bc(repo, "can-try", PHASE, "01.1", "opus", "high").returncode == 0 + + +def test_orchestrator_needs_session_only(repo): + bc(repo, "start", PHASE) + (repo / "src/b.txt").write_text("b2\n") + refused = record(repo, "01.2", "orchestrator", "high") + assert refused.returncode == 2 and "session_only" in refused.stderr + assert "attempts" not in stage_file(repo, "01.2")["record"] + edit_brief(repo, "01.2", session_only=True) + accepted = record(repo, "01.2", "orchestrator", "high") + assert accepted.returncode == 0, accepted.stdout + accepted.stderr + assert [x["model"] for x in stage_file(repo, "01.2")["record"]["attempts"]] == ["orchestrator"] + + +def test_rebuild_needs_fix(repo): + bc(repo, "start", PHASE) + build_a(repo) + record(repo, "01.1") + bc(repo, "commit", PHASE, "01.1") + (repo / "src/a.txt").write_text("a3\n") + attempts = stage_file(repo, "01.1")["record"]["attempts"] + refused = record(repo, "01.1", "sonnet", "medium") + assert refused.returncode == 2 and "--fix" in refused.stderr + assert stage_file(repo, "01.1")["record"]["attempts"] == attempts + assert record(repo, "01.1", "sonnet", "medium", 0, "300", "0.05", "--fix").returncode == 0 + + +def test_invalid_stage_file_after_start(repo): + bc(repo, "start", PHASE) + assert bc(repo, "can-try", PHASE, "01.1", "opus", "high").returncode == 0 + broken = stage_file(repo, "01.2") + write_json(repo / PHASE / "01.2.json", {"brief": broken["brief"]}) + result = bc(repo, "can-try", PHASE, "01.1", "opus", "high") + assert result.returncode == 2 and "Traceback" not in result.stderr + assert any("record" in json.loads(x)["msg"] for x in result.stdout.splitlines()) + write_json(repo / PHASE / "01.2.json", broken) + edit_brief(repo, "01.1", goal="Write a, edited") + assert bc(repo, "can-try", PHASE, "01.1", "opus", "high").returncode == 5 + + +def test_commit_staged_deletion(repo): + edit_brief(repo, "01.2", files=[{"path": "src/b.txt", "action": "delete", "role": "b"}]) + bc(repo, "start", PHASE) + git(repo, "rm", "-q", "src/b.txt") + assert record(repo, "01.2", "haiku", "high").returncode == 0 + done = bc(repo, "commit", PHASE, "01.2") + assert done.returncode == 0, done.stderr + assert changed(repo) == ["src/b.txt"] + assert "src/b.txt" not in git(repo, "ls-files") diff --git a/plugins/phased-delivery/tests/test_plan_check.py b/plugins/phased-delivery/tests/test_plan_check.py index 643ce70..4bba061 100644 --- a/plugins/phased-delivery/tests/test_plan_check.py +++ b/plugins/phased-delivery/tests/test_plan_check.py @@ -1,4 +1,5 @@ import copy +import importlib.util import json from pathlib import Path import subprocess @@ -8,61 +9,74 @@ SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "plan-check.py" +spec = importlib.util.spec_from_file_location("plan_check", SCRIPT) +plan_check = importlib.util.module_from_spec(spec) +spec.loader.exec_module(plan_check) + SPEC = "Users must log in. Five failed logins from one address within a minute get 429." BASIS = {"J": 1, "F": 1, "R": 1, "C": 1, "K": 1, "P": 1, "V": 0, "S": 0} +P1 = "01-rate-limit/" PLAN = { + "description": "Login rate limit", "goal": "Limit failed logins.", "why": "Stop guessing.", "size": {"verdict": "full", "evidence": ["a shared contract changes"]}, "outcomes": [{"id": "O1", "title": "limit", "observable": "the sixth failed login answers 429", "how_to_check": "test client posts /login six times", "sources": [{"doc": "spec", "section": "Goals", "quote": "Five failed logins from one address"}]}], "decisions": [{"id": "D1", "text": "Counts live in memory.", "reason": "single process", "phases": ["all"]}], - "contracts": [ - {"id": "C1", "kind": "function", "name": "check_rate", "shape": "check_rate(addr: str) -> bool", - "provided_by": "01.1", "used_by": ["01.2"]}, - {"id": "C2", "kind": "function", "name": "login", "shape": "login() -> Response", - "provided_by": "existing:app/views.py", "used_by": ["01.2"]}], - "outcome_tests": [{"outcome": "O1", "test": "tests/test_limit.py::test_sixth", "written_in": "01.2", - "passes_from": "01.2"}], - "phases": [{"phase": "01", "file": "01-rate-limit.md", "name": "rate limit", "kind": "behaviour", "stages": [ - {"id": "01.1", "title": "limiter", "files": [{"path": "app/ratelimit.py", "action": "create"}], - "lines": "30-150", "provides": ["C1"], "uses": [], "order": "first"}, - {"id": "01.2", "title": "wire it in", "files": [{"path": "app/views.py", "action": "edit"}, - {"path": "tests/test_limit.py", "action": "create"}], - "lines": "under 30", "provides": [], "uses": ["C1", "C2"], "order": "after 01.1"}]}], + "existing": [{"kind": "function", "name": "login", "shape": "login() -> Response", "path": "app/views.py"}], + "phases": [{"phase": "01", "dir": "01-rate-limit", "name": "rate limit", "kind": "behaviour"}], } - -def stage(sid, files, contracts, **kw): - return {"id": sid, "goal": "g", "context": {"builds_on": [], "code_read": [], "design": []}, - "contracts": contracts, "files": files, "behaviour": [], "external_inputs": [], "tests": [], - "done_when": ["pytest passes"], "out_of_scope": [], "model_basis": dict(BASIS), **kw} - - -PHASE = { - "before": "No limit.", "after": "Logins are limited.", "assumptions": [], "test_budget": "1 min", - "stages": [ - stage("01.1", [{"path": "app/ratelimit.py", "action": "create", "role": "holds check_rate"}], - [{"kind": "function", "name": "check_rate", "shape": "check_rate(addr: str) -> bool", - "direction": "provides", "counterparts": ["01.2"]}]), - stage("01.2", [{"path": "app/views.py", "action": "edit", "role": "login calls check_rate"}, - {"path": "tests/test_limit.py", "action": "create", "role": "the outcome test"}], - [{"kind": "function", "name": "check_rate", "shape": "check_rate(addr: str) -> bool", - "direction": "uses", "counterparts": ["01.1"]}]), - ], - "notes": [], +PHASE = {"brief": {"role": "r", "why": "w", "how": "h", "before": "No limit.", "after": "Logins are limited.", + "assumptions": [], "test_budget": "1 min", "notes": []}, + "record": {}} + + +def stage(title, order, lines, files, provides, uses, tests=()): + return {"brief": {"revision": 1, "title": title, "order": order, "lines": lines, "files": files, + "provides": provides, "uses": uses, "goal": "g", + "context": {"builds_on": [], "code_read": [], "design": []}, + "behaviour": [], "external_inputs": [], "tests": list(tests), "done_when": ["pytest passes"], + "checks": [], "out_of_scope": [], "model_basis": dict(BASIS)}, + "record": {}} + + +# the example plan: file path relative to the plan folder -> content +FILES = { + "plan.json": PLAN, + P1 + "phase.json": PHASE, + P1 + "01.1.json": stage("limiter", "first", "30-150", + [{"path": "app/ratelimit.py", "action": "create", "role": "holds check_rate"}], + [{"kind": "function", "name": "check_rate", "shape": "check_rate(addr: str) -> bool", + "used_by": []}], []), + P1 + "01.2.json": stage("wire it in", "after 01.1", "under 30", + [{"path": "app/views.py", "action": "edit", "role": "login calls check_rate"}, + {"path": "tests/test_limit.py", "action": "create", "role": "the outcome test"}], + [], ["check_rate", "login"], + [{"test": "tests/test_limit.py::test_sixth", "kind": "outcome", "action": "writes", + "proves": "p", "outcome": "O1"}]), } -def run(tmp_path, plan=PLAN, phase=PHASE, *extra): +def brief(f, sid): + return f[f"{P1}{sid}.json"]["brief"] + + +def changed(change): + f = copy.deepcopy(FILES) + change(f) + return f + + +def run(tmp_path, files=FILES, *extra): (tmp_path / "app").mkdir(exist_ok=True) (tmp_path / "app" / "views.py").write_text("def login():\n return render()\n") (tmp_path / "spec.md").write_text(SPEC) - d = tmp_path / "plan" / ".plan" - d.mkdir(parents=True, exist_ok=True) - (d / "plan.json").write_text(json.dumps(plan)) - if phase is not None: - (d / "01.json").write_text(json.dumps(phase)) + for name, data in files.items(): + path = tmp_path / "plan" / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data)) p = subprocess.run([sys.executable, SCRIPT, str(tmp_path / "plan"), "--repo", str(tmp_path), "--spec", str(tmp_path / "spec.md"), *extra], capture_output=True, text=True) rows = [json.loads(x) for x in p.stdout.splitlines()] @@ -73,87 +87,139 @@ def kinds(rows): return {x["kind"] for x in rows if x["level"] == "error"} -def test_clean_plan_renders(tmp_path): +def test_renders_layout(tmp_path): + decoy = tmp_path / "plan" / ".plan" / "plan.json" + decoy.parent.mkdir(parents=True) + decoy.write_text("not json") code, rows, summary = run(tmp_path) assert code == 0, rows - assert summary["rendered"] == ["01-rate-limit.md"] - md = (tmp_path / "plan" / "01-rate-limit.md").read_text() + assert sorted(summary["rendered"]) == [P1 + "phase.md", "plan.md"] + assert "[01 rate limit](01-rate-limit/phase.md)" in (tmp_path / "plan" / "plan.md").read_text() + md = (tmp_path / "plan" / P1 / "phase.md").read_text() assert "# Phase 01: rate limit" in md + assert "## 01.1 limiter" in md and "## 01.2 wire it in" in md assert "| 01.2 | g | middle | after 01.1 | planned |" in md assert "writes `tests/test_limit.py::test_sixth` (outcome): the sixth failed login answers 429" in md assert "- Counts live in memory. Reason: single process" in md assert "Model basis: J1 F1 R1 C1 K1 P1 V0 S0 = 6 -> middle" in md + assert [p.name for p in decoy.parent.iterdir()] == ["plan.json"] and decoy.read_text() == "not json" def test_outline_only_skips_phase_json(tmp_path): - code, rows, summary = run(tmp_path, PLAN, None, "--outline") - assert code == 0 and summary["rendered"] == [] - - -def broken_plan(change): - p = copy.deepcopy(PLAN) - change(p) - return p + files = changed(lambda f: f.pop(P1 + "phase.json")) + code, rows, summary = run(tmp_path, files, "--outline") + assert code == 0 and summary["rendered"] == [], rows @pytest.mark.parametrize("change, kind", [ - (lambda p: p["contracts"][0]["used_by"].append("01.9"), "ref"), - (lambda p: p["phases"][0]["stages"][1]["uses"].remove("C1"), "registry"), - (lambda p: p["outcome_tests"].clear(), "coverage"), - (lambda p: p["outcomes"][0]["sources"][0].update(quote="Ten failed logins"), "quote"), - (lambda p: p["phases"][0]["stages"][1]["files"].append({"path": "app/nope.py", "action": "edit"}), "files"), - (lambda p: p["contracts"][0].update(used_by=["tests/test_limit.py"]), "internal"), - (lambda p: p["phases"][0]["stages"][0].update(order="after 01.2"), "order"), - (lambda p: p["contracts"][1].update(provided_by="existing:app/gone.py"), "ref"), - (lambda p: p["decisions"][0].pop("reason"), "schema"), + (lambda f: brief(f, "01.2")["uses"].append("check_limit"), "ref"), + (lambda f: f["plan.json"]["existing"].append({**PLAN["existing"][0], "name": "check_rate"}), "registry"), + (lambda f: brief(f, "01.2")["tests"].clear(), "coverage"), + (lambda f: f["plan.json"]["outcomes"][0]["sources"][0].update(quote="Ten failed logins"), "quote"), + (lambda f: brief(f, "01.2")["files"].append({"path": "app/nope.py", "action": "edit", "role": "r"}), "files"), + (lambda f: (brief(f, "01.2")["uses"].remove("check_rate"), + brief(f, "01.1")["provides"][0].update(used_by=["tests/test_limit.py"])), "internal"), + (lambda f: brief(f, "01.1").update(order="after 01.2"), "order"), + (lambda f: f["plan.json"]["existing"][0].update(path="app/gone.py"), "ref"), + (lambda f: f["plan.json"]["decisions"][0].pop("reason"), "schema"), ]) def test_plan_errors(tmp_path, change, kind): - code, rows, _ = run(tmp_path, broken_plan(change), PHASE, "--outline") + code, rows, _ = run(tmp_path, changed(change)) assert code == 1 assert kind in kinds(rows), rows -def broken_phase(change): - d = copy.deepcopy(PHASE) - change(d) - return d - - @pytest.mark.parametrize("change, kind", [ - (lambda d: d["stages"][0]["contracts"].append({"kind": "function", "name": "_prune", "shape": "_prune()", - "direction": "provides", "counterparts": ["01.1"]}), "internal"), - (lambda d: d["stages"][1]["context"]["design"].append({"doc": "spec", "section": "s", "quote": "Admins skip limits"}), "quote"), - (lambda d: d["stages"][1]["context"]["code_read"].append({"where": "app/views.py:1", "shows": "def logout", "fact": "f"}), "cite"), - (lambda d: d["stages"][1]["context"]["code_read"].append({"where": "app/views.py:9", "shows": "x", "fact": "f"}), "cite"), - (lambda d: d["notes"].append("Follows C1."), "standalone"), - (lambda d: d["stages"][0]["files"].pop(), "plan"), - (lambda d: d["stages"][0]["contracts"].clear(), "plan"), - (lambda d: d["stages"][1]["tests"].append({"test": "tests/test_limit.py::test_sixth", "kind": "outcome", - "action": "writes", "proves": "p"}), "tests"), + (lambda f: brief(f, "01.1")["provides"].append({"kind": "function", "name": "_prune", "shape": "_prune()", + "used_by": []}), "internal"), + (lambda f: brief(f, "01.2")["context"]["design"].append({"doc": "spec", "section": "s", + "quote": "Admins skip limits"}), "quote"), + (lambda f: brief(f, "01.2")["context"]["code_read"].append({"where": "app/views.py:1", "shows": "def logout", + "fact": "f"}), "cite"), + (lambda f: brief(f, "01.2")["context"]["code_read"].append({"where": "app/views.py:9", "shows": "x", + "fact": "f"}), "cite"), + (lambda f: f[P1 + "phase.json"]["brief"]["notes"].append("Follows D1."), "standalone"), + (lambda f: f.update({P1 + "02.1.json": f[P1 + "01.2.json"]}), "id"), + (lambda f: brief(f, "01.1")["provides"].clear(), "ref"), + (lambda f: brief(f, "01.2")["tests"][0].pop("outcome"), "tests"), ]) def test_phase_errors_block_rendering(tmp_path, change, kind): - code, rows, summary = run(tmp_path, PLAN, broken_phase(change)) + code, rows, summary = run(tmp_path, changed(change)) assert code == 1 assert kind in kinds(rows), rows assert summary["rendered"] == [] def test_code_in_prose_is_a_warning(tmp_path): - d = broken_phase(lambda d: d["stages"][1]["behaviour"].append( + files = changed(lambda f: brief(f, "01.2")["behaviour"].append( {"given": "five failures", "when": "a sixth", "then": "`if n == 5 return False`"})) - code, rows, summary = run(tmp_path, PLAN, d) + code, rows, summary = run(tmp_path, files) assert code == 0 assert [x["kind"] for x in rows] == ["code"] and rows[0]["level"] == "warning" def test_valid_citation_passes(tmp_path): - d = broken_phase(lambda d: d["stages"][1]["context"]["code_read"].append( + files = changed(lambda f: brief(f, "01.2")["context"]["code_read"].append( {"where": "app/views.py:1-2", "shows": "def login", "fact": "the login view"})) - assert run(tmp_path, PLAN, d)[0] == 0 + assert run(tmp_path, files)[0] == 0 def test_quick_plan_renders_size(tmp_path): - p = broken_plan(lambda p: p["size"].update(verdict="quick", evidence=["total 6: one interface part"])) - code, rows, _ = run(tmp_path, p, PHASE) + files = changed(lambda f: f["plan.json"]["size"].update(verdict="quick", evidence=["total 6: one interface part"])) + code, rows, _ = run(tmp_path, files) assert code == 0, rows - assert "## Size\n\nQuick plan:\n- total 6: one interface part" in (tmp_path / "plan" / "01-rate-limit.md").read_text() + assert "## Size\n\nQuick plan:\n- total 6: one interface part" in (tmp_path / "plan" / P1 / "phase.md").read_text() + + +def test_brief_change_needs_revision(tmp_path): + # build-check.py writes `revisions` only from phase 03, so the record is written by hand here + built = changed(lambda f: f[P1 + "01.1.json"]["record"].update( + revisions={"1": plan_check.brief_hash(brief(f, "01.1"))})) + assert run(tmp_path, built)[0] == 0 + edited = copy.deepcopy(built) + brief(edited, "01.1")["goal"] = "g2" + code, rows, _ = run(tmp_path, edited) + assert code == 1 and [x["where"] for x in rows if x["kind"] == "revision"] == ["01.1"], rows + raised = copy.deepcopy(edited) + brief(raised, "01.1")["revision"] = 2 + assert run(tmp_path, raised)[0] == 0 + lowered = copy.deepcopy(raised) + lowered[P1 + "01.1.json"]["record"]["revisions"]["2"] = plan_check.brief_hash(brief(raised, "01.1")) + brief(lowered, "01.1")["revision"] = 1 + assert "revision" in kinds(run(tmp_path, lowered)[1]) + + +STALE = {"where": "app/views.py:1", "shows": "def logout", "fact": "f"} + + +def test_repository_checks_skip_done_stages(tmp_path): + def change(f): + f[P1 + "01.1.json"]["record"]["commit"] = "abc1234" + brief(f, "01.1")["context"]["code_read"].append(STALE) + brief(f, "01.2")["context"]["code_read"].append(STALE) + (tmp_path / "app").mkdir() + (tmp_path / "app" / "ratelimit.py").write_text("") + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "test_limit.py").write_text("") + code, rows, _ = run(tmp_path, changed(change)) + assert code == 1 + assert {(x["where"].split("/")[0], x["kind"]) for x in rows if x["level"] == "error"} == { + ("01.2", "files"), ("01.2", "cite")}, rows + + +def test_phase_scopes_repository_checks(tmp_path): + P2 = "02-more/" + + def change(f): + f["plan.json"]["phases"].append({"phase": "02", "dir": "02-more", "name": "more", "kind": "behaviour"}) + for sid in ("01.1", "01.2"): + f[f"{P1}{sid}.json"]["record"]["commit"] = "abc1234" + f[P1 + "phase.json"]["record"]["built"] = "abc1234" + f[P2 + "phase.json"] = PHASE + f[P2 + "02.1.json"] = stage("more", "after 01.2", "under 30", + [{"path": "app/views.py", "action": "edit", "role": "r"}], [], ["login"]) + f[P2 + "02.1.json"]["brief"]["context"]["code_read"].append(STALE) + files = changed(change) + assert run(tmp_path, files, "--phase", "01")[0] == 0 + code, rows, _ = run(tmp_path, files, "--phase", "02") + assert code == 1 and kinds(rows) == {"cite"}, rows diff --git a/plugins/phased-delivery/tests/test_plan_mode.py b/plugins/phased-delivery/tests/test_plan_mode.py index 9bbf83a..b001b74 100644 --- a/plugins/phased-delivery/tests/test_plan_mode.py +++ b/plugins/phased-delivery/tests/test_plan_mode.py @@ -1,6 +1,7 @@ import importlib.util import json from pathlib import Path +import shutil import subprocess import sys @@ -101,28 +102,33 @@ def test_existing_data_forces_full(tmp_path): assert call(tmp_path, "score", form(kind="data", existing_data=True))[2]["mode"] == "full" -def plan(tmp_path, stages, contracts, phases=1): - d = repo(tmp_path) / "docs" / "plan" / ".plan" - d.mkdir(parents=True, exist_ok=True) - ph = [{"phase": f"{i + 1:02}", "stages": stages if i == 0 else stages[:1]} for i in range(phases)] - (d / "plan.json").write_text(json.dumps({"contracts": contracts, "phases": ph})) - p = subprocess.run([sys.executable, SCRIPT, "rescore", str(d.parent), "--repo", str(tmp_path)], +def plan(tmp_path, stages, existing, phases=1): + d = repo(tmp_path) / "docs" / "plan" + shutil.rmtree(d, ignore_errors=True) # each call writes a fresh plan + ph = [{"phase": f"{i + 1:02}", "dir": f"{i + 1:02}-p", "name": "p", "kind": "skeleton"} for i in range(phases)] + for i, p in enumerate(ph): + (d / p["dir"]).mkdir(parents=True, exist_ok=True) + for s in (stages if i == 0 else stages[:1]): + (d / p["dir"] / f"{p['phase']}.{s['n']}.json").write_text(json.dumps({"brief": s["brief"], "record": {}})) + (d / "plan.json").write_text(json.dumps({"existing": existing, "phases": ph})) + p = subprocess.run([sys.executable, SCRIPT, "rescore", str(d), "--repo", str(tmp_path)], capture_output=True, text=True) return p.returncode, json.loads(p.stdout)["summary"] if p.stdout else None -def st(sid, files, provides=(), lines="30-150"): - return {"id": sid, "title": "t", "files": [{"path": f, "action": a} for f, a in files], - "lines": lines, "provides": list(provides), "uses": [], "order": "first"} +def st(n, files, provides=(), lines="30-150"): + return {"n": n, "brief": {"revision": 1, "title": "t", "order": "first", "lines": lines, + "files": [{"path": f, "action": a, "role": "r"} for f, a in files], + "provides": list(provides), "uses": []}} def test_rescore_kinds_and_reach(tmp_path): code, s = plan(tmp_path, [ - st("01.1", [("app/new.py", "create")]), - st("01.2", [("app/ratelimit.py", "edit")]), - st("01.3", [("app/views.py", "edit")], ["C2"], "under 30")], - [{"id": "C1", "name": "check_rate", "provided_by": "existing:app/ratelimit.py", "used_by": ["01.3"]}, - {"id": "C2", "name": "login_page", "provided_by": "01.3", "used_by": ["user"]}]) + st(1, [("app/new.py", "create")]), + st(2, [("app/ratelimit.py", "edit")]), + st(3, [("app/views.py", "edit")], + [{"kind": "route", "name": "login_page", "shape": "GET /login", "used_by": ["user"]}], "under 30")], + [{"kind": "function", "name": "check_rate", "shape": "check_rate(addr)", "path": "app/ratelimit.py"}]) assert code == 0 assert [p["kind"] for p in s["parts"]] == ["new", "interface", "interface"] assert s["parts"][1]["reach_files"] == ["app/views.py", "docs.md"] @@ -130,8 +136,19 @@ def test_rescore_kinds_and_reach(tmp_path): assert s["mode"] == "quick" and s["total"] == 1 + 6 + 3 +def test_rescore_skips_other_new_layout_plans(tmp_path): + other = tmp_path / "docs" / "other" + (other / "01-x").mkdir(parents=True) + (other / "01-x" / "phase.md").write_text("# Phase 01: x\n\nImplement with the implement-in-phases skill\n") + (other / "plan.md").write_text("check_rate\n") + (other / "plan.json").write_text('{"note": "check_rate"}\n') + code, s = plan(tmp_path, [st(1, [("app/ratelimit.py", "edit")])], + [{"kind": "function", "name": "check_rate", "shape": "check_rate(addr)", "path": "app/ratelimit.py"}]) + assert code == 0 and s["parts"][0]["reach_files"] == ["app/views.py", "docs.md"] + + def test_rescore_structure_forces_full(tmp_path): - stages = [st(f"01.{i}", [(f"app/f{i}.py", "create")], lines="under 30") for i in range(1, 5)] + stages = [st(i, [(f"app/f{i}.py", "create")], lines="under 30") for i in range(1, 5)] assert plan(tmp_path, stages, [])[1]["mode"] == "full" assert plan(tmp_path, stages[:1], [], phases=2)[1]["mode"] == "full" assert plan(tmp_path, stages[:1], [])[1]["mode"] == "direct" diff --git a/plugins/phased-delivery/tests/test_session_start.py b/plugins/phased-delivery/tests/test_session_start.py index a2f0428..f32119e 100644 --- a/plugins/phased-delivery/tests/test_session_start.py +++ b/plugins/phased-delivery/tests/test_session_start.py @@ -34,3 +34,15 @@ def test_codex_off_line(tmp_path): cache.write_text(json.dumps({"date": today, "on": True})) assert "Codex" not in hook_context(tmp_path) + + +def test_lists_phase_folders(tmp_path): + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + for name, status in (("01-a", "planned"), ("02-b", "built abc123")): + d = tmp_path / "docs" / "plans" / "x" / name + d.mkdir(parents=True) + (d / "phase.md").write_text( + f"# Phase\n\nImplement with the implement-in-phases skill; do not build.\nStatus: {status}\n") + context = hook_context(tmp_path) + assert "- docs/plans/x/01-a/phase.md (planned)" in context + assert "02-b" not in context