Refactor megaplan workflow routing to be declarative. Replace scattered is_light / configured_robustness checks in handle_critique, handle_revise, and handle_execute with a declared workflow definition (e.g. WORKFLOWS = {"light": ["plan", "critique", "revise", "finalize", "execute"], "standard": ["plan", "critique", "gate", "revise?", "finalize", "execute", "review"]}). Each handler should do its job and ask "what is next?" from the workflow instead of embedding routing decisions. Also clean up infer_next_steps to derive from the workflow definition.
The megaplan codebase currently embeds robustness-based routing decisions in 4 places across handlers.py and a hand-coded state machine in _core.py:662-686. The is_light = configured_robustness(state) == "light" pattern appears at:
handlers.py:806 — handle_critique: skips gate, writes synthetic gate artifact, routes to revise instead of gate
handlers.py:854,897,945 — handle_revise: skips gate precondition check, sets state to STATE_GATED instead of STATE_PLANNED, routes to finalize instead of critique
handlers.py:1179,1205 — handle_execute: transitions to STATE_DONE instead of STATE_EXECUTED, skips review
Meanwhile, infer_next_steps (_core.py:662-686) is a separate hand-coded state machine that doesn't account for robustness at all — it always returns standard-flow options.
Goal: Replace scattered conditionals with a declared workflow definition. Each handler does its job and asks the workflow "what's next?" Derive infer_next_steps from the same definition.
Constraint: The standard workflow has conditional branching (gate recommendation → ITERATE/ESCALATE/PROCEED) and override options (replan, force-proceed, abort, add-note). The declarative model must handle these — a simple linear list won't suffice.
Phase 1: Foundation — Workflow Definition and Router
Step 1: Audit and document the two actual flows ()
Assistant
{"flags":[{"id":"F001-router-purity","concern":"Workflow routing: Shared next-step logic must stay pure; Step 4's option to let the workflow router apply side effects would make //error paths mutate plan artifacts.","category":"correctness","severity_hint":"likely-significant","evidence":" is reused outside handlers in and , and also feeds errors from . The plan's Step 4 suggests or router-owned side effects for light-mode synthetic gate creation, but the current synthetic write is handler-local in . If the same workflow helper backs , those read-only callers would either write /touch state unexpectedly or need special-case forks."},{"id":"F002-infer-next-backcompat","concern":"Core API: currently tolerates partial state dicts; making it read robustness from without an explicit compatibility rule will break existing tests and callers.","category":"correctness","severity_hint":"likely-significant","evidence":"The plan's Step 2/7 says / should read , but currently does in . Existing tests call with no at all in , so a straight swap would raise unless the refactor preserves a default path for partial states."},{"id":"F003-overengineered-workflow-table","concern":"Workflow routing: Over-engineering: the proposed /override/side-effect framework is broader than the repo needs and risks duplicating logic that is already centralized elsewhere.","category":"maintainability","severity_hint":"likely-minor","evidence":"The actual robustness split is narrow: only three light-specific branches remain in , , and , while standard gate branching is already centralized in at . The plan expands the refactor to explicit conditional edges, override tables, and workflow-level side effects, even though overrides already live in dedicated handlers at . A smaller declarative map for post-step routing would match the codebase more closely."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
megaplan/_core.py
Scope: Small
Verify the exact state transitions for each robustness level by tracing both paths through handlers. The current flows are:
revise → critique (standard loop) vs revise → finalize (light)
execute → review (standard) vs execute → DONE (light)
Confirminfer_next_steps returns (standard-only, no robustness awareness): note that it always offers step as an option and override actions contextually.
Step 2: Design and implement the workflow definition (megaplan/_core.py)
Scope: Medium
Add a WorkflowDef data structure near the existing state constants (_core.py:~600). The definition needs to express:
Ordered step sequence per robustness level
Conditional transitions (gate outcomes)
Override options available at each state
The "step" escape hatch (always available after planning)
Implement a workflow_next(state: PlanState) -> list[str] function that:
Reads configured_robustness(state) once
Looks up transitions from the workflow definition
Applies robustness overrides
Returns the valid next steps (replacing infer_next_steps)
Keepinfer_next_steps as a thin wrapper or alias for backwards compatibility (it's exported in __init__.py:40,63 and used in cli.py:27,73,167).
Step 3: Validate the workflow definition with tests (tests/test_megaplan.py)
Scope: Small
Updatetest_infer_next_steps_matches_new_state_machine (test_megaplan.py:160-182) to test both robustness levels.
Add a parametrized test that walks each workflow end-to-end:
python
@pytest.mark.parametrize("robustness", ["light", "standard"])
def test_workflow_definition_is_complete(robustness):
"""Every state in the workflow has at least one transition."""
Add a test that verifies workflow_next returns the same results as the current hard-coded infer_next_steps for all standard-flow states (regression guard before we swap callers).
Phase 2: Handler Migration
Step 4: Refactor handle_critique to use workflow routing (megaplan/handlers.py:806-837)
Scope: Medium
Removeis_light conditional at line 806.
Extract the synthetic gate artifact creation into a helper (it's a workflow-level concern, not a critique concern). The workflow definition should indicate that light mode inserts a synthetic gate after critique.
Replace"next_step": "revise" if is_light else "gate" (line 837) with a call to workflow_next(state) to determine the next step.
Move the synthetic gate write to a _apply_workflow_side_effects(state, step="critique") helper that the workflow router calls, or keep it inline but driven by a workflow flag like skip_gate: True.
Key behavior to preserve: The synthetic gate.json with recommendation: "ITERATE" must still be written for light mode so handle_revise can reference it. The cleanest approach is to have the workflow definition include a side_effects callback or have the router handle it.
Step 5: Refactor handle_revise to use workflow routing (megaplan/handlers.py:854-953)
Scope: Medium
Removeis_light checks at lines 854, 897, 945.
Replace the gate precondition check (line 855: if not is_light and state["last_gate"].get("recommendation") != "ITERATE") with a workflow-derived precondition. The workflow knows whether gate is required before revise.
ReplaceSTATE_GATED if is_light else STATE_PLANNED (line 897) — the workflow definition specifies the next state after revise.
Replace"finalize" if is_light else "critique" (line 945) with workflow_next(state).
Preserve the state["last_gate"] = {} reset (line 900) for standard mode — this enables the critique→gate loop.
Step 6: Refactor handle_execute to use workflow routing (megaplan/handlers.py:1179-1210)
Scope: Small
Remove the duplicated light-robustness blocks at lines 1179-1184 and 1205-1209.
Replace with a single post-dispatch call: state, response = apply_workflow_transition(state, response, "execute") that consults the workflow to determine if review is next or if we go straight to DONE.
Preserve the save_state call when transitioning to DONE.
Step 7: Update infer_next_steps and require_state (megaplan/_core.py:662-698)
Scope: Small
Replace the body of infer_next_steps with a call to the workflow definition.
Makeinfer_next_steps robustness-aware by reading state["config"].
Updaterequire_state to optionally derive allowed states from the workflow (stretch goal — may keep as-is if the handler-level require_state calls are already correct).
Updatetest_workflow_light_robustness_single_pass (test_megaplan.py:264) to verify routing comes from the workflow definition.
Run the full existing test suite — all routing behavior should be unchanged:
bash
python -m pytest tests/ -x -q
Add integration-style tests that simulate a full light and standard workflow by calling handlers in sequence and verifying state transitions match the workflow definition.
Step 9: Clean up dead code and update exports (megaplan/_core.py, megaplan/__init__.py)
Scope: Small
Remove any remaining is_light / configured_robustness checks that were replaced by workflow routing (keep configured_robustness itself — it's still needed to read the config).
Exportworkflow_next from __init__.py if callers need it (or keep it internal).
Verifyrobustness_critique_instruction is untouched — it affects prompt content, not routing.
Execution Order
Steps 1-3 (Phase 1) first — define the workflow and prove it matches current behavior with tests before touching handlers.
Steps 4-6 (Phase 2) — migrate handlers one at a time, running tests after each.
Step 7 — swap infer_next_steps implementation last, since handlers already use the new routing.
Steps 8-9 (Phase 3) — final verification and cleanup.
Validation Order
Step 3 tests pass — workflow definition matches current behavior for both robustness levels.
After each handler migration (Steps 4-6):pytest tests/ -x -q passes with no regressions.
After Step 7:test_infer_next_steps passes with robustness-aware assertions.
Final: Full suite green, grep for is_light returns zero hits in handlers.py.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-26T00:53:47Z",
"hash": "sha256:890776ee8c762feb97573ade4052f7eabffb2138fdb25214144157d1f0747790",
"questions": [
"The standard workflow has conditional branching after gate (ITERATE \u2192 revise, ESCALATE \u2192 overrides, PROCEED \u2192 finalize). Should the declarative definition model these as explicit conditional edges (e.g. Transition(condition='gate:ITERATE', next='revise')), or should gate recommendation handling stay as handler logic and only the happy-path sequence be declared?",
"The synthetic gate artifact written in light mode (handlers.py:810-818) is a side-effect of skipping the gate step. Should this be modeled as a workflow-level side-effect (e.g. on_skip=['write_synthetic_gate']) or kept as inline logic in a small helper that the critique handler always calls?",
"Should infer_next_steps become robustness-aware (returning different options for light vs standard), or should it continue returning the union of all possible next steps regardless of robustness? Currently it's robustness-unaware and callers may depend on that.",
"The step command (manual plan editing) and override actions (add-note, force-proceed, abort, replan) are available at various states. Should these be part of the workflow definition or remain separate? They're not really 'workflow steps' \u2014 they're escape hatches."
],
"success_criteria": [
"Zero is_light checks remain in handlers.py \u2014 all routing decisions derive from the workflow definition",
"infer_next_steps derives its return values from the same workflow definition used by handlers",
"All existing tests pass without modification to test assertions (only test infrastructure may change)",
"A new test walks both light and standard workflows end-to-end via the workflow definition and confirms the step sequence matches current behavior",
"The workflow definition is a single source of truth: adding a new robustness level would only require adding entries to the definition, not modifying handler code",
"grep -r 'configured_robustness.*light' megaplan/handlers.py returns no matches"
],
"assumptions": [
"Two robustness levels only (light, standard) \u2014 no plans to add a third level soon. If a third level is likely, the workflow definition should be more data-driven.",
"The Transition dataclass approach (state \u2192 list of possible transitions with optional conditions) is preferred over a simple ordered list like ['plan', 'critique', 'revise', 'finalize', 'execute'] because the standard flow has non-linear branching.",
"The synthetic gate artifact for light mode is a necessary compatibility shim (revise prompt references gate.json) and should be preserved, just moved out of the routing conditional.",
"Override actions (force-proceed, replan, abort, add-note) will remain separate from the workflow definition \u2014 they're user escape hatches, not part of the declared flow.",
"Prompt-level robustness differences (via robustness_critique_instruction) are out of scope \u2014 this refactor only touches routing, not prompt content.",
"Backwards compatibility for infer_next_steps export is required since it's used in cli.py and exported in init.py."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: light. Be pragmatic. Only flag issues that would cause real failures. Ignore style, minor edge cases, and issues the executor will naturally resolve.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered step sections (`### Step N:` under `## Phase` headers, or flat `## Step N:`) with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`.
- Missing required sections or step coverage (for example: no H1, no `## Overview`, or no step sections at all) should be flagged as category `completeness` with severity_hint `likely-significant`.
- Structural formatting within steps (for example: prose instead of numbered substeps, or a missing file reference inside an otherwise actionable step) should usually be category `completeness` with severity_hint `likely-minor` because the executor can still follow the instructions.
- Ask whether the plan is the simplest approach that solves the stated problem, whether it could use fewer steps or less machinery, and whether it introduces unnecessary complexity.
- Over-engineering concerns should use category `maintainability`, should usually prefix the concern with "Over-engineering:", and should scale severity_hint to the practical impact.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.