# Plan adaptivity: letting the roadmap learn *Written 2026-09-10, from a review of the planning path after `ddf544e`.* ## Summary `plan-grounding-and-closure-invariants.md` established that every review gate read text and none touched the repository, and fixed that for *review*. The planning loop has the same disease and has not been treated: **the phase checkpoint that decides whether the roadmap is still right reads only task status strings, and the roadmap it is judging was written before a single file was read.** The system already contains almost every part needed to fix this. The just-in-time phase planner exists. The unconstrained planning prompt exists and is already written. Bounded autonomous task growth exists behind a config flag. Closure metrics — the invariant that makes loosening the plan safe — shipped last commit. What is missing is that the roadmap pins task identity at t=0 and nothing is allowed to disagree with it afterwards. This document proposes four changes, in increasing order of cost. The first is a deletion. --- ## 1. What the planning path actually does ### Phase expansion is already just-in-time `_campaign_expand_phase` (`campaign_runner.py:386`) calls `decompose_task` fresh at the start of each phase, against a re-scanned project directory (`auto_discover_project`), after all prior phases have landed. The docstring is explicit: *"Build and persist one phase's task DAG via the normal planner, just-in-time."* This is the right architecture and it is not the problem. ### But the roadmap pins task identity for all phases at t=0 `plan_phase_roadmap` (`campaign.py:405`) makes one reasoner call, with no project-writing capability and no repository access, that must return *"the exact globally unique task IDs it owns"* for every phase (`campaign.py:427-428`). Those IDs are parsed and frozen onto each `PhaseState.task_ids` (`campaign.py:467-491`), capped at 20 per phase. This call happens before any code has been read. It is the moment of maximum ignorance in the entire campaign, and it is the moment that fixes the shape of every phase's work. ### And the JIT planner is forbidden from disagreeing Two mechanisms enforce it: - `make_phase_batch_goal` (`campaign.py:351-354`) injects into the planner prompt: *"Plan exactly N tasks with these exact IDs and no others: ..."* - `_require_exact_phase_task_ids` (`campaign_runner.py:373`) raises `ClickException` if the freshly-planned task set differs from the roadmap's by one ID in either direction. So phase 4 is re-planned with four phases of hard-won ground truth in hand, and then required to produce exactly the task skeleton that was guessed before phase 1. The decomposer may rewrite task *descriptions* with fresh knowledge. It may not change how many tasks there are, what they are, or what they are called. **The fresh planning call is real. Its authority is not.** ### The one adaptive seam is one phase wide and prose only `PhaseReflection.revised_next_phase_goal` (`campaign_models.py:336`), applied at `campaign_runner.py:643-648`, lets the reasoner rewrite the **goal prose of the immediately next phase only**, capped at 4000 characters. The docstring at `campaign.py:531-534` states the limit plainly: it *"never invents new work outside the roadmap ... it cannot rewrite the roadmap, add phases, or touch a completed or in-progress phase."* Not task_ids. Not phase N+2. Not the phase count. Not the closure metric. --- ## 2. The asymmetry: the plan can shrink but not grow Autonomous **shrinking** is fully supported. A task can resolve not-applicable through evidence gating (`evidence_gated_by`, `accepts_not_applicable_dependencies`), a phase can be `SKIPPED`, and a trusted insufficient conclusion prevents speculative implementation. All automatic. Autonomous **growth** exists in exactly one form, and it is narrower than it first appears. The foreman may split a task into subtasks, bounded by `max_decompositions` (6), `max_subtasks_per_decomposition` (5) and `max_decomposition_depth` (1). With `require_supervisor_decomposition_approval=False` this applies immediately with no human (`queue.py:1644-1666`); with the default `True` it escalates and waits, though `SupervisorDecisionCoordinator` can deterministically auto-approve an exact-coverage proposal. The limit is not the gate. The limit is the **trigger and the scope**: - It fires from `recovery_coordinator.py:63,108` — *"Ask the foreman to split this **stuck** task"* — that is, only on repeated failure. - Its children must exactly cover the parent (`build_foreman_children`, "exact-coverage" validation in `supervisor_coordinator.py:39-42`). So the system can subdivide work it is already stuck on. It cannot add work it has *discovered it needs*. There is no path at all from "phase 2 taught us the plan for phase 5 is wrong" to a changed phase 5 — no amount of learning produces a stuck task, because the task that should exist was never planned. **Growth is a recovery mechanism, not a learning mechanism.** That is the gap. > *Correction to an earlier reading:* growth is not human-gated by > architecture. It is gated by a config default, with a working autonomous path > behind it. The defect is the trigger and scope, not the gate. --- ## 3. The reflection gate cannot see the repository `reflect_on_completed_phase` (`campaign.py:520`) receives exactly one input about what happened: `completed_task_summaries`, built at `campaign_runner.py:622-625` as ```python f"{task.id}: {task.status.value}; {task.failure_detail or task.not_applicable_reason}" ``` Task IDs, status enums, and failure strings. Truncated to 30 items at 500 chars. It does not receive: - the phase's `closure_metric.last_value` or `start_value` — **already measured and already on the model** (`campaign_models.py:107-109`) - the campaign's root `closure_metric`, the campaign's own contract - the ledger's scars and findings — the distilled negative and positive facts from `ddf544e`, which is precisely the record of *what we learned that we did not know at t=0* - anything at all from the working tree This is the identical failure the prior document diagnosed for review gates: **the gate that decides whether the plan is still right reads text and never touches the repo.** We fixed that for "is this task done." We did not fix it for "is this plan still the right plan." The second question is the one where being wrong costs a whole campaign. --- ## 4. Proposal one: stop pinning task IDs in the roadmap **This is a deletion, and the adaptive path is already written.** `make_phase_batch_goal` already has the branch (`campaign.py:358-362`): ```python else: task_scope = ( f"Plan a thorough, independently reviewable task list of {target_floor}-{ceiling} " "tasks that fully achieves this phase's goal and acceptance criteria. ..." ) ``` And `_require_exact_phase_task_ids` already returns early on an empty list (`campaign_runner.py:375-376`). The unconstrained, evidence-driven planning path is fully built and simply never taken, because the roadmap always populates `task_ids`. **Change:** drop `task_ids` from the roadmap reasoner's required JSON schema and prompt (`campaign.py:421-428`); keep the field on `PhaseState` as an *advisory* sketch the reasoner may emit but the planner is not shown and not graded against. Each phase is then planned, at its own start, from its goal, its acceptance criteria, its closure metric, and the actual repository. **What is lost:** the roadmap no longer tells a human the exact task IDs of phase 7 at approval time. That precision was fictional — it was a guess, and enforcing it converted a guess into a constraint. **What is kept:** the human still approves phase count, names, goals, acceptance criteria, and closure metrics. That is the auditable part, and it is the part that was ever real. --- ## 5. Proposal two: a divergence budget, recorded as a finding Deleting the constraint outright removes a real protection: silent scope growth and unbounded cost. Replace the equality assertion with a budget. **Change:** in `_campaign_expand_phase`, compare the fresh plan's task count against the roadmap's advisory sketch: - within `phase_divergence_budget` (new limit, suggest default 5, cap at `max_tasks_per_phase`) — proceed, and write one `LedgerEntry` of `kind="finding"` recording the delta and the planner's reason - beyond it — escalate to the human, as `_require_exact_phase_task_ids` does today, but with the divergence and its reason in the message rather than two raw ID lists The ledger entry is the point. Today a plan/reality mismatch is a `ClickException` — the most valuable signal the system produces, raised as an error and discarded. Recorded as a finding it becomes durable, hash-keyed evidence that the reflection step (proposal three) can read: *"phase 2 needed 9 tasks, not the 5 the roadmap guessed, because X."* That is exactly the fact that should inform phase 3's shape. --- ## 6. Proposal three: ground the reflection, then widen its authority Two steps, in this order. **Grounding must land before widening** — widening the authority of a gate that reads only status strings makes it worse, not better. ### 6a. Feed the checkpoint what it needs (no new authority) Extend `reflect_on_completed_phase`'s inputs to include: - `phase.closure_metric` — `start_value`, `last_value`, `target`, `describe_target()` - `campaign.closure_metric` — the root contract's current measured value - current ledger scars and findings, filtered through `entry_is_current` (`ledger.py:98`) so stale facts are excluded - the advisory-vs-actual task count divergence from proposal two This changes no decision vocabulary and no authority. It is strictly more evidence for the same three choices. Ship it alone; it is independently valuable, because `escalate` decisions made on better evidence are themselves better. ### 6b. Let the decision reshape remaining phases Extend the decision vocabulary with `reshape_future_phases`, carrying a typed `PhaseAmendment` rather than free prose: ```python class PhaseAmendment(BaseModel): """A bounded, reasoned change to one not-yet-started phase.""" target_ordinal: int = Field(ge=1) operation: Literal["revise_goal", "add", "drop", "split"] reason: str = Field(min_length=20, max_length=1_000) name: str = Field(default="", max_length=200) goal: str = Field(default="", max_length=4_000) acceptance_criteria: list[str] = Field(default_factory=list, max_length=20) closure_metric: ClosureMetric | None = None ``` Hard constraints, validated by the caller in the existing fail-closed style: - may only target a phase with `status is PhaseStatus.PLANNED` — never a completed, active, or skipped phase - resulting phase count must stay within `campaign.limits.max_phases` - an `add` or `split` must supply a `closure_metric`; a phase with no machine-checkable definition of half-done may not be created - **the campaign's root `closure_metric` is immutable** — see §7 - at most `max_phase_amendments` (new limit, suggest 3) per campaign, mirroring `max_decompositions` - every amendment persists to `campaign.phase_amendments` and to the ledger with its reason; the roadmap stays fully auditable after the fact This is the change Fable was pointing at, and it is deliberately last. The first two proposals are cheap and safe; this one is the one that needs the guardrails the others build. --- ## 7. What stays fixed, and why that makes this safe The objection to adaptive replanning is drift: a system that may rewrite its own plan can rewrite its way to declaring an unfinished job done. Closure metrics are the answer, and they are why this proposal is worth making *now* rather than a year ago. `campaign.closure_metric` (`campaign_models.py:229`, *"the root of the plan tree is itself a contract: measured before phase 1 and at the end"*) is a command that runs against the real repository and prints one integer. It is measured at phase-1 start and at campaign end, and no amount of replanning changes what it prints. So: - **The destination is pinned.** The root closure metric is immutable for the life of the campaign; only a human may change it, through the existing roadmap redraft flow. - **The path is free**, within budget, with every deviation carrying a written reason into the ledger. Today both are pinned, and the path is the half that should never have been. An adaptive planner anchored to an immutable measured contract is *safer* than a rigid planner anchored to nothing but text, because the rigid one can satisfy every task it planned and still deliver 77% of the goal — which is the documented history of the `6502-refactor` campaign. --- ## 8. Suggested order 1. **§6a — ground the reflection.** No authority change, immediately useful, no way for it to make anything worse. 2. **§4 — unpin roadmap `task_ids`.** Mostly a deletion; the adaptive path is already written and tested by the `else` branch. 3. **§5 — divergence budget + ledger finding.** Restores the protection §4 removes, and produces the evidence §6b consumes. 4. **§6b — `PhaseAmendment`.** Only after 1–3 are in and have run a campaign. Steps 1–3 are worth doing even if step 4 is never approved. --- ## 9. How we would know it worked The prior document's standard: name the measurement before building. - **Divergence is recorded, not raised.** After one campaign, `grep` the ledger for phase-divergence findings. A campaign that ran with zero divergence findings and zero escalations either had a genuinely correct roadmap or is not measuring — check which by hand the first time. - **Root closure metric at campaign end.** Unchanged as a pass/fail standard. This must not regress; it is the whole safety argument. - **Escalations shift earlier and get more specific.** A grounded checkpoint (§6a) should escalate at phase 2 with a measured reason rather than at phase 6 with a status-string summary. Compare escalation ordinal and message content against the `6502-refactor` baseline. - **Re-run the 6502 illegal-opcodes campaign.** The 12 unassigned mnemonics are a known, mechanically-detectable plan defect with a recorded ground truth. A system with §4–§6 should either plan a task that owns them or escalate saying it cannot. Today it cannot express either. --- ## 10. Open questions - **Does the reasoner actually use grounded evidence well?** §6a is cheap to ship and the honest way to find out before granting authority in §6b. If the checkpoint returns `complete_phase` while staring at a closure metric that barely moved, the problem is upstream of every proposal here. - **Should `revise_goal` survive?** §6b's `PhaseAmendment` subsumes `revised_next_phase_goal`. Keeping both is two paths to one outcome. Prefer deleting the narrow one once the typed one lands. - **Is the foreman's exact-coverage constraint right for discovered work?** Splitting a stuck task should stay exact-coverage. Adding discovered work is a different operation and should not reuse that path. - **Phase-level divergence vs. task-level.** This document only lets *phases* grow. A phase that discovers mid-flight that it needs a task no one is stuck on still cannot add one. That may be the right boundary — phase edges are the natural checkpoint — but it is a deliberate limit, not an oversight. --- ## 11. Implementation notes (2026-09-10, as built) All four proposals shipped on branch `plan-adaptivity`. 671 tests pass; the two failures in the suite (`test_search_evidence_text_reports_per_file_literal_counts`, `test_status_command_without_project_lists_projects_and_campaigns`) fail identically on `master` and are unrelated to this work. ### What shipped - **§6a** `reflect_on_completed_phase` now takes `ledger` and `divergence_note`, and builds a `MEASURED EVIDENCE` block (`_phase_checkpoint_evidence`) carrying the phase metric, the root metric, current ledger entries filtered through `entry_is_current`, and the divergence note. Its system prompt instructs the checkpoint to weigh that above task summaries, and names a barely-moved closure metric as grounds to escalate even when every task passed. - **§4** `PhaseState.task_sketch` holds the roadmap's advisory guess; `PhaseState.task_ids` now means "the tasks this phase actually owns," written at expansion. `make_phase_batch_goal` no longer has a constrained branch and never shows the planner the sketch. `phase_roadmap_fingerprint` reads `task_sketch`, so it still fingerprints what the human approved. - **§5** `_record_phase_divergence` replaces `_require_exact_phase_task_ids`. Within `phase_divergence_budget` (default 5) it records a ledger finding and sets `phase.divergence_note`; beyond it, it escalates naming the delta. - **§6b** `PhaseAmendment` + `apply_phase_amendments` in `campaign_models.py`, the `reshape_future_phases` decision, `_parse_phase_amendments`, and `_apply_phase_reshape` in the runner. Budget: `max_phase_amendments` (default 3). ### Deviations from the plan above - **`split` was not implemented.** The proposed four operations collapse to three: a split is `revise_goal` on the target plus `add` of the remainder, and both already validate correctly. A fourth operation would have been a second way to express the same change. - **`drop` marks a phase `SKIPPED` rather than removing it.** Phase task plans are persisted as `{campaign}-phase-{ordinal:03d}`, so ordinals are file identity. Skipping preserves the audit trail and `all_phases_resolved` already treats `SKIPPED` as resolved. - **Renumbering is confined to the unstarted tail.** `started_phase_frontier` returns the highest non-`PLANNED` ordinal; nothing at or below it may be amended or renumbered, which is precisely what makes inserting a phase safe against those ordinal-keyed plan files. - **Amendments are all-or-nothing and one-per-phase-per-checkpoint.** A checkpoint that half-understood the schema escalates rather than having its coherent half applied, and a repeated target is refused rather than resolved by ordering. ### Corrections to §2 as first written The claim that autonomous plan growth is human-gated by architecture was wrong and is corrected in the body above: `require_supervisor_decomposition_approval` is a config default, and `SupervisorDecisionCoordinator` can auto-approve an exact-coverage proposal. The defect is the trigger (a stuck task) and the scope (exact parent coverage), not the gate. An unreachable duplicate-task-ID check written into `_record_phase_divergence` was removed once `TaskPlan` was found to validate uniqueness at construction. ### Seam coverage The four functions above are unit-tested, but the bug worth fearing lives in the wiring, which had no coverage at all: `_campaign_close_out_phase` and `_campaign_expand_phase` were untested before this change. Three end-to-end tests now drive the real close-out path against a persisted `CampaignStore` -- a reshape that inserts a phase, a refused reshape that escalates, and the narrow `revise_future_phases` path -- and assert on the prompt the checkpoint actually received. Each was mutation-checked: severing the `_apply_phase_reshape` call fails two of them, and disabling the divergence budget fails `test_phase_divergence_beyond_budget_escalates`. Tests that pass on first write against new wiring are worth distrusting until something proves they can fail. ### Still open - `revised_next_phase_goal` and `revise_goal` remain two paths to one outcome (§10). Both ship; the narrow one should be deleted once the typed one has run a real campaign. - Nothing here has faced a live reasoner. §10's first bullet is still the open question, and §6a is the cheap way to answer it. --- ## 12. What the first live run changed (2026-09-11) The 6502 polish/refactor campaign was the first run of this machinery against a real reasoner and a real repository. Everything below was found by running it, not by reading it. ### The sketch has to be the same kind of thing it is compared against §4 made `task_sketch` advisory and reworded the roadmap prompt from "the exact globally unique task IDs it owns" to "a non-binding estimate of the work each phase contains". That changed the field's **type**. The reasoner answered with prose sentences, the phase planner produced nine task IDs, and §5 compared two sentences against nine IDs, reported `+7`, and escalated a healthy phase. Advisory does not mean unstructured. The sketch is now asked for as kebab-case IDs, and entries that are not ID-shaped are dropped at parse time so a prose sketch degrades to *no* sketch and skips the comparison instead of producing a number that measures nothing. The same prompt change also told the reasoner to estimate the real task count rather than summarise. Phase 3 had been sketched as two entries for twelve instruction families; it now sketches twelve. ### Only the count survives independent generation The first healthy divergence note read: sketched-but-not-planned `add-ci-workflow`, `capture-baseline`; planned-but-not-sketched `add-ci-quality-workflow`, `capture-refactor-baseline`. The same work, named twice. Sketch and plan IDs are produced by separate calls, so matching them by ID reports every renaming as divergence. The count is the only part that survives, so an unchanged count now records nothing at all, and the note says outright that its ID lists include renamed work. ### Closure metrics fail in three ways, and only the third is interesting Two are mechanical, and both were caught by gates that already existed: - A metric that reads an end-state path crashes at baseline. `_measure_root_start` refused it. The prompt had described the metric's *value* but never its *runnability*. - A metric written as a 1,000-character Python one-liner with nested quotes is rejected by `sh`, since the command runs with `shell=True`. The third is the one that matters. Asked for phase 3 -- *every opcode handler filed with its family* -- the reasoner produced `missing-instruction-family-modules`, counting the twelve family modules created. That reaches zero the moment twelve files exist, **whether or not any handler moved**. Measured on the real tree, 77 mnemonics are handled inline in `_execute_instruction`, and twelve of them belong to no family the goal names -- precisely the residual the earlier campaign shipped as complete. The module-count metric reads 0 for that repository. This is the failure from `plan-grounding-and-closure-invariants.md` one level up. There the gates read text and never touched the repository. Here the gate touches the repository and still cannot see the residual, because it measures a structural side effect of the work rather than the outcome the work was for. The prompt now carries the rule and its test: count the things not yet handled, never the files created, and ask what a half-finished phase that still creates every intended file would look like. If the metric reads 0 for that repository, it is the wrong metric. ### A dead metric must be caught at approval, not at its phase Only the root metric was measured before phase 1, so a phase metric that could never read non-zero was invisible until its own phase began -- or forever, since a metric that starts satisfied closes its phase regardless of outcome. Phase 5's metric ran `ruff` without the rule selection that phase exists to adopt: 0 at baseline, 0 always. Approval now measures every phase metric and refuses a roadmap carrying one already at its target. Metrics that cannot *run* yet are deliberately left alone: phases 3 and 4 legitimately read `src/sixfiveohtwo`, which phase 2 has not yet created, and those are already validated at their own phase start. Only a metric that runs and is satisfied is a provable defect at approval time. ### Redrafting is not convergent Three `plan --feedback` rounds each fixed the named problem and regressed something else; the last rewrote the root metric back to counting missing files despite being told to keep it. The root and phase-3 metrics were ultimately hand-written, which `campaign plan` explicitly supports ("a human may hand-edit the saved campaign JSON before approving"). Both now count inline mnemonics and read 77. Worth noting against §10's first open question: the checkpoint's ability to use grounded evidence is still untested, but the *planner's* ability to choose a grounded measurement is now measured, and it needed correction on every metric it produced.