During execute, the agent does all the work (modifies files, runs tests, completes tasks) but never saves its progress to finalize.json. The prompt explicitly says 'Do not create or rewrite tracking artifacts directly.' Instead, the agent returns one big JSON blob at the end, and the handler merges task_updates into finalize.json. If the agent times out or crashes, ALL tracking is lost even though the actual code changes are in the repo.
Solution: Make the agent save as it goes
Flip the prompt instruction. Tell the executor agent to update finalize.json directly after completing each task:
After finishing each task: update that task's entry in finalize.json with status, executor_notes, files_changed, commands_run. Save the file.
After each sense check acknowledgment: update that sense_check's entry in finalize.json with executor_note. Save the file.
The agent checks off tasks and adds notes in real-time as part of its natural workflow.
Handler changes
On timeout: read finalize.json from disk (which the agent has been updating). Whatever tasks are marked done are genuinely done. Use that as the source of truth.
On success: the handler already re-reads finalize.json at line 1247. The structured JSON output's task_updates become a validation/reconciliation layer, not the sole source of truth.
On timeout recovery: persist session ID, save state, leave state as 'finalized' so re-execution works. The re-run prompt already handles done vs pending tasks.
Key insight
The handler at handlers.py:1247 already does read_json(plan_dir / 'finalize.json') after the agent finishes. If the agent updates that file during execution, those updates are already there. We just need to:
Tell the agent to do it (prompt change)
Handle the timeout path to read what's on disk instead of just re-raising
Reconcile agent-written updates with structured output on success
Files involved
megaplan/prompts.py — Change execute prompt: tell agent to update finalize.json after each task and sense check
megaplan/handlers.py — Timeout recovery in handle_execute(): read finalize.json from disk, persist session, save state
megaplan/workers.py — Propagate session ID through timeout errors
Assistant
User
Assistant
{"flags":[{"id":"FLAG-001","concern":"The plan still does not provide a concrete way for the default execute path to write finalize.json, so the main timeout-loss problem remains unsolved.","category":"correctness","severity_hint":"likely-significant","evidence":"execute defaults to Codex (megaplan/types.py:223-230). The revised plan explicitly assumes Codex likely cannot write to the plan directory and treats that as acceptable degradation, but plan artifacts live outside project_dir (megaplan/_core.py:231-232) while Codex execute runs with -C project_dir and --full-auto (megaplan/workers.py:575-579). Exposing the absolute path in the prompt helps discovery, not access. If Codex still cannot write there, the default execute flow still loses tracking on timeout."},{"id":"FLAG-002","concern":"Session recovery is still incomplete for first-time persistent Codex timeouts.","category":"correctness","severity_hint":"likely-significant","evidence":"The revised plan fixes , but its Codex timeout propagation only attaches . On a new persistent Codex run, that value is still ; the repository currently derives the new session id by parsing raw output with (, ). Timeout errors already carry (), so a first-run timeout can still be resumable, but the plan drops that path and would fail to persist the new session id."}],"verified_flag_ids":["FLAG-003","FLAG-004"],"disputed_flag_ids":[]}
During execute, the agent does all the real work (edits files, runs tests) but never persists tracking to finalize.json. The handler merges a single structured JSON blob into finalize.json only after the agent completes (handlers.py:1247-1306). If the agent times out (workers.py:102-107, CliError code worker_timeout), the except CliError at handlers.py:1242 re-raises — losing all tracking even though code changes are on disk.
Goal: Tell the agent to update finalize.json incrementally during execution. On timeout, read what's on disk. On success, reconcile disk state with structured output.
Repo shape: Prompt lives in prompts.py:371-496. Handler in handlers.py:1226-1371. Workers in workers.py (timeout at line 102). Structured output schema in .megaplan/schemas/execution.json. Tests in tests/test_megaplan.py.
Key constraint: The handler already reads finalize.json at line 1247 and merges structured output on top. If the agent writes directly to finalize.json, those updates are already there when the handler reads. The structured output merge becomes reconciliation, not the sole source.
Phase 1: Prompt and Schema Changes
Step 1: Update execute prompt to instruct incremental saves (megaplan/prompts.py:428-496)
Scope: Small
Replace the line "Do not create or rewrite tracking artifacts directly." (line 458) with instructions to update finalize.json after each task/sense-check completion.
Add specific instructions:
After completing each task: read finalize.json, update that task's status, executor_notes, files_changed, commands_run, write it back.
After each sense check acknowledgment: update that sense check's executor_note.
Use atomic read-modify-write (read JSON, update in-memory, write back) to avoid corruption.
Keep the structured output requirement — the agent still returns task_updates and sense_check_acknowledgments in its final JSON. This becomes the reconciliation/validation layer.
Preserve the re-run guidance logic (prompts.py:399-418) — it already works by reading task status from finalize.json, which will now reflect incremental saves from prior (possibly timed-out) runs.
Step 2: No schema changes needed (.megaplan/schemas/execution.json)
Scope: None
The structured output schema stays the same — the agent still returns the same JSON shape. The only change is that finalize.json on disk may already contain updates before the handler reads it. No schema file changes required.
Phase 2: Timeout Recovery in Handler
Step 3: Extract timeout recovery logic in handle_execute (megaplan/handlers.py:1240-1244)
Scope: Medium
Replace the current timeout handling:
python
# Current: re-raises on any CliError including timeout
except CliError as error:
record_step_failure(plan_dir, state, step="execute", iteration=state["iteration"], error=error)
raise
Implement timeout-specific recovery path:
python
except CliError as error:
if error.code == "worker_timeout":
# Agent was updating finalize.json as it went — read what's on disk
finalize_data = read_json(plan_dir / "finalize.json")
# Extract session_id from partial output for re-execution continuity
raw_output = error.extra.get("raw_output", "")
session_id = extract_session_id(raw_output)
# ... (timeout recovery logic below)
else:
record_step_failure(plan_dir, state, step="execute", iteration=state["iteration"], error=error)
raise
In the timeout recovery path:
Count done/pending tasks from the disk finalize.json to assess progress.
Persist session_id via apply_session_update so re-execution can resume the session.
Keep current_state as STATE_FINALIZED (already the case — state doesn't change on error) so re-execution is valid.
Record a history entry with result="timeout" including partial progress stats.
save_state(plan_dir, state) to persist session info.
Return a StepResponse with success=False, next_step="execute", summary indicating timeout with partial progress, and the count of completed tasks.
Step 4: Handle session_id extraction from timeout errors (megaplan/workers.py:102-107)
Scope: Small
Inspect current timeout error: CliError extra contains raw_output which is str(exc.stdout or "") + str(exc.stderr or ""). The extract_session_id function at workers.py:118 can parse this.
For Claude agent: Session ID is set before the call (workers.py:518-524), so we need to make it available. The cleanest approach: include session_id in the CliError extra for timeout errors.
Updaterun_claude_step to catch the CliError from run_command and re-raise with session_id in extra:
python
try:
result = run_command(command, cwd=project_dir, stdin_text=prompt)
except CliError as error:
if error.code == "worker_timeout":
error.extra["session_id"] = session_id
raise
Similarly for run_codex_step: session_id is available at workers.py:596-598. Same pattern.
Phase 3: Reconciliation on Success
Step 5: Reconcile disk state with structured output on success (megaplan/handlers.py:1247-1267)
Scope: Small
Current behavior at line 1247: reads finalize.json (which now may have agent-written updates), then merges structured output on top via _validate_and_merge_batch. This already works correctly — the merge is last-write-wins by task_id, so structured output values overwrite disk values.
Add a reconciliation check: After merging, compare the structured output task statuses against what was on disk before merge. If they differ, log an advisory deviation (not blocking). This catches cases where the agent's incremental save disagrees with its final summary.
Implementation:
python
finalize_data = read_json(plan_dir / "finalize.json")
# Snapshot pre-merge state for reconciliation
pre_merge_statuses = {
task["id"]: task.get("status", "pending")
for task in finalize_data.get("tasks", [])
}
# ... existing merge logic ...
# After merge: check for discrepancies
for task in finalize_data.get("tasks", []):
pre = pre_merge_statuses.get(task["id"], "pending")
post = task.get("status", "pending")
if pre != "pending" and pre != post:
deviations.append(
f"Advisory: task {task['id']} was '{pre}' on disk but '{post}' in structured output"
)
Step 6: Tests (tests/test_megaplan.py)
Scope: Medium
Test timeout recovery: Mock run_step_with_worker to raise CliError("worker_timeout", ...). Pre-populate finalize.json with some tasks marked done (simulating agent's incremental saves). Verify handler reads disk state, persists session, returns proper response with next_step="execute".
Test incremental save reconciliation: Mock worker to return structured output that matches disk state. Verify no extra deviations. Then test mismatched case — verify advisory deviation is logged.
Test re-execution after timeout: Verify that a timed-out execution with partial progress in finalize.json allows re-execution, and the prompt correctly identifies done vs pending tasks (this largely already works via prompts.py:399-418).
Test prompt change: Verify the execute prompt no longer contains "Do not create or rewrite tracking artifacts directly" and instead contains the incremental save instructions.
Run existing tests to ensure no regressions: test_execute_happy_path_tracks_all_tasks, test_execute_deduplicates_task_updates_and_blocks_incomplete_coverage, test_execute_blocks_done_task_without_any_per_task_evidence.
Execution Order
Step 1 (prompt) — can be developed independently, no code dependencies.
Step 4 (session_id in timeout errors) — prerequisite for Step 3.
Step 3 (timeout recovery in handler) — depends on Step 4.
Step 5 (reconciliation) — depends on understanding from Step 3 but modifies the success path.
Step 6 (tests) — after all code changes are in place.
Validation Order
Run existing execute tests after Step 1 to catch regressions from prompt change.
Add timeout recovery test (Step 6.1) alongside Step 3.
Run full test suite after all steps complete.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-25T04:03:22Z",
"hash": "sha256:c0e82a2c36730ed2ab63ae3f6d47e6ec4f5389d76947b45f3dca2bf0957837eb",
"questions": [
"Should the timeout recovery path block or allow progression? Currently a timeout re-raises, so the orchestrator retries. With incremental saves, should a timeout with 100% tasks done be treated as success (auto-advance to review), or always require a re-run to get the structured output validation?",
"For the reconciliation check (Step 5): if the agent's incremental disk save says a task is 'done' but the structured output says 'skipped' (or vice versa), should we trust the structured output (last write wins, current behavior) or the disk state? The structured output is the agent's final deliberate answer; the disk state is the most recent incremental checkpoint.",
"Should the prompt instruct the agent to do a full read-modify-write of finalize.json (read entire file, update one task, write entire file) or a more targeted approach? Full read-modify-write is safer but means the agent writes the entire file N times. Given the file is typically small (<50KB), this seems fine, but worth confirming.",
"The agent might be running via Codex in full-auto mode (workers.py:579). Does Codex's sandbox allow writing to the plan directory (which is outside the project directory)? If not, the agent physically cannot update finalize.json and this feature only works with Claude."
],
"success_criteria": [
"Timeout during execute no longer loses tracking \u2014 tasks completed before timeout are persisted in finalize.json and visible on re-run",
"Session ID is preserved through timeout so re-execution can resume the agent session",
"The execute prompt instructs the agent to update finalize.json incrementally after each task and sense check",
"On successful completion, structured output is reconciled against disk state with advisory deviations logged for any discrepancies",
"Existing execute tests pass without modification (happy path, deduplication, evidence checks)",
"New tests cover: timeout recovery with partial progress, reconciliation mismatch detection, re-execution after timeout",
"State remains STATE_FINALIZED after timeout so re-execution is valid (no state corruption)"
],
"assumptions": [
"Full read-modify-write of finalize.json is acceptable \u2014 the file is small and the agent updates it sequentially (no concurrent writers)",
"Structured output remains the authoritative source on the success path \u2014 disk state is a safety net for timeouts, not a replacement for the merge logic",
"Codex full-auto sandbox can write to the plan directory (which is outside the project dir). If not, this feature is Claude-only and the prompt should be conditional.",
"The timeout recovery path should NOT auto-advance to review even if all tasks appear done on disk \u2014 it should return success=False with next_step='execute' to get a clean structured output pass",
"Session ID extraction from partial stdout/stderr (via extract_session_id) is reliable enough for Codex; for Claude, we'll explicitly include session_id in the timeout error extra"
],
"structure_warnings": [
"Each step section should include at least one numbered substep."
]
}
code
Plan structure warnings from validator:
[
"Each step section should include at least one numbered substep."
]
code
Existing flags:
[]
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: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- 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 structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- 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`.
{"flags":[{"id":"FLAG-001","concern":"The plan assumes the executor can directly update finalize.json, but the repository does not currently expose a writable artifact path to the worker.","category":"correctness","severity_hint":"likely-significant","evidence":"_execute_prompt shows the contents of finalize.json and the project directory, but not the actual path to the file (megaplan/prompts.py:430-458). Plan artifacts live under plans_root(root) (megaplan/_core.py:231-232), and the test fixture explicitly separates root from project_dir (tests/test_megaplan.py:62-84). The worker runners are launched around project_dir (megaplan/workers.py:513-526, 554-584). Without an explicit path/access mechanism, the agent cannot reliably read-modify-write the real finalize.json."},{"id":"FLAG-002","concern":"Timeout session recovery is underspecified: propagating only session_id is not enough to persist the execute session state.","category":"correctness","severity_hint":"likely-significant","evidence":"On the success path, handle_execute gets agent, mode, and refreshed from run_step_with_worker and passes all of them into apply_session_update (megaplan/handlers.py:1240-1241, 1324; megaplan/handlers.py:73-90). In the exception path those values are lost. run_step_with_worker computes them internally (megaplan/workers.py:663-669), and agent fallback can change the resolved agent (megaplan/workers.py:623-660). The proposed timeout change only mentions extracting session_id, so it still cannot reliably update state[\"sessions\"]."},{"id":"FLAG-003","concern":"The timeout path in the plan trusts on-disk task status too early and skips the repository's existing execution-evidence validation.","category":"correctness","severity_hint":"likely-significant","evidence":"The current success path does more than merge statuses: it checks for missing per-task evidence with _check_done_task_evidence and runs validate_execution_evidence against git state before rewriting finalize.json (megaplan/handlers.py:1290-1306). The plan says tasks marked done on disk are 'genuinely done' after a timeout, but it does not include those same validations for the recovery path, so a partial or hallucinated checkpoint could be treated as completed work."},{"id":"FLAG-004","concern":"The plan still fails the required step-section structure.","category":"completeness","severity_hint":"likely-significant","evidence":"The validator warning is still valid: ### Step 2: No schema changes needed contains prose only and no numbered substeps. The requested plan format requires numbered substeps under each step section, so the plan remains structurally incomplete."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
During execute, the agent does all the work (modifies files, runs tests, completes tasks) but never saves its progress to finalize.json. The prompt explicitly says 'Do not create or rewrite tracking artifacts directly.' Instead, the agent returns one big JSON blob at the end, and the handler merges task_updates into finalize.json. If the agent times out or crashes, ALL tracking is lost even though the actual code changes are in the repo.
Solution: Make the agent save as it goes
Flip the prompt instruction. Tell the executor agent to update finalize.json directly after completing each task:
After finishing each task: update that task's entry in finalize.json with status, executor_notes, files_changed, commands_run. Save the file.
After each sense check acknowledgment: update that sense_check's entry in finalize.json with executor_note. Save the file.
The agent checks off tasks and adds notes in real-time as part of its natural workflow.
Handler changes
On timeout: read finalize.json from disk (which the agent has been updating). Whatever tasks are marked done are genuinely done. Use that as the source of truth.
On success: the handler already re-reads finalize.json at line 1247. The structured JSON output's task_updates become a validation/reconciliation layer, not the sole source of truth.
On timeout recovery: persist session ID, save state, leave state as 'finalized' so re-execution works. The re-run prompt already handles done vs pending tasks.
Key insight
The handler at handlers.py:1247 already does read_json(plan_dir / 'finalize.json') after the agent finishes. If the agent updates that file during execution, those updates are already there. We just need to:
Tell the agent to do it (prompt change)
Handle the timeout path to read what's on disk instead of just re-raising
Reconcile agent-written updates with structured output on success
Files involved
megaplan/prompts.py — Change execute prompt: tell agent to update finalize.json after each task and sense check
megaplan/handlers.py — Timeout recovery in handle_execute(): read finalize.json from disk, persist session, save state
megaplan/workers.py — Propagate session ID through timeout errors
During execute, the agent does all the real work (edits files, runs tests) but never persists tracking to finalize.json. The handler merges a single structured JSON blob into finalize.json only after the agent completes (handlers.py:1247-1306). If the agent times out (workers.py:102-107, CliError code worker_timeout), the except CliError at handlers.py:1242 re-raises — losing all tracking even though code changes are on disk.
Goal: Tell the agent to update finalize.json incrementally during execution. On timeout, read what's on disk, validate evidence, and return a recoverable response. On success, reconcile disk state with structured output.
Repo shape: Prompt in prompts.py:371-496. Handler in handlers.py:1226-1371. Workers in workers.py (timeout at line 102). Plan artifacts live under plans_root(root) (_core.py:231-232), which is separate from project_dir. The prompt currently shows finalize.json contents but not its filesystem path.
Key constraint: The handler already reads finalize.json at line 1247 and merges structured output on top. If the agent writes directly to finalize.json, those updates are already there when the handler reads. The structured output merge becomes reconciliation, not the sole source.
Phase 1: Expose Artifact Path and Update Prompt
Step 1: Expose finalize.json path in the execute prompt (megaplan/prompts.py:371-496)
Scope: Small
Computefinalize_path = str(plan_dir / "finalize.json") at prompts.py:373 (where plan_dir is already available).
Add the absolute path to the prompt body, e.g. after line 438:
Replace the instruction at line 458 ("Do not create or rewrite tracking artifacts directly.") with incremental-save instructions:
After completing each task: read finalize.json from the path above, update that task's status, executor_notes, files_changed, commands_run, write the full JSON back.
After each sense check acknowledgment: update that sense check's executor_note in the same file.
Always read the full file, update the specific entry, write the full file back. Do not use partial writes.
Keep the structured output requirement — the agent still returns task_updates and sense_check_acknowledgments in its final JSON. State explicitly that the structured output is the authoritative final summary; the disk saves are a progress checkpoint.
Preserve the re-run guidance logic (prompts.py:399-418) unchanged — it already reads task status from finalize.json, which will now reflect incremental saves from prior (possibly timed-out) runs.
Note on Codex: Codex runs with -C project_dir and --full-auto (workers.py:575-579). The plan directory is outside project_dir. If Codex's sandbox blocks writes outside the project dir, incremental saves silently fail and the feature degrades to current behavior (structured output only). The prompt should frame incremental saves as "if possible" — not a hard requirement — so Codex runs don't error on sandbox restrictions. This is acceptable degradation: Codex timeouts lose tracking as they do today; Claude timeouts gain recovery.
Step 2: Verify schema needs no changes (.megaplan/schemas/execution.json)
Scope: Small
Confirm the structured output schema stays unchanged — the agent still returns the same JSON shape (task_updates, sense_check_acknowledgments, etc.).
Confirm no new fields are needed in the finalize schema (.megaplan/schemas/finalize.json) — the agent writes the same task fields (status, executor_notes, files_changed, commands_run) that the handler currently merges.
Phase 2: Worker-Level Session Propagation
Step 3: Resolve agent/mode/refreshed before the worker call (megaplan/handlers.py:1240-1241, megaplan/workers.py:663-669)
Scope: Small
Extract the resolve_agent_mode call from inside run_step_with_worker so the handler has access to agent, mode, and refreshed even on timeout. In handle_execute, call resolve_agent_mode directly before run_step_with_worker:
Pass these values through to run_step_with_worker (or call the underlying run_claude_step/run_codex_step directly). The simplest approach: add an optional resolved parameter to run_step_with_worker that skips its internal resolve_agent_mode call when provided.
Storeagent, mode, refreshed in local variables available to both the success path and the except block.
Step 4: Propagate session_id through timeout errors (megaplan/workers.py:510-539, 542-613)
Scope: Small
In run_claude_step (workers.py:526): wrap the run_command call to catch CliError with code worker_timeout and attach session_id to error.extra before re-raising. Session ID is already known at line 518-524.
python
try:
result = run_command(command, cwd=project_dir, stdin_text=prompt)
except CliError as error:
if error.code == "worker_timeout":
error.extra["session_id"] = session_id
raise
In run_codex_step (workers.py:584): same pattern. For persistent mode, session_id is available from session.get("id") at line 563. For ephemeral, session_id is None (acceptable — ephemeral sessions can't be resumed anyway).
python
try:
result = run_command(command, cwd=Path.cwd(), stdin_text=prompt)
except CliError as error:
if error.code == "worker_timeout":
error.extra["session_id"] = session.get("id")
raise
Phase 3: Timeout Recovery in Handler
Step 5: Implement timeout recovery path in handle_execute (megaplan/handlers.py:1240-1244)
Scope: Medium
Replace the current catch-all CliError handler with timeout-specific recovery:
python
except CliError as error:
if error.code != "worker_timeout":
record_step_failure(plan_dir, state, step="execute",
iteration=state["iteration"], error=error)
raise
# --- Timeout recovery: read incremental progress from disk ---
Readfinalize.json from disk (which the agent may have been updating):
Run evidence validation on the disk state — same checks as the success path:
Call _check_done_task_evidence(finalize_data.get("tasks", []), ...) to detect tasks claiming "done" without any evidence.
Call validate_execution_evidence(finalize_data, project_dir) to cross-check against git state.
Any tasks marked done but failing evidence checks get their status reset to "pending" with an executor_notes annotation like "Reset: marked done before timeout but missing evidence". This prevents hallucinated checkpoints from persisting.
Step 6: Add reconciliation check on the success path (megaplan/handlers.py:1247-1267)
Scope: Small
Snapshot pre-merge task statuses right after reading finalize.json at line 1247:
python
pre_merge_statuses = {
task["id"]: task.get("status", "pending")
for task in finalize_data.get("tasks", [])
}
Keep existing merge logic unchanged — _validate_and_merge_batch overwrites disk values with structured output (last-write-wins). Structured output is authoritative on success.
After the merge, compare and log advisory deviations for any discrepancies:
python
for task in finalize_data.get("tasks", []):
pre = pre_merge_statuses.get(task["id"], "pending")
post = task.get("status", "pending")
if pre != "pending" and pre != post:
deviations.append(
f"Advisory: task {task['id']} was '{pre}' on disk but '{post}' in structured output"
)
Test timeout with partial progress: Mock run_step_with_worker to raise CliError("worker_timeout", ..., extra={"session_id": "test-session", "raw_output": ""}). Pre-populate finalize.json with T1 marked done (with evidence) and T2 still pending. Verify:
Handler returns StepResponse with success=False, next_step="execute".
State remains STATE_FINALIZED.
Session is persisted (check state["sessions"]).
finalize.json on disk retains T1 as done.
Test timeout with bad evidence reset: Pre-populate finalize.json with T1 marked done but files_changed=[] and commands_run=[]. Verify the handler resets T1 to pending with annotation.
Test reconciliation mismatch: Mock worker returning structured output where T1 status is "skipped" but disk has T1 as "done". Verify advisory deviation is logged but merge proceeds (structured output wins).
Test prompt includes finalize path: Call _execute_prompt and verify the output contains the absolute path to finalize.json and the incremental save instructions. Verify it does NOT contain "Do not create or rewrite tracking artifacts directly."
Run existing execute tests to confirm no regressions: test_execute_happy_path_tracks_all_tasks (line 1699), test_execute_deduplicates_task_updates_and_blocks_incomplete_coverage (line 1774), test_execute_blocks_done_task_without_any_per_task_evidence (line 1967).
Execution Order
Step 1 (prompt + path exposure) — no code dependencies, can validate independently.
Step 3 (extract resolve_agent_mode) — pure refactor, prerequisite for Step 5.
Step 4 (session_id in timeout errors) — prerequisite for Step 5.
Step 5 (timeout recovery) — depends on Steps 3 and 4.
Step 6 (reconciliation) — independent of Step 5, can be done in parallel.
Step 7 (tests) — after all code changes.
Validation Order
Run existing execute tests after Step 1 to catch prompt regressions.
Run existing tests after Step 3 to confirm resolve_agent_mode refactor is clean.
Add reconciliation test (Step 7.3) alongside Step 6.
Full test suite after all steps.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-03-25T04:09:19Z",
"hash": "sha256:2b0b6ed1fa4a2c35017a52ecc5417ef041d496d855ac7ca99a770eefff1f0b7d",
"changes_summary": "Addressed all 4 flags. FLAG-001: Added Step 1 to expose plan_dir / \"finalize.json\" absolute path in the prompt and noted Codex sandbox graceful degradation. FLAG-002: Added Step 3 to extract resolve_agent_mode before the worker call so agent/mode/refreshed are available in the except block. FLAG-003: Added evidence validation in Step 5 (timeout path runs _check_done_task_evidence and validate_execution_evidence, resets tasks that fail). FLAG-004: All steps now have numbered substeps including the schema verification step.",
"flags_addressed": [
"FLAG-001",
"FLAG-002",
"FLAG-003",
"FLAG-004"
],
"questions": [
"Should the timeout recovery path also write execution_audit.json and final.md (like the success path at handlers.py:1305-1307), or just finalize.json? Writing them could be useful for debugging but adds complexity to the timeout path.",
"For the resolve_agent_mode extraction (Step 3): should we add an optional parameter to run_step_with_worker to accept pre-resolved values, or should handle_execute call the underlying run_claude_step/run_codex_step directly? The former is cleaner but changes the worker API; the latter avoids API changes but duplicates agent dispatch logic."
],
"success_criteria": [
"Timeout during execute no longer loses tracking \u2014 tasks completed before timeout are persisted in finalize.json and visible on re-run",
"Session ID and agent/mode/refreshed are preserved through timeout so re-execution can resume the agent session",
"The execute prompt includes the absolute finalize.json path and instructs the agent to update it incrementally after each task and sense check",
"Timeout recovery validates evidence on disk \u2014 tasks marked done without files_changed or commands_run are reset to pending",
"On successful completion, structured output is reconciled against disk state with advisory deviations logged for discrepancies",
"Existing execute tests pass without modification (happy path, deduplication, evidence checks)",
"New tests cover: timeout recovery with partial progress, evidence reset on timeout, reconciliation mismatch detection, prompt content verification",
"State remains STATE_FINALIZED after timeout so re-execution is valid (no state corruption)",
"Codex runs degrade gracefully \u2014 if sandbox blocks writes to plan_dir, execution proceeds as before without error"
],
"assumptions": [
"Full read-modify-write of finalize.json is acceptable \u2014 the file is small and the agent updates it sequentially (no concurrent writers)",
"Structured output remains the authoritative source on the success path \u2014 disk state is a safety net for timeouts, not a replacement for the merge logic",
"Codex full-auto sandbox likely cannot write to the plan directory (outside project_dir). The prompt frames incremental saves as best-effort, so Codex runs degrade to current behavior (no recovery on timeout). This is acceptable \u2014 the feature primarily benefits Claude runs.",
"The timeout recovery path never auto-advances to STATE_EXECUTED \u2014 it always returns success=False with next_step='execute' to require a clean re-run with structured output validation",
"Tasks marked done on disk but failing evidence validation get reset to pending \u2014 we do not trust agent claims without verifiable evidence, even from incremental saves"
],
"structure_warnings": [],
"delta_from_previous_percent": 71.49
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "The plan assumes the executor can directly update finalize.json, but the repository does not currently expose a writable artifact path to the worker.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Timeout session recovery is underspecified: propagating only session_id is not enough to persist the execute session state.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-003",
"concern": "The timeout path in the plan trusts on-disk task status too early and skips the repository's existing execution-evidence validation.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-004",
"concern": "The plan still fails the required step-section structure.",
"status": "addressed",
"severity": "significant"
}
]
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: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- 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 structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- 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`.
agent/mode/refreshed
session.get(\"id\")
None
extract_session_id
megaplan/workers.py:118-125
596-599
raw_output
megaplan/workers.py:102-106
Not yet included in a published release.
Record history entry with result="timeout" and partial progress:
python
append_history(state, make_history_entry(
"execute", duration_ms=0, cost_usd=0.0, result="timeout",
message=f"Timeout with {len(done_tasks)}/{total_tasks} tasks tracked on disk",
))
save_state(plan_dir, state)
Return a recoverable StepResponse — success=False, next_step="execute", state=STATE_FINALIZED:
python
return {
"success": False,
"step": "execute",
"summary": f"Execute timed out. {len(done_tasks)}/{total_tasks} tasks saved from incremental progress. Re-run to continue.",
"artifacts": ["finalize.json"],
"next_step": "execute",
"state": STATE_FINALIZED,
"deviations": [f"Execution timed out after partial completion ({len(done_tasks)}/{total_tasks} tasks)"],
"warnings": [error.message],
}