diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..a046485 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,25 @@ +name: Tests + +# Run the phased-delivery plugin's test suite on every pull request and on +# pushes to main. The tests use only the Python standard library, git and +# POSIX sh; external CLIs (claude, codex) are stubbed. + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + pytest: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.x" + - run: python -m pip install pytest + - run: python -m pytest -q -p no:cacheprovider plugins/phased-delivery/tests diff --git a/README.md b/README.md index e4fddd7..c947881 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,19 @@ 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. +### 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 +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 user asks. To allow it, add to the project's `AGENTS.md` or `CLAUDE.md`: @@ -194,7 +207,7 @@ start (the ai-coding sandbox already sets it). ### Tracking which model did what -implement-in-phases commits each stage on its own, with trailers for the +implement-in-phases commits each stage on its own (`build-check.py commit`), with trailers for the stage, plan, tier, model, effort, attempt, token count and cost, and gives later fixes to a stage their own commits marked `Fixes-Stage:`. When the plan is done, it writes `work-report.md` in the plan directory: per model and diff --git a/docs/plans/implement-structured/01-contracts.md b/docs/plans/implement-structured/01-contracts.md new file mode 100644 index 0000000..82a9304 --- /dev/null +++ b/docs/plans/implement-structured/01-contracts.md @@ -0,0 +1,189 @@ +# Phase 01: Schemas, script interface and outcome tests + +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: built 4d47781 +Before: implement-in-phases is one prose SKILL.md; the orchestrator writes commit trailers, tracks attempts and sums premium spend by hand. No build-check script or revision and review schemas exist. +After: `revision.schema.json` and `review.schema.json` exist; `scripts/build-check.py` accepts every subcommand with its arguments and exit codes, validates the revision and review JSON, and returns mock results. `tests/test_build_check.py` holds every outcome test, marked expected-fail. + +## Assumptions +- Verified: plan-check.py's validate handles the schema features the new schemas need: type, required, enum, items, additionalProperties, pattern. (plugins/phased-delivery/scripts/plan-check.py:46, used by plan.schema.json and phase.schema.json) +- Verified: stage-stats.sh reads only trailers, so commits made by a script count exactly like hand-written ones. (plugins/phased-delivery/scripts/stage-stats.sh:20, git log --format with trailers) +- Verified: Check commands run with `sh -c` from the repository root in the session's environment. (decided here; the revise guide (03.1) tells the orchestrator to write checks that run from the repository root) + +## Outcome tests +Budget: Under 10 s for test_build_check.py: each test makes one temporary git repository; the plugin's suite stays under a minute. + +| Outcome | Test | Written in | Passes from | +| --- | --- | --- | --- | +| After a build that changes only its stage's files and passes the stage's check commands, `build-check.py record` exits 0 and `build-check.py commit` makes one commit holding only that stage's changed files, with Stage, Plan, Tier, Tool, Model, Effort, Attempt, Tokens, Cost and Tool-Calls trailers that `stage-stats.sh` counts as one stage. | `plugins/phased-delivery/tests/test_build_check.py::test_accepted_stage_commit` | 01.3 | 02.2 | +| A build that changes a file outside its stage's files makes `record` exit 1 and print the file under `outside`; the stage is not accepted. | `plugins/phased-delivery/tests/test_build_check.py::test_outside_change_fails` | 01.3 | 02.1 | +| A build whose check command fails makes `record` exit 1; a second attempt on another pair that passes is accepted, and its commit has `Attempt: 2` and one `Earlier-Attempt:` trailer naming the first pair. | `plugins/phased-delivery/tests/test_build_check.py::test_failed_check_then_retry` | 01.3 | 02.2 | +| `build-check.py can-try` exits 1 for a model and effort already tried for the stage, and 0 for one not yet tried or whose only attempt ended in an error (the build never ran to a verdict). | `plugins/phased-delivery/tests/test_build_check.py::test_can_try_refuses_repeat` | 01.3 | 02.1 | +| `build-check.py spend` prints the phase's premium spend in dollars: the cost of every attempt and review recorded as premium, using its cap when the cost is unknown. | `plugins/phased-delivery/tests/test_build_check.py::test_premium_spend` | 01.3 | 02.1 | +| Files already modified when `start` runs are neither counted as outside changes nor included in any stage commit. | `plugins/phased-delivery/tests/test_build_check.py::test_preexisting_edits_left_alone` | 01.3 | 02.2 | +| `start` exits 1 when the revision JSON breaks its schema, and `finish` exits 1 when the review JSON breaks its schema, each printing a JSON line that names the field; nothing is written or committed. | `plugins/phased-delivery/tests/test_build_check.py::test_invalid_json_refused` | 01.3 | 01.3 | +| After every stage is committed and the review JSON is valid, `finish` sets the phase file's status line to `built `, marks each stage row done, and commits the phase file and the `.build` files with a `Phase:` trailer. | `plugins/phased-delivery/tests/test_build_check.py::test_finish_phase` | 01.3 | 02.2 | +| A fix recorded with `record --fix` for a committed stage is committed with a `Fixes-Stage:` trailer instead of `Stage:`, which `stage-stats.sh` counts as a fix needed for that stage's model. | `plugins/phased-delivery/tests/test_build_check.py::test_fix_commit` | 01.3 | 02.2 | + +## Stages + +| Stage | Goal | Tier | Order | Status | +| --- | --- | --- | --- | --- | +| 01.1 | The revision and review JSON formats exist as schemas in the implement-in-phases skill directory, in the subset plan-check.py's validate understands. | top | first | done | +| 01.2 | `scripts/build-check.py` exists with every subcommand, argument, output line and exit code of its contracts; start and finish validate their JSON for real, the rest return mock results. | top | after 01.1 | done | +| 01.3 | `tests/test_build_check.py` holds every outcome test of the plan's script outcomes, each driving build-check.py in a temporary git repository and marked `xfail(strict=True)` against the mocks. | middle | after 01.2 | done | + +## 01.1 Revision and review schemas + +Goal: The revision and review JSON formats exist as schemas in the implement-in-phases skill directory, in the subset plan-check.py's validate understands. + +Context: +- `plugins/phased-delivery/scripts/plan-check.py:46`: The plugin's stdlib JSON Schema subset; returns (where, msg) pairs. +- `plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md:22-43`: The eight current review checks the closed finding types replace. +- Design, Revision: "for each stage, the files it may change, +the check commands that show its "Done when", and its re-scored measures" +- Design, Review: "untraced change, check on internal data, bug or contract +mismatch" + +Contracts: +- format `revision JSON` (provides; 01.2, 02.1, 03.1, disk): `/.build/NN-revision.json` per `revision.schema.json`: {phase, stages: [{id, title, files: [{path, action}], checks: [shell command], scores: "J1F1R0C0K0P0V0S0", tier}], assumptions: [{text, verdict: verified|wrong, evidence}], adjustments: [string]} +- format `review JSON` (provides; 01.2, 02.2, 03.2, disk): `/.build/NN-review.json`: {findings: [{type: untraced-change|internal-check|bug|not-done|test|assumption|rule|unneeded-code, severity: blocking|should-fix, stage, file, line, evidence, action: remove|fix|plan-gap|question}], verdict: ready|not-ready} + +Files: +- `plugins/phased-delivery/skills/implement-in-phases/revision.schema.json` (create): holds the revision JSON schema +- `plugins/phased-delivery/skills/implement-in-phases/review.schema.json` (create): holds the review JSON schema + +Behaviour: +- Given a revision with every field filled and each stage's `checks` non-empty, when it is validated against revision.schema.json, then no errors are returned. +- Given a revision stage without a `checks` key, when it is validated against revision.schema.json, then an error names `checks`; an empty list is allowed for a stage verified only by reading. +- Given `scores` not matching eight letter-digit pairs in the order JFRCKPVS, or a `tier` other than small, middle, middle+ or top, when it is validated, then an error names the field. +- Given a review finding whose `type` or `action` is outside its enum, or a finding without `evidence`, when it is validated against review.schema.json, then an error names the field. +- Given any object with an unlisted key, when it is validated, then an error names the key (additionalProperties false everywhere). + +External inputs: +none + +Tests: +none + +Done when: +- Both files parse as JSON and plan-check.py's validate accepts a valid example of each and rejects the cases in Behaviour; 01.3's tests exercise them. + +Out of scope: +- phase.schema.json and plan.schema.json +- phase-reviewer.md text (03.2) + +Model basis: J1 F1 R0 C2 K1 P1 V0 S0 = 6 -> top (override: J, C or K = 2) + +## 01.2 build-check.py interface with mock bodies + +Goal: `scripts/build-check.py` exists with every subcommand, argument, output line and exit code of its contracts; start and finish validate their JSON for real, the rest return mock results. + +Context: +- Builds on 01.1: revision JSON and review JSON schemas +- `plugins/phased-delivery/scripts/plan-check.py:46`: The plugin's stdlib JSON Schema subset; returns (where, msg) pairs. +- `plugins/phased-delivery/scripts/plan-mode.py:61-63`: How a script loads plan-check.py by path to reuse it. +- `plugins/phased-delivery/scripts/plan-check.py:430-441`: Loads a JSON file and reports schema errors; the pattern for start and finish. +- `plugins/phased-delivery/scripts/plan-check.py:2-22`: Docstring-as-usage and the one-JSON-line-per-problem output to copy. +- Design, Bookkeeping: "The script owns the per-phase ledger" + +Contracts: +- format `revision JSON` (uses; 01.1): as 01.1 defines it; read from `/.build/NN-revision.json` +- format `review JSON` (uses; 01.1): as 01.1 defines it; read from `/.build/NN-review.json` +- format `ledger JSON` (provides; 02.1, 02.2, disk): `/.build/NN-ledger.json`: {start_commit, preexisting: [path], attempts: [{stage (id or review), n, fix, tool, model, effort, exit, tokens, cost, cap, tool_calls, premium, result: accepted|failed|stopped|error|rejected|review, why, commit}]} +- cli `build-check.py start` (provides; 03.1, user): start PHASE_FILE [--repo DIR]: validates the revision; writes the ledger with HEAD and paths modified now, or keeps an existing one. Exit 0; 1 invalid revision or a stage file already modified, one JSON line each; 2 usage. +- cli `build-check.py can-try` (provides; 03.1, user): can-try PHASE_FILE STAGE MODEL EFFORT: exit 1, printing it, when the stage has a failed, stopped, rejected or accepted attempt on the pair; else 0. `error` attempts do not count. +- cli `build-check.py record` (provides; 03.1, user): record PHASE_FILE STAGE|review --tool T --model M --effort E --exit N --tokens X --cost Y [--cap USD] [--tool-calls N] [--premium] [--fix]: logs an attempt and gates it. Exit 0 accepted; 1 failed; 3 budget stop; 4 error. +- cli `build-check.py reject` (provides; 03.1, user): reject PHASE_FILE STAGE WHY: marks the stage's accepted, uncommitted attempt rejected with WHY. Exit 0; 1 no such attempt. +- cli `build-check.py commit` (provides; 03.1, user): commit PHASE_FILE STAGE [--subject-suffix TEXT] [--extra-trailer LINE]...: commits only the stage's changed files with the stage trailers, then marks the row done in the working tree. Prints the hash. Exit 0; 1 nothing accepted. +- cli `build-check.py spend` (provides; 03.1, user): spend PHASE_FILE: prints a bare number, two decimals: the cost of every attempt recorded with --premium (builds and reviews), its cap when the cost is unknown. Exit 0. +- cli `build-check.py finish` (provides; 03.1, user): finish PHASE_FILE [--stopped] [--extra-trailer LINE]...: validates the review JSON; sets `Status: built `; commits the phase file's directory with `Phase: `. --stopped skips review and status. Exit 0; 1 invalid review or stage uncommitted; 2 usage. + +Files: +- `plugins/phased-delivery/scripts/build-check.py` (create): holds every build-check.py subcommand, the ledger format and the usage docstring + +Behaviour: +- Given no arguments, an unknown subcommand or a missing PHASE_FILE, when the script runs, then it prints the usage to stderr and exits 2. +- Given a PHASE_FILE named `NN-name.md`, when any subcommand runs, then it reads and writes `.build/NN-*.json` in the phase file's directory. +- Given a revision that breaks the schema, when `start` runs, then it prints one JSON line per problem naming the field, writes no ledger and exits 1. +- Given a valid revision, when `start` runs, then it writes the ledger (mock: empty preexisting, current HEAD) and exits 0. +- Given a review that breaks the schema, when `finish` runs, then it prints one JSON line per problem and exits 1 without committing. +- Given valid input to record, can-try, reject, commit, spend or finish, when it runs, then it prints a fixed mock result in its contract's output shape and exits 0 (record's JSON line has result `accepted`). + +External inputs: +- revision and review JSON written by the orchestrator LLM: schema validation with plan-check.py's validate; on failure, one JSON line per problem, exit 1 +- command-line arguments: argparse types and choices; on failure, usage on stderr, exit 2 + +Tests: +none + +Done when: +- `python3 plugins/phased-delivery/scripts/build-check.py --help` prints the usage and each subcommand's `--help` works +- `build-check.py` with no arguments exits 2 + +Out of scope: +- Real git work, scope checks and check commands (phase 02) +- select-models.py and claude-build.sh + +Model basis: J1 F0 R1 C2 K2 P1 V0 S0 = 7 -> top (override: J, C or K = 2) + +## 01.3 Outcome tests, expected to fail + +Goal: `tests/test_build_check.py` holds every outcome test of the plan's script outcomes, each driving build-check.py in a temporary git repository and marked `xfail(strict=True)` against the mocks. + +Context: +- Builds on 01.2: every build-check.py subcommand +- Builds on 01.1: revision JSON and review JSON formats for the fixtures +- `plugins/phased-delivery/tests/test_codex_build.py:6`: The plugin's tests are pytest files that run scripts with subprocess. +- `plugins/phased-delivery/tests/test_claude_build.py:23-38`: Pattern: a helper that builds a temporary directory and runs the script with subprocess. +- `plugins/phased-delivery/scripts/stage-stats.sh:1-5`: The work report the commits must feed; tests run it on the temporary repo. +- `plugins/phased-delivery/hooks/session-start.sh:17-20`: The session hook treats a phase as finished when its Status line starts with built or reviewed. +- Design, Validation: "Offline tests run the script against temporary git repositories with no +model calls." + +Contracts: +none + +Files: +- `plugins/phased-delivery/tests/test_build_check.py` (create): holds the outcome tests and a fixture that makes a temporary git repository with a plan directory, a phase file and a revision JSON + +Behaviour: +- Given the mock script, when the suite runs, then the invalid-JSON test passes with no mark (01.2 validates for real); every other outcome test is xfail and none xpass. +- Given the fixture, when a test starts, then it has a git repository with one commit, a phase file in the rendered layout with one or two stages, and `.build/NN-revision.json` listing each stage's files and checks. + +External inputs: +none + +Tests: +- writes `plugins/phased-delivery/tests/test_build_check.py::test_accepted_stage_commit` (outcome): After a build that changes only its stage's files and passes the stage's check commands, `build-check.py record` exits 0 and `build-check.py commit` makes one commit holding only that stage's changed files, with Stage, Plan, Tier, Tool, Model, Effort, Attempt, Tokens, Cost and Tool-Calls trailers that `stage-stats.sh` counts as one stage. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_outside_change_fails` (outcome): A build that changes a file outside its stage's files makes `record` exit 1 and print the file under `outside`; the stage is not accepted. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_failed_check_then_retry` (outcome): A build whose check command fails makes `record` exit 1; a second attempt on another pair that passes is accepted, and its commit has `Attempt: 2` and one `Earlier-Attempt:` trailer naming the first pair. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_can_try_refuses_repeat` (outcome): `build-check.py can-try` exits 1 for a model and effort already tried for the stage, and 0 for one not yet tried or whose only attempt ended in an error (the build never ran to a verdict). +- writes `plugins/phased-delivery/tests/test_build_check.py::test_premium_spend` (outcome): `build-check.py spend` prints the phase's premium spend in dollars: the cost of every attempt and review recorded as premium, using its cap when the cost is unknown. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_preexisting_edits_left_alone` (outcome): Files already modified when `start` runs are neither counted as outside changes nor included in any stage commit. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_invalid_json_refused` (outcome): `start` exits 1 when the revision JSON breaks its schema, and `finish` exits 1 when the review JSON breaks its schema, each printing a JSON line that names the field; nothing is written or committed. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_finish_phase` (outcome): After every stage is committed and the review JSON is valid, `finish` sets the phase file's status line to `built `, marks each stage row done, and commits the phase file and the `.build` files with a `Phase:` trailer. +- writes `plugins/phased-delivery/tests/test_build_check.py::test_fix_commit` (outcome): A fix recorded with `record --fix` for a committed stage is committed with a `Fixes-Stage:` trailer instead of `Stage:`, which `stage-stats.sh` counts as a fix needed for that stage's model. + +Done when: +- `python3 -m pytest -q -p no:cacheprovider --basetemp=/cache/pytest-bc plugins/phased-delivery/tests/test_build_check.py` exits 0 with one passed test and the rest xfailed +- `python3 -m pytest -q -p no:cacheprovider --basetemp=/cache/pytest-bc plugins/phased-delivery/tests` passes as before + +Out of scope: +- Tests of select-models.py or claude-build.sh + +Model basis: J1 F0 R1 C1 K0 P1 V0 S0 = 4 -> middle + +## Notes +- The script is `scripts/build-check.py`, standard library only, and every subcommand takes the phase file path; the plan directory and phase number come from it, the repository from `--repo` (default: the current directory). Reason: Matches plan-check.py and select-models.py; the phase file is what the orchestrator already holds. +- Revision, ledger and review files live in `/.build/` as `NN-revision.json`, `NN-ledger.json` and `NN-review.json` and are committed with the phase, so a resumed session reads them. Reason: Resume needs the ledger; keeping them next to the plan keeps them out of the code tree. +- Schemas are checked with plan-check.py's `validate`, loaded by path as plan-mode.py and select-models.py already do. Reason: One JSON Schema subset in the plugin; no new dependency. +- The scope check compares uncommitted changes against HEAD (git status, so ignored files are not seen). Not outside: the stage's files, files of other revision stages that have no commit yet, the phase file's whole directory, preexisting paths, and `__pycache__`, `*.pyc` and `.pytest_cache` paths. record lists outside paths on every build result, including a budget stop; the orchestrator restores them before a retry. start refuses (exit 1) when a stage's file is already modified. Reason: Parallel stages, plan regeneration mid-phase and test caches must not fail a stage; a committed stage's files must not change unseen; leftovers must not fail the next attempt. +- A build exit other than 0 and 8 is recorded as `error` (record exit 4): not a try of the pair (can-try ignores it) and no Earlier-Attempt. The orchestrator then applies today's rule for that tool and exit: claude-build.sh stops and reports; a failed Codex build is rebuilt by the routing rule. Reason: Bookkeeping must not blame the model for a build that never reached a verdict; each tool's failure rule keeps its current meaning. +- Stage commits hold only the stage's files; the phase file, `.build/` and any regenerated plan files are updated in the working tree and committed by `finish` (with `--stopped` at a routing stop, which skips the review and completeness checks and leaves the status in progress). Reason: Keeps the design's 'staging only the stage's files'; resume reads the working tree. +- A review is recorded as stage `review`; `spend` counts only attempts recorded with `--premium`, which the build guide sets for premium-pair builds and for every review run by claude-build.sh, never for Codex. Reason: Matches model-selection.md's premium budget rules. +- commit takes `--subject-suffix TEXT` for subject annotations such as `[skip ci]` and `--extra-trailer LINE` for added trailers such as `Co-Authored-By`. Reason: Project rules may require both; today the orchestrator adds them by hand. +- Plan start: ae57d33. +- 2026-11-24: stages built directly by the orchestrator (one script, its schemas and tests; tightly coupled), so commits carry Model: orchestrator and no token counts. +- 2026-11-24: phase 01's review is folded into phase 02's: 01 holds mock bodies that 02 replaces, so reviewing them alone would cost a review for code about to change. diff --git a/docs/plans/implement-structured/02-internals.md b/docs/plans/implement-structured/02-internals.md new file mode 100644 index 0000000..e439f51 --- /dev/null +++ b/docs/plans/implement-structured/02-internals.md @@ -0,0 +1,149 @@ +# Phase 02: Check gate and bookkeeping + +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: built 1e03273 +Before: build-check.py validates the revision and review JSON; every other subcommand returns mock results, and the outcome tests are expected to fail. +After: build-check.py does the real work: it records attempts, gates each build on scope and check commands, refuses repeated pairs, sums premium spend, and makes the stage, fix and phase commits with stage-stats trailers. Every script outcome test passes with no expected-fail mark. + +## Assumptions +- Verified: `git status --porcelain --untracked-files=all` lists modified and untracked paths and leaves out ignored ones, which is the baseline the scope check needs. (standard git behaviour; the scope rule is the plan decision on what counts as outside) +- Open: A check command that needs a long run (a full test suite) fits within the stage's test budget. (checked when 03.4 runs a real phase; if checks time out, the revision guide limits checks to the stage's own tests) + +## Outcome tests +Budget: Under 10 s for test_build_check.py. + +| Outcome | Test | Written in | Passes from | +| --- | --- | --- | --- | +| After a build that changes only its stage's files and passes the stage's check commands, `build-check.py record` exits 0 and `build-check.py commit` makes one commit holding only that stage's changed files, with Stage, Plan, Tier, Tool, Model, Effort, Attempt, Tokens, Cost and Tool-Calls trailers that `stage-stats.sh` counts as one stage. | `plugins/phased-delivery/tests/test_build_check.py::test_accepted_stage_commit` | 01.3 | 02.2 | +| A build that changes a file outside its stage's files makes `record` exit 1 and print the file under `outside`; the stage is not accepted. | `plugins/phased-delivery/tests/test_build_check.py::test_outside_change_fails` | 01.3 | 02.1 | +| A build whose check command fails makes `record` exit 1; a second attempt on another pair that passes is accepted, and its commit has `Attempt: 2` and one `Earlier-Attempt:` trailer naming the first pair. | `plugins/phased-delivery/tests/test_build_check.py::test_failed_check_then_retry` | 01.3 | 02.2 | +| `build-check.py can-try` exits 1 for a model and effort already tried for the stage, and 0 for one not yet tried or whose only attempt ended in an error (the build never ran to a verdict). | `plugins/phased-delivery/tests/test_build_check.py::test_can_try_refuses_repeat` | 01.3 | 02.1 | +| `build-check.py spend` prints the phase's premium spend in dollars: the cost of every attempt and review recorded as premium, using its cap when the cost is unknown. | `plugins/phased-delivery/tests/test_build_check.py::test_premium_spend` | 01.3 | 02.1 | +| Files already modified when `start` runs are neither counted as outside changes nor included in any stage commit. | `plugins/phased-delivery/tests/test_build_check.py::test_preexisting_edits_left_alone` | 01.3 | 02.2 | +| After every stage is committed and the review JSON is valid, `finish` sets the phase file's status line to `built `, marks each stage row done, and commits the phase file and the `.build` files with a `Phase:` trailer. | `plugins/phased-delivery/tests/test_build_check.py::test_finish_phase` | 01.3 | 02.2 | +| A fix recorded with `record --fix` for a committed stage is committed with a `Fixes-Stage:` trailer instead of `Stage:`, which `stage-stats.sh` counts as a fix needed for that stage's model. | `plugins/phased-delivery/tests/test_build_check.py::test_fix_commit` | 01.3 | 02.2 | + +## Stages + +| Stage | Goal | Tier | Order | Status | +| --- | --- | --- | --- | --- | +| 02.1 | start records the real start state, record gates each attempt on scope and check commands, can-try refuses tried pairs and spend sums premium cost. | top | first | done | +| 02.2 | commit, reject and finish make the stage, fix and phase commits with the trailers stage-stats.sh reads, and update the phase file's stage table and status line. | top | after 02.1 | done | + +## 02.1 Start, record, can-try and spend + +Goal: start records the real start state, record gates each attempt on scope and check commands, can-try refuses tried pairs and spend sums premium cost. + +Context: +- Builds on 01.2: build-check.py start, can-try, record and spend with mock bodies; the ledger JSON format +- Builds on 01.1: revision JSON: each stage's files and checks +- Builds on 01.3: the outcome tests to turn on +- `plugins/phased-delivery/scripts/claude-build.sh:14-19`: The build exit codes record receives; 8 is a budget stop. +- `plugins/phased-delivery/skills/plan-in-phases/model-selection.md:218-225`: Premium spend counts each premium run's Cost, or its cap_usd when unknown, and every review. +- `plugins/phased-delivery/tests/test_codex_build.py:6`: The plugin's tests are pytest files run with pytest. +- Design, Check gate: "no file outside the stage's files changed (edits present before the phase do not count), and every +check command passes" + +Contracts: +- format `revision JSON` (uses; 01.1): as 01.1 defines it +- format `ledger JSON` (uses; 01.2): as 01.2 defines it + +Files: +- `plugins/phased-delivery/scripts/build-check.py` (edit): start, can-try, record and spend do their real work +- `plugins/phased-delivery/tests/test_build_check.py` (edit): the three outcome tests this stage makes pass lose their expected-fail marks + +Behaviour: +- Given tracked or untracked paths already modified, when start writes a new ledger, then they are stored in `preexisting` with HEAD as `start_commit`, unless one is a stage's file, which makes start exit 1 naming it; an existing ledger is kept as it is. +- Given a build attempt with exit 0, when record runs, then each uncommitted path that is not allowed by the scope rule in the Notes is listed in `outside`; any listed path fails the attempt. +- Given a build attempt with exit 0 and no outside path, when record runs, then each of the stage's checks runs with `sh -c` in the repository root; any non-zero exit fails the attempt; the JSON line lists each command with its exit. +- Given build exit 8, or another non-zero exit, when record runs, then 8 is stored as `stopped` (why `budget reached`, exit 3) and any other as `error` (exit 4); no checks run, and `outside` still lists stray paths. +- Given stage `review`, when record runs, then it is stored for spend only; no scope check or checks run; exit 0. +- Given attempts on the stage, when can-try runs for a model and effort, then it exits 1 if a non-error attempt used that pair, else 0. +- Given attempts recorded with and without `--premium`, when spend runs, then it prints the sum over the `--premium` ones of the cost, or the cap when the cost is unknown, as a bare number with two decimals. + +External inputs: +- --tokens and --cost values copied from the build script's output: a number or `unknown`; on failure, usage on stderr, exit 2 + +Tests: +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_outside_change_fails` (outcome): A build that changes a file outside its stage's files makes `record` exit 1 and print the file under `outside`; the stage is not accepted. +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_can_try_refuses_repeat` (outcome): `build-check.py can-try` exits 1 for a model and effort already tried for the stage, and 0 for one not yet tried or whose only attempt ended in an error (the build never ran to a verdict). +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_premium_spend` (outcome): `build-check.py spend` prints the phase's premium spend in dollars: the cost of every attempt and review recorded as premium, using its cap when the cost is unknown. + +Done when: +- `python3 -m pytest -q -p no:cacheprovider --basetemp=/cache/pytest-bc plugins/phased-delivery/tests/test_build_check.py` passes, with the outcome tests for outside changes, repeated pairs and premium spend no longer expected to fail +- `python3 -m pytest -q -p no:cacheprovider --basetemp=/cache/pytest-bc plugins/phased-delivery/tests` passes + +Out of scope: +- commit, reject and finish (02.2) +- select-models.py route + +Model basis: J1 F1 R1 C1 K2 P1 V0 S0 = 7 -> top (override: J, C or K = 2) + +## 02.2 Commit, reject and finish + +Goal: commit, reject and finish make the stage, fix and phase commits with the trailers stage-stats.sh reads, and update the phase file's stage table and status line. + +Context: +- Builds on 02.1: the ledger filled with real attempts and results +- Builds on 01.1: review JSON schema +- `plugins/phased-delivery/skills/implement-in-phases/SKILL.md:118-150`: The stage commit trailers, the Attempt count and the Earlier-Attempt format the commits must carry. +- `plugins/phased-delivery/scripts/stage-stats.sh:20`: stage-stats.sh reads Stage, Fixes-Stage, Model, Effort, Attempt, Tokens, Earlier-Attempt and Tool trailers. +- `plugins/phased-delivery/hooks/session-start.sh:17-20`: A phase is finished for the session hook when its Status line starts with built or reviewed. +- `plugins/phased-delivery/skills/plan-in-phases/phase-file-template.md:8`: The Status line values the script writes. +- `plugins/phased-delivery/scripts/plan-check.py:386-388`: The rendered stage table whose last cell the script sets. +- Design, Bookkeeping: "makes each stage commit (staging only the stage's +files, with the trailers from the ledger)" + +Contracts: +- format `review JSON` (uses; 01.1): as 01.1 defines it +- format `ledger JSON` (uses; 01.2): as 01.2 defines it +- format `stage commit trailers` (uses; plugins/phased-delivery/scripts/stage-stats.sh): Stage or Fixes-Stage, Plan, Tier, Tool, Model, Effort, Attempt, Tokens, Cost, Tool-Calls, and `Earlier-Attempt: ` per failed try + +Files: +- `plugins/phased-delivery/scripts/build-check.py` (edit): commit, reject and finish do their real work +- `plugins/phased-delivery/tests/test_build_check.py` (edit): the remaining outcome tests lose their expected-fail marks + +Behaviour: +- Given an accepted, uncommitted build attempt, when commit runs, then it stages only the stage's files that changed (minus preexisting) and commits with subject `NN.n ` plus any `--subject-suffix`, the trailers and any `--extra-trailer` lines; Attempt counts the stage's non-error attempts; each failed, stopped or rejected earlier one adds an Earlier-Attempt with its why. +- Given the commit is made, when the phase file is updated in the working tree, then the stage's row Status cell reads `done`, the Status line reads `in progress (stages done: <ids>)`, and the ledger stores the commit hash; neither file is committed here. +- Given an accepted fix attempt, when commit runs, then the trailer is `Fixes-Stage: NN.n` instead of `Stage:`, with that fix's Model, Effort and Tokens. +- Given no accepted, uncommitted attempt for the stage, when commit or reject runs, then it exits 1 and changes nothing. +- Given an accepted attempt the orchestrator rejects with a reason, when reject runs, then the attempt becomes `rejected` with that why and counts as an Earlier-Attempt. +- Given every stage committed and a valid review JSON, when finish runs, then the Status line reads `built <last stage commit short hash>` and one commit holds the phase file's directory with `Phase: <phase file>`; with `--stopped` it commits the directory without those checks or the status change. +- Given a stage without a commit or an invalid review, when finish runs, then it exits 1 and HEAD is unchanged. + +External inputs: +- review JSON written by the reviewing agent: review.schema.json; on failure, one JSON line per problem, exit 1 + +Tests: +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_accepted_stage_commit` (outcome): After a build that changes only its stage's files and passes the stage's check commands, `build-check.py record` exits 0 and `build-check.py commit` makes one commit holding only that stage's changed files, with Stage, Plan, Tier, Tool, Model, Effort, Attempt, Tokens, Cost and Tool-Calls trailers that `stage-stats.sh` counts as one stage. +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_failed_check_then_retry` (outcome): A build whose check command fails makes `record` exit 1; a second attempt on another pair that passes is accepted, and its commit has `Attempt: 2` and one `Earlier-Attempt:` trailer naming the first pair. +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_preexisting_edits_left_alone` (outcome): Files already modified when `start` runs are neither counted as outside changes nor included in any stage commit. +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_finish_phase` (outcome): After every stage is committed and the review JSON is valid, `finish` sets the phase file's status line to `built <commit>`, marks each stage row done, and commits the phase file and the `.build` files with a `Phase:` trailer. +- turns on `plugins/phased-delivery/tests/test_build_check.py::test_fix_commit` (outcome): A fix recorded with `record --fix` for a committed stage is committed with a `Fixes-Stage:` trailer instead of `Stage:`, which `stage-stats.sh` counts as a fix needed for that stage's model. + +Done when: +- `python3 -m pytest -q -p no:cacheprovider --basetemp=/cache/pytest-bc plugins/phased-delivery/tests/test_build_check.py` passes with no expected-fail mark left +- `python3 -m pytest -q -p no:cacheprovider --basetemp=/cache/pytest-bc plugins/phased-delivery/tests` passes +- `sh plugins/phased-delivery/scripts/stage-stats.sh` on a test repository counts the script's commits (shown by the accepted-stage and fix tests) + +Out of scope: +- stage-stats.sh +- The skill text (phase 03) + +Model basis: J1 F1 R1 C1 K2 P1 V0 S0 = 7 -> top (override: J, C or K = 2) + +## Notes +- The script is `scripts/build-check.py`, standard library only, and every subcommand takes the phase file path; the plan directory and phase number come from it, the repository from `--repo` (default: the current directory). Reason: Matches plan-check.py and select-models.py; the phase file is what the orchestrator already holds. +- Revision, ledger and review files live in `<plan>/.build/` as `NN-revision.json`, `NN-ledger.json` and `NN-review.json` and are committed with the phase, so a resumed session reads them. Reason: Resume needs the ledger; keeping them next to the plan keeps them out of the code tree. +- Schemas are checked with plan-check.py's `validate`, loaded by path as plan-mode.py and select-models.py already do. Reason: One JSON Schema subset in the plugin; no new dependency. +- The scope check compares uncommitted changes against HEAD (git status, so ignored files are not seen). Not outside: the stage's files, files of other revision stages that have no commit yet, the phase file's whole directory, preexisting paths, and `__pycache__`, `*.pyc` and `.pytest_cache` paths. record lists outside paths on every build result, including a budget stop; the orchestrator restores them before a retry. start refuses (exit 1) when a stage's file is already modified. Reason: Parallel stages, plan regeneration mid-phase and test caches must not fail a stage; a committed stage's files must not change unseen; leftovers must not fail the next attempt. +- A build exit other than 0 and 8 is recorded as `error` (record exit 4): not a try of the pair (can-try ignores it) and no Earlier-Attempt. The orchestrator then applies today's rule for that tool and exit: claude-build.sh stops and reports; a failed Codex build is rebuilt by the routing rule. Reason: Bookkeeping must not blame the model for a build that never reached a verdict; each tool's failure rule keeps its current meaning. +- Stage commits hold only the stage's files; the phase file, `.build/` and any regenerated plan files are updated in the working tree and committed by `finish` (with `--stopped` at a routing stop, which skips the review and completeness checks and leaves the status in progress). Reason: Keeps the design's 'staging only the stage's files'; resume reads the working tree. +- A review is recorded as stage `review`; `spend` counts only attempts recorded with `--premium`, which the build guide sets for premium-pair builds and for every review run by claude-build.sh, never for Codex. Reason: Matches model-selection.md's premium budget rules. +- commit takes `--subject-suffix TEXT` for subject annotations such as `[skip ci]` and `--extra-trailer LINE` for added trailers such as `Co-Authored-By`. Reason: Project rules may require both; today the orchestrator adds them by hand. +- 2026-11-24: stages built directly by the orchestrator, as in phase 01. +- 2026-11-24: review of phases 01 and 02 together (fable high, in-session subagent): ready, 0 blocking, 12 should-fix. Fixed in 4312f37 (02.1: rename sources count as changed, attempt numbers skip committed tries, real paths and a root-level plan directory, script errors exit 2) and 1e03273 (02.2: reasons folded to one line in trailers, fix commits leave the status line alone, finish marks rows done and names the last stage commit by git order). Added tests for renames and for reject, budget stop and retry. +- 2026-11-24: contract additions from the review: the ledger's result may be `review`; finish takes `--extra-trailer LINE` like commit. +- 2026-11-24: open: check commands run with no timeout; kept until 03.4 shows whether long checks matter. diff --git a/docs/plans/implement-structured/03-cutover.md b/docs/plans/implement-structured/03-cutover.md new file mode 100644 index 0000000..6f60c76 --- /dev/null +++ b/docs/plans/implement-structured/03-cutover.md @@ -0,0 +1,224 @@ +# Phase 03: Skill guides, closed review and validation + +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: built cb5dd40 +Before: implement-in-phases is one 231-line prose SKILL.md; the orchestrator keeps attempts, trailers and premium spend by hand; the phase reviewer has an open list of checks and writes prose findings. build-check.py works but no skill uses it. +After: SKILL.md is short and sends each step to its guide (revise-guide.md, build-guide.md, phase-reviewer.md); the orchestrator writes the revision JSON, calls build-check.py for every gate, commit and spend, and the reviewer writes review JSON with closed finding types. A notes file records why, and the driver-script option as a todo. One paid run shows the skill builds a real phase. + +## Assumptions +- Verified: Nothing outside the skill parses implement-in-phases SKILL.md headings; the hooks only name the skill. (plugins/phased-delivery/hooks/session-start.sh:27 and prompt-reminder.sh mention the skill by name only) +- Verified: The builder evals copy only stage-builder.md, so the restructure does not change them. (evals/lib/make-repo.sh:14 copies DIRECTIONS into stage-builder.md) +- Open: A headless session can load the branch's plugin with `claude --plugin-dir`. (checked at the start of 03.4 with `claude --help`; if it cannot, the run copies the branch's skill into the run repository's plugin directory instead) + +## Outcome tests +Budget: The plugin suite stays under a minute; 03.4's paid run has a ceiling of about $8 (session $2.40 plus the stage and review caps) and runs once. + +| Outcome | Test | Written in | Passes from | +| --- | --- | --- | --- | +| An Opus session at medium thinking, given the restructured skill and the p2-multistep eval task as a one-phase plan in a git repository, builds it through build-check.py: the task's three files pass the hidden check and the stage commit carries the trailers. | `evals/tasks/p2-multistep/check.sh::run repo of 03.4` | 03.4 | 03.4 | + +## Stages + +| Stage | Goal | Tier | Order | Status | +| --- | --- | --- | --- | --- | +| 03.1 | SKILL.md is a short outline that sends revising to revise-guide.md and building, routing, failures and commits to build-guide.md, with every bookkeeping step done through build-check.py. | top | first | done | +| 03.2 | phase-reviewer.md limits findings to the closed types and has the reviewer write the review JSON. | middle+ | parallel with 03.1 | done | +| 03.3 | A notes file explains why implementation uses JSON, a script gate and closed review types, and records the driver script as a todo; the README and plugin version describe the change. | middle | after 03.1 | done | +| 03.4 | One paid run of the restructured skill, built in this session, implements the p2-multistep eval task as a one-phase plan, and its result is recorded in the notes file. | middle+ | after 03.3 | done | + +## 03.1 Thin SKILL.md and step guides + +Goal: SKILL.md is a short outline that sends revising to revise-guide.md and building, routing, failures and commits to build-guide.md, with every bookkeeping step done through build-check.py. + +Context: +- Builds on 01.1: revision JSON format the revise guide tells the orchestrator to write +- Builds on 02.2: build-check.py with every subcommand working +- `plugins/phased-delivery/skills/implement-in-phases/SKILL.md:30-44`: The revision rules that move to revise-guide.md. +- `plugins/phased-delivery/skills/implement-in-phases/SKILL.md:46-116`: Routing, failure ladder, premium spend and Codex rules that move to build-guide.md. +- `plugins/phased-delivery/skills/implement-in-phases/SKILL.md:118-156`: Hand-written trailers, replaced by build-check.py commit. +- `plugins/phased-delivery/skills/plan-in-phases/model-selection.md:218-225`: Describes the hand-kept Premium spend Notes line; becomes build-check.py spend. +- `plugins/phased-delivery/skills/plan-in-phases/SKILL.md:131-143`: The pattern to mirror: a short step that names the guide and the script. +- Design, What stays the same: "They move from +SKILL.md into guides or into the script, not into new rules." +- Design, Check gate: "The orchestrator cannot accept a +stage past a failing check; it may still reject one that passes." + +Contracts: +- format `revision JSON` (uses; 01.1): as 01.1 defines it +- cli `build-check.py start` (uses; 01.2): as 01.2 defines it +- cli `build-check.py can-try` (uses; 01.2): as 01.2 defines it +- cli `build-check.py record` (uses; 01.2): as 01.2 defines it +- cli `build-check.py reject` (uses; 01.2): as 01.2 defines it +- cli `build-check.py commit` (uses; 01.2): as 01.2 defines it +- cli `build-check.py spend` (uses; 01.2): as 01.2 defines it +- cli `build-check.py finish` (uses; 01.2): as 01.2 defines it +- cli `select-models.py route` (uses; plugins/phased-delivery/scripts/select-models.py): route AVAILABLE.json --scores J1F1R0C0K0P0V0S0 [--down N | --up N] [--premium-spent USD] [--review]: one JSON line {model, effort, tier, premium, score, cap_tokens, cap_usd, why} +- cli `claude-build.sh` (uses; plugins/phased-delivery/scripts/claude-build.sh): claude-build.sh REPO PROMPT MODEL EFFORT BUDGET_USD OUTDIR: prints `Tokens: N` and `Cost: X.XX`; exit 0 built, 2 usage, 8 budget reached + +Files: +- `plugins/phased-delivery/skills/implement-in-phases/SKILL.md` (edit): the short outline: before the first phase, each phase's steps, the stop and report, the work report, corrections; each step names its guide and script +- `plugins/phased-delivery/skills/implement-in-phases/revise-guide.md` (create): how to revise the phase file against the repository and write the revision JSON, field by field +- `plugins/phased-delivery/skills/implement-in-phases/build-guide.md` (create): routing, dispatch, the failure ladder, Codex rules and the build-check.py calls for gate, reject, commit and spend +- `plugins/phased-delivery/skills/plan-in-phases/model-selection.md` (edit): its premium budget and Earlier-Attempt lines name build-check.py instead of hand-kept Notes + +Behaviour: +- Given a phase to build, when the orchestrator follows SKILL.md, then it revises, writes `.build/NN-revision.json`, and runs `build-check.py start` before the first dispatch. +- Given a pair route prints, when the orchestrator dispatches, then it runs `can-try` first; on exit 1 it follows the existing rule for a pair already tried (revise the plan). +- Given a finished build, when the orchestrator checks it, then it runs `record`; exit 1 or 3 means restore the outside paths, then `route --up 1` or `route --down 1`; exit 4 means today's rule for that tool and exit; only exit 0 may be committed. +- Given `route` needs the premium spend, when the orchestrator calls it, then it passes `build-check.py spend` output as `--premium-spent`. +- Given SKILL.md, when it is read, then every rule it held before is in it or in a guide it links, with the same meaning; it holds no trailer list or spend arithmetic. +- Given a routing stop after every stage but before the review, when the orchestrator stops, then it sets the Status line to `in progress (stages done: all; review pending)` and runs `finish --stopped`; a capped review is judged by claude-build.sh's own exit, as today. + +External inputs: +none + +Tests: +none + +Done when: +- `wc -l` shows SKILL.md under 110 lines +- Every relative link in SKILL.md, revise-guide.md and build-guide.md resolves to an existing file +- A side-by-side read of the old SKILL.md finds each of its rules in the new files (recorded in the phase Notes) + +Out of scope: +- stage-builder.md (unchanged, the builder evals measure it) +- select-models.py and the routing rules' meaning +- phase-reviewer.md (03.2) + +Model basis: J2 F1 R1 C1 K1 P1 V2 S0 = 9 -> top (override: J, C or K = 2) + +## 03.2 Phase reviewer with closed finding types + +Goal: phase-reviewer.md limits findings to the closed types and has the reviewer write the review JSON. + +Context: +- Builds on 01.1: review JSON format and its finding types +- `plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md:22-43`: The eight open checks to map onto the closed types; Simplicity is narrowed to unneeded code. +- `plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md:45-60`: The prose report and remove/fix/plan-gap actions the JSON replaces. +- `plugins/phased-delivery/skills/plan-in-phases/plan-reviewer.md:20-24`: The plan reviewer's closed-type wording to mirror. +- Design, Review: "The open-ended +"a simpler structure exists" check is dropped." + +Contracts: +- format `review JSON` (uses; 01.1): as 01.1 defines it + +Files: +- `plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md` (edit): closed finding types with what counts as evidence for each, where to look, and the review JSON as its only output + +Behaviour: +- Given a reviewer following phase-reviewer.md, when it reports, then it writes `.build/NN-review.json` that passes review.schema.json, one finding per problem of a listed type, and nothing else. +- Given a structure the reviewer thinks could be simpler but no code is unused, unasked-for or duplicated, when it reviews, then it is not a finding. +- Given a finding needing something the plan lacks, when it is written, then its action is `plan-gap`, and anything the reviewer would add is a `question`. +- Given a change in the plan directory other than the phase file's status, table and Notes and the `.build` files, when the reviewer reads the diff, then it is an untraced change. + +External inputs: +none + +Tests: +none + +Done when: +- Each of the eight types in review.schema.json is defined in phase-reviewer.md with its evidence +- The reviewer's inputs still name the phase file, diff, pre-existing edits and project instructions + +Out of scope: +- The review routing (`route --review`) and who runs the review + +Model basis: J1 F0 R1 C1 K0 P0 V2 S0 = 5 -> middle+ (override: middle with a measure at 2) + +## 03.3 Notes, driver todo, README and version + +Goal: A notes file explains why implementation uses JSON, a script gate and closed review types, and records the driver script as a todo; the README and plugin version describe the change. + +Context: +- Builds on 03.1: the new guides and build-check.py usage to describe +- `plugins/phased-delivery/skills/plan-in-phases/structured-planning-notes.md:1-5`: The notes file to mirror for implementation. +- `README.md:195-200`: The README section describing how trailers are written today. +- `plugins/phased-delivery/.claude-plugin/plugin.json:3`: Version to raise to 0.11.0. +- Design, Later: "the draft on the `plan-phase-driver` branch) is recorded as a todo +for later investigation" + +Contracts: +none + +Files: +- `plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md` (create): why the restructure, what it replaced, and a Later section with the driver-script todo and its trade-offs, pointing at the plan-phase-driver branch +- `README.md` (edit): the phased-delivery section names build-check.py and the step guides +- `plugins/phased-delivery/.claude-plugin/plugin.json` (edit): version 0.11.0 + +Behaviour: +- Given a maintainer wondering whether to build the driver, when they read the notes file's Later section, then it names the plan-phase-driver branch, what the driver would add, what it would cost, and what to measure first. + +External inputs: +none + +Tests: +none + +Done when: +- `grep -n plan-phase-driver` finds the todo in structured-implementation-notes.md +- plugin.json version is 0.11.0 + +Out of scope: +- Deleting or changing the plan-phase-driver branch + +Model basis: J1 F1 R1 C0 K0 P0 V1 S0 = 4 -> middle + +## 03.4 Paid end-to-end run on p2-multistep + +Goal: One paid run of the restructured skill, built in this session, implements the p2-multistep eval task as a one-phase plan, and its result is recorded in the notes file. + +Context: +- Builds on 03.1: the restructured skill +- Builds on 03.3: the notes file to record the result in +- `evals/new-run.sh:2-4`: Makes the run repository with the task's phase file in plan/. +- `evals/lib/make-repo.sh:18-19`: The phase file lands at plan/01-<task>.md. +- `evals/README.md:93-99`: Runs use EVAL_HOME in /cache because /tmp is noexec. +- `evals/lib/scope.py:9-16`: The hidden check fails on any file outside files.txt, so it runs on a copy holding only the task's files. +- Design, Validation: "it runs only after the user +confirms its cost" + +Contracts: +none + +Files: +- `plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md` (edit): a Measured section with the run's result, cost and what went wrong + +Behaviour: +- Given the user's ceiling of about $8, when the run is set up, then `new-run.sh p2-multistep` makes the repository; it gets a models-available.json offering only opus and haiku, a models.md regenerated by the branch's selector (`check` exits 0), project rules that allow git and plan edits and say only opus and haiku are available, then `git init` and one commit. +- Given that repository, when the run starts, then a headless Opus session at medium thinking with `--plugin-dir` set to the branch's plugin, the installed phased-delivery turned off through `--settings`, and `--max-budget-usd 2.40` is asked to implement its plan, naming the branch's scripts by absolute path. +- Given the run ends, when it is checked, then the three files in the task's files.txt are copied onto a fresh `new-run.sh p2-multistep` repository and `sh collect.sh` runs there; the RESULT line, the commits and trailers in the built repository, the total cost and any skill rule the session skipped are recorded. + +External inputs: +none + +Tests: +- writes `evals/tasks/p2-multistep/check.sh::run repo of 03.4` (outcome): An Opus session at medium thinking, given the restructured skill and the p2-multistep eval task as a one-phase plan in a git repository, builds it through build-check.py: the task's three files pass the hidden check and the stage commit carries the trailers. + +Done when: +- The notes file's Measured section records the run: check result, commits with trailers, cost +- The user has seen the result + +Out of scope: +- Old-versus-new comparison runs +- Changing the eval tasks + +Model basis: J1 F0 R1 C0 K0 P1 V1 S2 = 6 -> middle+ (override: middle with a measure at 2) + +## Notes +- The script is `scripts/build-check.py`, standard library only, and every subcommand takes the phase file path; the plan directory and phase number come from it, the repository from `--repo` (default: the current directory). Reason: Matches plan-check.py and select-models.py; the phase file is what the orchestrator already holds. +- Revision, ledger and review files live in `<plan>/.build/` as `NN-revision.json`, `NN-ledger.json` and `NN-review.json` and are committed with the phase, so a resumed session reads them. Reason: Resume needs the ledger; keeping them next to the plan keeps them out of the code tree. +- stage-builder.md does not change. Reason: The builder evals measure it; changing it would break comparison with earlier runs. +- Routing, the retry ladder, caps, premium budget and Codex rules keep their meaning and move into build-guide.md; only who keeps the numbers changes. Reason: Agreed scope: restructure, not new rules. +- The scope check compares uncommitted changes against HEAD (git status, so ignored files are not seen). Not outside: the stage's files, files of other revision stages that have no commit yet, the phase file's whole directory, preexisting paths, and `__pycache__`, `*.pyc` and `.pytest_cache` paths. record lists outside paths on every build result, including a budget stop; the orchestrator restores them before a retry. start refuses (exit 1) when a stage's file is already modified. Reason: Parallel stages, plan regeneration mid-phase and test caches must not fail a stage; a committed stage's files must not change unseen; leftovers must not fail the next attempt. +- A build exit other than 0 and 8 is recorded as `error` (record exit 4): not a try of the pair (can-try ignores it) and no Earlier-Attempt. The orchestrator then applies today's rule for that tool and exit: claude-build.sh stops and reports; a failed Codex build is rebuilt by the routing rule. Reason: Bookkeeping must not blame the model for a build that never reached a verdict; each tool's failure rule keeps its current meaning. +- Stage commits hold only the stage's files; the phase file, `.build/` and any regenerated plan files are updated in the working tree and committed by `finish` (with `--stopped` at a routing stop, which skips the review and completeness checks and leaves the status in progress). Reason: Keeps the design's 'staging only the stage's files'; resume reads the working tree. +- A review is recorded as stage `review`; `spend` counts only attempts recorded with `--premium`, which the build guide sets for premium-pair builds and for every review run by claude-build.sh, never for Codex. Reason: Matches model-selection.md's premium budget rules. +- commit takes `--subject-suffix TEXT` for subject annotations such as `[skip ci]` and `--extra-trailer LINE` for added trailers such as `Co-Authored-By`. Reason: Project rules may require both; today the orchestrator adds them by hand. +- 2026-11-24: stages built directly by the orchestrator, as in phases 01 and 02; 03.3 was committed before 03.2 (they share no file). +- 2026-11-24: 03.1 Done when, side-by-side read: every rule of the old SKILL.md is in SKILL.md, revise-guide.md, build-guide.md or model-selection.md; "two stages sharing a commit" is gone, since build-check.py commits one stage at a time. SKILL.md is 109 lines. +- 2026-11-24: 03.4 run: RESULT pass, $0.84 in total (session $0.54, review $0.30); details in structured-implementation-notes.md, "Measured". Open assumption on `--plugin-dir` verified: only the branch's plugin loaded (`phased-delivery@inline`, 0.11.0). +- 2026-11-24: phase review (fable high, in-session subagent, new phase-reviewer.md with review JSON): ready, 0 blocking, 2 should-fix, both fixed: plan-directory edits recorded in the Notes count as traced (c9c27fd, a revision of 03.2's brief wording); phase-level fixes are recorded against the stage they change (d1ca4e9). Commit trailers of 03.2 and 03.4 say middle and small where the plan said middle+; all stages were built by the orchestrator. +- 2026-11-24: the notes file points at the plan-phase-driver branch, which exists only locally; push it before relying on that pointer. +- 2026-11-24: commit 064c397 (CI workflow for pull requests) is outside the plan, added for the PR at the user's request. diff --git a/docs/plans/implement-structured/design.md b/docs/plans/implement-structured/design.md new file mode 100644 index 0000000..1710303 --- /dev/null +++ b/docs/plans/implement-structured/design.md @@ -0,0 +1,70 @@ +# Structured implementation: design + +Agreed with the user on 2026-11-23. The plan in this folder builds it. + +## Goal + +implement-in-phases follows the architecture plan-in-phases now has: a +short SKILL.md that sends each step to its own guide, JSON written against +schemas where a step's result is read by something else, a script that +decides everything that needs no judgment, and a review limited to a +closed list of finding types. The LLM still orchestrates the phase. + +## What stays the same + +The routing, budget, retry ladder, premium spend limit, Codex rules, +commit trailers and work report keep their current meaning. They move from +SKILL.md into guides or into the script, not into new rules. The trailer +format is unchanged, so `stage-stats.sh` needs no change. + +## Revision + +Revising a phase against the repository ends in a revision JSON for the +phase, written against a schema: for each stage, the files it may change, +the check commands that show its "Done when", and its re-scored measures; +the verdict on each open assumption; and the adjustments made. The script +reads the revision JSON, not the phase file's prose, so plans written in +older layouts work too. + +## Check gate + +After each build, the script checks the stage: no file outside the stage's +files changed (edits present before the phase do not count), and every +check command passes. A failing check counts as a failed "Done when": the +stage goes to `route --up` as today. The orchestrator cannot accept a +stage past a failing check; it may still reject one that passes. + +## Bookkeeping + +The script owns the per-phase ledger: each attempt's tool, model, effort, +exit status, tokens, cost and check result. From it the script refuses a +pair already tried for the stage, reports the premium spend for +`route --premium-spent`, makes each stage commit (staging only the stage's +files, with the trailers from the ledger), and updates the phase file's +stage table and status line. The orchestrator no longer writes trailers +or sums spend by hand. + +## Review + +The phase reviewer reports only these finding types, each with file, line +and evidence: untraced change, check on internal data, bug or contract +mismatch, unmet "Done when" or "After", missing or wrong test, broken +assumption, project rule broken, and unneeded code (code nothing calls, a +wrapper or option no brief asks for, or duplicated logic). The open-ended +"a simpler structure exists" check is dropped. Findings are written as +JSON against a schema, each with its action: remove, fix, plan gap or +question. + +## Validation + +Offline tests run the script against temporary git repositories with no +model calls. One paid end-to-end run of the new skill on the builder eval +task `p2-multistep` (Opus, medium thinking, with a ceiling of about $8: the session capped at $2.40 plus the stage and review caps route prints; agreed with the user 2026-11-24) checks +that an agent follows the split guides; it runs only after the user +confirms its cost. + +## Later + +A driver script that owns the whole loop and calls `claude -p` for each +step (the draft on the `plan-phase-driver` branch) is recorded as a todo +for later investigation, not built here. diff --git a/docs/plans/implement-structured/models-available.json b/docs/plans/implement-structured/models-available.json new file mode 100644 index 0000000..42422f4 --- /dev/null +++ b/docs/plans/implement-structured/models-available.json @@ -0,0 +1,14 @@ +{ + "tool": "claude-code", + "tool_version": "2.1.330", + "looked_up_from": "Agent tool parameter description (model and effort enums), 2026-11-23", + "subagent_model_choice": "allowed", + "opted_in": true, + "opt_in_where": "phased-delivery skills set model and effort per models.md", + "models": [ + {"id": "fable", "efforts": ["low", "medium", "high", "xhigh", "max"]}, + {"id": "opus", "efforts": ["low", "medium", "high", "xhigh", "max"]}, + {"id": "sonnet", "efforts": ["low", "medium", "high", "xhigh", "max"]}, + {"id": "haiku", "efforts": ["low", "medium", "high", "xhigh", "max"]} + ] +} diff --git a/docs/plans/implement-structured/models.md b/docs/plans/implement-structured/models.md new file mode 100644 index 0000000..e689549 --- /dev/null +++ b/docs/plans/implement-structured/models.md @@ -0,0 +1,46 @@ +# Models + +Generated by `scripts/select-models.py` from `models-available.json` and +the plugin's `model-profiles.json`; rerun it rather than editing this file. + +Looked up: claude-code 2.1.330, from Agent tool parameter description (model and effort enums), 2026-11-23 +Profiles: 438ab73a830ba4736e7ab9e51196e3b2c0ccfdc3ce65c2a7889d70081e9d9749 (data checked 2026-11-21); Data: Artificial Analysis (https://artificialanalysis.ai) +Subagent model choice: allowed +Score: intelligence; cost: run_cost_usd; best score 61.8; floors: top 97%, middle 85%, small 50%; cheaper within 3 points wins + +| Tier | Model | Effort | Score | Cost | Report row | +| --- | --- | --- | --- | --- | --- | +| small | haiku | xhigh | 34.6 | 192.70 | Claude Haiku 5.5 (Xhigh) | +| middle | opus | high | 51.8 | 2715.98 | Claude Opus 5.5 (High, Default Fallback) | +| middle+ | fable | low | 53.9 | 2861.78 | Claude Fable 5.2 (Low, Default Fallback) | +| top | fable | high | 61.8 | 7105.77 | Claude Fable 5.2 (High, Default Fallback) | + +Matches (tool model -> report model): +- fable -> Claude Fable 5.2 (alias: newest release containing the name) +- opus -> Claude Opus 5.5 (alias: newest release containing the name) +- sonnet -> Claude Sonnet 5.5 (alias: newest release containing the name) +- haiku -> Claude Haiku 5.5 (alias: newest release containing the name) + +Candidates considered: +- fable at high: score 61.8, cost 7105.77 +- fable at medium: score 56.4, cost 3359.66 +- fable at low: score 53.9, cost 2861.78 +- opus at high: score 51.8, cost 2715.98 +- opus at medium: score 48.2, cost 2031.27 +- sonnet at high: score 41.5, cost 1268.30 +- opus at low: score 34.8, cost 979.66 +- haiku at xhigh: score 34.6, cost 192.70 +- sonnet at medium: score 30.8, cost 679.16 +- haiku at high: score 29.9, cost 121.41 +- sonnet at low: score 25.6, cost 499.20 +- haiku at medium: score 24.6, cost 72.70 +- haiku at low: score 18.6, cost 39.60 + +Excluded: +- fable at max: denied: above this model's high ceiling +- fable at xhigh: denied: above this model's high ceiling +- opus at max: denied: above this model's high ceiling +- opus at xhigh: denied: above this model's high ceiling +- sonnet at max: denied: above this model's high ceiling +- sonnet at xhigh: denied: above this model's high ceiling +- haiku at max: denied: above this model's xhigh ceiling diff --git a/docs/plans/implement-structured/work-report.md b/docs/plans/implement-structured/work-report.md new file mode 100644 index 0000000..66820ba --- /dev/null +++ b/docs/plans/implement-structured/work-report.md @@ -0,0 +1,32 @@ +# Work report: implement-structured + +## Work by model + +Range `ae57d33..HEAD`: 9 accepted stages, 5 later fixes. + +| Model | Effort | Tool | Stages | First try | Clean | Failed tries | Fixes needed | Tokens spent | Wasted | Per stage | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| orchestrator | default | claude-code | 9 | 9/9 | 4/9 | 0 | 5 | 0 (+14 unknown) | 0 | n/a | +| **All** | | | 9 | 9/9 | 4/9 | 0 | 5 | 0 (+14 unknown) | 0 | | + +### Reruns + +None. + +### Fixes after acceptance + +- 03.4 (built by orchestrator default): Fix 03.4: list can-try and headless dispatch as not exercised; by orchestrator default, unknown tokens [cb5dd40] +- 03.1 (built by orchestrator default): Fix 03.1 review finding: record phase-level fixes against the stage they change; by orchestrator default, unknown tokens [d1ca4e9] +- 03.2 (built by orchestrator default): Fix 03.2 review finding: plan-directory edits recorded in the Notes are traced; by orchestrator default, unknown tokens [c9c27fd] +- 02.2 (built by orchestrator default): Fix 02.2 review findings: one-line reasons, status after fixes, finish rows and last commit; by orchestrator default, unknown tokens [1e03273] +- 02.1 (built by orchestrator default): Fix 02.1 review findings: renames, attempt numbers, paths, script errors; by orchestrator default, unknown tokens [4312f37] + +## Reading + +- **Effectiveness:** every one of the 9 stages was built by the orchestrator in the session and accepted first try, but only 4 of 9 are clean. The 5 fixes came from the two phase reviews. In phase 02 they were edge cases the briefs named only loosely: renames, a second fix of a stage, multi-line reasons, stages committed out of order, and a plan directory at the repository root. In phase 03 the cause was wording that conflicted between two guides. Nothing here judges a routed model, because none was dispatched. +- **Cost:** no token counts. The stages ran inside this session, which reports no per-stage usage. The paid costs were the review subagents (in-session, unreported) and the validation run in 03.4 ($0.84). +- **Candidates:** there's no evidence to change any tier's candidate: no stage went to a routed builder. + +## Unknown token counts + +All 14 commits (9 stages, 5 fixes) say `Tokens: unknown`, because they were built in the orchestrator session, which has no per-stage usage report. diff --git a/plugins/phased-delivery/.claude-plugin/plugin.json b/plugins/phased-delivery/.claude-plugin/plugin.json index d1ae80a..165aef5 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.10.0", + "version": "0.11.0", "description": "Plan work as self-contained phases, then implement it phase by phase.", "author": { "name": "Bryan" diff --git a/plugins/phased-delivery/scripts/build-check.py b/plugins/phased-delivery/scripts/build-check.py new file mode 100755 index 0000000..4ebc867 --- /dev/null +++ b/plugins/phased-delivery/scripts/build-check.py @@ -0,0 +1,418 @@ +#!/usr/bin/env python3 +"""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] + [--extra-trailer LINE]... [--repo DIR] + build-check.py spend PHASE_FILE + build-check.py finish PHASE_FILE [--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. +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. +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). +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 <commit>" and commits + the phase file's directory with a Phase: trailer. --stopped skips + the review and status and only commits the directory. + +Exit codes not listed: 0 done; 1 refused (one JSON line per problem for +invalid JSON); 2 bad usage or a missing file. +""" + +import argparse +import importlib.util +import json +import os +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +SKILL = os.path.join(HERE, "..", "skills", "implement-in-phases") +_spec = importlib.util.spec_from_file_location("plan_check", os.path.join(HERE, "plan-check.py")) +plan_check = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(plan_check) + + +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")} + + +def load_checked(path, schema_name, label): + """Return (data, problems); problems are printed as JSON lines by the caller.""" + if not os.path.isfile(path): + raise Usage(f"missing {path}") + try: + data = json.load(open(path)) + except ValueError as e: + return None, [{"file": label, "where": "/", "msg": f"not valid JSON: {e}"}] + schema = json.load(open(os.path.join(SKILL, schema_name))) + errs = plan_check.validate(data, schema) + return (None if errs else data), [{"file": label, "where": w or "/", "msg": m} for w, m in errs] + + +def report(problems): + for p in problems: + print(json.dumps(p)) + return 1 if problems else 0 + + +# ---- repository and ledger + +def git(repo, *args, check=True): + r = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True) + if check and r.returncode: + raise Usage(f"git {' '.join(args)}: {(r.stderr + r.stdout).strip()}") + return r.stdout + + +def toplevel(repo): + return git(repo, "rev-parse", "--show-toplevel").strip() + + +def changed_paths(top): + """Uncommitted paths against HEAD, untracked included and ignored files left out.""" + out = git(top, "status", "--porcelain", "-z", "--untracked-files=all").split("\0") + found, i = [], 0 + while i < len(out): + entry = out[i] + i += 1 + if not entry: + continue + found.append(entry[3:]) + if entry[0] in "RC": + found.append(out[i]) # the rename's source path: it changed too + i += 1 + return found + + +def rel(top, path): + return os.path.relpath(os.path.realpath(path), top) + + +def in_dir(path, directory): + return directory == "." or (path + "/").startswith(directory + "/") + + +def is_cache(path): + parts = path.split("/") + 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 committed_stages(ledger): + return {a["stage"] for a in ledger["attempts"] if a["result"] == "accepted" and a["commit"] and not a["fix"]} + + +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"]} + 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)] + + +def run_checks(top, commands): + return [{"cmd": c, "exit": subprocess.run(["sh", "-c", c], cwd=top, capture_output=True).returncode} + for c in commands] + + +def amount(x): + return "unknown" if x is None else f"{x:.2f}" + + +def count(x): + return "unknown" if x is None else str(int(x)) + + +# ---- subcommands + +def cmd_start(a): + f = paths(a.phase_file) + revision, problems = load_checked(f["revision"], "revision.schema.json", "revision") + if problems: + return report(problems) + if os.path.exists(f["ledger"]): + 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] + if dirty: + return report(dirty) + save(f["ledger"], {"start_commit": git(top, "rev-parse", "HEAD").strip(), "preexisting": now, "attempts": []}) + 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": + 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) + 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"]: + return x + return None + + +def cmd_reject(a): + f = paths(a.phase_file) + ledger = ledger_of(f) + x = open_attempt(ledger, a.stage) + 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) + 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) + 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) + 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: + 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"] + 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)) + 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"]) + print(f"{total:.2f}") + return 0 + + +def cmd_finish(a): + f = paths(a.phase_file) + ledger, revision = ledger_of(f), load(f["revision"]) + 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() + 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)) + return 0 + + +def number(text): + if text == "unknown": + return None + try: + return float(text) + except ValueError: + raise argparse.ArgumentTypeError(f"not a number or 'unknown': {text}") + + +def parse_args(argv): + p = argparse.ArgumentParser(prog="build-check.py", description=__doc__, + 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("--repo", default=".") + s = sub.add_parser("can-try") + for k in ("phase_file", "stage", "model", "effort"): + s.add_argument(k) + s = sub.add_parser("record") + s.add_argument("phase_file") + s.add_argument("stage") + for k in ("--tool", "--model", "--effort"): + s.add_argument(k, required=True) + s.add_argument("--exit", type=int, required=True, dest="exit_code") + s.add_argument("--tokens", type=number, required=True) + s.add_argument("--cost", type=number, required=True) + s.add_argument("--cap", type=number) + s.add_argument("--tool-calls", type=number) + s.add_argument("--premium", action="store_true") + s.add_argument("--fix", action="store_true") + s.add_argument("--repo", default=".") + s = sub.add_parser("reject") + for k in ("phase_file", "stage", "why"): + s.add_argument(k) + s = sub.add_parser("commit") + s.add_argument("phase_file") + 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 = sub.add_parser("finish") + s.add_argument("phase_file") + s.add_argument("--stopped", action="store_true") + s.add_argument("--extra-trailer", action="append", default=[]) + s.add_argument("--repo", default=".") + return p.parse_args(argv) + + +COMMANDS = {"start": cmd_start, "can-try": cmd_can_try, "record": cmd_record, "reject": cmd_reject, + "commit": cmd_commit, "spend": cmd_spend, "finish": cmd_finish} + + +def main(argv): + a = parse_args(argv) + try: + return COMMANDS[a.cmd](a) + except (Usage, OSError, ValueError) as e: + print(e, file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md index d32018f..0a82c7f 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/SKILL.md +++ b/plugins/phased-delivery/skills/implement-in-phases/SKILL.md @@ -10,6 +10,14 @@ 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. +Each step below has its own guide; read it when you reach the step. +`scripts/build-check.py` (in this plugin, two directories above this +skill's directory) decides what needs no judgment: whether a build stayed +in its files and passed its checks, which model and thinking level pairs +were already tried, the premium spend, and every commit with its trailers. +Do not count, sum or write those by hand. Why it works this way is in +[structured-implementation-notes.md](structured-implementation-notes.md). + ## Before the first phase 1. Read the project instructions, specification, design and every phase file. @@ -19,168 +27,43 @@ unchanged. 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: <commit>`; the work report counts - from it. On resume, find where the phase left off from its - status line and stage table. + from it. On resume, find where the phase left off from its status line, + stage table and `.build/NN-ledger.json`. 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 the phase file - -Before building, check the phase file against what actually exists: earlier -phases may have changed names, paths or details. Update its context, contracts -and briefs so each stage is correct for the repository as it is, and 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. - -### 2. Build the stages - -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. Delegation keeps each agent's context -focused on its brief. - -Before the phase's first dispatch, run `scripts/select-models.py check -<plan>/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](../plan-in-phases/model-selection.md) describes. - -Route every dispatch by "Route each stage" in model-selection.md: start -from the brief's `Model basis` scores, re-score against the revised brief -and the code as it now is, record any change in the Notes, and run -`scripts/select-models.py route <plan>/models-available.json --scores -<scores> --premium-spent <X>`, with X from the phase's -`Premium spend: $X of $10` Notes line (0 until the first premium run). -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 <repo> <prompt> <model> <effort> <cap_usd> -<outdir>` with route's `model`, `effort` and `cap_usd`. Read its report -from `<outdir>/report.md`; it prints `Tokens:` and `Cost:` for the commit. -Accept it exactly as a subagent's work. The limits: - -- **Exit 8, budget reached:** retry with `route --down 1`, one step - further on each further stop; each stopped attempt is an Earlier-Attempt. - Never re-dispatch a pair already tried for the stage; when `route` would, - revise the plan (model-selection.md, "Adjust while working"). -- **Any other non-zero exit** (2: bad arguments or permissions setting; - otherwise claude's own status, such as a sign-in or service failure): - report stderr's last line to the user and stop; do not step up. -- **Fails its "Done when" or is harder than its scores:** rerun with - `route --up 1` (one step further on each further failure). When it stops - because the brief is wrong, revise the plan instead. -- **Premium spend:** after each `claude-build.sh` run of a pair route - printed with `"premium": true`, and of every review it runs, add its - `Cost:` (its `cap_usd` when unknown) to the `Premium spend` line. From - $10, builds get no premium pair. Codex runs add nothing and their - `route` calls pass no `--premium-spent`. -- `CLAUDE_BUILD_PERMISSIONS` unset gives the builder `acceptEdits`: file - edits, and commands the project's allow rules permit. A session already - in a sandbox container may set it to `bypassPermissions` (the ai-coding - sandbox sets it already). - -When the plan has `models-codex.md` and the session is not Codex, take -Codex availability from the daily check in "Builders in another tool" in -model-selection.md: off when the session was told at start that Codex is -off today, otherwise what `scripts/codex-usage.py` answers from its daily -cache before the phase's first dispatch. When Codex is off, skip the rest -of this paragraph and record why in the Notes. While Codex is on, refresh -`models-codex.md` the same way, then before each dispatch run -`scripts/claude-usage.py` and `scripts/codex-usage.py` and route the stage -by the routing table there. A Codex dispatch runs alone (stages marked -parallel run one after another when one goes to Codex) and starts with the -snapshot of REPO; follow the rules there for failed Codex builds. -For a Codex build, write stage-builder.md and its filled-in inputs to a -prompt file outside the repository and run `scripts/codex-build.sh <repo> <prompt> <model> <effort> -<outdir>`, with the model and effort `route` prints for -`models-available-codex.json` (Codex builds have no cap). -Read its report from `<outdir>/report.md`; it prints the token count for -the commit. Accept it exactly as a subagent's work. - -For a `small` stage, never take the builder's report as evidence: rerun its -"Done when" commands yourself and read its diff before accepting it. - -When a stage is accepted, mark its status in the table and commit it (see -"Commit each stage" below). - -### Commit each stage - -One local commit per stage, so each model's work can be traced and counted. -Stage only that stage's files; keep edits that were already present out of -it. Stages built in parallel are still committed one by one; if two must -share a commit, give it one set of trailers per stage. Subject: the stage -number and title, plus the project's required annotations (such as -`[skip ci]`). End the message with these trailers: - -``` -Stage: 02.3 -Plan: <path to the phase file> -Tier: small -Tool: <tool that built it, such as claude-code or codex> -Model: <model as dispatched> -Effort: <thinking level as dispatched, or "default"> -Attempt: 1 -Tokens: <total tokens for this attempt, or "unknown"> -Cost: <the Cost line claude-build.sh printed, or "unknown"> -Tool-Calls: <count, or "unknown"> -``` - -- **Model, Effort** are what was dispatched; "orchestrator" when the stage - was built directly. -- **Tokens, Cost, Tool-Calls** come from the tool's own usage report (the - lines `claude-build.sh` or `codex-build.sh` prints; for an in-session - subagent, its completion notice), never from the builder's report. Use - "unknown" when the tool gives none; the build scripts print no tool-call - count. -- **Attempt** counts dispatches of this stage, including `--down` and - `--up` reruns; commit only the accepted attempt, and list earlier ones as - `Earlier-Attempt: <model> <effort> <tokens> <why it failed>` (for exit 8, - "budget reached"). -- A change made later to fix a committed stage, from the phase review or - later work, gets its own commit with `Fixes-Stage: <stage>`, - `Model:`, `Effort:` and `Tokens:` of whoever made the fix. - -`scripts/stage-stats.sh` turns these trailers into the work report (see -"Report the models' work" below). - -### 3. Review the phase - -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`; add its -`Cost:` to the phase's premium spend. A review never drops a step: if it -stops at its cap (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`. It reads the actual diff and code, not -the builders' reports. Then read the diff yourself and decide on each -finding. - -The review may remove, simplify or fix deviations. Anything it wants to add -goes in the report as a question. Problems the plan does not cover go back -through plan-in-phases' revision rules -([revising.md](../plan-in-phases/revising.md)) before any code changes. - -### 4. Commit and stop - -Commit each review fix as described in "Commit each stage". Then update the -phase's status line and Notes and commit them on their own, with the -trailer `Phase: <phase file>`. Never push or publish unless asked. - -Stop and report to the user: +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 <phase file>` 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. +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 <phase file> + 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 + 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; + - `question`: put it to the user in the report. +4. **Finish.** Update the phase's Notes, then run `build-check.py finish + <phase file>`: it checks the review JSON and that every stage has a + commit, sets `Status: built <commit>` and commits the plan directory + with a `Phase:` trailer. Never push or publish unless asked. + +Then stop and report to the user: - each stage: done or not, and where to see it; - deviations from the briefs, or "none"; @@ -192,15 +75,10 @@ Stop and report to the user: - whether Codex was on or off this phase, and why; - questions, and the next phase. -When the routing rule stops the phase (both tools nearly out), stop the -same way after committing the stage in progress, and also report the -stages left and both usage scripts' output lines (usage and reset times). -A stop at the check before the review sets -`Status: in progress (stages done: all; review pending)`; resuming starts -with the review, after checking availability and the routing rule again. +A routing stop follows build-guide.md, "Stopping mid-phase"; report it the +same way, adding the stages left and both usage scripts' output lines. -Continue to the next phase only when the user says so. An explicit user stop -always wins. +Continue to the next phase only when the user says so; a user stop wins. ## Report the models' work diff --git a/plugins/phased-delivery/skills/implement-in-phases/build-guide.md b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md new file mode 100644 index 0000000..afba66f --- /dev/null +++ b/plugins/phased-delivery/skills/implement-in-phases/build-guide.md @@ -0,0 +1,147 @@ +# Build the stages: guide + +How to route, dispatch, gate and commit each stage of a phase. The routing +rules are in [model-selection.md](../plan-in-phases/model-selection.md); +`scripts/build-check.py` keeps the attempts, 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. + +## Models + +Before the phase's first dispatch, run `scripts/select-models.py check +<plan>/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 +describes. + +## Route and dispatch each stage + +1. Take the stage's `scores` from the revision JSON. +2. Run `scripts/select-models.py route <plan>/models-available.json + --scores <scores> --premium-spent $(scripts/build-check.py spend <phase + file>)` ("Route each stage" in model-selection.md). +3. Run `build-check.py can-try <phase file> <stage> <model> <effort>`. Exit + 1 means the pair was already tried for this stage: do not dispatch it; + revise the plan (model-selection.md, "Adjust while working"). +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 <repo> <prompt> <model> <effort> <cap_usd> + <outdir>` with route's `model`, `effort` and `cap_usd`. Read the + builder's report from `<outdir>/report.md`; the script prints `Tokens:` + and `Cost:`. Accept it exactly as a subagent's work. + +`CLAUDE_BUILD_PERMISSIONS` unset gives the builder `acceptEdits`: file +edits, and commands the project's allow rules permit. A session already in +a sandbox container may set it to `bypassPermissions` (the ai-coding +sandbox sets it already). + +## Gate each build + +After every build, record it: + +``` +build-check.py record <phase file> <stage> --tool claude-code --model <m> --effort <e> \ + --exit <build exit> --tokens <Tokens> --cost <Cost> --cap <cap_usd> [--tool-calls N] [--premium] +``` + +Pass `--premium` when route printed `"premium": true`. `--tool-calls` comes +from the tool's own usage report (an in-session subagent's completion +notice); leave it out when there is none. Tokens and cost are `unknown` +when the tool gives none, never the builder's own claim. + +It prints one JSON line and exits: + +- **0, accepted:** no changed file outside the scope rule, 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 <phase file> <stage> + "<why>"` 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. +- **3, budget reached** (build exit 8): restore the `outside` paths, then + retry with `route --down 1`, one step further on each further stop. +- **4, error** (any other build exit): not a try of the pair. Apply that + tool's rule: for `claude-build.sh` (2: bad arguments or permissions; + otherwise claude's own status, such as a sign-in or service failure), + report stderr's last line to the user and stop; for a failed Codex build, + follow model-selection.md ("After a failed build"). + +A stage that has both hit its cap and failed its checks goes back to +planning; never net `--down` against `--up`. + +For a `small` stage, never take the builder's report as evidence: the +checks are rerun by `record`, and read its diff before committing. + +## Premium spend + +`build-check.py spend <phase file>` prints the phase's premium spend: the +cost of every attempt recorded with `--premium`, its cap when the cost is +unknown. Pass `--premium` for every `claude-build.sh` run of a premium pair +and for every phase review run through `claude-build.sh`. From $10, builds +get no premium pair (route does this). Codex runs are never `--premium` and +their `route` calls pass no `--premium-spent`. + +## Commit each stage + +When a stage is accepted, run: + +``` +build-check.py commit <phase file> <stage> [--subject-suffix "[skip ci]"] [--extra-trailer "Co-Authored-By: ..."] +``` + +It commits only the stage's changed files, with the subject `NN.n <title>` +and the trailers `stage-stats.sh` reads (Stage, Plan, Tier, Tool, Model, +Effort, Attempt, Tokens, Cost, Tool-Calls, and an Earlier-Attempt per +failed, stopped or rejected try), and marks the stage done in the phase +file's table and status line (in the working tree; `finish` commits them). +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 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. + +## Codex + +When the plan has `models-codex.md` and the session is not Codex, take +Codex availability from the daily check in "Builders in another tool" in +model-selection.md: off when the session was told at start that Codex is +off today, otherwise what `scripts/codex-usage.py` answers from its daily +cache before the phase's first dispatch. When Codex is off, skip the rest +of this section and record why in the Notes. + +While Codex is on, refresh `models-codex.md` the same way as `models.md`, +then before each dispatch run `scripts/claude-usage.py` and +`scripts/codex-usage.py` and route the stage by the routing table there. A +Codex dispatch runs alone (stages marked parallel run one after another +when one goes to Codex) and starts with the snapshot of REPO; follow the +rules there for failed Codex builds. For a Codex build, write +stage-builder.md and its filled-in inputs to a prompt file outside the +repository and run `scripts/codex-build.sh <repo> <prompt> <model> <effort> +<outdir>`, with the model and effort `route` prints for +`models-available-codex.json` (Codex builds have no cap), and record it +with `--tool codex`. Read its report from `<outdir>/report.md`; it prints +the token count. + +## Stopping mid-phase + +When the routing rule stops the phase (both tools nearly out), commit the +stage in progress, then run `build-check.py finish <phase 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. 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 bb6b8fd..76a5b16 100644 --- a/plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md +++ b/plugins/phased-delivery/skills/implement-in-phases/phase-reviewer.md @@ -12,6 +12,7 @@ Inputs the orchestrator fills in: - 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` --- @@ -19,42 +20,67 @@ You are reviewing the code a phase actually changed, against its plan. Read the diff and the code, not the builders' reports, and none of your own assumptions about the codebase: open the files. -## What to check - -1. **Traceability:** every changed line maps to a stage brief. List any that - does not. -2. **Checks:** every validation or error check maps to an external input - listed in a brief. List checks on internal data. -3. **Correctness:** the code does what each brief's goal and contracts say, - including edge cases the brief names. Look for bugs, broken callers and - contract mismatches between stages. -4. **Simplicity:** a simpler structure exists: fewer wrappers, less state, - fewer branches, no repeated work. Compressed syntax or complexity moved - elsewhere is not simpler. -5. **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. -6. **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 - phase have no expected-fail mark left. Report tests the briefs do not - name, and tests that are flaky or over the phase's budget. -7. **Assumptions:** the phase's assumptions still hold in the built code. A - wrong assumption that affects later phases or earlier architecture must be - reported, with which phase it affects. -8. **Rules:** project rules and limits are kept. +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, style, or a structure you would have chosen differently. + +`scripts/build-check.py` has already checked, for every stage, that no file +outside the stage's files changed and that the stage's check commands +passed. Do not re-run those to confirm them; spend the reading on what needs +judgment. + +## Where to look + +- **Traceability:** every changed line maps to a stage brief. +- **Checks:** every validation or error check maps to an external input + listed in a brief. +- **Correctness:** the code does what each brief's goal, contracts and + behaviour rules say, including the edge cases they name. Look for bugs, + broken callers and contract mismatches between stages. +- **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 + 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. +- **Unneeded code:** code nothing calls, options and wrappers no brief asks + for, and logic duplicated from existing code. + +## What counts as a finding + +| 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 | +| `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 | +| `test` | a test a brief names is missing, does not check what a user observes, fails, is flaky or over the budget, or an expected-fail mark is left on a test that should pass; or a test no brief names | a test you would structure differently | +| `assumption` | a phase assumption is false in the built code; say in `evidence` which later phase or earlier architecture it affects | | +| `rule` | a project rule or limit is broken | | +| `unneeded-code` | code nothing calls, an option or wrapper no brief asks for, or logic that duplicates existing code; cite both places for a duplicate | a structure that could be simpler but where nothing is unused, unasked-for or duplicated | ## Report -List findings, most serious first. For each: severity (`blocking` or -`should fix`), file and line, the problem, the evidence, and the -recommended fix, marked as one of: +Write the review file named in the inputs as JSON in +[review.schema.json](review.schema.json), and nothing else: -- **remove or simplify:** the orchestrator may do it directly; -- **fix:** a bug inside the brief's scope; -- **plan gap:** the plan does not cover it; it goes back through - plan-in-phases' revision rules - ([revising.md](../plan-in-phases/revising.md)). +- `findings`, most serious first, each with: + - `type`: one of the types above; + - `severity`: `blocking` when the phase must not be accepted as it is, + otherwise `should-fix`; + - `stage`: the stage id it belongs to, or `phase` for the phase's After; + - `file` and `line`: where it is (`line` 0 for a whole file); + - `evidence`: what is wrong and how you know: the run and its output, or + the brief's words and the code that disagrees; + - `action`: `remove` (delete or simplify, nothing added), `fix` (a bug + inside the brief's scope), `plan-gap` (the plan does not cover it; it + goes back through plan-in-phases' revision rules, + [revising.md](../plan-in-phases/revising.md)) or `question` (anything + you would add, for the user). +- `verdict`: `ready` when no finding is `blocking`, otherwise `not-ready`. -End with one line: `Verdict: ready` or `Verdict: not ready`, with -the count of blocking findings. +Then end your reply with one line: `Verdict: ready` or `Verdict: not +ready`, with the count of blocking findings. -Do not edit any files. +Do not edit any file other than the review file. diff --git a/plugins/phased-delivery/skills/implement-in-phases/review.schema.json b/plugins/phased-delivery/skills/implement-in-phases/review.schema.json new file mode 100644 index 0000000..7c58976 --- /dev/null +++ b/plugins/phased-delivery/skills/implement-in-phases/review.schema.json @@ -0,0 +1,25 @@ +{ + "type": "object", + "additionalProperties": false, + "required": ["findings", "verdict"], + "properties": { + "findings": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["type", "severity", "stage", "file", "line", "evidence", "action"], + "properties": { + "type": {"enum": ["untraced-change", "internal-check", "bug", "not-done", "test", "assumption", "rule", "unneeded-code"]}, + "severity": {"enum": ["blocking", "should-fix"]}, + "stage": {"type": "string", "pattern": "^(\\d\\d\\.\\d+|phase)$"}, + "file": {"type": "string"}, + "line": {"type": "integer", "minimum": 0}, + "evidence": {"type": "string"}, + "action": {"enum": ["remove", "fix", "plan-gap", "question"]} + } + } + }, + "verdict": {"enum": ["ready", "not-ready"]} + } +} diff --git a/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md b/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md new file mode 100644 index 0000000..425d526 --- /dev/null +++ b/plugins/phased-delivery/skills/implement-in-phases/revise-guide.md @@ -0,0 +1,68 @@ +# 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. diff --git a/plugins/phased-delivery/skills/implement-in-phases/revision.schema.json b/plugins/phased-delivery/skills/implement-in-phases/revision.schema.json new file mode 100644 index 0000000..a89f350 --- /dev/null +++ b/plugins/phased-delivery/skills/implement-in-phases/revision.schema.json @@ -0,0 +1,51 @@ +{ + "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 new file mode 100644 index 0000000..83cf9c5 --- /dev/null +++ b/plugins/phased-delivery/skills/implement-in-phases/structured-implementation-notes.md @@ -0,0 +1,99 @@ +# Why implementation uses a revision JSON, 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/`. + +## What changed + +Planning moved to JSON with a checking script and a closed list of review +finding types (see +[structured-planning-notes.md](../plan-in-phases/structured-planning-notes.md)): +judgment words were replaced by things that can be checked, and the review +stopped ratcheting. implement-in-phases now follows the same pattern: + +- **Short SKILL.md, one guide per step.** The 231-line SKILL.md held every + rule inline; it is now an outline that sends revising to + revise-guide.md and building to build-guide.md. The rules kept their + meaning; they moved. +- **Revision as JSON.** Revising a phase ends in `.build/NN-revision.json`: + each stage's files, the commands that show it is done, and its scores. + Older phase files differ in layout, and "Done when" is prose, so the + script reads this file instead of parsing the phase file. +- **A gate the orchestrator cannot argue with.** `build-check.py record` + fails a build that changed files outside its stage or whose checks fail; + the orchestrator may still reject a passing build, never accept a + failing one. Before, acceptance rested on the orchestrator's reading. +- **Bookkeeping in the script.** Attempt counts, Earlier-Attempt lines, + pairs already tried and the premium spend were kept by hand in Notes + lines and commit messages, where a slip changes routing (a wrong spend + lets premium pairs through; a forgotten try gets re-dispatched) and the + work report. The ledger holds them and `commit` writes the trailers in + the format `stage-stats.sh` already read. +- **Closed review types.** The phase reviewer reports only untraced + change, check on internal data, bug, not done, test, assumption, rule + and unneeded code, as JSON. The open "a simpler structure exists" check + was dropped: it is the kind of judgment finding that made plan review + ask for more every round. Unneeded code (unused, unasked-for or + duplicated) keeps the useful part. + +## 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 + 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 + unseen. + +## Later: a driver script + +Investigate, not built. The `plan-phase-driver` branch holds an unreviewed +draft plan (2026-11-22) for a Python driver that owns the whole phase loop +and calls `claude -p` for each step (revise, build, review, triage), with +the orchestrator LLM only handling halts. + +- **What it would add:** rules that hold every time (no step skipped), no + orchestrator tokens, clean halts and resume on usage limits, and the + whole loop testable offline with a fake `claude`. +- **What it would cost:** a larger build than this one; the draft predates + `claude-build.sh`, `route`, the premium budget and this script, so it + needs re-planning on top of `build-check.py`. While both paths exist, + the loop's rules live in prose and Python. Codex routing was deferred in + the draft, and every case the rules do not cover becomes a halt for the + user. +- **What to measure first:** with this version in use, how often the + orchestrator skips or misapplies a step the script does not gate, and + how much of a phase's usage the orchestrator itself spends. If both are + small, the driver is not worth it. + +## Measured + +One validation run, 2026-11-24: a headless Opus session at medium thinking +(`--max-budget-usd 2.40`, the branch's plugin only, Opus and Haiku offered) +implemented the builder eval task `p2-multistep` as a one-phase plan in a +git copy of the eval repository. + +- **Result:** the task's files, copied onto a fresh eval repository, pass + the hidden check (`RESULT pass`). Cost $0.84: $0.54 for the session (15 + turns) and $0.30 for the review on Opus high (248k tokens, no findings). +- **The script path was followed end to end:** the session wrote a + revision JSON with five real check commands (the test suite, the + behaviour cases, an unchanged selector output, the doc sentence, the new + test), ran `start`, `record` (accepted), `commit` (stage trailers), + recorded the review with `--premium`, and ran `finish` (`Status: built`) + and the work report. +- **Where it bent the rules:** it built the `small` stage itself instead of + dispatching the routed Opus medium build ($1.60 cap), and ran the review + with a $1.50 cap instead of route's $4.00, both because its own $2.40 + session cap could not cover them. Both are recorded in the phase Notes. + The lesson is about the run's setup, not the skill: a session capped + below the caps it must pay for will economize. Nothing the script gates + was skipped. +- **Not exercised:** `can-try` and a headless stage build (the session + built the stage itself), a failing build, a retry or a budget stop (the + stage passed first time), Codex, and check commands that run long; the open + question on check timeouts stays open. 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 7679399..d0fa875 100644 --- a/plugins/phased-delivery/skills/plan-in-phases/model-selection.md +++ b/plugins/phased-delivery/skills/plan-in-phases/model-selection.md @@ -215,12 +215,12 @@ at the top of the script. there. A paid calibration run is still to set the caps. - **Budget stop:** a build that `claude-build.sh` stops at its cap (exit 8) is retried one step down the frontier (see "Adjust while working"). -- **Premium budget, $10 per phase:** the implementer keeps a - `Premium spend: $X of $10` line in the phase's Notes. After each +- **Premium budget, $10 per phase:** the implementer records each `claude-build.sh` run of a pair `route` printed with `"premium": true`, - and after every phase review it runs, it adds the run's `Cost:` (its - `cap_usd` when the cost is `unknown`) and passes X to `route` as - `--premium-spent`. Once X reaches $10, builds get no premium pair for + and every phase review it runs, with `build-check.py record ... + --premium`, and passes `build-check.py spend <phase file>` (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. - **Reviews** use `route --review`: always `top`, their cost counted against the premium budget when built by `claude-build.sh`, never a step @@ -294,7 +294,8 @@ R = 2, check whether the stage should be split. - **Planning and plan revision** use `top`. - 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. + budget stop is recorded by its Earlier-Attempt trailer, which + `build-check.py commit` writes from the ledger. ## Builders in another tool @@ -423,7 +424,7 @@ the session cannot continue does sparing its quota outweigh that. `route` reads the new scores. - If `claude-build.sh` stops a build at its cap (exit 8), retry it with `route --down 1`, and one step further on each further stop (`--down 2`, - and so on). Record each stopped attempt as an Earlier-Attempt. When + and so on). Each stopped attempt becomes an Earlier-Attempt (`build-check.py`). When `why` says it moved fewer pairs than asked, or `route` prints a pair already tried for this stage, the stage is too big for its cap: revise the plan. diff --git a/plugins/phased-delivery/tests/test_build_check.py b/plugins/phased-delivery/tests/test_build_check.py new file mode 100644 index 0000000..2482e32 --- /dev/null +++ b/plugins/phased-delivery/tests/test_build_check.py @@ -0,0 +1,260 @@ +import json +import os +from pathlib import Path +import subprocess + +import pytest + + +SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" +SCRIPT = SCRIPTS / "build-check.py" +PHASE = "docs/plan/01-demo.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": [], +} + +REVIEW = {"findings": [], "verdict": "ready"} + + +def git(repo, *args): + return subprocess.run(["git", "-C", str(repo), *args], env={**os.environ, **GIT_ENV}, + capture_output=True, text=True, check=True).stdout + + +@pytest.fixture +def repo(tmp_path): + """A git repository with one commit holding a phase file, its revision JSON and two stage files.""" + r = tmp_path / "repo" + (r / "src").mkdir(parents=True) + (r / "docs/plan/.build").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)) + git(r, "init", "-q") + git(r, "add", ".") + git(r, "commit", "-q", "-m", "base") + return r + + +def bc(repo, *args): + return subprocess.run(["python3", str(SCRIPT), *args], cwd=repo, env={**os.environ, **GIT_ENV}, + capture_output=True, text=True) + + +def record(repo, stage, model="opus", effort="high", code=0, tokens="1200", cost="0.40", *extra): + return bc(repo, "record", PHASE, stage, "--tool", "claude-code", "--model", model, "--effort", effort, + "--exit", str(code), "--tokens", tokens, "--cost", cost, *extra) + + +def build_a(repo): + (repo / "src/a.txt").write_text("a2\n") + (repo / "src/done.txt").write_text("done\n") + + +def message(repo, rev="HEAD"): + return git(repo, "log", "-1", "--format=%B", rev) + + +def changed(repo, rev="HEAD"): + return git(repo, "show", "--name-only", "--format=", rev).split() + + +def stats(repo): + return subprocess.run(["sh", str(SCRIPTS / "stage-stats.sh"), "HEAD"], cwd=repo, + capture_output=True, text=True, check=True).stdout + + +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" + 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"] + msg = message(repo) + assert msg.startswith("01.1 Write a") + for line in ("Stage: 01.1", f"Plan: {PHASE}", "Tier: middle", "Tool: claude-code", "Model: opus", + "Effort: high", "Attempt: 1", "Tokens: 1200", "Cost: 0.40", "Tool-Calls: 7", + "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() + assert "| 01.1 | Write a | middle | first | done |" in text + assert "Status: in progress (stages done: 01.1)" in text + + +def test_outside_change_fails(repo): + bc(repo, "start", PHASE) + build_a(repo) + (repo / "src/other.txt").write_text("changed\n") + (repo / "src/__pycache__").mkdir() + (repo / "src/__pycache__/x.pyc").write_text("cache") + (repo / "src/b.txt").write_text("b2\n") # stage 01.2 has no commit yet: not outside + result = record(repo, "01.1") + assert result.returncode == 1 + assert json.loads(result.stdout)["outside"] == ["src/other.txt"] + + +def test_failed_check_then_retry(repo): + bc(repo, "start", PHASE) + (repo / "src/a.txt").write_text("a2\n") + first = record(repo, "01.1", "haiku", "high", 0, "500", "0.10") + assert first.returncode == 1 + assert json.loads(first.stdout)["checks"] == [{"cmd": "test -f src/done.txt", "exit": 1}] + (repo / "src/done.txt").write_text("done\n") + second = record(repo, "01.1", "opus", "medium", 0, "900", "0.30") + assert second.returncode == 0 + assert bc(repo, "commit", PHASE, "01.1").returncode == 0 + msg = message(repo) + assert "Attempt: 2" in msg + assert "Earlier-Attempt: haiku high 500 check failed" in msg + + +def test_can_try_refuses_repeat(repo): + bc(repo, "start", PHASE) + (repo / "src/a.txt").write_text("a2\n") + assert record(repo, "01.1", "opus", "high").returncode == 1 + assert record(repo, "01.1", "sonnet", "high", 1, "unknown", "unknown").returncode == 4 + assert bc(repo, "can-try", PHASE, "01.1", "opus", "high").returncode == 1 + assert bc(repo, "can-try", PHASE, "01.1", "sonnet", "high").returncode == 0 + assert bc(repo, "can-try", PHASE, "01.1", "fable", "low").returncode == 0 + + +def test_premium_spend(repo): + bc(repo, "start", PHASE) + build_a(repo) + record(repo, "01.1", "fable", "low", 0, "800", "1.25", "--premium") + record(repo, "review", "fable", "high", 0, "unknown", "unknown", "--cap", "3.00", "--premium") + record(repo, "01.2", "opus", "high", 0, "100", "2.00") + result = bc(repo, "spend", PHASE) + assert result.stdout.strip() == "4.25" + + +def test_preexisting_edits_left_alone(repo): + (repo / "src/other.txt").write_text("mine\n") + bc(repo, "start", PHASE) + build_a(repo) + assert record(repo, "01.1").returncode == 0 + assert bc(repo, "commit", PHASE, "01.1").returncode == 0 + assert "src/other.txt" not in changed(repo) + assert " M src/other.txt" in git(repo, "status", "--porcelain") + + +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)) + result = bc(repo, "start", PHASE) + assert result.returncode == 1 + assert "checks" in result.stdout + assert not (repo / "docs/plan/.build/01-ledger.json").exists() + + (repo / "docs/plan/.build/01-revision.json").write_text(json.dumps(REVISION)) + 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)) + result = bc(repo, "finish", PHASE) + assert result.returncode == 1 + assert "type" in result.stdout + assert git(repo, "rev-parse", "HEAD") == head + + +def test_finish_phase(repo): + bc(repo, "start", PHASE) + 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)) + 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") + bc(repo, "commit", PHASE, "01.2") + 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() + 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 git(repo, "status", "--porcelain") == "" + + +def test_fix_commit(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") + assert record(repo, "01.1", "sonnet", "medium", 0, "300", "0.05", "--fix").returncode == 0 + assert bc(repo, "commit", PHASE, "01.1").returncode == 0 + 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) + + +def test_rename_from_outside_fails(repo): + bc(repo, "start", PHASE) + (repo / "src/a.txt").write_text("a2\n") + git(repo, "mv", "src/other.txt", "src/done.txt") # into a stage file + result = record(repo, "01.1") + assert result.returncode == 1 + assert "src/other.txt" in json.loads(result.stdout)["outside"] + + +def test_reject_budget_stop_then_retry(repo): + bc(repo, "start", PHASE) + (repo / "src/other.txt").write_text("stray\n") + stopped = record(repo, "01.1", "haiku", "high", 8, "400", "0.25") + assert stopped.returncode == 3 + assert json.loads(stopped.stdout)["outside"] == ["src/other.txt"] + git(repo, "checkout", "src/other.txt") + build_a(repo) + assert record(repo, "01.1", "sonnet", "high").returncode == 0 + assert bc(repo, "reject", PHASE, "01.1", "tests check nothing\nsee diff").returncode == 0 + assert bc(repo, "commit", PHASE, "01.1").returncode == 1 + assert record(repo, "01.1", "opus", "high").returncode == 0 + assert bc(repo, "commit", PHASE, "01.1").returncode == 0 + msg = message(repo) + assert "Attempt: 3" in msg + 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)