You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are creating an implementation plan for the following idea.
code
Idea:
Implement v0.15.0 doc-mode per /Users/user_c042661f/Documents/megaplan/idea-doc-mode.txt — see that file for full spec.
code
Assistant
Now let me look at the specific files that need changes.
Assistant
Let me read the remaining critical files.
Assistant
Let me check a few more critical locations.
Assistant
Let me check handle_init and the checks module.
Assistant
Let me check the remaining files: the review prompt, prep prompt, and test structure.
Assistant
Let me check the review prompt builder and finalize prompt builder.
Assistant
Now let me look at the _review_prompt builder and check the critique category enum.
Assistant
I now have a thorough understanding of the codebase. Let me read the remaining bit of the review prompt to complete my picture.
Assistant
I have all the information I need to write the plan. Let me construct it now.
User
Continue from where you left off.
Assistant
No response requested.
User
Assistant
Let me examine the specific files referenced by the critique flags to understand the exact code that needs doc-mode branches.
Assistant
Now let me check the hermes reconstruct function and the finalize handler section.
Assistant
Now I have all the evidence I need. All four flags are valid and target real code-level gaps. None suggests a wrong root cause — they all point to code-mode assumptions that the original plan missed branches for. Let me produce the revised plan.
Project directory:
/Users/user_c042661f/Documents/megaplan
No prior clarification artifact exists. Identify ambiguities, ask clarifying questions, and state your assumptions inside the plan output.
Requirements:
- If the engineering brief suggests an approach, use it as your starting hypothesis — but before committing, consider if there's a simpler or more fundamental fix. The brief is well-researched input, not a final answer.
- If the brief is absent, incomplete, or says "skip", inspect the repository yourself before planning.
- Stay focused on the requested idea. If repo exploration surfaces unrelated issues or docs, ignore them and return to the task.
- Prefer source code, tests, and directly relevant config files. Avoid `.megaplan/`, prior plan artifacts, and unrelated `docs/` or ops/deployment material unless the task explicitly depends on them.
- Stop exploring once you have enough evidence to name the concrete touch points and validation path. Do not keep browsing after you can write the plan.
- Produce a concrete implementation plan in markdown.
- Define observable success criteria as objects with `criterion` (string) and `priority` (`must`, `should`, or `info`):
- `must` — hard gate. The reviewer will block on failure. Use for correctness, functional requirements, and verifiable outcomes (e.g., "all existing tests pass", "API returns 200 for valid input"). Every `must` criterion must have a clear yes/no answer.
- `should` — quality target. The reviewer flags but does not block. Use for subjective goals, numeric guidelines, and best-effort improvements (e.g., "file under ~300 lines", "no deeply nested conditionals", "each function has a single responsibility").
- `info` — documented for humans, reviewer skips. Use for criteria that cannot be verified in this pipeline (e.g., "13 manual smoke tests pass", "stakeholder sign-off obtained").
- Use the `questions` field for ambiguities that would materially change implementation.
- Use the `assumptions` field for defaults you are making so planning can proceed now.
- Prefer cheap validation steps early.
- Keep the plan proportional to the task. A 1-line fix needs a 2-step plan (apply fix + run tests), not a 5-step investigation.
- If user notes answer earlier questions, incorporate them into the draft plan instead of re-asking them.
- Fix the problem fully. Do not limit scope just to avoid breaking existing tests — update the tests too if needed.
- Prefer the simplest, most direct fix. No fallbacks, type conversions, or defensive wrappers without concrete evidence they are needed.
- If the task or issue hints suggest a specific approach, follow it. Only deviate with concrete counter-evidence.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are revising an implementation plan after critique and gate feedback.
Implement v0.15.0 doc-mode per /Users/user_c042661f/Documents/megaplan/idea-doc-mode.txt — see that file for full spec.
code
Current plan (markdown):
# Implementation Plan: v0.15.0 doc-mode (metaplan)
Overview
Megaplan currently only produces code artifacts. This feature adds --mode doc so the same harness can produce structured documents (plans, RFCs, design docs). The core state machine, flag taxonomy, critique/gate/revise loop, and robustness levels are unchanged. What changes: (1) plan.json gains mode and output_path fields, (2) new doc-mode prompt variants for prep, execute, and review, (3) a new execution schema with sections_written instead of files_changed, (4) a new doc_assembly.py module to assemble sections into the output file, (5) validate_execution_evidence branches on mode, and (6) a doc-quality critique category.
The spec is well-scoped: single output file, no mixed-mode, no loop-mode doc support. Existing code-mode tests remain untouched.
Phase 1: Foundation — Types, Config, CLI, Schema
Step 1: Add mode/output_path to plan config and types (megaplan/types.py, megaplan/_core/state.py)
Scope: Small
Addmode and output_path as optional fields to PlanConfig TypedDict (megaplan/types.py:28). mode is str (values: "code", "doc"), output_path is str.
Verify that PlanState inherits config: PlanConfig at types.py:115, so the new fields propagate automatically.
Step 2: Wire --mode and --output CLI flags (megaplan/cli.py:811)
Scope: Small
Add--mode argument to init_parser with choices=["code", "doc"], default="code" (cli.py:811, after line 820).
Add--output argument to init_parser (cli.py:811). Required only when mode=doc. Validate in handle_init that --output is provided when --mode doc and raise CliError otherwise.
Updatehandle_init (handlers.py:738) to persist mode and output_path in state["config"]. Default mode to "code" for backward compatibility.
Extend the category enum in SCHEMAS["critique.json"] at schemas.py:204 to include "doc-quality".
Verifychecks.py critique check specs — the category is a free string in the critique prompt, not hardcoded in the check registry. No change needed in checks.py itself unless a doc-specific check is desired (out of scope for v0.15.0).
Update schema selection logic: wherever SCHEMAS["execution.json"] is looked up (primarily workers.py:51STEP_SCHEMA_FILENAMES), branch on mode. The simplest approach: add a helper get_execution_schema(mode: str) in schemas.py that returns the correct schema dict.
Step 5: Bump version and add CHANGELOG entry (pyproject.toml, CHANGELOG.md)
Scope: Small
Updatepyproject.toml:7 version from "0.14.4" to "0.15.0".
Add a ## v0.15.0 CHANGELOG entry describing doc-mode.
Createmegaplan/prompts/prep_doc.py with a _prep_doc_prompt(state, plan_dir, root=None) function. Repoint the prompt from "search the codebase for relevant files" to "what sources, prior art, related docs should inform this document?" Sense-check items become "did you read X?" rather than "did you find the relevant module?"
Keep the output schema identical to prep.json — the fields (key_evidence, relevant_code, constraints, suggested_approach) still apply, just the content and prompt framing change. relevant_code becomes references to existing docs/prior art.
Createmegaplan/prompts/execute_doc.py with _execute_doc_prompt and _execute_doc_batch_prompt.
Frame the executor as an author writing a document. Its only filesystem operation is writing to the configured output_path. Replace files_changed references with sections_written.
Include the doc-mode output shape example (JSON with sections_written instead of files_changed, no commands_run in task_updates).
Reuse shared helpers: _execute_nudges, _execute_approval_note, _execute_rerun_guidance, _render_prep_block from existing code.
Createmegaplan/prompts/review_doc.py with _review_doc_prompt(state, plan_dir, *, review_intro, criteria_guidance, ...).
Reword to treat the deliverable as text: instead of "cross-reference files_changed against git diff", say "read the output file and judge it against success criteria." Remove git-diff and execution_audit.json references — the audit for doc mode is section-based, not git-based.
Keep the same review.json output schema — must/should/info criteria, task_verdicts, sense_check_verdicts all apply.
Step 9: Wire doc-mode prompts into dispatch (megaplan/prompts/__init__.py)
Scope: Small
Import the new prompt builders.
Update_CLAUDE_PROMPT_BUILDERS, _CODEX_PROMPT_BUILDERS, _HERMES_PROMPT_BUILDERS to dispatch to doc-mode builders when state["config"].get("mode") == "doc". The cleanest approach: modify create_claude_prompt / create_codex_prompt / create_hermes_prompt to check mode and select the appropriate builder for prep, execute, and review steps. Other steps (plan, critique, gate, finalize, revise) use the same builders regardless of mode.
Finalize prompt (finalize.py): add a conditional block for doc mode that replaces references to files_changed with sections_written in the task schema guidance. The simplest approach: an if mode == "doc": block at the end of _finalize_prompt that appends doc-specific task field guidance.
assemble_doc(plan_dir: Path, output_path: Path, finalize_data: dict) -> Path: reads per-batch executor outputs, orders sections by plan position, writes the assembled file atomically (temp file + rename).
extract_sections(batch_payloads: list[dict]) -> dict[str, str]: maps section_id → rendered text from executor output.
Idempotent: running twice on the same plan replaces the file completely.
Call site: invoked at the end of execute (after all batches complete) in execution.py.
Step 11: Update merge validation for doc mode (megaplan/merge.py, megaplan/execution.py:280)
Scope: Medium
Update_merge_batch_results in execution.py:256 to branch on mode. When mode is "doc":
Required fields for task_updates become ("task_id", "status", "executor_notes", "sections_written") instead of including files_changed and commands_run.
Merge fields become ("status", "executor_notes", "sections_written").
Update_validate_and_merge_batch call in execution.py correspondingly — swap array_fields to ("sections_written",).
Step 12: Branch validate_execution_evidence for doc mode (megaplan/evaluation.py:123)
Scope: Medium
Add a mode parameter to validate_execution_evidence (or read it from finalize_data).
When mode is "doc", replace the git-status comparison with:
Extract planned sections from finalize_data tasks (all sections_written across tasks).
Read the output file and verify: all planned sections present, no unclaimed sections, file exists and is non-empty.
Return findings in the same {"findings": [...], "skipped": False} shape.
When mode is "code", behavior is unchanged (existing git-status logic).
Update callers: execution.py:423 passes the project_dir — for doc mode, also pass the output_path so the audit can read the file.
Step 13: Update status display for doc mode (megaplan/cli.py:341)
Scope: Small
Update_build_status_payload (in cli.py) to include mode and output_path in the status output when present in state config.
Phase 4: Wiring — Handlers and Execution Loop
Step 14: Update execute handler for doc mode (megaplan/handlers.py:1337, megaplan/execution.py)
Scope: Medium
Inhandle_execute (handlers.py:1337): detect mode from state["config"].get("mode", "code"). When "doc":
After all batches complete, call assemble_doc() to produce the output file.
In_run_and_merge_batch (execution.py:349): when mode is "doc", skip _observe_git_changes, _collect_quality_deviations, and capture_before_line_counts (no git changes expected). Keep _check_done_task_evidence but adapt evidence check: for doc mode, has_evidence checks sections_written instead of files_changed.
In_build_aggregate_execution_payload (execution.py:136): when mode is "doc", aggregate sections_written instead of files_changed.
Step 15: Update review handler for doc mode (megaplan/handlers.py:1576)
Scope: Small
Inhandle_review: when mode is "doc", skip mechanical pre-checks that depend on code (test pass/fail, type checking). The review prompt already handles the rest via the doc-mode review prompt.
In_parallel_review_context (prompts/review.py:78): when mode is "doc", replace git_diff with the output file content.
Steps 17–18 (tests) — prove the change works and nothing regressed.
Validation Order
Run pytest tests/test_schemas.py after Step 4 to verify new schema is valid.
Run pytest tests/ after Step 5 to verify no regressions from version bump.
Run pytest tests/test_doc_mode.py after Step 17 for focused doc-mode coverage.
Run full pytest tests/ after Step 18 for final regression check.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-04-15T07:48:05Z",
"hash": "sha256:4b51ecac9a4a1e801b8784b0be8e2ac1efe370350b3fa1da50a57a11bcc21b20",
"questions": [
"The spec says 'output file exists and is non-empty' in the doc-mode audit. Should the audit also verify that the output file is valid markdown (or whatever format), or just check existence + non-empty?",
"For doc-mode execute, should the executor agent have full filesystem read access (to reference existing docs/code) but only write access to the output path? Or should read access also be restricted?",
"The spec says section assembly happens at 'finalize-end' but also mentions per-batch executor outputs. Should assembly happen after each batch (incremental) or only after all batches complete? The spec's mention of 'the harness assembles sections in plan-order into the output file at the end of the batch' is ambiguous \u2014 does 'the batch' mean each batch or the final batch?"
],
"success_criteria": [
{
"criterion": "megaplan init --mode doc --output X '...' produces a plan with mode: doc and output_path in state.json",
"priority": "must"
},
{
"criterion": "megaplan init --mode doc without --output raises a clear error",
"priority": "must"
},
{
"criterion": "All existing code-mode tests pass unchanged (pytest tests/ green)",
"priority": "must"
},
{
"criterion": "Doc-mode audit rejects an executor that claims a section not in the plan",
"priority": "must"
},
{
"criterion": "Doc-mode audit rejects an executor that skips a section without marking the task blocked/skipped",
"priority": "must"
},
{
"criterion": "Doc-mode execute produces a non-empty file at the configured output_path",
"priority": "must"
},
{
"criterion": "pyproject.toml version is 0.15.0",
"priority": "must"
},
{
"criterion": "CHANGELOG has a v0.15.0 entry describing doc-mode",
"priority": "must"
},
{
"criterion": "Doc-mode execution schema (execution_doc.json) validates correctly via strict_schema",
"priority": "must"
},
{
"criterion": "Doc-mode review with a must criterion about doc content can fail and trigger needs_rework",
"priority": "must"
},
{
"criterion": "New prompt files (prep_doc.py, execute_doc.py, review_doc.py) each under ~300 lines",
"priority": "should"
},
{
"criterion": "doc_assembly.py under ~150 lines \u2014 simple section concatenation, not a complex engine",
"priority": "should"
},
{
"criterion": "No changes to existing code-mode prompt files beyond adding mode-dispatch branches",
"priority": "should"
},
{
"criterion": "megaplan status shows mode: doc and output_path when in doc mode",
"priority": "should"
},
{
"criterion": "Full end-to-end doc-mode plan lifecycle tested manually (init through review)",
"priority": "info"
}
],
"assumptions": [
"Assembly happens once after all batches complete (not incrementally per-batch). The spec says 'assembles sections in plan-order' which implies a final assembly step, and incremental assembly would require conflict resolution between partial writes.",
"The output_path is relative to project_dir as stated in the spec. Validation ensures it doesn't escape the project directory (no '../' traversal).",
"Doc-mode tasks in finalize.json use the same task schema but with instead of . The finalize schema gains an optional field on tasks, populated only in doc mode.",
"Existing plans with no field default to 'code' \u2014 this is a backward-compatible addition, not a migration.",
"The doc-mode review uses the same review.json output schema. The only difference is prompt framing \u2014 criteria like 'the doc names every blocking risk' replace 'tsc clean'.",
"The flag is not required for doc-mode execute since it only writes a single output file, not repo code."
],
"structure_warnings": []
}
code
Gate summary:
{
"recommendation": "ITERATE",
"rationale": "Light robustness: single revision pass to incorporate critique feedback.",
"signals_assessment": "",
"warnings": [],
"settled_decisions": []
}
code
Open significant flags:
[
{
"id": "FLAG-001",
"severity": "significant",
"status": "open",
"concern": "Finalize contract: the plan treats finalize as mostly shared, but the current finalize prompt and handler are hard-wired for code execution. _finalize_prompt() still requires the final task to run tests and even create a throwaway repro script, while _write_finalize_artifacts() always captures a pytest baseline and _ensure_verification_task() appends a test task with files_changed/commands_run. Without an explicit doc-mode branch for finalize, doc plans will be mutated back into code-style execution checklists before execute starts.",
"evidence": "The spec says doc-mode tasks use sections_written and doc review judges text, not tests (idea-doc-mode.txt:52-56,97-103). The current finalize prompt still says the final task MUST run tests and create a repro script (megaplan/prompts/finalize.py:96-97). The handler then unconditionally captures baseline tests and injects a verification task (megaplan/handlers.py:376-380,1171-1239)."
},
{
"id": "FLAG-002",
"severity": "significant",
"status": "open",
"concern": "Timeout recovery: the execute timeout/checkpoint path is still code-only, and the plan does not include it. If a doc-mode execute times out, _merge_timeout_checkpoint() requires files_changed and commands_run, and _reset_timeout_invalid_tasks() revalidates tasks against git-diff-style evidence. That will drop or reset legitimate doc-mode progress instead of recovering it.",
"evidence": "Doc mode is supposed to keep the same batch execution and audit loop (idea-doc-mode.txt:72-95). But timeout recovery still merges checkpoint task updates with required fields files_changed/commands_run and re-audits against files_in_diff (megaplan/execution_timeout.py:41-101,110-140,202-217). The implementation plan only calls out execution.py, evaluation.py, and merge.py, not this timeout path."
},
{
"id": "FLAG-003",
"severity": "significant",
"status": "open",
"concern": "Agent coverage: the worker changes are incomplete for Hermes. The plan mentions workers.py schema selection, but hermes_worker.py independently loads the execute schema from STEP_SCHEMA_FILENAMES and reconstructs failed execute payloads with files_changed/commands_run. Doc mode would therefore remain code-shaped or fail under --hermes and any Hermes fallback path.",
"evidence": "Megaplan already exposes Hermes for normal phases, including execute (megaplan/types.py:239-249, ). Hermes still resolves execute schemas through () and its execute fallback reconstructs only / payloads (, plus at )."
},
{
"id": "FLAG-004",
"severity": "significant",
"status": "open",
"concern": "Output-path containment: the plan assumes will be validated and doc execute will only write that file, but no implementation step actually adds that enforcement. In the current runner, Codex execute is given the whole project as a writable root, and trusted-container mode bypasses Codex sandboxing entirely. Skipping for doc mode is unsafe unless the plan also adds concrete path normalization and worker-level write restriction.",
"evidence": "The spec requires to be relative to and says doc execute's only filesystem tool is writing the configured output path (). The plan's assumptions mention containment, but none of its steps add a resolver/guard for traversal or tighten worker permissions. Today Codex execute writes under , or runs unsandboxed in trusted-container mode ()."
}
]
code
Requirements:
- Before addressing individual flags, check: does any flag suggest the plan is targeting the wrong code or the wrong root cause? If so, consider whether the plan needs a new approach rather than adjustments. Explain your reasoning.
- Update the plan to address the significant issues.
- Keep the plan readable and executable.
- Return flags_addressed with the exact flag IDs you addressed.
- Include `changes_summary` as a short plain-English summary of what changed in the revision. If there were no concrete flags, say that explicitly (for example: `No critique flags were raised; refined wording and kept the plan aligned for execution.`).
- Preserve or improve success criteria quality. Each criterion must have a `priority` of `must`, `should`, or `info`. Promote or demote priorities if critique feedback reveals a criterion was over- or under-weighted.
- Verify that the plan remains aligned with the user's original intent, not just internal plan quality.
- Remove unjustified scope growth. If critique raised scope creep, narrow the plan back to the original idea unless the broader work is strictly required.
- Maintain the structural template: H1 title, ## Overview, phase sections with numbered step sections, ## Execution Order or ## Validation Order.
- CRITICAL: Your entire revised plan markdown (all sections) must be output as the `plan` field in the structured output. The prose response must not contain the plan text.
- CRITICAL: Return only the structured JSON object for the schema fields `plan`, `changes_summary`, `flags_addressed`, `assumptions`, `success_criteria`, and `questions`. Do not add commentary before or after the JSON object.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.