Perfect! Now I have a complete picture. Let me compile a comprehensive final report.
Summary: Megaplan Project Structure and Gate/Review System
I've completed a thorough exploration of the megaplan project. Here are my findings:
1. Overall File Structure
Top-level:
/megaplan/ — main package (32 modules)
/tests/ — comprehensive test suite (24 test files)
/CHANGELOG.md — v0.16.0 current (released 2026-04-15)
/pyproject.toml — version 0.16.0, Python 3.11+, depends on PyYAML
Key subdirectories:
megaplan/_core/ — state management, registries, workflow logic, I/O
megaplan/loop/ — loop mode (iterative planning)
megaplan/prompts/ — phase-specific prompt builders
megaplan/data/ — schema/data definitions
2. Gate/Review System - How Gates Work
Gate Flow (from handlers.py:handle_gate):
Gate Signals Built (build_gate_signals in evaluation.py):
Collects unresolved significant flags, weighted scores, plan deltas, recurring critiques
Computes weighted trajectory and debt overlaps
Generates warnings if scope creep, high iteration count, or escalated debt subsystems exist
Worker Runs Gate (calls Claude/Codex with _gate_prompt):
Gate receives: plan, critique results, success criteria, gate signals, unresolved flags
Returns one of three recommendations: PROCEED, ITERATE, ESCALATE
Flag Resolution Validation (_apply_gate_outcome lines 614-641):
Blocking flags (severity = "significant" or "likely-significant"):
If PROCEED recommended: EVERY blocking flag must have a flag_resolutions entry
No implicit acceptance — unresolved blocking flags trigger automatic reprompt
Valid resolutions :
action: "dispute" — critique is factually wrong (requires concrete evidence, not rubber-stamp)
action: "accept_tradeoff" — concern is real but intentionally accepted (requires specific rationale)
Invalid/rubber-stamp evidence/rationale entries are skipped (see is_rubber_stamp() in evaluation.py:103)
Reprompt Logic (lines 1087-1141):
If PROCEED has blocking unresolved flags, a reprompt is issued once with missing flag IDs
If retry still leaves blocking flags unresolved: auto-downgrade to ITERATE with explanation
gate_summary["reprompted"] flag tracks if reprompt occurred
Gate Outcome (lines 651-666):
PROCEED + preflight_passed → move to finalize
PROCEED + !preflight_passed → move to revise (blocked status)
ITERATE → move to revise
ESCALATE → move to override add-note (user decision point)
Debt Recording (when PROCEED + accepted tradeoffs):
_record_gate_debt_entries() creates debt registry entries for accepted tradeoffs
Tracks subsystem, concern, flag_ids, plan_ids, occurrence count
3. Criteria Evaluation in Milestone/Step Model
Data Structures (types.py):
PlanState : Contains name, idea, current_state, iteration, config, sessions, history, meta, last_gate
PlanMeta (TypedDict):
significant_counts: list of flag counts per iteration
weighted_scores: gate signal scores per iteration
plan_deltas: % change between plan versions
recurring_critiques: flags that appear in multiple iterations
total_cost_usd: cumulative cost
notes: user annotations
user_approved_gate: if user manually approved
LastGateRecord : Stores latest gate output (recommendation, rationale, warnings, settled_decisions, passed status, preflight_results)
Success Criteria (from schemas.py + plan metadata):
Plan includes success_criteria array in plan.json schema
Each criterion has: criterion (string description), priority (must/should/info)
Evaluation happens in critique checks (see checks.py for critique check specs)
Review phase verifies criteria pass/fail against execution
4. YAML Schema for Plans (Chain Driver)
Chain Spec Structure (chain.py:11-27 docstring + ChainSpec class):
yaml Copy code
seed:
plan: <existing-plan-name> # optional, drives first
milestones:
- label: m1 # required
idea: /path/to/idea-m1.txt # required
branch: megaplan/m1-foundation # optional (informational)
- label: m2
idea: /path/to/idea-m2.txt
on_failure:
abort: stop_chain # stop_chain | skip_milestone | retry_milestone
on_escalate:
abort: stop_chain # stop_chain | skip_milestone | retry_milestone
driver:
stall_threshold: 5 # iterations before escalation
max_iterations: 200 # hard cap
poll_sleep: 2.0 # seconds between status checks
phase_timeout: 300.0 # per-phase timeout
status_timeout: 30.0 # status command timeout
on_escalate: force-proceed # force-proceed | abort | fail
robustness: standard # tiny | light | standard | robust | superrobust
auto_approve: true
Progress Persisted to chain_state.json:
current_milestone_index: -1 (seed), 0+ (milestone index)
current_plan_name: active plan name
last_state: terminal state of last completed plan
completed: list of completed milestone records
5. Verify/Verification Patterns
Test Verification Task (handlers.py:_ensure_verification_task lines 1171-1239):
Finalize appends a verification task (test-run) if not already present
Task description instructs: "Run the tests specified in the task description...run the full test file/module...run the project's existing test suite — do NOT create new test files."
Automatically creates sense check: "Did the verification tests pass? Were any regressions found and fixed?"
Tracks baseline test failures so executor doesn't scope-creep fixing pre-existing failures
Criteria Quality Check (checks.py:criteria_quality):
Critique checks whether success criteria are verifiable (must criteria must have clear yes/no answers)
Flag subjective goals or numeric guidelines that should be should instead of must
No explicit "verify" step — verification is baked into:
Critique checks (including verification check in extended tier)
Finalize's auto-appended verification task
Review phase validates execution against criteria
6. CHANGELOG.md — Recent Entries
v0.16.0 (2026-04-15):
Chain driver: new megaplan chain subcommand with YAML spec, resume-from-state, seed plan handling
Tests cover spec parsing, chain status, validation, happy path, state resume, on-failure policies
v0.14.0 (2026-04-15):
Strict gate flag resolution: PROCEED now requires explicit flag_resolutions for ALL blocking flags
Reprompt once if first response leaves blocking flags unresolved
Auto-downgrade to ITERATE if retry still fails to resolve blocking flags
Rubber-stamp detection rejects vague dispute evidence and generic tradeoff rationale
v0.12.0 (2026-04-15):
Auto driver: megaplan auto --plan <name> drives plan to terminal state
Cross-directory plan discovery
Standard robustness now includes init→plan transition
v0.10.0 (2026-04-10):
Codex backend hardening (timeout recovery, partial output extraction, error classification)
Plan locking (fcntl) to prevent concurrent step execution
Active step tracking in state.json (active_step field with stale detection at 300s)
megaplan status / megaplan watch unified monitoring
Tiny robustness level (skips critique + gate)
Parallel review for heavy robustness
OpenAI strict-schema compatibility (all properties required)
7. Version & Schema Locations
Version : 0.16.0 defined in /pyproject.toml (line 7)
JSON Schemas : /megaplan/schemas.py — SCHEMAS dict with keys:
plan.json, prep.json, revise.json, critique.json, gate.json, finalize.json, execution.json, review.json, loop_plan.json, loop_execute.json
strict_schema() function enforces additionalProperties: false and auto-populates required arrays
Notable: gate.json requires flag_resolutions (array of flag resolution objects) and accepted_tradeoffs
Notable: review.json has rework_items with explicit required fields (exception to strict_schema auto-population)
8. Key Gate/Criteria Files
/megaplan/handlers.py — gate execution (lines 1049-1169), flag resolution validation (lines 604-666), debt recording
/megaplan/evaluation.py — gate signals building, flag weighting, rubber-stamp detection, evidence validation
/megaplan/prompts/gate.py — gate prompt with blocking flag requirements and examples
/megaplan/checks.py — 8 critique checks including criteria_quality (verifiability check)
/megaplan/review_checks.py — 4 review checks (coverage, placement, adjacent_calls, simplicity)
/megaplan/_core/workflow.py — state machine with gate-driven transitions
/megaplan/types.py — data structures, flag statuses, gate artifact TypedDict
/tests/test_megaplan.py — comprehensive gate tests showing flag_resolutions, reprompt, auto-downgrade patterns
This comprehensive system ensures gates are non-bypassable (blocking flags require explicit resolution, reprompt on incomplete first attempt, auto-downgrade if still unresolved) while maintaining auditability through debt registry, flag history, and settled decisions.