| name | iterative-planner |
| planner_version | 7.6.40 |
| description | State-machine driven iterative planning and execution for complex coding tasks. Cycle: Explore → Plan → Execute → Reflect → Validate → Close / Re-plan. Filesystem as persistent memory. Use for multi-file tasks, migrations, refactoring, failed tasks, audit remediations, or anything non-trivial.
|
Iterative Planner
Core Principle: Context Window = RAM. Filesystem = Disk.
Write to disk immediately. The context window will rot. The files won't.
Doctrine: Loop First, Determinism Second, Generalize Last.
The core loop is EXPLORE → PLAN → EXECUTE → REFLECT → VALIDATE → CLOSE, with REFLECT → RE-PLAN/EXPLORE still available when the solution is wrong or semantically incoherent.
Deterministic scripts support that loop, mistake registries preserve memory, and generalized guards should only be promoted after real recurrence.
Quick Reference: Gate Transitions
ALL transitions use ONE command. Do NOT run verify_gate, checklist_runner, or project_health individually at gate points.
| # | Gate | Command | Key Requirements |
|---|
| 1 | explore-to-plan | node <sp>/scripts/transition.mjs explore-to-plan | ≥3 findings, KB read, intent contract for user-facing goals |
| 2 | plan-to-execute | node <sp>/scripts/transition.mjs plan-to-execute | Problem stmt, files list, user approved, deliverable mapping, criterion/story linkage, verification obligation synthesis + context-sensitive verification matrix for recipe/orchestration/integration work |
| 3 | execute-to-reflect | node <sp>/scripts/transition.mjs execute-to-reflect | Red-team notes (≥3 vectors) + persona audit |
| 4 | reflect-to-validate | node <sp>/scripts/transition.mjs reflect-to-validate | Reflection verdicts, semantic coherence, KB/semantic upkeep, progress complete |
| 5 | validate-to-close | node <sp>/scripts/transition.mjs validate-to-close | Proof of work, verification sufficiency, persona audit, intent/test evidence |
| 6 | notify-user | node <sp>/scripts/transition.mjs notify-user | Final handoff audit (available from VALIDATE or CLOSE; reachability audit disabled) |
<sp> = .agent/skills/iterative-planner
- Gate chain (I-015): Gates must run in order (1→2→3→4→5). Skipping a gate triggers Prolog invariant I-015.
- Transition nonce: Each successful transition writes a nonce to
state.json. The next gate verifies it — direct state.md edits are detected and blocked.
- Approval nonce: Gate 1 generates a nonce. Before Gate 2 passes, the nonce must appear as
[APPROVED:<nonce>] in decisions.md. In default auto mode, transition.mjs explore-to-plan writes it directly. In interactive mode, use approval_daemon.mjs or nonce_reveal.mjs. In multi-agent mode, the story review agent writes the approval marker after reviewing findings coverage.
- KB digest: At EXPLORE, read all KB files, then persist the KB digest salt in
findings_ledger.json (kb_digest_salt) or add [KB_DIGEST:<hash>] to findings.md (salt shown by Gate 1). Proves KB was actually read.
- Content depth: Findings need ≥30 words each. Red-team vectors need ≥3 content lines each. Empty code blocks don't count as proof of work.
- FAIL = blocked: Fix all FAIL items before proceeding. WARN = advisory.
- Deterministic repair packet: When a gate blocks and prints
Deterministic Repair Packet, follow that packet before guessing at prose. It names the target artifact, missing section shape, diagnostic commands, loop-recovery command, and retry transition.
- Paste output: Always paste the transition command output into the conversation so the user can see it.
- Verification obligation synthesis: If repo/task context, ontology signals, persona signals, or touched boundaries imply operational verification risk,
plan.md must include ## Verification Obligation Synthesis with Repo/system context, Task shape, Ontology signals, Persona signals, System boundaries touched, and Derived verification obligations. This section is where discovery context becomes an explicit verification contract.
- Context-sensitive verification: If the plan touches recipe/orchestration/browser/integration/backend operational behavior,
## Verification Strategy must be a table with Criterion | Story linkage | Repo/system context | Required proof type | Concrete command or action | Pass means | What remains unverified. The matrix should justify the proof mode from the changed system and from the synthesized obligations; do not treat wrapper/unit tests as production proof by default. Frontend/browser work should propose real rendered-journey proof and screenshot/captured-viewport artifacts using proof IDs such as proof:browser_journey, proof:browser_screenshot, and proof:visual_proof when those are locally feasible. A ## Success Criteria markdown table is valid when it includes a Criterion column; Verification Strategy criterion cells may use stable IDs such as sc_1 instead of copying full prose, and proof wording may be natural prose when it matches a canonical proof family, so do not force exact proof:* tokens as a formatting ritual.
- Matrix diagnostics: When
GATE-PLN-017 is unclear, run node .agent/skills/iterative-planner/scripts/verification_matrix.mjs lint --plan <plan-dir> --json to inspect the selected table, parsed criteria count, row family matches, recognized proof:* IDs, malformed rows, synthesized-obligation coverage, and the shared Evidence guidance packet without changing planner state.
- Low-level agent gate packet: When
verify_gate.mjs plan-to-execute blocks, read the printed Low-Level Agent Gate Packet before editing prose. It names exact schema/list fields for intent_contract.json, unresolved story IDs, required Verification Obligation Synthesis labels, matrix columns, shared evidence guidance, and deterministic lint/repair commands. Treat that packet as the short prompt for smaller agents; do not duplicate it by hand in every user prompt.
- Evidence guidance surfaces:
bootstrap.mjs status, verification_matrix.mjs lint, and the blocked plan-to-execute packet render the same analyzer-derived Evidence guidance. Use it before authoring matrix evidence; copied placeholder/example cells are intentionally rejected as incomplete proof.
- Closeout reporting: When verification-obligation synthesis is active,
verification.md must record ## Systems Exercised, ## Remaining Unverified, and ## Verification Sufficiency, and the Validation Status ladder must stop leaving the required proof levels at PENDING.
- KB sign-off at REFLECT:
reflection.md includes a prefilled ## Knowledge Base Sign-Off section. Leave it pending until REFLECT, then either update plans/knowledge/ for real reusable learnings or set Decision: no_new_learnings with a specific Reason:. Do not edit state.json.close_signals; that JSON is generated by the planner from artifacts.
- Compliance audit:
node <sp>/scripts/gate_compliance.mjs — reports which gates were run/skipped.
{plan-dir} = plans/plan_YYYY-MM-DD_XXXXXXXX/ (active plan directory under project root).
Discovery: plans/.current_plan contains the plan directory name. One active plan at a time.
Cross-plan context: plans/FINDINGS.md and plans/DECISIONS.md persist across plans (merged on close).
Cross-plan context entrypoint: start with plans/INDEX.md, then use plans/FINDINGS.md and plans/DECISIONS.md for deep dives.
Long-term memory: plans/knowledge/ accumulates mistakes, patterns, and gotchas across all plans (updated at close, read at explore).
Intent capture: plans/<plan>/intent_contract.json records user, JTBD, anti-goals, and required deliverables for user-facing or deliverable-heavy work. Internal planner-maintenance goals should remain NOT_REQUIRED unless the goal text clearly carries real audience or user-facing deliverable obligations. Gates 1, 2, and 5 enforce the required path.
When to Use This (vs. Lightweight Flow)
| Situation | Use |
|---|
| Multi-file changes (3+ files) | Iterative Planner |
| Migrations, refactors, audit remediations | Iterative Planner |
| New feature pipeline / major component | Iterative Planner |
| Tasks that have already failed once | Iterative Planner |
| Cross-system work (2+ systems) | Iterative Planner |
| Scientific / quant / data-modeling work — TrueSkill, Markov, backtests, calibration, data lineage, coverage, temporal split, leakage checks | Iterative Planner with scientific shape. EXPLORE must record assumption probes before PLAN treats data claims as true. |
| Roadmaps spanning multiple epics, tickets, migrations, dependencies, or child plans | Program Manager first, then child Iterative Planner plans |
| Debugging with unclear root cause | Iterative Planner |
| Confirming prior fixes / re-verifying state (>50% findings pre-fixed) | Lightweight with triage file as plan |
| Single-file fixes, obvious solutions | Lightweight (task.md → implementation_plan.md → walkthrough.md) |
| Single-file static/UI/page-clone deliverables | Lightweight |
| Quick feature / extraction | Lightweight |
| Known-root-cause bug fixes | Lightweight |
| History-poisoned or abandoned plan where the remaining work is now simple | Lightweight after recover-poison or abandon |
| Operational chores — ad budget changes, credential rotations, settings toggles, schedule edits, content tweaks, dashboard configuration | Skip the planner entirely. Just do the task and commit. If bootstrap.mjs new is run anyway, it will detect chore shape and minimise gates, but the planner state machine is overkill — chores aren't engineering work. |
| Questions — "what does X do?", "how is Y wired?", "why is Z failing?" | Skip the planner — answer the user. The state machine is for tracking work; questions don't need a plan. Run bootstrap.mjs triage "<goal>" first if unsure. |
| Analysis tasks — review / audit / explain / inspect / list / summarize, with no code-change verbs | Skip the planner or use lightweight. Detected as analysis shape with minimal gates. Run bootstrap.mjs triage "<goal>" to get a recommendation before opening anything. |
Trigger phrases: "plan this", "figure out", "help me think through", "I've been struggling with", "debug this complex issue"
Autonomous batch trigger: "fix these autonomously", "audit loop", "turbo mode", "run unattended", "batch fix" — see Autonomous Batch Mode section.
Deterministic Preflight
Before choosing between the lightweight flow, the full planner, or poisoned-plan recovery, run:
node <sp>/scripts/planner_preflight.mjs --goal "<goal>" --json
If an active plan already exists, you can omit --goal and let the preflight classify the current plan context.
The returned contract is the shared routing surface used by /safe-plan, /safe-change, /safe-change-power, and /advisor:
flow.mode
evidence.mode
workflow.recommended + escalation_reason
recovery.mode + recovery command
anti_ritual
authority_profile
task_profile
semantic_upkeep
validation_bundle
strictness_mode
audit_posture
recommended_path
operator_action + operator_question when user input is required
persona_activation_authority
Async Cheap-LLM Drift Steward
Planner drift can be reviewed by a secondary OpenAI-compatible LLM without making that model a gate authority.
Configure the provider with:
export PLANNER_DRIFT_LLM_API_KEY="..."
export PLANNER_DRIFT_LLM_MODEL="..."
export PLANNER_DRIFT_LLM_BASE_URL="https://provider.example/v1"
export PLANNER_DRIFT_LLM_TIMEOUT_MS=20000
export PLANNER_DRIFT_LLM_PHASES=gate,post_task
export PLANNER_DRIFT_LLM_WRITE_MODE=safe_apply
For local development, the drift client also reads a gitignored .env.local
from the project root as a fallback. Use the planner-specific variables above,
or use DEEPSEEK_API_KEY by itself to select the DeepSeek defaults:
PLANNER_DRIFT_LLM_MODEL=deepseek-chat and
PLANNER_DRIFT_LLM_BASE_URL=https://api.deepseek.com/v1. Explicit process
environment variables always win over .env.local, and missing provider
configuration remains fail-open advisory.
Useful commands:
node <sp>/scripts/llm_drift_auditor.mjs --mode gate --gate plan-to-execute --json
node <sp>/scripts/llm_drift_maintenance.mjs enqueue --plan <plan-dir> --reason post_task
node <sp>/scripts/llm_drift_maintenance.mjs run --job plans/<plan-dir>/async/<job>.json
Rules:
- Gate-time drift audit is advisory and fail-open. Missing config, invalid JSON, timeout, HTTP error, or
stale_blocking output cannot fail a gate by itself.
- Provider calls request OpenAI-compatible JSON-object mode. If a provider answers with malformed JSON, the shared client makes one bounded JSON repair retry before returning fail-open
unavailable.
- Async maintenance may safe-apply deterministic report regeneration, but LLM-suggested
@planner:proves, @planner:story, story registry, ontology, or user-claim edits are review artifacts unless deterministic validation proves they are unambiguous.
- Every async report includes ontology usage proof from annotation validation, ontology serialization, invariant checks, story verification, story registry validation, and the traceability audit pack.
- If ontology facts change but no audit, gate, traceability, story, or rule-engine decision changes, classify the change as
ritual_only.
Program Manager Layer
Use /program-manager when the request is roadmap/program-shaped rather than one
implementation plan. It creates or updates a Program Packet at:
plans/programs/<program-id>/program_packet.json
Generic idea, backlog, GitHub Issue, and GitHub Project intake also belongs here.
Draft local tickets first:
node <sp>/scripts/program_manager.mjs init --program <program-id> --title "<program title>" --goal "<program goal>" --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --from-text "<idea>" --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --from-text "<idea>" --title "<short title>" --ticket-type quant_exploration --persona-review --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --from-text "<idea>" --auto-story --write --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --from-file <path> --write --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --from-json-array '[{"title":"Quant exploration","type":"quant_exploration","persona_review":true,"text":"US-079: Explore target semantics"},{"title":"Code refactor","ticket_type":"code_refactor","persona_review":true,"text":"US-079: Refactor parser boundaries"}]' --write --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --issue <n> --repo owner/name --json
node <sp>/scripts/program_manager.mjs intake --program <program-id-or-path> --project-item <id-or-url> --repo owner/name --write --json
Use init when the Program Packet does not exist yet; it writes the valid empty
schema skeleton and refuses accidental overwrite unless --force is passed.
Intake is dry-run by default. --write updates only the local Program Packet and
the local intake/<ticket-id>_intake_packet.json artifact. Text and file intake
sources are mirrored as external_refs kinds local_text and local_file;
GitHub issue/project sources use github_issue and github_project_item.
Use --title for long single-ticket text bodies; if the derived title is longer
than 70 characters and no explicit title exists, intake tries a redacted cheap
LLM summary and falls back to a concise deterministic title. Use
--from-json-array for bulk discrete tickets. Use --ticket-type to record a
specialized lane while preserving the schema-safe base type; for example
quant_exploration maps to research and code_refactor maps to refactor.
Use --persona-review to attach advisory persona-review metadata, and
--persona-packs <csv> to override default packs. JSON-array items may set
ticket_type or type, persona_review, and persona_packs; item metadata
overrides CLI defaults for mixed programs. Use --auto-story when storyless
intake should append review-needed NOT_IMPLEMENTED draft stories to
reports/user_story_audit/story_registry.json and link those IDs to the ticket
without marking it ready.
Each intake result emits a Ticket Intake Receipt with the /program-manager
front door, source/action, Program Packet path, ticket id, traceability refs,
acceptance-criteria refs, verification refs, deterministic status, advisory
DeepSeek status/summary/artifact path, ticket type, persona review status/packs,
recurrence status/counts, quant persona gate status when applicable, and next
required command. Intake packets include
retro_recurrence_check; trusted active mistakes and
retro-promoted obligations can block tickets until the required guards or
evidence are present. Quant-shaped intake also includes a deterministic
quant_persona_gate; missing what-happened overview, target/outcome, data
lineage, temporal/leakage handling, controls, or quant verification rows keeps
the ticket blocked regardless of DeepSeek output. Agents should surface that
receipt before creating, reviewing, or publishing any GitHub ticket. GitHub
publication is separate and explicit:
node <sp>/scripts/github_ticket_review.mjs publish --program <program-id-or-path> --ticket <ticket-id> --repo owner/name --json
node <sp>/scripts/github_ticket_review.mjs publish --program <program-id-or-path> --ticket <ticket-id> --repo owner/name --project <id-or-url> --write --json
Do not create GitHub tickets directly from an idea/backlog prompt. Create or
update the local Program Packet ticket first with program_manager.mjs intake,
surface the Ticket Intake Receipt, then publish with github_ticket_review.mjs publish only when GitHub should mirror the local ticket.
Validate with:
node <sp>/scripts/program_manager.mjs check --program plans/programs/<program-id>/program_packet.json
node <sp>/scripts/program_manager.mjs check --program plans/programs/<program-id>/program_packet.json --remediate --json
node <sp>/scripts/program_manager.mjs verify design-to-ready --program plans/programs/<program-id>/program_packet.json
node <sp>/scripts/program_manager.mjs verify ready-to-execution --program plans/programs/<program-id>/program_packet.json
node <sp>/scripts/program_manager.mjs verify execution-to-program-validate --program plans/programs/<program-id>/program_packet.json
node <sp>/scripts/program_manager.mjs verify validate-to-program-close --program plans/programs/<program-id>/program_packet.json
When program_manager.mjs verify <gate> --write passes deterministic Program
Packet validation and ontology checks, it advances the program status:
design-to-ready -> ready, ready-to-execution -> executing,
execution-to-program-validate -> validating, and
validate-to-program-close -> closed. Dry-runs and failed gates remain
read-only. Output reports previous_status, new_status, and
transition_written.
--remediate on check or verify translates blocked-ticket advisory
recommended_actions into local remediation task packets. Dry-run is default;
--write writes a remediation/remediation_<timestamp>.json artifact. The CLI
does not directly spawn Codex subagents and cannot override deterministic packet
status.
Ticket-centered GitHub review uses the Program Packet as truth and GitHub as the
visible mirror:
node <sp>/scripts/github_ticket_review.mjs review --issue <n> --program <program-id-or-path> --ticket <ticket-id> --json
node <sp>/scripts/github_ticket_review.mjs review --project-item <project-item-id-or-url> --program <program-id-or-path> --ticket <ticket-id> --write --json
node <sp>/scripts/github_ticket_review.mjs review --issue <n> --program <program-id-or-path> --ticket <ticket-id> --show-deepseek-block --json
Dry-run is the default. --write is required before the command edits the
Program Packet, writes reviews/<ticket-id>_review_packet.json, posts/updates a
GitHub issue comment, applies planner lifecycle labels, or updates a GitHub
Project Status field. It still will not close an issue unless
--close-github-issue is passed. The command records ticket external_refs
for GitHub mirrors plus local intake sources. The metadata contract includes review_artifacts, github_sync, review_status, and deterministic last_review_status.
Ticket lifecycle values submitted and review_ready are accepted as review-facing
compatibility aliases, but Program Manager gates normalize them through
effective lifecycle semantics so dispatch remains deterministic.
Review and publish results also emit a Ticket Intake Receipt so the handoff
shows the local ticket, deterministic status, advisory status/summary/artifact,
and GitHub mirror action that were used. Review Packets and GitHub review
comments include a Retro Recurrence Check section before advisory findings
so retros are predictive ticket guards, not only closeout history.
Quant-shaped Review Packets and comments also include a Quant Persona Gate
section. DeepSeek sees that deterministic gate in its packet and may critique
the risk, but it cannot clear missing quant/persona evidence or call a blocked
ticket verified.
DeepSeek may classify the Review Packet as advisory (needs_story,
needs_annotation, needs_verification, ontology_conflict, blocked,
review_ready), but deterministic Program Packet, story, annotation, ontology,
and test evidence remains authoritative.
Default text output and GitHub comments show compact DeepSeek proof
(status, one-line summary, and local artifact path). The full fenced verdict
stays in local JSON artifacts and JSON fields; render it in text only when an
operator explicitly requests --show-deepseek-block.
Program gates are additive and do not add states to the iterative planner state machine.
Missing Program Packets return SKIP. Executable tickets become child iterative plans
when they touch migration, delete/move work, shared/core surfaces, user-facing capability
behavior, cross-system dependencies, public interfaces, planner-core files, or anything
beyond artifact-only administrative scope.
Commit Message Guard
Planner release, phase, feature, fix, and chore commits should install the portable commit-msg hook:
node .agent/skills/iterative-planner/scripts/planner.mjs install-hook commit-msg
The hook invokes commit_msg_check.mjs, which requires guarded commit subjects to include Why:, What:, and Proof: body headings. Emergency bypass remains PLANNER_ALLOW_EMPTY_BODY=1, and every bypass is logged for later review.
planner_findings.mjs --json extends that route with:
anti_ritual
proof_posture
phase_contract
phase_profiles.reflect
phase_profiles.validate
adversarial_profile
suggested_attack_vectors
knowledge_resolver.mjs --json extends discovery with:
symmetry_hunts
adversarial_profile
suggested_attack_vectors
related_retros
- optional red-team artifact awareness via
reports/red_team_audit/anti_patterns.json
Phase Authority Model
The planner is intentionally asymmetric by phase:
EXPLORE: agent primary, personas widen discovery, ontology stays advisory
PLAN: agent primary, personas challenge assumptions, ontology enforces contracts
EXECUTE: agent primary, personas/ontology stay boundary-only; do not add continuous EXECUTE-time second-guessing. The hard quant persona gate still runs at phase boundaries for quant-shaped work.
REFLECT: agent primary, personas challenge solution quality, ontology checks semantic coherence and required upkeep
VALIDATE: agent primary, personas challenge proof sufficiency, ontology checks proof consistency and waiver honesty
CLOSE: agent primary, handoff integrity wins over tidy prose; the final bundle must agree with the validated result
This keeps the original simple loop intact. The planner should help the agent notice missed risk and step back safely, not supervise every keystroke.
Approval Mode
The approval mode controls who writes [APPROVED:<nonce>] to decisions.md after a successful explore-to-plan.
- In default
auto mode, transition.mjs explore-to-plan writes it directly.
- In
auto mode (default), no extra PLAN-phase user action is needed.
- Default full workflows use
approval.mode = "auto", so do not tell the user to start the approval daemon unless the project has explicitly switched to interactive mode.
Lightweight Invocation (via /safe-change)
When triggered by the /safe-change workflow for changes ≤3 files / ≤30 lines / no new abstractions, or when the remaining work after poisoned-plan recovery is now small and local:
- Start approval daemon — spawn in background:
node <sp>/scripts/approval_daemon.mjs --auto &. This auto-approves the plan-to-execute gate so the workflow runs without interruption (only for nonces tagged safe-change).
- Set workflow type — when running explore-to-plan transition, set:
_PLANNER_WORKFLOW_TYPE=safe-change node <sp>/scripts/transition.mjs explore-to-plan. This tags the nonce so the daemon knows it's safe to auto-approve.
- Skip bootstrap — do NOT run
bootstrap.mjs. Use the standard artifact files (task.md, implementation_plan.md, walkthrough.md) instead of plans/ state files.
- EXPLORE lite — still required, but write findings directly to
implementation_plan.md instead of findings.md. Minimum 3 grep/search calls.
- PLAN — write
implementation_plan.md (user-facing). Auto-approve if ≤3 files.
- EXECUTE — TDD: write invariant test first. Implement. Run test. Run full suite.
- REFLECT — verify test count ≥ baseline + 1. Check for regressions.
- CLOSE — write
walkthrough.md. If plans/knowledge/ exists, append learnings. If not, embed learnings in walkthrough under "## Lessons Learned".
Pure static UI/page deliverables (for example a standalone HTML clone) should use structured manual validation when the intent contract marks the work as manual_observation; do not invent a fake test file just to satisfy planner bureaucracy.
This avoids the overhead of the full state machine for simple, well-scoped changes while still enforcing TDD and regression gates.
Integration with Existing Artefacts
When the iterative planner is active, the agent should:
- Still update
task.md (top-level progress tracking) — keep the high-level bullet points in sync with progress.md
- Use
plans/ for detailed state — the state machine files (state.md, plan.md, decisions.md, etc.) live here
- Write
implementation_plan.md if the user requests a formal plan review — the iterative planner's plan.md is the working plan; implementation_plan.md is the user-facing summary
- Write
summary.md at CLOSE — summarise what was done; this is the canonical close artifact for the full flow. (The legacy walkthrough.md fallback for KB evidence in full plans was retired in v7.1+; it remains the canonical close artifact only for the lightweight /safe-change flow.)
Supporting Utilities
These supporting scripts are part of the planner's canonical surface and should stay documented when they change:
knowledge_resolver.mjs — deterministic routing and knowledge discovery for workflows, recipes, and repo-first scans
retro_registry.mjs — read-only retro archive retrieval for list, show, search, related-mistake, and active-for-plan
planner_findings.mjs — one-shot deterministic findings bundle for route, semantic blockers, repairable variance, telemetry-derived proof gaps, and semantic-substrate gaps including missing semantic substrate, with active-plan annotation scans scoped to ## Files To Modify plus nearby real-code adjacency
planner_hygiene.mjs — compact low-token cleanup surface that buckets planner findings into auto_fix, needs_decision, and defer, now including additive anti_ritual drift visibility. Treat it as optional expert triage and advisor input, not as mandatory ritual; anti-ritual warnings stay advisory unless backed by real semantic/proof/integrity risk.
knowledge_benchmark.mjs — golden and real-project benchmark runner for route/tier/deep-search behavior
annotation_assist.mjs — assisted bootstrapper for @planner: annotation suggestions and apply flows
persona_adapt.mjs — read-only persona fit/usage scanner plus explicit apply --safe for high-confidence additive seed-role upgrades
semantic_maintenance.mjs — fleet semantic-health scanner and explicit safe repair layer for host-owned persona, annotation, telemetry, workflow-history, and semantic-backlog drift
pre_commit_policy.mjs — scoped planner commit-blocking policy used by the hook surface
pre-commit-hook.sh — shell entrypoint that invokes planner pre-commit enforcement
post_tool_use.mjs — lightweight hook for Codex/IDE tool-trace capture and compact proof telemetry when the environment supports it
Planner-core work in this repo should treat config/planner_manifesto.json as the machine-readable north star and references/planner-manifesto.md as the human-readable mirror. The manifesto is intentionally narrow: semantic risk can hard-block, known wording variance should canonicalize before blocking, ontology should challenge reasoning rather than replace it, impact beats ritual, and warnings stay advisory unless they are backed by real semantic/proof/integrity risk.
State Machine
stateDiagram-v2
[*] --> EXPLORE
EXPLORE --> PLAN : enough context
PLAN --> EXPLORE : need more context
PLAN --> PLAN : user rejects / revise
PLAN --> EXECUTE : user approves
EXECUTE --> REFLECT : phase ends/failed/surprise/leash
REFLECT --> VALIDATE : solution/semantic judgment ready
VALIDATE --> CLOSE : proof sufficient
REFLECT --> RE_PLAN : failed / better approach
REFLECT --> EXPLORE : need more context
RE_PLAN --> PLAN : new approach ready
CLOSE --> [*]
| State | Purpose | Allowed Actions |
|---|
| EXPLORE | Gather context | Read-only on project. Write only to {plan-dir}. |
| PLAN | Design approach | Write plan.md. NO code changes. |
| EXECUTE | Implement step-by-step | Edit files, run commands, write code. |
| REFLECT | Evaluate solution + semantics | Read outputs, compare against intended outcome, write reflection.md, update decisions.md. |
| VALIDATE | Evaluate proof sufficiency | Read verification.md, check exercised systems and remaining risk, prepare for close. |
| RE-PLAN | Revise direction | Log pivot in decisions.md. Do NOT write plan.md yet. |
| CLOSE | Finalise | Write summary.md. Audit decision anchors. Merge findings/decisions to consolidated files. |
## Files To Modify should use raw path-only bullets. The shared reader also tolerates common recovery forms such as code-spanned bullets and ### [NEW] path/to/file headings, but that tolerance is for keeping scope from collapsing to ambient dirty files — not a replacement for the canonical bullet format.
Transitions
| From → To | Trigger |
|---|
| EXPLORE → PLAN | Sufficient context. ≥3 indexed findings in the effective findings source. |
| PLAN → EXPLORE | Can't state problem, can't list files, or insufficient findings. |
| PLAN → PLAN | User rejects plan. Revise and re-present. |
| PLAN → EXECUTE | User explicitly approves. |
| EXECUTE → REFLECT | Execution phase ends (all steps done, failure, surprise, or leash hit). |
| REFLECT → VALIDATE | Reflection says the solution and semantic upkeep are ready for proof challenge. |
| VALIDATE → CLOSE | Validation says proof is sufficient for the task profile. |
| REFLECT → RE-PLAN | Failure or better approach found. |
| REFLECT → EXPLORE | Need more context before re-planning. |
| RE-PLAN → PLAN | New approach formulated. Decision logged. |
Every transition → log in state.md. RE-PLAN transitions → also log in decisions.md (what failed, what learned, why new direction).
At CLOSE → audit decision anchors (references/decision-anchoring.md). Refresh plans/INDEX.md, then merge per-plan findings/decisions to plans/FINDINGS.md and plans/DECISIONS.md.
Mandatory Re-reads (CRITICAL)
These files are active working memory. Re-read during the conversation, not just at start.
| When | Read | Why |
|---|
| Before any EXECUTE step | state.md, plan.md, progress.md, persona_guidance.md | Confirm step, manifest, fix attempts, progress sync, domain guidance |
| Before writing a fix | decisions.md | Don't repeat failed approaches. Check 3-strike. |
Before modifying DECISION-commented code | Referenced decisions.md entry | Understand why before changing |
| Before PLAN or RE-PLAN | decisions.md, findings.md, findings_ledger.json, findings/*, persona_constraints.md, persona_guidance.md | Ground plan in known facts + domain constraints |
| Before any REFLECT | plan.md (criteria), progress.md, verification.md | Compare against written criteria, not vibes |
| Every 10 tool calls | state.md | Reorient. Right step? Scope crept? |
| Every 15 tool calls during EXECUTE | plan.md (current step) | Drift check — is current activity aligned with plan step? |
>50 messages: re-read state.md + plan.md before every response. Files are truth, not memory.
Bootstrapping
Stable dispatcher:
node <skill-path>/scripts/planner.mjs status
node <skill-path>/scripts/planner.mjs new "goal"
node <skill-path>/scripts/planner.mjs resume
node <skill-path>/scripts/planner.mjs gate <gate-name>
node <skill-path>/scripts/planner.mjs verify-fleet --json
node <skill-path>/scripts/bootstrap.mjs "goal"
node <skill-path>/scripts/bootstrap.mjs new "goal"
node <skill-path>/scripts/bootstrap.mjs new --force "goal"
node <skill-path>/scripts/bootstrap.mjs resume
node <skill-path>/scripts/bootstrap.mjs status
node <skill-path>/scripts/bootstrap.mjs recover-poison
node <skill-path>/scripts/bootstrap.mjs close
node <skill-path>/scripts/bootstrap.mjs close --informational
node <skill-path>/scripts/bootstrap.mjs list
Self-heal + install health (v3.10.2): bootstrap.mjs and transition.mjs still run the built-in-first self-heal preflight before they load planner-local modules. bootstrap.mjs install-health now uses the same canonical source contract to report whether the local planner install is aligned, whether repair is needed, whether advisory-only drift exists, and whether self-heal is available. Project-specific customization of CLAUDE.md / GEMINI.md / AGENTS.md is advisory and does not trigger self-heal. Use PLANNER_SOURCE_REPO=/abs/path/to/Iterative Planner to override the source locator or PLANNER_SKIP_SELF_HEAL=1 to disable the preflight while debugging.
Active-plan alias + stale-context guards (v3.10.3): bootstrap.mjs and transition.mjs now keep plans/ACTIVE_PLAN.md and plans/ACTIVE_PLAN.json in sync with plans/.current_plan. bootstrap.mjs status and resume warn when recent tool traces touched a non-active plans/plan_* directory, and transition.mjs blocks with GATE-CTX-001 if recent trace evidence shows edits or writes against a non-active plan. Read-only stale-plan evidence produces GATE-CTX-002 warnings. If either fires, reopen plans/ACTIVE_PLAN.md, switch back to the active plan, and retry.
Enforcement Scripts
node <skill-path>/scripts/verify_gate.mjs explore-to-plan
node <skill-path>/scripts/verify_gate.mjs plan-to-execute
node <skill-path>/scripts/verify_gate.mjs execute-to-reflect
node <skill-path>/scripts/verify_gate.mjs reflect-to-validate
node <skill-path>/scripts/verify_gate.mjs validate-to-close
node <skill-path>/scripts/transition.mjs notify-user
node <skill-path>/scripts/checklist_runner.mjs explore-to-plan
node <skill-path>/scripts/checklist_runner.mjs execute-to-reflect
node <skill-path>/scripts/checklist_runner.mjs --list
node <skill-path>/scripts/test_baseline.mjs capture "<test-command>"
node <skill-path>/scripts/test_baseline.mjs verify
node <skill-path>/scripts/test_baseline.mjs show
node <skill-path>/scripts/ripple_check.mjs
node <skill-path>/scripts/ripple_check.mjs execute-to-reflect
node <skill-path>/scripts/gate_compliance.mjs
node <skill-path>/scripts/gate_compliance.mjs --strict
node <skill-path>/scripts/gate_compliance.mjs --json
node <skill-path>/scripts/planner_hygiene.mjs scan --compact
node <skill-path>/scripts/planner_hygiene.mjs scan --json
node <skill-path>/scripts/planner_hygiene.mjs fix-safe
node <skill-path>/scripts/planner_hygiene.mjs fix-safe --write
node <skill-path>/scripts/hooks/install.mjs
node <skill-path>/scripts/hooks/install.mjs --uninstall
node <skill-path>/scripts/rule_engine.mjs reachability-audit
node <skill-path>/scripts/rule_engine.mjs reachability-audit --json
node <skill-path>/scripts/trace_auditor.mjs
node <skill-path>/scripts/trace_auditor.mjs --phase EXPLORE
node <skill-path>/scripts/hooks/install.mjs --trace-hook
node <skill-path>/scripts/approval_daemon.mjs
node <skill-path>/scripts/approval_daemon.mjs --auto
node <skill-path>/scripts/approval_daemon.mjs --once
node <skill-path>/scripts/nonce_reveal.mjs
node <skill-path>/scripts/validate-plan.mjs
node <skill-path>/scripts/validate-plan.mjs <plan-name>
node <skill-path>/scripts/close_guard.mjs check
node <skill-path>/scripts/close_guard.mjs template
node <skill-path>/scripts/blast_radius.mjs
node <skill-path>/scripts/verify_manifest.mjs
node <skill-path>/scripts/escalation_check.mjs
node <skill-path>/scripts/escalation_check.mjs --json
node <skill-path>/scripts/project_health.mjs
node <skill-path>/scripts/annotation_assist.mjs
node <skill-path>/scripts/annotation_assist.mjs --apply
node <skill-path>/scripts/annotation_assist.mjs --json
node <skill-path>/scripts/annotation_parser.mjs
node <skill-path>/scripts/story_registry.mjs evidence US-001
node <skill-path>/scripts/ontology_serializer.mjs
bash .agent/scripts/migrate-all-projects.sh
Traceability Model (Coverage vs Evidence vs Linkage)
The planner uses three related but different traceability layers:
@planner: annotations — coverage and ontology hints.
story_registry.json evidence refs — code_refs, test_refs, and validation_refs.
plan.md Verification Strategy linkage — Criterion | Story linkage | Check | Pass means.
Annotations help coverage and ontology facts, but they do not create code_refs, test_refs, or validation_refs. If broken_evidence_chain fires, fix the missing story linkage or story-registry evidence first; annotations alone will not satisfy the chain.
Active-plan annotation refreshes are intentionally scoped: the planner scans ## Files To Modify plus bounded nearby real-code adjacency when computing semantic substrate, then falls back to repo-wide scanning only when no usable planned-file set exists. This keeps fixtures/examples/docs from polluting close-time reasoning while preserving standalone discoverability for no-plan tooling.
The semantic substrate is a deterministic machine pipeline, not a new prose artifact:
@planner: annotations, story_registry.json, and persona artifacts become ontology/provenance inputs
- Prolog diagnostics derive compact gap ids such as
missing_mutually_exclusive_facts, missing_story_postconditions, and missing_story_conflict_facts
- planner refresh persists only the compact summary in
state.json.close_signals.semantic_substrate
execute-to-reflect warns on task-relevant semantic-substrate gaps; reflect-to-validate fails if relevant blocking gaps remain
Integrity Model (RT6)
The planner uses a layered tamper-detection system to prevent LLMs from bypassing gates:
| Layer | What's Protected | Mechanism | Failure Mode |
|---|
| Config integrity (AV-13) | config/*.json, enforcement scripts, Prolog rules | SHA-256 baseline in .config_integrity | FAIL — gate aborted |
| state.json integrity (RT6-C1) | State, transitions, approval nonces, gate results | _state_hash field (SHA-256 of sorted keys) | FAIL — gate aborted |
| Decision log chain (RT-AUDIT-M2) | Historical audit trail | Hash chain (_prev_hash linking records) | FAIL — gate blocked |
| Checklist integrity (AV-17) | YAML gate checklists | SHA-256 baseline in .checklist_integrity | FAIL — checklist skipped |
| Command allowlist (RT6-C2) | Checklist command_succeeds items | Token-based: only node .agent/.../scripts/*.mjs | FAIL — command blocked |
| Prolog rule integrity (RT6-M2) | prolog/*.pl semantic rules | Included in config integrity baseline | FAIL — gate aborted |
Key invariant: state.json can ONLY be modified by transition.mjs via writeStateJson(). Direct edits are detected by the _state_hash integrity check and cause the next gate transition to abort.
Backwards compatibility: Plans created before RT6-C1 will not have _state_hash. The first transition after upgrade adds the hash automatically. Until then, the integrity check passes with a "no hash yet" advisory.
IDE Support Matrix
The planner captures tool call traces to verify the agent reads required files at each phase. The same PostToolUse hook can also append compact proof telemetry under plans/<plan>/telemetry/ so planner_findings.mjs can detect missing proof from actual work without another AI pass. Trace capture is IDE-dependent:
| IDE | Detection | Trace Method | Setup |
|---|
| VS Code (Claude Code) | CLAUDE_CODE_VERSION env var | PostToolUse hook → tool_trace.jsonl | install.mjs --trace-hook |
| Antigravity IDE | ANTIGRAVITY_IDE env or .antigravity/ dir | antigravity-trace JSONL adapter | trace_auditor.mjs --import-antigravity <file> |
| Cursor | CURSOR_SESSION_ID env var | PostToolUse hook (Claude Code compatible) | install.mjs --trace-hook |
| Codex | CODEX_THREAD_ID or CODEX_SANDBOX env var | External hook trace is not applicable | No setup required; gate records a clean skip |
| Other / Unknown | None of the above | Not available | GATE-TRC-009 warning emitted |
WARNING: Unsupported IDEs still produce WARN results (GATE-TRC-009) but will NOT block transitions. Codex is treated separately as a no-hook environment where the external trace audit is not applicable, so it records a clean PASS instead of a warning. Trace audit requires the tool_trace feature flag in config/determinism.json to be enabled ("enabled": true). Advisory proof telemetry uses the separate proof_telemetry feature flag and never hard-fails on telemetry absence alone.
IDE recovery path: Even without trace capture, plans/ACTIVE_PLAN.md remains the canonical file-based recovery target for both Antigravity IDE and VS Code. If your editor is open on an older plans/plan_* tab, switch back through the active-plan alias before you continue.
Setup steps:
- Enable the feature flag: set
"tool_trace": { "enabled": true } in config/determinism.json
- Install the hook:
node <skill-path>/scripts/hooks/install.mjs --trace-hook
- Verify: the PostToolUse hook entry appears in
.claude/settings.local.json
- Optional but recommended: keep
"proof_telemetry": { "enabled": true } so planner_findings.mjs --json can surface missing proof like missing_visual_evidence, quant validation gaps, and missing postcondition/conflict evidence from trusted local events.
Trace failure codes (GATE-TRC-001 through GATE-TRC-009): See config/failure-codes.json for full definitions. Key checks:
- GATE-TRC-002: KB files not read during EXPLORE
- GATE-TRC-004:
plan.md not re-read every 15 tool calls during EXECUTE (drift check)
- GATE-TRC-005: Writes to files not listed in plan.md (scope creep, WARN only)
- GATE-TRC-009: Unsupported IDE (WARN only)
- GATE-CTX-001: Recent edits hit a non-active
plans/plan_* directory (transition blocked until you switch back)
- GATE-CTX-002: Recent reads hit a non-active
plans/plan_* directory (warning only)
Prolog invariant I-016: Fires when trace coverage drops below 60%. Disabled when tool_trace feature is off (defaults to 100% coverage).
Registries (single source of truth)
| File | What it controls |
|---|
config/version.json | Planner version — migrate.mjs reads from here, ripple_check.mjs validates SKILL.md matches |
config/gates.json | Gate definitions (from/to states, persona_audit flag, health_scan mode, trace_audit flag) — transition.mjs, ripple_check.mjs, and rule_engine.mjs all read from here |
config/program_gates.json | Program Manager gate definitions — program_manager.mjs validates these separately from iterative planner transitions |
config/program_packet.schema.json | Program Packet artifact schema for plans/programs/<program-id>/program_packet.json |
config/trace_rules.json | Per-phase tool trace coverage rules — trace_auditor.mjs reads from here to determine required reads and thresholds |
config/determinism.json | Feature flags (including tool_trace) — all scripts check isFeatureEnabled() before trace capture/audit |
new refuses if active plan exists — use resume, close, or --force.
new ensures .gitignore includes plans/ — prevents plan files from being committed during EXECUTE step commits.
close merges per-plan findings/decisions to consolidated files, updates state.md, and removes the .current_plan pointer. The protocol CLOSE state (writing summary.md, auditing decision anchors) should be completed by the agent before running close.
After bootstrap → read every file in {plan-dir} (state.md, plan.md, decisions.md, findings.md, progress.md, reflection.md, verification.md) before doing anything else. Then begin EXPLORE. User-provided context → write to findings.md first.
If the remaining work after bootstrap.mjs recover-poison or abandon is now a simple single-file fix or a static/UI deliverable, switch to the Lightweight flow instead of re-entering the full planner.
Filesystem Structure
plans/
├── .current_plan # → active plan directory name
├── INDEX.md # Compact cross-plan entrypoint derived from goal + summary.md
├── FINDINGS.md # Consolidated findings across all plans (merged on close)
├── DECISIONS.md # Consolidated decisions across all plans (merged on close)
├── knowledge/ # Persistent knowledge base (survives across all plans)
│ ├── index.md # Master catalogue (topic → file path + summary)
│ ├── mistakes.md # Recurring mistakes and antipatterns
│ ├── patterns.md # Proven implementation patterns
│ ├── gotchas.md # Non-obvious traps and constraints
│ ├── tech-debt.md # Structural fragility register (areas needing consolidation)
│ └── topics/ # Auto-created when files exceed 150 lines
│ └── {topic-slug}.md # Split-out topic files
├── programs/ # Optional Program Manager packets
│ └── PGM-001/
│ ├── program_packet.json # Canonical program artifact
│ └── program.md # Human mirror
└── plan_2026-02-14_a3f1b2c9/ # {plan-dir}
├── state.md # Current state + transition log
├── plan.md # Living plan (rewritten each iteration)
├── decisions.md # Append-only decision/pivot log
├── findings.md # Readable summary + index (synced projection when ledger is populated)
├── findings_ledger.json # Structured findings source (authoritative when it has authored findings content)
├── findings/ # Detailed finding files (subagents write here)
├── progress.md # Done vs remaining
├── reflection.md # Reflection verdicts per REFLECT cycle
├── verification.md # Verification results per VALIDATE cycle
├── checkpoints/ # Snapshots before risky changes
├── batch.md # Autonomous batch tracking (only in batch mode)
└── summary.md # Written at CLOSE
Templates: references/file-formats.md
File Lifecycle Matrix
R = read only | W = update (implicit read + write) | R+W = distinct read and write operations | — = do not touch (wrong state if you are).
Read-before-write rule: Always read a plan file before writing/overwriting it. This applies to every W and R+W cell below.
| File | EXPLORE | PLAN | EXECUTE | REFLECT | VALIDATE | RE-PLAN | CLOSE |
|---|
| state.md | W | W | R+W | W | W | W | W |
| plan.md | — | W | R+W | R | R | R | R |
| decisions.md | — | R+W | R | R+W | R | R+W | R |
| findings.md | W | R | — | R | R | R+W | R |
| findings_ledger.json | W | R | — | R | R | R+W | R |
| findings/* | W | R | — | R | R | R+W | R |
| progress.md | — | W | R+W | R+W | R | W | R |
| reflection.md | — | — | W | R+W | R | R | R |
| verification.md | — | W | W | R | R+W | R | R |
| checkpoints/* | — | — | W | R | R | R | — |
| summary.md | — | — | — | — | — | — | W |
| batch.md | — | — | R+W | R+W | R+W | — | R |
| plans/INDEX.md | R | R | — | — | — | R | W |
| plans/FINDINGS.md | R | R | — | — | — | R | W(merge) |
| plans/DECISIONS.md | R | R | — | — | — | R | W(merge) |
| plans/knowledge/index.md | R | R | — | — | — | R | W |
| plans/knowledge/*.md | R | R | — | — | — | R | W |
Per-State Rules
EXPLORE
- Approval mode reminder — Default full workflows use
approval.mode = "auto", so do not tell the user to start the approval daemon unless the project has explicitly switched to interactive mode.
- Read
state.md and plans/INDEX.md at start of EXPLORE for cross-plan context. Open plans/FINDINGS.md and plans/DECISIONS.md only when the compact index, the goal, or the current finding suggests a deeper dive is needed.
- Read
state.md, plans/FINDINGS.md and plans/DECISIONS.md at start of EXPLORE for cross-plan context.
- Read
plans/knowledge/index.md — scan for relevant mistakes, patterns, and gotchas. If the current problem matches a known entry, read the detailed file. Do NOT repeat a known mistake. DO apply a known pattern.
- Read code, grep, glob, search. One focused question at a time.
- Flush to the effective findings source after every 2 reads: update
findings_ledger.json first when it is the authored source, and keep the readable findings.md summary aligned. Planner-owned readers and writers now synchronize findings.md automatically when the ledger has renderable content, but you should still read before each manual write.
- Include file paths + code path traces (e.g.
service.py:23 → OrderService.process → adapter.load_data).
- DO NOT skip EXPLORE even if you think you know the answer.
- Minimum depth: ≥3 indexed findings in the effective findings source before transitioning to PLAN. During rollout,
findings_ledger.json is authoritative when it has authored findings content; otherwise the gate falls back to findings.md. Keep the readable ## Index in findings.md, then expand each indexed item into its own self-contained ## F-..., ## Finding N, or ## N. section. Findings must cover: (1) problem scope, (2) affected files, (3) existing patterns or constraints. Fewer than 3 → keep exploring.
- Use subagents to parallelise research. All subagent output →
{plan-dir}/findings/ files. Never rely on context-only results. Main agent updates findings.md index after subagents write — subagents don't touch the index. Naming: findings/{topic-slug}.md (kebab-case, descriptive).
- REFLECT → EXPLORE loops: append to existing findings, don't overwrite. Mark corrections with
[CORRECTED iter-N].
- Multi-persona payload mapping check — For campaign, outreach, ad, email, segmentation, or audience-persona work, verify that multi-persona campaigns have unique, non-overlapping payload mappings. Record which source object maps each persona/audience/ad set to copy, creative assets, overlays, and provisioning payloads; if names differ but payloads are shared, treat it as silent degradation and continue EXPLORE.
- Preflight artifact completeness check — For launch, campaign, approval, preflight, review, or audit HTML work, find and reuse the repo's established preflight/review generator before creating a new report. The deliverable must render the actual source payload: creative images or previews, overlay/messaging text, copy variations, persona/audience/ad-set mappings, payload/status metadata, and the live/no-live boundary. A summary-only or link-only index is not a valid preflight.
- Module extraction audit — When refactoring a single file into sub-modules (mixin extraction, split files), verify that module-level directives (e.g.,
from __future__ import annotations, __all__, encoding declarations, "use strict") are replicated in EACH new file.
- Parallel path audit — When adding a function call to one execution path (e.g., a factory function), grep for all other functions that duplicate its body structure and verify they get the same update. In
rule_engine.mjs the parallel paths are createEngine() and runSemanticChecks() — any new loadXxxFacts() must appear in both.
- Active plan pointer check — At session start after context resumption, verify
cat plans/.current_plan matches the plan directory you are about to work in, or simply open plans/ACTIVE_PLAN.md. If .current_plan points to an empty/phantom plan, update it before running any gates.
- Advisor auto-trigger —
bootstrap.mjs status will print ⚠️ Advisor review recommended when the configured advisor staleness threshold is crossed (default: 15 commits or 5 days since last advisor session) or when the recent change context looks meaningful enough to justify a proactive review (for example: shared/core modules changed, many new files, or turbulent execution). If this warning appears, run /advisor before starting EXPLORE or after landing the change. This ensures session lessons are captured, proactive follow-up work is suggested, and messy user intent can be consolidated into a draft intent_contract.json before the gates enforce it.
- Advisor autorun contract (v7.6.26+) —
bootstrap.mjs status now embeds a pre-rendered supervisor verdict block (NEXT/WHY/Run lines) when advisor-review is hot. Reproduce that block verbatim in your reply to the user; do not paraphrase. Acknowledge by running node .agent/skills/iterative-planner/scripts/escalation_check.mjs log advisor to clear the trigger. Manually invoke /advisor for a full session report only when the verdict block shows Supervisor: unavailable (LLM disabled, missing API key, or malformed response) or when the user explicitly asks. The legacy [WORKFLOW_AUTORUN:/advisor] stdout marker is still emitted as a fallback when the supervisor itself is offline. Do not auto-run from a low-confidence workflow.recommended=/advisor result alone.
- Stewardship escalation — When
/advisor shows clustered drift across docs, ontology, personas, annotations, stories, or user intent, escalate to /steward instead of chaining several narrow workflows manually. /advisor triages; /steward orchestrates the deeper consolidation pass and writes durable stewardship outputs.
EXPLORE Sub-Gates (Detailed Procedures)
The following sub-gates are MANDATORY before transitioning to PLAN. Full procedures are in references/explore-procedures.md. Summary:
- Diagnostic-First Gate — For runtime/integration bugs: verify actual runtime state before writing any fix. Record
[RUNTIME_STATE] in findings.md.
- Assumption Ledger — For integration, regression, migration, planner-core, and scientific/quant plans: record concrete assumptions with probe commands and pasted output. Scientific/quant probes should cover data source/lineage, coverage, temporal ordering, leakage risk, and benchmark/calibration claims as applicable. ❌ VIOLATED assumptions = investigate before fixing. FAIL if missing for those shapes (write "Assumption Ledger: N/A" only when the detected shape does not require it).
- Environment Config Verification — For config-dependent changes: list and verify all env vars/config values.
- Knowledge Base Gate — Read ALL
plans/knowledge/ files (mistakes, patterns, gotchas). Then store the digest salt in findings_ledger.json (kb_digest_salt) or add [KB_DIGEST:<hash>] to findings.md. The hash is shown when you run transition.mjs explore-to-plan. FAIL if digest missing or wrong — proves you actually read the KB.
Fresh plan / first-run fix: If kb_not_read fires on the very first explore-to-plan attempt (no kb_digest_hash yet in state.json), use _PLANNER_FAST_TRACK=1 node <skill-path>/scripts/transition.mjs explore-to-plan. The hash will be generated and stored on that run. Do NOT manually edit state.json to inject hashes — this corrupts plan state (G-010 gotcha).
- Story Elicitation (new-feature plans only — skip if: (a) goal is a bug fix / refactor / audit, OR (b) story_registry.json does not exist) — If the plan goal starts with "Add"/"Build"/"Implement"/"New" or root cause is "N/A — feature work", check whether an existing story covers the new functionality. If no existing story maps to it: ask the user 5 structured questions and record answers under
## Story Candidates in findings.md, then:
- Run
node <skill-path>/scripts/story_registry_bootstrap.mjs to assign US-NNN IDs.
- Run
node <skill-path>/scripts/ontology_serializer.mjs to emit updated Prolog traceability facts (wires the new story into the ontology for future gate enforcement).
- Q1: Who is the primary user of this feature? (role / persona)
- Q2: What problem does it solve for them? (pain point)
- Q3: What does success look like from their perspective? (outcome)
- Q4: What would they do differently after this feature exists? (behaviour change)
- Q5: What is the smallest useful version of this? (MVP scope)
- Root Cause Verification — Ask "Why?" twice. Write root-cause chain. FAIL if missing (write "Root Cause: N/A — feature work" for non-bug tasks).
- External Identifier Verification — For scripts interacting with external systems (e.g., Calendar events, Slack channels, Trello boards): explicitly check and verify that any hardcoded IDs correspond to the current or upcoming operational target before execution. FAIL if using stale identifiers.
- Adjacency Discovery — Run
blast_radius.mjs on files to modify. FAIL if missing (write "Adjacency: N/A — single file" if not applicable).
- Existing Capability Audit — Search before building. Log
[EXISTING_CAPABILITY] in findings.
- Content Depth — Each indexed finding section must carry its own analysis. Headings or
### subheads alone do not count; add at least a short paragraph or 2-3 real content lines under each ## F-... / ## Finding N / ## N. section. FAIL if findings are shallow.
Fast-Track Mode (Relaxed EXPLORE Gate)
For bug-fix plans, audit-driven plans, or tasks where findings are pre-known (e.g., from an existing audit report), fast-track mode relaxes the EXPLORE depth gate:
| Check | Standard | Fast-Track |
|---|
| Words per finding | ≥50 | ≥20 |
| Max shallow sections | 0 | 1 |
Activation (either method):
- Add
[FAST_TRACK] tag anywhere in findings.md
- Set
"fast_track": true in findings_ledger.json
- Set environment variable:
_PLANNER_FAST_TRACK=1 node <skill-path>/scripts/transition.mjs explore-to-plan
When to use: The task is a known bug fix, the findings come from an existing audit report, or the problem is already well-understood and deep exploration would be ceremony without value. All other EXPLORE gates (KB read, adjacency, root cause) still apply.
When NOT to use: Greenfield features, unclear root causes, or tasks where the solution direction is uncertain. If you're unsure, don't use fast-track.
Transition command (runs all checks): node <skill-path>/scripts/transition.mjs explore-to-plan
Quant/Trading Optimization Scale Contract (MANDATORY for model, strategy, or staking optimization)
If the task involves Optuna, model-family search, strategy/staking optimization, backtest parameter tuning, or any claim that an optimizer result explains profitability, EXPLORE must record an ## Optimization Scale Contract with:
- Run class:
smoke, wiring_proof, exploratory, serious_search, or promotion_candidate.
- Trial budget and completion count, plus whether the objective was frozen or sampled.
- Count of unique optimizer parameter names where discoverable from code/artifacts.
- Active parameter count per trial, including conditional model/policy/calibration branches where applicable.
- Model families, policy/strategy families, calibration choices, feature-selection surface, and objective choices.
- Coverage statement: combinations tried versus combinations available when artifacts expose it.
- Interpretation boundary: what the run can prove and what it cannot prove.
For smoke or wiring-proof runs, do not interpret ROI, IC, calibration, or promotion failure as final optimization evidence. Treat the result as artifact/protocol proof only and make the next serious search budget explicit.
PLAN
Fix Classification (MANDATORY in plan.md)
Purpose: Force explicit classification of the proposed fix approach. This prevents symptom-suppression fixes from being presented as root-cause fixes.
Classify your proposed fix in plan.md:
| Type | Definition | Example | Action |
|---|
| Root-cause fix | Removes the defect that caused the failure | Fix the validation logic that drops legitimate data | ✅ Proceed |
| Symptom suppression | Disables/bypasses the check that caught the failure | Add skip_check=True config toggle | 🛑 STOP. Explain why root-cause fix is impossible. |
| Defense in depth | Adds a secondary safety layer alongside root-cause fix | Add config toggle as backup opt-out | ✅ OK as secondary addition AFTER root-cause fix |
- If your fix is symptom suppression, you MUST document why a root-cause fix is impossible and get explicit user approval.
- If your fix is defense in depth, it must accompany a root-cause fix, never replace it.
Quant/Trading PLAN Extension: Optimization Adequacy Contract
For model, strategy, staking, calibration, or backtest optimization plans, plan.md must include:
## Optimization Run Class: state whether this is smoke, exploratory, serious search, or promotion candidate.
## Search-Space Dimensions: list concrete parameter counts, conditional branches, and feature-selection surfaces.
## Objective Contract: declare the primary objective, whether alternative objectives are frozen into separate studies, and how controls affect scoring.
## Search Budget Rationale: explain why the trial count is adequate for the active dimensions, or explicitly label it underpowered.
## Reporting Boundary: state that positive ROI or IC is not profitability proof unless controls, calibration, bet count, drawdown, and final OOS gates pass.
If the plan cannot count the dimensions yet, it must include a discovery step that computes them before any optimizer result is interpreted.
EXECUTE
- Pre-Step Checklist in
state.md: reset all boxes [ ], then check each [x] as completed before starting the step.
- Iteration 1, first EXECUTE → create
checkpoints/cp-000-iter1.md (nuclear fallback).
- One step at a time. Post-Step Gate after each (see below).
- Checkpoint before risky changes (3+ files, shared modules, destructive ops).
- Commit after each successful step:
[iter-N/step-M] description.
- If something breaks → STOP. 2 fix attempts max (Autonomy Leash). Each must follow Revert-First.
- Irreversible operations (DB migrations, external API calls, service config, non-tracked file deletion): mark step
[IRREVERSIBLE] in plan.md during PLAN. Full procedure: references/code-hygiene.md.
- Surprise discovery (behaviour contradicts findings, unknown dependency, wrong assumption) → note in
state.md, finish or revert current step, transition to REFLECT. Do NOT silently update findings during EXECUTE.
- Add
# DECISION D-NNN comments where needed (references/decision-anchoring.md).
External Communication Gate (MANDATORY)
Purpose: Prevent unauthorized emails, messages, or external communications from being sent to live customers without human review.
Procedure:
- Before dispatching any live external communication (e.g.
gmail.send_draft, sending Slack messages to customers), you MUST present the exact payload or draft ID to the user.
- You MUST receive explicit "YES SEND IT" approval from the user.
- Bypassing this gate and sending live external communications autonomously is a critical safety violation.
Drift Detection Gate (every 15 tool calls during EXECUTE)
- Every 15 tool calls, re-read
plan.md (current step) and progress.md
- Compare: is the current activity directly related to the current
In Progress step?
- If YES → continue
- If NO → log
[DRIFT_WARNING] in state.md with what you were doing vs what you should be doing, then re-focus
- If 3+ drift warnings accumulate → auto-transition to REFLECT ("scope creep detected")
Post-Step Gate (successful steps only — all 4 before moving on)
Purpose: Prevent LLM scope creep during long EXECUTE phases. The agent drifts from the plan without realizing it.
Procedure:
- Every 15 tool calls, re-read
plan.md (current step) and progress.md
- Compare: is the current activity directly related to the current
In Progress step?
- If YES → continue
- If NO → log
[DRIFT_WARNING] in state.md with what you were doing vs what you should be doing, then re-focus
- If 3+ drift warnings accumulate → auto-transition to REFLECT ("scope creep detected")
[!WARNING]
Drift is the most common failure mode in MCP/orchestration projects and any session exceeding 30 tool calls. The plan is truth — if you're doing something the plan doesn't mention, that's drift.
Post-Step Gate (successful steps only — all 5 before moving on)
0. Adversarial Red-Team Roleplay Gate: Before the iterative planner is allowed to transition from EXECUTE to REFLECT, you must switch personas. Explicitly write down 3 ways an adversarial hacker or a catastrophic input (like an API sending null for everything) could break the code you just wrote. If the code can't survive those 3 scenarios, you are not allowed to commit the code. Enforcement: Document each attack vector as a ## Vector N heading in red_team_notes.md (scaffolded at plan creation). Each vector must include Attack, Impact, and Mitigation sections with real, non-template content. Accepted label styles include Attack:, **Attack**:, or heading-style subsections such as ### Attack. Single-line sections are acceptable if they are substantive; adding fake line breaks is not required. Run verify_gate.mjs execute-to-reflect or transition.mjs execute-to-reflect — the gate blocks unless ≥3 substantive vectors are documented.
0b. Compulsory Persona Audit (v2.1.0+): transition.mjs execute-to-reflect automatically runs all persona packs configured in audit.config.json against the current project. If any finding meets or exceeds the fail_on threshold, the transition is blocked. This ensures domain-specific rules (quant data integrity, UX accessibility, etc.) are enforced before reflection. Escape hatch: set env var PLANNER_SKIP_PERSONA_AUDIT="justification" (v3.0 — CLI flags and config-file skips removed; only env vars work since LLMs cannot set them).