Explore the megaplan project at /Users/user_c042661f/Documents/megaplan. I'm planning to add "step receipts" — structured per-phase audit records with scope-drift detection — and need a precise map of touch points.
Please report on the following (be specific with file paths and line numbers):
Handler structure: How are phases wired? Look in megaplan/handlers/ — especially shared.py (look for _finish_step and make_history_entry). Each phase handler (plan, critique, gate, finalize, execute, review) — list them. What do they pass to _finish_step? Where is the "immediately before _finish_step" insertion point?
Prompt rendering: How are prompts built and rendered for each phase? Where does the full rendered prompt string live at the time of hermes call? We need to hash it. Look at megaplan/prompts/ and any render functions. Does the current code already capture a rendered prompt, or is it built and handed straight to hermes?
Hermes integration: How does megaplan talk to hermes? Where are sessions logged (the prompt says ~/.hermes/sessions/session_<id>.json)? Where does megaplan get model_configured vs model_actual — the latter being what hermes actually returned. Look in megaplan/hermes_worker.py, megaplan/agent/, or wherever hermes calls happen.
Plan directory / state: Where is the plan directory root, and what's the convention for state.history and per-phase artifact files (plan_v1.md, critique_v1.json, execution.json, review_output.json, finalize.json)? How is iteration number tracked? Look at megaplan/types.py and megaplan/handlers/shared.py.
Execute phase + scope drift: Look at megaplan/execute/quality.py. Is there already any scope-drift detection? What robustness levels exist and how are they checked (standard, robust, superrobust)? How does it currently decide to block vs advise?
CLI structure: Look at megaplan/cli.py — how are subcommands registered? I need to add megaplan audit query.
Existing tests: Where are tests kept and what style? Are there fixture-based tests for handlers?
Assistant
I'll systematically explore the megaplan project to map these touch points. Let me start with parallel searches.
Assistant
Now let me search the key files in parallel:
Assistant
Good. Now let me get the shared.py handler file and hermes integration:
Assistant
Now let me check hermes integration and cli:
Assistant
Now let me check execute quality.py and prompt rendering:
Assistant
Now let me check state.py and look at the plan directory structure:
Assistant
Now let me check one more critical file - the execute handler to see how it calls _finish_step:
Assistant
Now let me get the critical files for hermes and worker results:
Assistant
Quick look at types: What does SessionInfo look like in megaplan/types.py (recent commit mentioned a sandbox_hash field regression)?
Be concrete — give me file:line references so I can drop changes in without re-exploring. Aim for ~600–800 words max.
Perfect. Now I have enough context. Let me compile the findings into a comprehensive report:
Step Receipts Implementation Map for Megaplan
1. Handler Structure & Integration Points
Phase wiring lives in /Users/user_c042661f/Documents/megaplan/megaplan/handlers/:
Plan phase: plan.py → calls _run_worker()
Critique: critique.py
Gate: gate.py
Finalize: finalize.py
Execute: execute.py (delegates to execute/core.py)
Review: review.py
Shared utilities: shared.py (lines 217–276)
Critical insertion point is /Users/user_c042661f/Documents/megaplan/megaplan/handlers/shared.py:217–276 in _finish_step(). This function:
These return fully rendered prompt strings — ready for hashing. The prompt is built in _run_worker() at /Users/user_c042661f/Documents/megaplan/megaplan/handlers/shared.py:139–182:
Line 165–172: prompt can be overridden or passed via prompt_kwargs
The rendered prompt string is sent directly to worker_module.run_step_with_worker()
Current code does NOT capture the rendered prompt — it's built, passed to hermes, and discarded
To capture it: Store the fully rendered prompt (after builder returns, before worker call) in a variable; hash it with sha256_text() (available from megaplan._core); pass to _finish_step() via history_fields.
3. Hermes Integration & Session Logging
Hermes runs in /Users/user_c042661f/Documents/megaplan/megaplan/hermes_worker.py. Key facts:
Session creation: hermes_worker.py:23–36 imports AIAgent, SessionDB from run_agent and hermes_state
Sessions stored in ~/.hermes/sessions/session_<id>.json (outside megaplan, managed by hermes runtime)
Megaplan receives session_id back in WorkerResult (line 94 in /Users/user_c042661f/Documents/megaplan/megaplan/workers.py)
@dataclass
class WorkerResult:
payload: dict[str, Any]
raw_output: str
session_id: str | None = None
prompt_tokens: int = 0
completion_tokens: int = 0
total_tokens: int = 0
No model_configured vs model_actual field yet — that comes from the worker's resolution in /Users/user_c042661f/Documents/megaplan/megaplan/handlers/shared.py:155: agent, mode, refreshed, model = resolved or _handlers_pkg.resolve_agent_mode(step, args). The model is passed through; to capture actual model from hermes payload, add to WorkerResult or extract from payload.
4. Plan Directory & State Convention
Root: .megaplan/plans/<plan_name>/
State file: state.json (PlanState dict)
Iteration tracking: state["iteration"] (integer, incremented per phase)
Execute: execution_batch_<num>.json or execution_v{iteration}.json
Review: review_v{iteration}.json
History: state["history"] is a list of HistoryEntry dicts (typed at /Users/user_c042661f/Documents/megaplan/megaplan/types.py:96–115). Each entry has step, timestamp, duration_ms, cost_usd, artifact_hash, session_id.
5. Execute Phase & Scope Drift
Scope-drift detection defined in /Users/user_c042661f/Documents/megaplan/megaplan/types.py:327, 337–342:
Existing commands like audit, status, progress use the pattern (line 927–932):
python
for name in ["status", "audit", "progress", "watch"]:
step_parser = subparsers.add_parser(name)
step_parser.add_argument("--plan")
To add megaplan audit query: Either extend the existing audit subparser (add subcommand handling) or create a top-level command audit-query and wire it in the dispatch in /Users/user_c042661f/Documents/megaplan/megaplan/cli.py:1200–1350.
7. Tests & Fixtures
Test structure in /Users/user_c042661f/Documents/megaplan/tests/:
From /Users/user_c042661f/Documents/megaplan/megaplan/types.py:64–77:
python
class SessionInfo(TypedDict, total=False):
id: str
mode: str
created_at: str
last_used_at: str
refreshed: bool
sandbox_hash: str # Fingerprint of sandbox-affecting config
The sandbox_hash (line 76) was added to prevent silent sandbox drift when resuming sessions after config changes (e.g., MEGAPLAN_TRUSTED_CONTAINER, --work-dir toggles).
Summary: All phase handlers funnel through _finish_step() at shared.py:217 where you should capture the rendered prompt (hash it before/after worker call), inject receipt metadata into history_fields, and append the receipt record. The plan directory follows iteration-numbered artifacts; state.history already tracks phases, costs, tokens, and session IDs—step receipts add the scope-drift signal hash and prompt audit trail.