# Plan grounding and closure invariants *Written 2026-09-09, from the post-mortem of the `6502-refactor` campaign.* ## Summary A campaign can pass every task, report `completed`, keep a 682-test suite green, and still deliver 77% of its stated goal. That happened here. The cause was not a model failure and not a bug -- it was that **every review gate in the pipeline reads text, and none of them touches the target repository.** This document proposes three changes. The first two have obvious homes in the existing codebase; the third is a one-field schema change. --- ## 1. The evidence The `6502-refactor` campaign's phase 3 was to extract each 6502 instruction family out of a 400-line `if mnemonic == ...` chain into per-family mixin modules, so that "every opcode handler is greppable by mnemonic and filed with its group." Twelve tasks, one per family. All twelve passed review. The campaign reported `completed`. The give-away was arithmetic: `core.py` shrank from 1,421 lines to 1,284. If ~400 lines of dispatch had really moved out, it should have landed near 1,000. Measuring the chain directly: - **58 of 75 mnemonics (77%)** delegate to a mixin - **17 remain inline** in `_execute_instruction`, about 121 lines The stragglers are `ALR, ANC, ANE, ARR, LAS, LXA, SBX, SHA, SHX, SHY, TAS, USBC`. ### The root cause is one phrase in the spec The goal enumerated twelve families, ending with: > ...and the undocumented combined operations. That reads as a catch-all. It is a proper subset. `SAX/LAX/DCP/ISC/SLO/RLA/ SRE/RRA` genuinely are the *combined* operations, and task P3-T12 implemented exactly those -- correctly and completely. But `ANE/LXA/TAS/SHA/SHX/SHY/LAS` are *unstable* operations, `ALR/ANC/ARR/SBX` are immediate-ALU illegals, and `USBC` is a duplicate SBC. Different categories. No task owned them. **AFK did not fail. The spec asked for less than the goal needed.** ### It was mechanically detectable before launch Set-difference the spec's twelve buckets against the real opcode table: ``` mnemonics in the real opcode table : 77 mnemonics named by the 12 families : 65 coverage : 84% NOT ASSIGNED TO ANY FAMILY (12): ALR, ANC, ANE, ARR, LAS, LXA, SBX, SHA, SHX, SHY, TAS, USBC ``` Those twelve are exactly the twelve left inline. The check is about twenty lines and runs in under a second. It was never run, because nothing in the pipeline runs anything against the repo before task 1. --- ## 2. Why the existing gates could not catch it The workflow was deliberate and, on paper, thorough: | Gate | What it did | Why it could not catch this | | --- | --- | --- | | Top model writes the spec | Produced a plausible 12-family taxonomy | It was writing prose. Nothing prompted it to enumerate 77 mnemonics. | | Terra plans | Faithfully decomposed the spec into 12 tasks | A correct decomposition of an incomplete taxonomy. | | Top model reviews the plan | Asked "is this plan sensible?" | It was sensible. Catching this required a set-difference against the artifact, not a reading. | | Per-task review | Checked each task's acceptance criteria | Each task owned one family and satisfied its criteria. | The acceptance criteria for phase 3 actually contained the right words: > CPU inherits every extracted mixin, and every opcode handler remains > greppable by mnemonic in its family module. But that was evaluated **per task**. Each task owned one family, and each was telling the truth. **Nobody owned the residual.** There was no place in the system where "the chain is now empty" could be asserted or falsified. Stated generally: **a spec review without an oracle is the same Goodhart failure one level up.** This project already solved that problem for CPU behaviour -- SingleStepTests is a machine oracle, so behaviour cannot silently drift. The same instinct was never pointed at the spec itself. --- ## 3. Proposal one: ground the plan preflight in the target repo **The hook already exists and is philosophically aligned.** `afk_developer/planner/plan_verifier.py::preflight_plan` is documented as "pure deterministic validation for newly generated task plans ... without making semantic or model judgments." It already produces a `PlanPreflightEvidence` record and attaches it to the plan. It validates only the plan's *internal* graph: task IDs present, dependencies resolvable, no cycles, task count within bounds. It never opens the target repository, so it cannot check any of the plan's *external* claims. ### Add repo-grounded checks Give `preflight_plan` access to `project_dir` and add checks that can fail: 1. **Partition / coverage.** When a phase decomposes an enumerable set into buckets, require the plan to declare how that set is enumerated (a command or import that yields the items), then assert the buckets cover it exhaustively. Report uncovered items by name. This is the check that would have caught the twelve opcodes. 2. **Mutation footprint.** For each phase, estimate changed files and lines against `max_changed_files_per_task` / `max_changed_lines_per_task` and fail when a phase cannot fit. Note the guard counts `git diff --numstat HEAD` **plus every untracked file at full length** (`scheduler/reviewer.py::_worktree_change_scope`), so a copy+delete file move scores far higher than a staged `git mv`. This campaign lost two separate runs to footprint overruns that were both measurable in advance: - phase 2 (`src/` move): 11 files / 3,776 lines against a 6 / 400 ceiling - phase 5 (lint parity): 9 changed files against a 6-file ceiling 3. **Residual assertion present.** Fail the preflight when a phase has no closure invariant (see proposal two). These are deterministic and cheap. They belong in the same function, not in a model call. --- ## 4. Proposal two: metric baselines (closure invariants as ratchets) The structural goal needs to be an oracle, exactly as SingleStepTests is the oracle for behaviour. ### Why a plain test does not work The obvious move -- add `test_execute_instruction_is_pure_delegation()` -- fails the first eleven of twelve tasks. Since every task must leave the suite green, it would block the whole phase. ### Use a ratchet instead Commit a measured number and require it to decrease monotonically: ``` assert measured <= committed_ceiling # committed_ceiling lowered by each task ``` For phase 3 the metric is "count of mnemonic guards remaining in `core.py`": starts at ~78, each task lowers the committed ceiling, and the final task drives it to zero. A task that adds a delegating stub but leaves the body behind cannot lower the number, so it cannot pass. ### This is the existing lint baseline, generalised `afk_developer/scheduler/lint_baseline.py` is the template. `LintBaseline` already carries `schema_version`, `project_name`, `project_path`, `command`, `captured_at`, `git_head`, and a list of fingerprints, with `capture_*` and `save_baseline` helpers. A `MetricBaseline` needs the same shape with: - `metric_name` -- human-readable, e.g. `mnemonic_guards_in_core` - `command` -- any command printing a single integer to stdout - `value` -- the measurement at capture time - `target` -- optional; the value the phase must reach (usually `0`) - `direction` -- `non_increasing` (default) or `non_decreasing` Then `lint_mode: strict | baseline` gains a sibling for arbitrary metrics, and `campaign create` accepts per-phase metric declarations. This also closes a second, independently observed gap: AFK has a lint baseline but **no test baseline**, which blocked a read-only audit task in an earlier campaign because it could not tolerate known pre-existing failures. Both are the same feature. --- ## 5. Proposal three: make the half-done question a required field Add a required per-phase field, refused at `campaign approve` when empty: > **What would fail if this phase were only half done?** If the honest answer is "nothing," the phase has no oracle and must not be approved. Phase 3's honest answer was *"nothing; the tests pass either way."* That is the entire failure in one sentence, and it was answerable before launch. Machine-checkable version: the field must name a command or test ID, not prose. --- ## 6. Where to spend the expensive model Not on the hard tasks. On **generating each phase's closure invariant**: > Given this phase goal, write the machine check that is false until the phase > is completely done. One cheap call per phase converts an aesthetic goal into an oracle. That is what moves a phase from 77% to 100% without any model becoming more capable. For cost context: the entire 6502 core cost **$6.69 metered**, against **$6.73** priced at OpenAI public list rates for the same tokens -- a 1% gap, so Copilot credits are pass-through, not subsidised. Tokens are not the constraint. Supervision time is. --- ## 7. Suggested order | # | Change | Effort | Catches | | --- | --- | --- | --- | | 1 | Footprint check in `preflight_plan` | small | Both failures that stalled this campaign live | | 2 | Required half-done field | small | Phases with no oracle, at approve time | | 3 | `MetricBaseline` + ratchet review mode | medium | Incomplete work that satisfies per-task criteria | | 4 | Partition / coverage check | medium | Underspecified taxonomies like this one | One and two are cheap and would have paid for themselves in this campaign alone. ## 8. How we would know it worked Dogfood it on the outstanding cleanup. Twelve opcodes (`ALR, ANC, ANE, ARR, LAS, LXA, SBX, SHA, SHX, SHY, TAS, USBC`) are still inline in `core.py`. Run that as a one-phase campaign with: - a partition check over the real opcode table, - a metric baseline on the guard count with `target: 0`, - a populated half-done field. Success is the campaign refusing to report `completed` until the guard count reaches zero -- rather than reporting success at 77% as it did the first time. --- ## 9. Implementation notes and revisions (2026-09-09, second review) A second pass re-examined the proposals against the persisted campaign state (`~/.afk-developer/projects/6502-refactor*`) rather than against the prose above. Three things changed. ### What shipped: one concept, `PhaseState.closure_metric` Proposals two and three collapsed into a single field. The "half-done question" is only worth asking if the answer is a command, and once it is a command it *is* the metric. So each phase now carries an optional `ClosureMetric` (`name`, `command`, `target`, `direction`) and the runner uses it at exactly three points: | When | Where | What happens | | --- | --- | --- | | Phase expansion (before the planner runs) | `campaign_runner._measure_phase_start` | Runs the command. Fails closed if it errors, or if it *already* satisfies the target -- a metric that reads done before the phase starts cannot detect a half-done phase. Records `start_value`. | | Task planning | `campaign.make_phase_batch_goal` | Tells the task planner the command, target, and current reading, and that "the final task must own whatever residual the earlier tasks leave behind." Nobody owned the residual before; now the planner is told to. | | Phase close (after every task has passed) | `campaign_runner._require_phase_closure` | Runs the command again. If unsatisfied, the campaign **escalates** with the reading, the target and the start value in `stop_reason`, and the phase stays open. This is the gate that would have stopped the 77% result. | `campaign approve` refuses phases with no metric unless `--allow-unmeasured-phases` is passed, and prints each phase's metric so the human is approving a specific command, not a vibe. `campaign plan`, `approve`, and `status` all show the metric and its latest reading. The command supports a `{python}` placeholder that resolves to the target interpreter (explicit `AFK_TARGET_PYTHON`, else the project `.venv`) and refuses to fall back to ambient Python. The roadmap fingerprint covers the metric's definition but not its readings, and contributes nothing for phases without one, so previously approved campaigns keep their fingerprints. Deliberately **not** built: a per-task ratchet inside `review_task`. The phase-close gate already avoids the "plain test fails eleven of twelve tasks" problem, and it catches the same failure (a stubbed task cannot bring the reading to target). Threading a metric through the six `review_task` call sites and `TaskNode` would add governance surface for earlier detection only; the repo's own history shows that surface is not free. Revisit if a real run shows the earlier signal is worth it. ### Proposal one (footprint preflight) is not implementable as written The plan does not declare per-task mutation footprints. `TaskNode.files_created` is **worker-reported after the fact**, and the planner's only path declaration is `required_artifacts`, which lists deliverables, not touched files -- the phase 5 lint task declared one artifact (`pyproject.toml`) and touched nine files. There is nothing in a fresh plan to estimate against. Two honest ways to get the effect, neither done here: - Add a planner-declared `expected_touched_paths` and check its count against `max_changed_files`. Only as good as the planner's guess. - Make the review-time measurement itself rename-aware. `_worktree_change_scope` counts an untracked file at full length, so a copy+delete `src/` move scores the whole package as new lines. Measuring through a temporary index (`GIT_INDEX_FILE= git add -A && git diff --cached --numstat -M HEAD`) would have scored phase 2's move near its true edit size. This is a targeted, testable change to `scheduler/reviewer.py` and the better of the two, but it is a separate decision about what the ceiling is meant to bound. Also corrected from section 3: the campaign was created with a 6-file / 400-line ceiling and the campaign JSON was hand-raised to 10 files mid-run (the `.bak` still shows 6). Both recorded `mutation_scope_exceeded` attempts were same-turn `task_complete` rejections, not retries. ### Proposal four (partition / coverage) remains deferred It is the specialised, plan-time form of what the closure metric checks at close time, and it needs schema the planner does not yet emit (an enumeration command plus per-task bucket claims). With the metric in place, an under-specified taxonomy now costs one escalated phase instead of a silent 77%; that is the cheap version of the same protection. ### Recovery path when a phase escalates on its metric The phase stays open with the reading recorded. Close the residual (by hand, or via a new plan), clear the campaign's `status`/`stop_reason` in the saved JSON as documented for other checkpoint escalations, and resume: `_campaign_ensure_phased_queue` re-measures and closes the phase only when the target is met. A `campaign add-task`-style command for the residual is the obvious follow-up once a real run shows what the residual looks like.