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:
v0.14.0 — strict flag-resolution at the gate
Goal
Remove the silent implicit-acceptance of unresolved blocking flags when the gate recommends PROCEED. Make the gate either resolve every blocking flag explicitly, or pick ITERATE / ESCALATE. Reject rubber-stamp rationale on accept_tradeoff actions, not just on dispute actions.
Motivation
The current gate logic (v0.13) has two related problems:
The gate prompt tells the agent "you may resolve at most 3 flags explicitly per gate call. Any remaining blocking flags are implicitly accepted as tradeoffs if you recommend PROCEED." (prompts/gate.py, around lines 105-114)
The handler enforces this by silently auto-marking unresolved blocking flags as accept_tradeoff (handlers.py, around lines 621-635 inside _apply_gate_outcome).
The rubber-stamp check (handlers.py around lines 600-607) only validates dispute.evidence — it accepts any accept_tradeoff.rationale including boilerplate.
Net effect: a gate PROCEED can ship with 5 unresolved blocking flags, silently auto-accepted, with zero resistance from the system. The human reviewing the PR sees them in accepted_tradeoffs but the agent was never forced to reason about each one.
Exact changes
Change 1: prompts/gate.py
Replace the block that currently reads roughly:
"You may resolve at most 3 flags explicitly per gate call. Any remaining
blocking flags are implicitly accepted as tradeoffs if you recommend PROCEED.
If a flag is structurally unresolvable (e.g., references infrastructure
outside the repo), you should still PROCEED — do not loop indefinitely
on flags that cannot be addressed."
with strict language:
"If you recommend PROCEED, you MUST provide a flag_resolutions entry for
every blocking flag. There is no implicit acceptance. If you cannot
resolve every blocking flag, choose ITERATE (send back for revision)
or ESCALATE (human intervention needed). Structurally unresolvable flags
(infrastructure outside the repo, product decision required) are ESCALATE,
not PROCEED with a non-answer.
For each blocking flag:
dispute: critique is factually wrong. Evidence must cite specific
file/line/doc — generic statements like 'handled correctly' are invalid.
accept_tradeoff: concern is real but accepted as a known limitation.
Rationale must be specific to this flag — 'acceptable within scope'
is not valid rationale."
Assistant
I'll explore the key files mentioned in the brief to map exact touch points.
Assistant
Let me check the key test that exercises the implicit-acceptance path and the handle_gate caller.
Assistant
Now I have a clear picture. Let me check how handle_gate passes args so I understand the reprompt mechanism.
Assistant
I have enough context now. Let me produce the plan.
Assistant
Plan produced. The three open questions are:
Reprompt wiring — should _apply_gate_outcome gain args/root params to call _run_worker, or should the reprompt loop live in handle_gate itself (cleaner separation)?
accepted_tradeoffs vs flag_resolutions — the brief doesn't mention changing debt tracking. I'm assuming they stay separate.
Artifact write ordering — re-write gate.json after mutation, or move the initial write to after _apply_gate_outcome?
User
Assistant
Let me investigate the flag concerns before revising the plan.
Assistant
All three flags are valid implementation concerns, not wrong-root-cause signals. The core approach is right but the wiring needs restructuring. Key changes: (1) reprompt lives in handle_gate, not _apply_gate_outcome; (2) debt recording moves after outcome; (3) debt derivation from flag_resolutions.
Assistant
All three flags addressed. The main structural change: reprompt logic moved from _apply_gate_outcome up to handle_gate (fixes FLAG-001's full-prompt issue), debt recording moved after outcome (fixes FLAG-002's premature-debt issue), and debt derivation now supplements accepted_tradeoffs from flag_resolutions (fixes FLAG-003's missing-debt issue). No new questions — the answers fell out of the restructuring.
Keep the existing example JSON, but update it to show explicit resolutions for every listed blocking flag (not just a subset).
Replace the silent implicit-acceptance block (the "Implicitly accept remaining blocking flags as tradeoffs" branch around lines 621-635) with:
If PROCEED and blocking_unresolved is non-empty:
If this is the first attempt for this iteration: reprompt the gate worker once, with the missing flag IDs listed in the new prompt. The existing worker machinery should support this (see _run_worker and the refreshed flag).
If reprompt also returns blocking_unresolved: force-downgrade recommendation to ITERATE. Mutate gate_summary in place so the artifact reflects the downgrade. Append to gate_summary["rationale"]: " [Auto-downgraded from PROCEED: N blocking flag(s) not resolved after reprompt]"
Return next_step = "revise".
Do NOT call update_flags_after_gate with implicit resolutions for unresolved flags. Remove the implicit_resolutions list entirely.
Persist a marker in state or the gate artifact so we can tell whether reprompt already happened this iteration. Either a field on gate_summary (e.g., reprompted: true) or a key in state meta. Pick whichever is less invasive.
In the loop around lines 597-608 that processes resolutions:
Keep the existing dispute check (skip if evidence is missing or is_rubber_stamp returns True).
Add a matching check for accept_tradeoff: skip if rationale is missing or is_rubber_stamp(rationale, strict=True) returns True. A skipped accept_tradeoff means the flag is treated as unresolved and falls through to the Change 2 logic.
Change 4: tests
Update existing gate tests:
Test that a PROCEED with 3 resolutions out of 5 blocking flags triggers a reprompt, not silent acceptance.
Test that a PROCEED still missing flags after reprompt is auto-downgraded to ITERATE, with the appended rationale.
Test that an accept_tradeoff with rubber-stamp rationale ("acceptable", "fine as is") is rejected.
Test that an accept_tradeoff with concrete rationale passes.
Test that PROCEED with every blocking flag resolved (no reprompt needed) still works end-to-end.
Remove any existing test that asserts the implicit-acceptance behavior (that was testing a bug).
Change 5: version bump
pyproject.toml: version "0.13.0" -> "0.14.0".
CHANGELOG.md: new v0.14.0 entry summarizing the above.
Out of scope (explicitly NOT doing in v0.14.0)
Do not add a separate per-flag resolve phase.
Do not add scaffolding-level recurrence counters or divergence detectors — the gate agent already sees iteration history via gate_signals and can reason about recurrence on its own.
Do not add severity-gated auto-ITERATE rules beyond what the existing logic covers.
Do not change the flag severity taxonomy (blocking = significant + likely-significant; noted = everything else).
Do not change the override commands (force-proceed, abort, replan, add-note).
Do not touch the gate signals computation, preflight checks, or worker infrastructure.
Branch + commit hygiene
Create branch gate-strict-flag-resolution off main.
One commit for the code change, one for the test update is fine, or a single atomic commit — reviewer preference.
Commit message must reference v0.14.0 and summarize the behavior change.
Open a PR on GitHub against main when done. Do not auto-merge.
Success criteria (verifiable)
All existing megaplan tests pass.
New tests above pass.
Running the existing test fixture that simulates a gate PROCEED with unresolved flags produces an ITERATE downgrade (not silent acceptance).
pyproject.toml version is "0.14.0".
CHANGELOG.md has the new entry.
Working directory
/Users/user_c042661f/Documents/megaplan
Uncommitted state warning
CHANGELOG.md has a pre-existing uncommitted modification and there are two untracked JSON files in the repo root. Do not commit or stash these. Work only on the specific files listed above, and only the specific regions described.
code
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.
Remove the silent implicit-acceptance of unresolved blocking flags when the gate recommends PROCEED. Make the gate either resolve every blocking flag explicitly, or pick ITERATE / ESCALATE. Reject rubber-stamp rationale on accept_tradeoff actions, not just on dispute actions.
Motivation
The current gate logic (v0.13) has two related problems:
The gate prompt tells the agent "you may resolve at most 3 flags explicitly per gate call. Any remaining blocking flags are implicitly accepted as tradeoffs if you recommend PROCEED." (prompts/gate.py, around lines 105-114)
The handler enforces this by silently auto-marking unresolved blocking flags as accept_tradeoff (handlers.py, around lines 621-635 inside _apply_gate_outcome).
The rubber-stamp check (handlers.py around lines 600-607) only validates dispute.evidence — it accepts any accept_tradeoff.rationale including boilerplate.
Net effect: a gate PROCEED can ship with 5 unresolved blocking flags, silently auto-accepted, with zero resistance from the system. The human reviewing the PR sees them in accepted_tradeoffs but the agent was never forced to reason about each one.
Exact changes
Change 1: prompts/gate.py
Replace the block that currently reads roughly:
"You may resolve at most 3 flags explicitly per gate call. Any remaining
blocking flags are implicitly accepted as tradeoffs if you recommend PROCEED.
If a flag is structurally unresolvable (e.g., references infrastructure
outside the repo), you should still PROCEED — do not loop indefinitely
on flags that cannot be addressed."
with strict language:
"If you recommend PROCEED, you MUST provide a flag_resolutions entry for
every blocking flag. There is no implicit acceptance. If you cannot
resolve every blocking flag, choose ITERATE (send back for revision)
or ESCALATE (human intervention needed). Structurally unresolvable flags
(infrastructure outside the repo, product decision required) are ESCALATE,
not PROCEED with a non-answer.
For each blocking flag:
dispute: critique is factually wrong. Evidence must cite specific
file/line/doc — generic statements like 'handled correctly' are invalid.
accept_tradeoff: concern is real but accepted as a known limitation.
Rationale must be specific to this flag — 'acceptable within scope'
is not valid rationale."
Keep the existing example JSON, but update it to show explicit resolutions for every listed blocking flag (not just a subset).
Replace the silent implicit-acceptance block (the "Implicitly accept remaining blocking flags as tradeoffs" branch around lines 621-635) with:
If PROCEED and blocking_unresolved is non-empty:
If this is the first attempt for this iteration: reprompt the gate worker once, with the missing flag IDs listed in the new prompt. The existing worker machinery should support this (see _run_worker and the refreshed flag).
If reprompt also returns blocking_unresolved: force-downgrade recommendation to ITERATE. Mutate gate_summary in place so the artifact reflects the downgrade. Append to gate_summary["rationale"]: " [Auto-downgraded from PROCEED: N blocking flag(s) not resolved after reprompt]"
Return next_step = "revise".
Do NOT call update_flags_after_gate with implicit resolutions for unresolved flags. Remove the implicit_resolutions list entirely.
Persist a marker in state or the gate artifact so we can tell whether reprompt already happened this iteration. Either a field on gate_summary (e.g., reprompted: true) or a key in state meta. Pick whichever is less invasive.
In the loop around lines 597-608 that processes resolutions:
Keep the existing dispute check (skip if evidence is missing or is_rubber_stamp returns True).
Add a matching check for accept_tradeoff: skip if rationale is missing or is_rubber_stamp(rationale, strict=True) returns True. A skipped accept_tradeoff means the flag is treated as unresolved and falls through to the Change 2 logic.
Change 4: tests
Update existing gate tests:
Test that a PROCEED with 3 resolutions out of 5 blocking flags triggers a reprompt, not silent acceptance.
Test that a PROCEED still missing flags after reprompt is auto-downgraded to ITERATE, with the appended rationale.
Test that an accept_tradeoff with rubber-stamp rationale ("acceptable", "fine as is") is rejected.
Test that an accept_tradeoff with concrete rationale passes.
Test that PROCEED with every blocking flag resolved (no reprompt needed) still works end-to-end.
Remove any existing test that asserts the implicit-acceptance behavior (that was testing a bug).
Change 5: version bump
pyproject.toml: version "0.13.0" -> "0.14.0".
CHANGELOG.md: new v0.14.0 entry summarizing the above.
Out of scope (explicitly NOT doing in v0.14.0)
Do not add a separate per-flag resolve phase.
Do not add scaffolding-level recurrence counters or divergence detectors — the gate agent already sees iteration history via gate_signals and can reason about recurrence on its own.
Do not add severity-gated auto-ITERATE rules beyond what the existing logic covers.
Do not change the flag severity taxonomy (blocking = significant + likely-significant; noted = everything else).
Do not change the override commands (force-proceed, abort, replan, add-note).
Do not touch the gate signals computation, preflight checks, or worker infrastructure.
Branch + commit hygiene
Create branch gate-strict-flag-resolution off main.
One commit for the code change, one for the test update is fine, or a single atomic commit — reviewer preference.
Commit message must reference v0.14.0 and summarize the behavior change.
Open a PR on GitHub against main when done. Do not auto-merge.
Success criteria (verifiable)
All existing megaplan tests pass.
New tests above pass.
Running the existing test fixture that simulates a gate PROCEED with unresolved flags produces an ITERATE downgrade (not silent acceptance).
pyproject.toml version is "0.14.0".
CHANGELOG.md has the new entry.
Working directory
/Users/user_c042661f/Documents/megaplan
Uncommitted state warning
CHANGELOG.md has a pre-existing uncommitted modification and there are two untracked JSON files in the repo root. Do not commit or stash these. Work only on the specific files listed above, and only the specific regions described.
code
Current plan (markdown):
# Implementation Plan: v0.14.0 — Strict Flag Resolution at the Gate
Overview
The gate currently has two leniency holes: (1) unresolved blocking flags are silently auto-accepted as tradeoffs when the gate says PROCEED, and (2) accept_tradeoff resolutions bypass the rubber-stamp check that dispute resolutions must pass. This change enforces that every blocking flag must be explicitly resolved for a PROCEED to stand, rejects boilerplate accept_tradeoff rationale, and introduces a one-shot reprompt before auto-downgrading to ITERATE.
The branch gate-strict-flag-resolution already exists (current branch).
Phase 1: Prompt & Validation Changes
Step 1: Update the gate prompt (megaplan/prompts/gate.py:100-133)
Scope: Small
Replace lines 100-113 (the "You may resolve at most 3…" paragraph and the implicit-acceptance guidance) with the strict language from the brief: PROCEED requires a flag_resolutions entry for every blocking flag; no implicit acceptance; structurally unresolvable flags → ESCALATE.
Add the rubber-stamp rejection language for accept_tradeoff under the bullet list (lines 105-108): rationale must be specific, "acceptable within scope" is not valid.
Remove the "at most 3" cap language entirely.
Update the example JSON block (lines 119-132) to show resolutions covering every listed blocking flag, not just a subset.
Step 2: Add rubber-stamp check for accept_tradeoff (megaplan/handlers.py:600-608)
Scope: Small
Replace the elif action == "accept_tradeoff": pass # always allowed block at line 604-605 with validation:
python
elif action == "accept_tradeoff":
rationale = res.get("rationale", "").strip()
if not rationale or is_rubber_stamp(rationale, strict=True):
continue # rubber-stamp tradeoff — skip
This makes rubber-stamp accept_tradeoff resolutions fall through as unresolved, feeding into Step 3's enforcement logic.
Phase 2: Enforcement Logic
Step 3: Replace implicit-acceptance with reprompt/downgrade (megaplan/handlers.py:586-635)
Scope: Medium
Remove the 3-resolution cap (lines 586-593). The gate can now resolve all blocking flags.
Remove the entire implicit-acceptance block (lines 621-635) — no more implicit_resolutions list, no more update_flags_after_gate with auto-generated tradeoffs.
Add new logic after line 615 (after blocking_unresolved is computed):
If blocking_unresolved is non-empty and gate_summary.get("reprompted") is falsy:
Set gate_summary["reprompted"] = True.
Build a reprompt message listing the missing flag IDs and asking the gate to resolve them or change recommendation.
Re-run the gate worker via _run_worker("gate", state, plan_dir, args, root=root, prompt_override=reprompt_text). This reuses the existing prompt_override kwarg on _run_worker.
Re-extract flag_resolutions from the new worker result, re-validate, and recompute blocking_unresolved.
If blocking_unresolved is still non-empty after reprompt (or if reprompted was already True):
Mutate gate_summary["recommendation"] to "ITERATE".
Append to gate_summary["rationale"]: " [Auto-downgraded from PROCEED: N blocking flag(s) not resolved after reprompt]".
Set gate_summary["passed"] = False.
Return ("blocked", "revise", summary) — the existing ITERATE branch handles the rest.
Note:_apply_gate_outcome needs the args and root parameters to call _run_worker. Update the function signature from _apply_gate_outcome(state, gate_summary, *, robustness, plan_dir) to also accept args and root. Update the single call site at handlers.py:1011.
Persistreprompted: true on the gate_summary dict itself (it's written to gate.json before _apply_gate_outcome returns via the existing _store_last_gate call, but the artifact file is already written at line 1007). Since the artifact is written before _apply_gate_outcome, we need to re-write the gate artifact after mutation. Add a _write_json_artifact(plan_dir, "gate.json", gate_summary) call after returning from if the summary was mutated (or always re-write it, since it's idempotent).
Step 4: Wire _apply_gate_outcome into handle_gate (megaplan/handlers.py:1011-1038)
Scope: Small
Update the _apply_gate_outcome call at line 1011 to pass args=args, root=root.
After_apply_gate_outcome returns, re-write gate.json if gate_summary.get("reprompted"):
python
if gate_summary.get("reprompted"):
_write_json_artifact(plan_dir, "gate.json", gate_summary)
This ensures the final artifact reflects the reprompt and any auto-downgrade.
Fix test_gate_proceed_without_accepted_tradeoffs_registers_fallback_debt (line 1366): This test currently expects a PROCEED with unresolved blocking flags to succeed. Under the new logic, the gate will reprompt and then auto-downgrade to ITERATE. Update the monkeypatch to return two responses: the first with unresolved flags (triggering reprompt), the second also unresolved (triggering downgrade). Assert the response shows recommendation: "ITERATE" and the rationale contains [Auto-downgraded from PROCEED.
Fix test_gate_proceed_with_accepted_tradeoffs_creates_debt (line 1290): This test has explicit accepted_tradeoffs and empty flag_resolutions. The blocking flag is still unresolved by the new logic (no resolution entry). Update to either: (a) add a valid flag_resolutions entry for the flag, or (b) expect the downgrade behavior.
Check all other gate tests for assumptions about implicit acceptance and update accordingly.
Step 6: Add new targeted tests (tests/test_megaplan.py)
Scope: Medium
test_gate_proceed_with_partial_resolutions_triggers_reprompt: Mock gate returning PROCEED with 3/5 flags resolved. First call returns partial, second call returns all resolved. Assert PROCEED stands and no downgrade.
test_gate_proceed_still_missing_after_reprompt_downgrades_to_iterate: Mock gate returning PROCEED with missing flags on both calls. Assert auto-downgrade to ITERATE, rationale contains [Auto-downgraded, next_step == "revise".
test_gate_accept_tradeoff_rubber_stamp_rejected: Gate returns PROCEED with accept_tradeoff resolutions using boilerplate rationale ("acceptable", "fine as is"). Assert these are treated as unresolved.
test_gate_accept_tradeoff_concrete_rationale_accepted: Gate returns PROCEED with specific accept_tradeoff rationale. Assert it passes validation.
test_gate_proceed_all_flags_resolved_no_reprompt: Gate returns PROCEED with every blocking flag resolved. Assert no reprompt, PROCEED stands.
Step 7: Run the full test suite
Scope: Small
pytest tests/ — all existing + new tests must pass.
Phase 4: Finalize
Step 8: Version bump + changelog (pyproject.toml, CHANGELOG.md)
Scope: Small
Bumppyproject.toml version from "0.13.0" to "0.14.0".
Add v0.14.0 changelog entry to CHANGELOG.md summarizing: strict flag resolution (no implicit acceptance), rubber-stamp rejection for accept_tradeoff, one-shot reprompt with auto-downgrade.
Do not touch the pre-existing uncommitted CHANGELOG.md changes or the untracked JSON files.
Step 9: Commit and PR
Scope: Small
Commit all changes with message referencing v0.14.0.
Open PR against main.
Execution Order
Steps 1-2 first (prompt + validation changes) — low risk, no behavioral change until enforcement lands.
Steps 3-4 (enforcement logic) — the core behavioral change.
Steps 5-6 (test updates + new tests) — validates the above.
Step 7 (full suite) — integration check.
Steps 8-9 (version bump, commit, PR) — finalize.
Validation Order
After Step 2: quick pytest tests/test_evaluation.py to confirm is_rubber_stamp still works.
After Step 4: pytest tests/test_megaplan.py -k gate to surface test breakage early.
After Step 6: pytest tests/test_megaplan.py -k gate with new tests.
Step 7: full pytest tests/.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-04-15T03:33:15Z",
"hash": "sha256:32086224797d68e0b84267268d32c166c9bfefcc211c0b4abc9197aa915959a4",
"questions": [
"The reprompt mechanism requires calling _run_worker from inside _apply_gate_outcome, which currently doesn't have access to args or root. The plan adds these parameters. Is there a lighter-weight alternative you'd prefer (e.g., passing a callable instead, or restructuring so the reprompt happens in handle_gate before calling _apply_gate_outcome)?",
"The existing accepted_tradeoffs field on the gate payload (separate from flag_resolutions) is used for debt tracking. Under strict resolution, should accepted_tradeoffs still be populated by the gate LLM, or should it be derived from flag_resolutions entries with action: accept_tradeoff? The brief doesn't mention changing debt tracking.",
"The gate artifact (gate.json) is written at line 1007 before _apply_gate_outcome is called. If the outcome mutates the summary (reprompt/downgrade), we need to re-write it. The plan proposes a conditional re-write. Alternatively, we could move the initial write to after _apply_gate_outcome. Any preference?"
],
"success_criteria": [
{
"criterion": "All existing pytest tests/ pass (no regressions)",
"priority": "must"
},
{
"criterion": "Gate PROCEED with unresolved blocking flags triggers reprompt, not silent acceptance",
"priority": "must"
},
{
"criterion": "Gate PROCEED still unresolved after reprompt is auto-downgraded to ITERATE with appended rationale",
"priority": "must"
},
{
"criterion": "accept_tradeoff with rubber-stamp rationale is rejected (treated as unresolved)",
"priority": "must"
},
{
"criterion": "accept_tradeoff with concrete rationale passes validation",
"priority": "must"
},
{
"criterion": "Gate PROCEED with all blocking flags explicitly resolved works end-to-end (no reprompt triggered)",
"priority": "must"
},
{
"criterion": "pyproject.toml version is 0.14.0",
"priority": "must"
},
{
"criterion": "CHANGELOG.md has v0.14.0 entry",
"priority": "must"
},
{
"criterion": "Implicit-acceptance code path is fully removed (no implicit_resolutions list)",
"priority": "must"
},
{
"criterion": "3-resolution cap is removed from both prompt and handler",
"priority": "must"
},
{
"criterion": "gate.json artifact reflects final state including any reprompt/downgrade mutations",
"priority": "should"
},
{
"criterion": "Reprompt adds at most one extra LLM call per gate invocation",
"priority": "should"
},
{
"criterion": "No changes to unrelated files or uncommitted state",
"priority": "must"
}
],
"assumptions": [
"The _run_worker function can be called a second time within the same gate step to reprompt \u2014 the worker infrastructure supports re-invocation with prompt_override.",
"The field on is sufficient state tracking \u2014 we don't need to persist it in since it's only relevant within a single gate call.",
"The function already handles the boilerplate phrases we care about ('acceptable within scope', 'fine as is', etc.) \u2014 no changes needed to .",
"The field and debt-tracking logic remain unchanged; debt is still recorded from in the gate payload, not from .",
"Existing test helpers (, , etc.) are sufficient to build the new tests without new fixtures."
],
"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": "Gate reprompt prompt construction: the proposed reprompt path uses _run_worker(..., prompt_override=reprompt_text), but in this repo prompt_override replaces the entire gate prompt rather than appending to it. A short missing-flag reprompt would drop the normal gate instructions, schema shape, and gate context, so the second call is likely to return the wrong payload.",
"evidence": "Both worker backends use prompt = prompt_override if prompt_override is not None else create_*_prompt(...) (megaplan/workers.py:1062-1068, megaplan/workers.py:1111-1117). The plan's Step 3 explicitly says to reprompt the gate with _run_worker(..., prompt_override=reprompt_text)."
},
{
"id": "FLAG-002",
"severity": "significant",
"status": "open",
"concern": "Gate downgrade debt logging: the plan adds the reprompt/downgrade logic inside _apply_gate_outcome, but handle_gate() currently records debt before calling _apply_gate_outcome(). With that call order, an initial PROCEED would still write debt entries even when the reprompt forces the final result to ITERATE.",
"evidence": "handle_gate() writes gate.json, then immediately calls _record_gate_debt_entries(...), and only afterward calls _apply_gate_outcome(...) (megaplan/handlers.py:1007-1016). _record_gate_debt_entries() records debt whenever gate_summary['recommendation'] == 'PROCEED', using either accepted_tradeoffs or the unresolved-flags fallback (megaplan/handlers.py:440-487)."
},
{
"id": "FLAG-003",
"severity": "significant",
"status": "open",
"concern": "Gate accept_tradeoff debt derivation: the plan leaves debt tracking sourced from accepted_tradeoffs, but under strict resolution a successful PROCEED will no longer have unresolved flags for the fallback debt path. Explicit accept_tradeoff resolutions can therefore stop creating debt entries unless the plan also derives debt entries from flag_resolutions or otherwise keeps accepted_tradeoffs synchronized.",
"evidence": "The gate prompt currently shows an accept_tradeoff resolution while still returning \"accepted_tradeoffs\": [] (megaplan/prompts/gate.py:105-129). Debt tracking only reads worker_payload['accepted_tradeoffs'] and falls back to gate_summary['unresolved_flags'] when that list is empty (megaplan/handlers.py:443-487). After this change, successful PROCEED paths are supposed to resolve every blocking flag explicitly, so that unresolved-flags fallback disappears."
}
]
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.