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.
WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are creating an implementation plan for the following idea.
code
Idea:
Sprint 4 — Lift RunPod to a peer Astrid capability
Astrid reshape sprint 4. Full design: /Users/user_c042661f/Documents/reigh-workspace/Astrid/idea.md § Sprint 4 (lines 299–365). Profile: led/standard — cross-repo lift with mostly-mechanical code movement; one premium model on the plan, cheap models for the rest.
Working directory: /Users/user_c042661f/Documents/reigh-workspace/Astrid. Start from reshape/sprint-3 (after it merges); create reshape/sprint-4 off it.
Move the generic "ship work to a GPU pod" recipe out of vibecomfy and into runpod-lifecycle. Shrink vibecomfy to a thin consumer. Stand up external.runpod.* as a first-class Astrid pack. Ship a sweeper as the safety net for the split provision/exec/teardown trio.
After this sprint, any orchestrator (lora_train, scene_render, future GPU work, the Sprint 5a hype port) can request GPU compute through one substrate without going through vibecomfy.
Foundational decisions (locked, do not re-debate)
The three-layer split
Draw the line cleanly between "extract the archive" (lifecycle) and "interpret the archive" (consumer):
runpod-lifecycle owns: pod launch, stateless reattach by id, + signal handlers, the entire upload mechanism (sftp_walk + tarball, exclude set, disk preflight), sync + detached-with-poll exec, artifact archive pull + extract.
Assistant
Plan delivered. Key shape: 4 phases (lifecycle lift → vibecomfy shrink stop-line → Astrid pack → tests), 16 steps, with the locked pre-resolved findings (Pod.is_idle, /v1/networkvolumes, guard_factory injection, auto_terminate flag, pod_handle.json schema, session breadcrumb-before-exec) called out at the exact steps they constrain. Three open questions surfaced (live-session ack artifact, ensure-storage cost emission, append_event_locked bypass support) — all answerable cheaply before Phase 3.
PodGuard
vibecomfy keeps: _runpod_config_kwargs (env-var conventions), REMOTE_ROOT, DEFAULT_UPLOAD_EXCLUDES as module constants, and the entire artifact-format reader stack (_parse_tsv, _collect_outputs, _collect_run_metadata, _collect_watchdogs, _build_artifact_manifest, _write_artifact_report, _print_detached_summary). These read vibecomfy-shaped paths and are genuinely consumer concerns.
Astrid gets a new pack at astrid/packs/external/runpod/ with four executors plus a sweeper. Consumes the lifted lifecycle directly; does not go through vibecomfy.
One critical new flag
terminate_after_exec: bool = True on ship_and_run / ship_and_run_detached. Vibecomfy's current code always terminates; Astrid's split provision/exec/teardown trio needs to leave the pod alive between exec calls. The flag is the only behavioral addition beyond the lift.
Storage volume creation
Today runpod-lifecycle handles discovery, attachment, expansion. Missing piece is creation. v0.2 adds api.create_network_volume(api_key, name, size_gb, datacenter_id) (POST against the same REST endpoint that PATCH already uses) plus Pod.create_storage() / Pod.list_storages() / Pod.get_storage(name_or_id) as composable surface methods. Deletion stays out — rare, scary, RunPod console handles it.
Vibecomfy backward compat is non-negotiable
Post-shrink, vibecomfy/scripts/runpod_runner.py re-exports run_pod, run_pod_detached, REMOTE_ROOT, DEFAULT_UPLOAD_EXCLUDES, and the artifact-format readers. Every existing caller (runpod_validate.py, runpod_model_matrix.py, runpod_corpus_matrix.py) imports unchanged. Behavior is identical; only the engine room moves.
Astrid pack shape
One folder, four executors in a single executor.yaml (matches the external.vibecomfy.{run,validate} precedent):
external.runpod.session — workhorse, composite. provision → exec → download → terminate inside a single Python try/finally. Guaranteed cleanup. Day-one default for lora_train and most callers.
external.runpod.provision — emits pod_handle.json ({pod_id, ssh, name, terminate_at, config_snapshot}). Does not terminate.
external.runpod.exec — consumes pod_handle.json, reattaches via discovery.get_pod, ships local_root + remote_script, downloads artifacts. Leaves pod alive.
Astrid has no try/finally / on_failure / cleanup step kind at the plan level. Two consequences:
The composite session executor is mandatory, not optional — only honest way to guarantee teardown for callers that don't need a hot pod across steps.
The split provision/exec/teardown trio needs a sweeper as its safety net — a crashed orchestrator between provision and teardown would leak a paid GPU pod. Sweeper covers that case.
astrid runpod sweep walks every astrid-projects/<project>/runs/<run-ulid>/steps/<step-id>/v<N>/[iterations/NNN/]produces/pod_handle.json, parses, calls runpod-lifecycle's discovery.list_pods with the pack's name_prefix, decides per-pod with a two-mode policy:
Default (safe) mode — terminate only if all of: terminate_at has passed; no live session has the handle ack'd; no in-flight exec on the pod (lifecycle's discovery.get_pod reports idle, not running). Pods that fail any check are left alone and reported.
--hard mode — bypasses the live-session and idle-exec checks. Terminates anything past terminate_at regardless.
Every termination — in either mode — appends a pod_terminated_by_sweep event to the owning run's events.jsonl with {pod_id, terminate_at, mode: "default"|"hard", reason}.
astrid doctorreports stale handles (read-only); the sweep verb mutates. Doctor is the alert; sweep is the broom.
Cost emission
Each executor declares cost: {amount, currency: "USD", source: "runpod", basis} on its completion event per Sprint 3's cost contract. The trio's three partial costs sum to what session would emit as one. Hourly rates come from RunPod's pricing API with a pinned-table fallback shipped in the pack.
Cost basis is wallclock_seconds * gpu_hourly_rate for the session/exec window.
Migration order is forced by the dependency direction
Cut runpod-lifecycle v0.2 with the lift; vibecomfy continues working via re-exports.
Shrink vibecomfy; verify all three existing scripts run unchanged. Stop-line.
Build the Astrid pack.
Wire the sweeper + doctor reporting.
Each step has to land cleanly before the next.
Deliverables
runpod-lifecycle v0.2.0 (the substrate)
New modules:
guard.py — PodGuard + opt-in signal handlers (lifted from vibecomfy).
shipping.py — UploadHeartbeat, both upload modes (sftp_walk + tarball), disk preflight, artifact download.
Live-pod test coverage for: sftp_walk upload, tarball upload, sync exec, detached-with-poll exec, reattach by pod_id, terminate_after_exec=False round-trip.
Tagged release: pinned git tag at minimum, PyPI if convenient. Astrid pack pins runpod-lifecycle>=0.2.
vibecomfy shrink
vibecomfy/scripts/runpod_runner.py shrunk from ~1.2k to ~250 lines.
Re-exports run_pod, run_pod_detached, REMOTE_ROOT, DEFAULT_UPLOAD_EXCLUDES for source-compat.
Retains the artifact-format readers (_parse_tsv, _collect_*, _build_artifact_manifest, _write_artifact_report, _print_detached_summary, _runpod_config_kwargs); these are now layered on top of lifecycle's ship_and_run_detached result.
vibecomfy/commands/runpod.py (vibecomfy runpod list|status|terminate|gpu-types) unchanged — still passes through to lifecycle.
Verified backward compatibility (the stop-line):runpod_validate.py, runpod_model_matrix.py, runpod_corpus_matrix.py all pass a live RunPod run against the lifted lifecycle with zero source change.
Astrid pack external.runpod
New pack astrid/packs/external/runpod/ with:
executor.yaml — single JSON array declaring four executors.
Pack registered in astrid/packs/external/pack.yaml. Same on-disk shape as external.vibecomfy/.
Inputs/produces per executor follow the Sprint 3 step schema. All pod_handle.json artifacts land at the canonical produces path (steps/<id>/v<N>/[iterations/NNN/]produces/pod_handle.json):
session: inputs of provision + exec, no pod_handle escapes; produces exec_result (with full cost) + artifact_dir.
Cost emission per the Sprint 3 contract (already covered above).
Astrid verbs
astrid runpod sweep — default-mode and --hard mode. Default mode skips pods with a live ack'd session or in-flight exec; --hard bypasses both checks. Every termination emits pod_terminated_by_sweep to the owning run's events.jsonl with {pod_id, terminate_at, mode, reason}.
astrid runpod ensure-storage <name> [--size <GB>] [--datacenter <id>] — find-or-create a storage volume by name. Resolves via Pod.get_storage(name); if missing, calls Pod.create_storage(name, size_gb, datacenter_id) (default size from a pack-level config, default datacenter from env / pack default). Idempotent. external.runpod.session and external.runpod.provision continue to error clearly when storage_name resolves to nothing — they do NOT silently auto-create. Auto-create as a side effect of a render is too easy a way to spend money by accident.
astrid runpod volumes ls — passes through to runpod-lifecycle's volumes ls. Read-only.
astrid doctor integration reports stale pod_handle.json files (read-only; same scan logic as sweep, no mutation).
Live tests (gated behind a RUNPOD_LIVE_TESTS=1 env var so they don't run in CI):
End-to-end smoke: plan-template invocation of external.runpod.session with remote_script = "nvidia-smi -L; echo ok" produces a verified exec_result.json (including non-zero cost) and artifact_dir/.
End-to-end sweeper test: provision via external.runpod.provision, kill the orchestrator process before teardown runs, then invoke astrid runpod sweep and verify (a) the pod is terminated through the lifecycle API, (b) a pod_terminated_by_sweep event lands in the owning run's events.jsonl. Re-run with --hard against a deliberately ack'd handle to verify the bypass path.
vibecomfy regression tests against the lifted lifecycle (this is the stop-line, see below).
All Sprint 0-3 tests still pass.
Stop-lines
Vibecomfy regression. If runpod_validate.py or runpod_corpus_matrix.py regresses against the lifted lifecycle, halt and reshape the public API surface before tagging v0.2. Vibecomfy regression is the canary; if it dies, the lift is wrong. Do NOT proceed to the Astrid pack until vibecomfy is green.
Sweeper double-termination. If the sweeper's default mode terminates a pod that has a live session ack'd, that's a stop-line. The default mode's job is to be safe. Prove the live-session check is correct before shipping.
pod_handle.json schema drift between lifecycle's primitives and the pack's contract. If the pack invents a shape that lifecycle can't round-trip cleanly via discovery.get_pod, the seam is wrong — fix in the pack, not in lifecycle.
vibecomfy/scripts/runpod_runner.py is ≤ 300 lines (down from ~1.2k).
All three vibecomfy scripts (runpod_validate.py, runpod_model_matrix.py, runpod_corpus_matrix.py) run unchanged against the lifted lifecycle (verified via at least one real RunPod launch per script if credentials are available; otherwise verified via mock-driven import-and-instantiate smoke).
astrid/packs/external/runpod/ exists with four executors + sweeper.
astrid runpod sweep round-trips against mocked lifecycle: default-mode skip cases work; --hard overrides; events emitted to events.jsonl.
astrid runpod ensure-storage find-or-create works against mocked lifecycle; session/provision still error-loudly when storage_name resolves to nothing.
astrid doctor reports stale pod_handle.json files without mutating.
All Sprint 0-3 tests still green (modulo the 7 pre-existing unrelated failures verified in S2).
New pack tests at tests/packs/runpod/ all green (mocked-lifecycle subset; live tests gated behind env var).
Useful repo references
/Users/user_c042661f/Documents/reigh-workspace/vibecomfy/scripts/runpod_runner.py — the 1.2k-line file being shrunk.
/Users/user_c042661f/Documents/reigh-workspace/runpod-lifecycle/src/runpod_lifecycle/ — current package; v0.1 surface area.
astrid/packs/external/vibecomfy/ — the precedent for pack shape (single executor.yaml, single run.py argparse dispatcher).
astrid/core/task/events.py — append_event_locked from S1; reuse for pod_terminated_by_sweep.
astrid/core/timeline/ — S2 pack; do not modify.
astrid/core/task/plan.py (post-S3) — step schema with adapter field; external.runpod.* executors all use adapter: local (the executor handles the SSH from inside its process).
Live tests gated behind RUNPOD_LIVE_TESTS=1 env var; CI does not run them.
Cross-repo edits: in runpod-lifecycle and vibecomfy, follow each repo's existing conventions (don't impose Astrid's style on them).
pod_handle.json is canonical Astrid pack contract; lifecycle exposes the primitives to round-trip a pod by id but doesn't define this artifact shape.
Megaplan-specific guidance
Profile is led/standard per the megaplan-rubric: cross-repo lift is mostly mechanical movement of code between three repos, with a few new modules. The plan is the hard part (sequencing the migration order, deciding the seam between lifecycle and consumer); execution against a planned migration is mechanical.
Cross-repo work means the executor will need to write to three project trees. Be explicit in the plan about which repo each task touches.
The vibecomfy regression stop-line is the canary — surface it as a SC item in the plan so the executor verifies vibecomfy still works before moving on to the Astrid pack.
Live RunPod tests cost real money; gate them behind RUNPOD_LIVE_TESTS=1 and document the cost-per-test in the brief.
Pre-resolved gate findings (do NOT relitigate — these are codebase ground truth)
A prior gate pass on a thinner version of this brief surfaced 22 flags from a real codebase scan. The findings below are now load-bearing decisions — the planner should treat them as locked, not as open questions. Each is cited to the file/line that established it.
Codebase ground truth
Pod.is_idle(threshold_seconds) already exists at runpod-lifecycle/src/runpod_lifecycle/pod.py:102-118. The sweeper's "no in-flight exec" check uses this method directly; do NOT invent a new exec-marker-file heuristic. discovery.get_pod does NOT expose idle/busy state — that's Pod.is_idle's job.
Network-volume REST endpoints are at /v1/networkvolumes, not /v2/pods/network_volume. Existing usage: runpod-lifecycle/src/runpod_lifecycle/storage.py:30 uses https://rest.runpod.io/v1/networkvolumes/{volume_id}; api.py:20 defines NETWORK_VOLUMES_URL = 'https://api.runpod.io/v1/networkvolumes'. create_network_volume POSTs to the same /v1/networkvolumes root.
Vibecomfy has cancellation tests that monkeypatch runpod_runner.PodGuard at vibecomfy/tests/test_runpod_runner.py:197-224. After the lift, PodGuard instantiation moves inside runpod_lifecycle.runner.ship_and_run, which would bypass the shim-level monkeypatch. Solution: ship_and_run accepts an optional guard_factory (or guard instance) parameter that the vibecomfy shim can monkeypatch in its tests. Default is the real PodGuard; tests inject a mock.
runpod_corpus_matrix.py imports ROOT from vibecomfy/scripts/runpod_runner.py. Re-export ROOT from the post-shrink module.
PodGuard's asyncio watchdog terminates after max_runtime_seconds unconditionally. That conflicts with terminate_after_exec=False. Resolution: PodGuard accepts auto_terminate: bool = True. When False, the watchdog still detects max_runtime_seconds elapsed but only emits a warning + records the breach in the pod handle's breach_log field; it does NOT terminate. Caller is responsible for terminating later.
pod_handle.json schema is locked
json
{
"pod_id": "...",
"ssh": "user@host -p PORT",
"name": "<full pod name from RunPod, used by sweeper for name_prefix correlation>",
"name_prefix": "<the prefix the pack used for grouping>",
"terminate_at": "<ISO-8601 deadline>",
"gpu_type": "RTX 4090 / A100 / etc.",
"hourly_rate": 0.34,
"provisioned_at": "<ISO-8601 timestamp>",
"config_snapshot": {
"api_key_ref": "<env var name, NEVER the literal key>",
"datacenter_id": "...",
"image": "...",
"container_disk_in_gb": 30,
"volume_in_gb": 0,
"network_volume_id": "<optional>",
"ports": "8888/http,22/tcp"
}
}
hourly_rate lives in the top-level handle (not just inside config_snapshot) so exec/teardown reuse the provision-time rate without re-querying the pricing API. Cost summation invariant: provision.cost + exec.cost + teardown.cost == session.cost for the same pod, regardless of pricing API drift between provision and teardown.
config_snapshot.api_key_ref is an env var name (e.g. RUNPOD_API_KEY); the literal key is NEVER persisted to disk. exec/teardown reconstruct RunPodConfig by reading os.environ[config_snapshot.api_key_ref] plus the other snapshot fields.
name (full pod name) and name_prefix (the grouping prefix the pack used) are both required. The sweeper correlates pods returned by discovery.list_pods(name_prefix=...) against handles by name.
CLI wiring is part of the deliverable
astrid/pipeline.py MUST be modified to register the new astrid runpod {sweep, ensure-storage, volumes, doctor} verbs. The plan must enumerate the specific lines + functions to change. Without this wiring, the verbs are unreachable.
The session gate allowlist for unbound-session verbs lives in _verb_is_unbound_allowlisted, NOT in the dead _UNBOUND_TOP_LEVEL constant. Modify the active function. Reference: this is the same gate Sprint 1 wired; check astrid/pipeline.py for the current location.
Pack registration: the pack must be added to astrid/packs/external/pack.yaml. Don't omit this — packs aren't auto-discovered by directory scan.
executor.yaml format is {"executors": [...]} (a dict with an executors key wrapping the array), or a single executor dict. A bare top-level array fails _validate_manifest_payload. Match the format used by astrid/packs/external/vibecomfy/executor.yaml.
Subprocess executors (the four external.runpod.* runners) cannot call append_event_locked because they don't hold the writer lease. The lease is per-session-per-run; subprocesses inherit ASTRID_SESSION_ID but not the lease lock. Resolution: subprocess executors emit completion events via the standard step completion path that Astrid's executor framework already provides (the parent process — astrid next / lifecycle — owns the lease and writes the event). Subprocesses just print() structured JSON to stdout per the existing executor protocol; the parent reads + writes the event. Cost emission piggybacks on the same path.
The sweeper (astrid runpod sweep) IS a CLI verb running in a session-bound process, so it CAN call append_event_locked for the owning run's events. But only against the run whose pod it's terminating — not arbitrary cross-run mutation. The sweeper opens each owning run's lease, appends the pod_terminated_by_sweep event, releases. If a target run's lease is held by a live writer, the sweeper either skips that pod (default mode) or in --hard mode appends with expected_writer_epoch=None (which the locked-append code path supports for the sweeper-specific case — see SC below).
New SC for the plan: pod_terminated_by_sweep event hash-chains correctly even under --hard mode against an active run. Test by holding a writer lease in one process and running sweep --hard in another; verify the event lands and the chain is intact.
Session executor's OOM-kill blind spot
The session executor's try/finally guarantees teardown for graceful Python exit. It does NOT guarantee teardown for crash modes (segfault, OOM-kill, SIGKILL, machine reboot, network partition mid-call). For these cases the sweeper is the only safety net.
BUT: the sweeper needs a pod_handle.json artifact to find the orphaned pod. The session executor does NOT normally emit one (the handle is internal to the try/finally). Resolution: session writes a pod_handle.json at the canonical produces path immediately after provision succeeds, BEFORE entering exec. It deletes the handle on graceful teardown. If the process crashes between provision and graceful teardown, the handle is the breadcrumb the sweeper needs. The handle's presence after session.exec_result.json exists also means the teardown failed — sweeper treats this as a normal default-mode candidate.
New SC: provision via external.runpod.session with a deliberately-crashing remote script (kill -9 $$) leaves a pod_handle.json behind that the sweeper picks up.
Vibecomfy-shrink test compatibility
The vibecomfy backward-compat stop-line includes the existing test suite at vibecomfy/tests/. Specifically test_runpod_runner.py:197-224 (cancellation test that monkeypatches PodGuard). The lift must include making PodGuard injectable into ship_and_run (per "Codebase ground truth" above).
Run pytest vibecomfy/tests/ after the shrink; ALL existing tests must pass without source change. This is the canary alongside the live-script smoke.
Function naming consistency
Lifecycle's pod-launch function is launch at runpod-lifecycle/src/runpod_lifecycle/runner.py (existing) — NOT launch_pod. The plan must reference the actual name. New ship_and_run and ship_and_run_detached live alongside it in the same module.
sys.path hack
Migration scripts (scripts/migrations/sprint-3/* already do this; pattern persists) use a sys.path.insert(0, str(_REPO)) shim to import astrid.* when invoked from outside the repo. This is acceptable per existing pattern. The Astrid pack's run.py argparse dispatcher does NOT need this hack — it runs as part of astrid invocation which already has the path set up.
How the planner should use this section
Read this section BEFORE drafting the plan.
Each pre-resolved finding is a constraint. The plan must reference them where relevant (e.g., the sweeper section must explicitly say "uses Pod.is_idle() at pod.py:102-118"; the ship_and_run section must say "accepts guard_factory parameter for vibecomfy test injection").
If a finding turns out to be wrong upon deeper inspection, surface it explicitly in the plan with a rationale (don't silently override). Otherwise treat as locked.
The cost summation invariant, OOM-kill SC, and pod_terminated_by_sweep --hard SC are NEW success criteria added by this section — include them.
code
Project directory:
/Users/user_c042661f/Documents/reigh-workspace/Astrid
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").
- Each success criterion should include a `requires` field listing the capabilities needed for verification. Valid capability strings: `run_shell`, `read_files`, `run_tests`, `parse_diff`, `read_build_output`, `run_linter` (container), `drive_browser`, `inspect_runtime_ui`, `observe_runtime_logs`, `subjective_judgment`, `verify_physical_device` (human). `must` criteria MUST have non-empty `requires`. Example: `{"criterion": "All tests pass", "priority": "must", "requires": ["run_tests"]}`.
- 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.