Skip to content

Architecture

idea-to-mvp is a Gradio + LangGraph app that takes a product idea through a structured multi-agent pipeline and produces a built, tested first version. This file is the single home for how it is put together; setup lives in CONTRIBUTING.md, settings in .env.example, and the threat model in SECURITY.md.

Pipeline

  1. Research (optional, ENABLE_RESEARCH) — a researcher model searches the web with its provider's own search tool and a validated, cited ResearchBrief (competitors with links, market notes, gaps) is handed to the panel and shown in the chat (see The research step).
  2. Panel — three agents (PM, Tech Lead, Skeptic) write their opening statements in parallel, then a moderator picks who speaks next and ends the debate early once it has converged, within a turn budget of rounds × 3 (PANEL_MODE=round_robin keeps the fixed rotation).
  3. Summarizer — executive brief plus exactly 5 clarifying MVP questions.
  4. Answers gate — the graph pauses at collect_answers (interrupt()); the user's answers resume it. Each question carries a reason it matters and a suggested answer.
  5. Architect + architecture gate — two options; the graph pauses at arch_choice for a structured {option, notes} decision.
  6. Strategy — emits a validated ExecutionStrategy {mode, reasoning, workstreams, template} choosing subagents vs agent_team and the starter template the project begins from, or none (deterministic fallback strategy if the model output stays invalid; see Starter templates; EXECUTION_STRATEGY=agent_team|subagents replaces the model's mode, and the reasoning then says so, see Parallel execution).
  7. Plan gate + blueprint — pause at plan_gate (static question); {generate, notes} resumes and writes the blueprint pack in three dependency waves (PRD and architecture first, then the plan and guides written from them, then the subagents and the agent harness written from the plan); the plan writer and the harness writer also get the stack's experience library as reference data (see Experience library).
  8. Implementation gate + implementer — pause at implement_gate with a cost warning and a truthful statement of the sandbox status, permission mode, and allowed domains (a red warning card when the sandbox is off or the mode is bypassPermissions); {implement, notes} resumes. the prepare_workspace node copies the pack into the projects directory as a git repository and, when the strategy chose a starter template, lays its scaffold down on top and commits it as scaffold (its own checkpointed step, so a continued run reuses the same workspace), the acceptance_author writes a held-out acceptance suite from the PRD and the plan's public contracts and keeps it outside the workspace (see Held-out acceptance tests), the optional harness_tuning subgraph tunes the agent harness on a pilot task when the gate chose it (see Harness tuning), then it is built: one fresh Claude Agent SDK session per plan task for strategy mode agent_team, run in parallel git worktrees by the implement_plan subgraph (or one at a time by implementer when IMPLEMENTER_MAX_PARALLEL=1; see The implementation engine), or one lead session with subagents for subagents; sessions are configured by implementation/options.py and the orchestrator commits.
  9. Verification + delivery report — three read-mostly lanes (tests, quality, requirements), and a fourth (acceptance) when the version has a held-out suite, run in parallel and each returns a structured LaneReport; a verdict node folds them with the test-integrity findings (a session that deleted, skipped, or weakened a test; see Test integrity), failed rounds go to a fix node and back to verify (a bounded, checkpointed loop in which each attempt reads the earlier ones; see Verification lanes), then a deterministic delivery report (with the delivery zip and a v0.<n> git tag when verification passed) follows.
  10. Reflection (EXPERIENCE_LIBRARY) — reflect writes what the delivery's evidence showed into the stack's experience library: edit rows for what the run tried and at most one lesson for the next project of that stack (see Experience library).
  11. Iterate gate — after every delivery the graph pauses at iterate_gate with {iterate, feedback}: changes loop through change_planner and acceptance_author (a new suite for the new version) back into the same engine; finishing (or reaching MAX_ITERATIONS) ends the run (see Iteration loop). Beside that decision the gate offers Publish to GitHub, a side action that does not resume the graph (see Publishing a delivery).

The graph below is generated from the real StateGraph (uv run python scripts/gen_graph_diagram.py; a test fails if it drifts).

---
config:
  flowchart:
    curve: linear
---
graph TD;
    __start__([<p>__start__</p>]):::first
    research(research)
    summarizer(summarizer)
    collect_answers(collect_answers)
    architect(architect)
    arch_choice(arch_choice)
    strategy(strategy)
    plan_gate(plan_gate)
    implement_gate(implement_gate)
    prepare_workspace(prepare_workspace)
    acceptance_author(acceptance_author)
    implementer(implementer)
    verify(verify)
    verify_lane(verify_lane)
    verdict(verdict)
    fix(fix)
    delivery_report(delivery_report)
    reflect(reflect)
    iterate_gate(iterate_gate)
    change_planner(change_planner)
    __end__([<p>__end__</p>]):::last
    __start__ -.-> panel\3a__start__;
    __start__ -.-> research;
    acceptance_author -.-> harness_tuning\3apilot;
    acceptance_author -.-> implement_plan\3aprepare;
    acceptance_author -.-> implementer;
    arch_choice --> strategy;
    architect --> arch_choice;
    change_planner -.-> __end__;
    change_planner -.-> acceptance_author;
    collect_answers --> architect;
    delivery_report -.-> __end__;
    delivery_report -.-> iterate_gate;
    delivery_report -.-> reflect;
    fix --> verify;
    harness_tuning\3a__end__ -.-> implement_plan\3aprepare;
    harness_tuning\3a__end__ -.-> implementer;
    implement_gate -.-> __end__;
    implement_gate -.-> prepare_workspace;
    implement_plan\3afinish --> verify;
    implementer --> verify;
    iterate_gate -.-> __end__;
    iterate_gate -.-> change_planner;
    panel\3a__end__ --> summarizer;
    plan_bundle\3awrite --> implement_gate;
    plan_gate -.-> __end__;
    plan_gate -.-> plan_bundle\3awave_1;
    prepare_workspace --> acceptance_author;
    reflect -.-> __end__;
    reflect -.-> iterate_gate;
    research --> panel\3a__start__;
    strategy --> plan_gate;
    summarizer --> collect_answers;
    verdict -. &nbsp;exhausted&nbsp; .-> delivery_report;
    verdict -. &nbsp;retry&nbsp; .-> fix;
    verify -.-> delivery_report;
    verify -.-> verify_lane;
    verify_lane --> verdict;
    subgraph panel
    panel\3a__start__(<p>__start__</p>)
    panel\3aopening_turn(opening_turn)
    panel\3amerge_openings(merge_openings)
    panel\3amoderator(moderator)
    panel\3aspeaker_turn(speaker_turn)
    panel\3a__end__(<p>__end__</p>)
    panel\3a__start__ -.-> panel\3aopening_turn;
    panel\3a__start__ -.-> panel\3aspeaker_turn;
    panel\3amerge_openings -.-> panel\3a__end__;
    panel\3amerge_openings -.-> panel\3amoderator;
    panel\3amoderator -.-> panel\3a__end__;
    panel\3amoderator -.-> panel\3aspeaker_turn;
    panel\3aopening_turn --> panel\3amerge_openings;
    panel\3aspeaker_turn -.-> panel\3a__end__;
    panel\3aspeaker_turn -.-> panel\3amoderator;
    panel\3aspeaker_turn -.-> panel\3aspeaker_turn;
    end
    subgraph plan_bundle
    plan_bundle\3awave_1(wave_1)
    plan_bundle\3adoc_1(doc_1)
    plan_bundle\3awave_2(wave_2)
    plan_bundle\3adoc_2(doc_2)
    plan_bundle\3awave_3(wave_3)
    plan_bundle\3adoc_3(doc_3)
    plan_bundle\3aplan_writer(plan_writer)
    plan_bundle\3aharness_writer(harness_writer)
    plan_bundle\3areview(review)
    plan_bundle\3arevise(revise)
    plan_bundle\3arewrite_doc(rewrite_doc)
    plan_bundle\3arewrite_plan(rewrite_plan)
    plan_bundle\3awrite(write)
    plan_bundle\3adoc_1 --> plan_bundle\3awave_2;
    plan_bundle\3adoc_2 --> plan_bundle\3awave_3;
    plan_bundle\3adoc_3 --> plan_bundle\3areview;
    plan_bundle\3aharness_writer --> plan_bundle\3areview;
    plan_bundle\3aplan_writer --> plan_bundle\3awave_3;
    plan_bundle\3areview -.-> plan_bundle\3arevise;
    plan_bundle\3areview -.-> plan_bundle\3awrite;
    plan_bundle\3arevise -.-> plan_bundle\3arewrite_doc;
    plan_bundle\3arevise -.-> plan_bundle\3arewrite_plan;
    plan_bundle\3arewrite_doc --> plan_bundle\3areview;
    plan_bundle\3arewrite_plan --> plan_bundle\3areview;
    plan_bundle\3awave_1 -.-> plan_bundle\3adoc_1;
    plan_bundle\3awave_1 -.-> plan_bundle\3awave_2;
    plan_bundle\3awave_2 -.-> plan_bundle\3adoc_2;
    plan_bundle\3awave_2 -.-> plan_bundle\3aplan_writer;
    plan_bundle\3awave_2 -.-> plan_bundle\3awave_3;
    plan_bundle\3awave_3 -.-> plan_bundle\3adoc_3;
    plan_bundle\3awave_3 -.-> plan_bundle\3aharness_writer;
    plan_bundle\3awave_3 -.-> plan_bundle\3areview;
    end
    subgraph harness_tuning
    harness_tuning\3apilot(pilot)
    harness_tuning\3apropose(propose)
    harness_tuning\3aprobe_wave(probe_wave)
    harness_tuning\3aprobe(probe)
    harness_tuning\3acompose(compose)
    harness_tuning\3aselect(select)
    harness_tuning\3aadopt(adopt)
    harness_tuning\3a__end__(<p>__end__</p>)
    harness_tuning\3acompose --> harness_tuning\3aadopt;
    harness_tuning\3apilot -.-> harness_tuning\3a__end__;
    harness_tuning\3apilot -.-> harness_tuning\3apropose;
    harness_tuning\3aprobe --> harness_tuning\3acompose;
    harness_tuning\3aprobe --> harness_tuning\3aselect;
    harness_tuning\3aprobe_wave -.-> harness_tuning\3aprobe;
    harness_tuning\3apropose --> harness_tuning\3aprobe_wave;
    harness_tuning\3aselect --> harness_tuning\3aadopt;
    harness_tuning\3aadopt --> harness_tuning\3a__end__;
    end
    subgraph implement_plan
    implement_plan\3aprepare(prepare)
    implement_plan\3apick_wave(pick_wave)
    implement_plan\3arun_task_node(run_task_node)
    implement_plan\3amerge_wave(merge_wave)
    implement_plan\3afinish(finish)
    implement_plan\3amerge_wave --> implement_plan\3apick_wave;
    implement_plan\3apick_wave -.-> implement_plan\3afinish;
    implement_plan\3apick_wave -.-> implement_plan\3arun_task_node;
    implement_plan\3aprepare --> implement_plan\3apick_wave;
    implement_plan\3arun_task_node --> implement_plan\3amerge_wave;
    end
    classDef default fill:#f2f0ff,line-height:1.2
    classDef first fill-opacity:0
    classDef last fill:#bfb6fc

panel is a subgraph (see The panel below); plan_gate and implement_gate can end the run early.

The graph runs on a single checkpointer thread per session; the UI resumes interrupts with Command(resume=...). There is no phase field — UI mode is derived from the interrupt the graph is paused at.

LangGraph patterns used

Each row is a pattern, the code that implements it, and a test that would fail without it (the paths and test names are checked by tests/test_docs_sync.py).

Pattern Where Test
Human gates: interrupt() pauses the thread with a payload, Command(resume=...) continues it; autopilot auto-resumes the safe gates, never the implement gate src/idea_to_mvp/nodes/gates.py tests/test_graph_lifecycle.py::test_full_pipeline_pauses_resumes_and_declines
Durable checkpointer and resume: AsyncSqliteSaver behind GraphProvider; a paused gate survives a restart and a crashed step continues with astream(None, config) src/idea_to_mvp/graph.py tests/test_persistence.py::test_run_that_crashed_mid_step_continues_from_its_checkpoint
Send map-reduce (1/4): the panel's three opening statements, merged in canonical order src/idea_to_mvp/nodes/panel.py tests/test_panel.py::test_openings_run_in_parallel_and_land_in_canonical_order
Send map-reduce (2/4): blueprint documents in dependency waves, one task per document src/idea_to_mvp/nodes/blueprint_graph.py tests/test_blueprint_dag.py::test_each_wave_requests_all_of_its_documents_concurrently
Send map-reduce (3/4): independent plan tasks in parallel git worktrees, merged back in task order src/idea_to_mvp/nodes/implement_graph.py tests/test_implement_parallel.py::test_the_demo_plan_runs_its_independent_tasks_in_parallel_and_merges_them
Send map-reduce (4/4): the verification lanes (three, four with a held-out acceptance suite) src/idea_to_mvp/nodes/verify.py tests/test_verify_graph.py::test_a_clean_verification_runs_three_lanes_in_parallel_and_needs_no_fix
Reducers for parallel writers: dict-merge channels (opening_turns, blueprint_docs, task_results, lane_reports) so concurrent branches add to state instead of overwriting it src/idea_to_mvp/state.py tests/test_panel.py::test_panel_usage_is_recorded_once_in_the_parent_state
Subgraphs with a narrower input schema (PanelInput, BlueprintInput) so accumulating channels are not counted twice; streamed with subgraphs=True and folded by merged_values src/idea_to_mvp/nodes/panel.py tests/test_panel.py::test_the_panel_is_one_node_whose_llm_nodes_carry_the_retry_policy
Structured output: Pydantic schemas, one retry with the validation error, then a deterministic fallback src/idea_to_mvp/llm/structured.py tests/test_structured.py::test_retries_once_with_the_validation_error_then_succeeds
Evaluator-optimizer loop (1/2): a critic reviews the blueprint and only the documents it blocks are regenerated, up to MAX_BLUEPRINT_REVISIONS src/idea_to_mvp/nodes/blueprint_graph.py tests/test_blueprint_dag.py::test_blockers_regenerate_only_the_named_documents_then_the_pack_is_reviewed_again
Evaluator-optimizer loop (2/2): verify, then a checkpointed fix step, then verify again, bounded by MAX_FIX_ATTEMPTS src/idea_to_mvp/graph.py tests/test_verify_graph.py::test_every_fix_attempt_is_its_own_checkpointed_graph_step_until_the_attempts_run_out
Retry policies: LLM_RETRY re-runs model nodes on transient errors only (rate limit, timeout, 5xx) src/idea_to_mvp/resilience.py tests/test_resilience.py::test_node_is_retried_on_transient_errors_until_it_succeeds
Custom stream events: get_stream_writer() publishes live implementation events beside the updates stream src/idea_to_mvp/nodes/implement.py tests/test_implement_engine.py::test_custom_events_stream_while_the_node_runs
Token streaming (messages mode), attributed to a speaker through the model's metadata src/idea_to_mvp/ui/view.py tests/test_panel.py::test_demo_panel_turns_stream_token_by_token_with_their_speaker
Propose–Probe–Compose subgraph (Harness²'s Behavioral Contrast): an optional stage that fans out twice with Send (two proposals, then two probes in parallel worktrees) between a base run and a composer for whom keeping the base is a valid answer, runs a blind selection of the pilot builds beside the composer (a join edge waits for both), and asserts its ledger count src/idea_to_mvp/nodes/harness_tuning.py tests/test_harness_tuning.py::test_the_demo_tunes_the_harness_on_a_pilot_before_the_first_task
Cross-thread memory: what one thread's delivery taught is written to a store outside the checkpointer (the experience library, per stack) and read by the next thread of that stack; read once into the state, so a resumed run and its reflection see the same entries src/idea_to_mvp/nodes/reflect.py tests/test_library.py::test_a_second_demo_project_of_the_stack_is_planned_and_tuned_with_the_first_ones_lesson
Conditional entry edge: an optional node that the graph skips unless enabled src/idea_to_mvp/nodes/research.py tests/test_research.py::test_research_runs_only_when_enabled
Cancellation: Gradio's cancels= stops the run between checkpoints; the thread keeps its last checkpoint and the UI offers Continue src/idea_to_mvp/ui/service.py tests/test_stop.py::test_a_stopped_run_continues_to_the_next_gate

Modules

Everything lives in the idea_to_mvp package under src/.

Module Role
config.py Pydantic Settings loaded from .env; get_settings(); output directories (exports_dir, blueprints_dir, projects_dir under output_dir); PROFILES, the model choice of every role and of each kind of agent session (implementer_model, verifier_model, escalation_model) per model_profile (fast / balanced / quality), built from the model catalog; balanced equals the field defaults, a test keeps them equal
model_catalog.py, models.toml The model catalog: one validated entry per model (provider, id and aliases, tier, status, $ per million tokens in / out / cached, context window, max output, structured-output / sampling / web-search support, checked date, source URL), the model each profile gives each role and each kind of agent session (AGENT_ROLES: implementer, verifier, escalation), and the token shape of a typical run. get_catalog(), ModelCatalog.find / estimate_run (a profile's models, any of them replaced by the configured ones), accepts_sampling (the catalog decides for a listed model, a name pattern for the rest), parse_model_id, list_provider_models (each provider's models API, key in a header) and check_models. It imports nothing from the package, so config.py builds on it
model_report.py idea-to-mvp models: roles x profiles, the price list, the estimated cost of a typical run, and with --check the live comparison with each provider's list (exit 1 for an unknown or deprecated model)
state.py IdeaDiscussionState TypedDict — the single shared state contract — and make_initial_state()
graph.py build_graph(checkpointer): nodes and conditional routing; open_graph() (SQLite/memory checkpointer lifecycle), GraphProvider (lazy, loop-safe handle for the UI), pending_interrupt(), read_thread() (a thread's ThreadView: values with a running subgraph folded in, pending gate, next nodes; shared by the UI and the CLI), update_thread() (write to a thread's state outside a run and keep the gate it waits at)
resilience.py LLM_RETRY: LangGraph retry policy (3 attempts, backoff) for transient errors only (is_transient)
usage.py UsageRecord, the @with_usage(role=...) node decorator (prices every call), summarize_usage (planning spend, agent spend, and the calls left unpriced, apart)
pricing.py Dollars for model calls from the catalog or the MODEL_PRICES_FILE override (call_cost, price_for, load_price_overrides), the earlier-projects task history (task_cost_history), and the implement gate's dollar range (estimate_run_cost, CostRange)
observability.py apply_tracing_env(): exports only LANGSMITH_*/LANGCHAIN_* from .env
doctor.py, cli.py idea-to-mvp doctor (keys, models, agent CLI; offline it also warns about a model the catalog does not know, has no price for, or marks deprecated) and the command-line entry point (doctor, models, run, resume, sessions, publish, bench; a usage error exits 1, because 2 means "delivered with failures")
publish.py Publishing a delivery to GitHub (see Publishing a delivery): plan_publish (the PublishPlan the user confirms: repository, visibility, branch, commit, tags, files, and the problems that forbid it), its fingerprint, publish_plan (creates the repository and pushes for a confirmation that quotes the fingerprint), render_plan, publish_options (what the iterate gate's payload tells the UI), and the clients behind GitHubClient: RestClient (a token) and GhClient (the gh CLI), chosen by make_client; LLM-free, tests fake the clients
headless.py Headless runs (see Headless runs): HeadlessOptions (the gate flags), decide (a gate's resume value from the flags, or why the run stops there), drive / run_idea / resume_thread (stream the thread and answer the gates the flags answer), summarize (RunSummary with the exit code), render_summary, and the sessions rows
mcp_server.py The MCP server behind idea-to-mvp mcp (see MCP server): create_server (an MCPServer with the five tools and a lifespan that opens the graph), Orchestrator (the tools' logic: start_run, get_status, answer_gate, list_sessions, get_delivery, and the background runs it keeps), GateAnswer / build_resume (the tool's arguments as the resume value of the gate they answer, and the confirm_spend rule), serve; drives headless.py, no graph code of its own
bench.py The end-to-end benchmark behind idea-to-mvp bench (see Benchmark): BenchIdea / load_ideas, parse_overrides and applied_env (the settings of one run), take_snapshot / snapshot_differences, idea_budget, score_run (a headless run's state as an IdeaResult, scored or unscored), totals, run_bench (the ideas of a run folder, saved after each), compare_runs, and the renderers; drives headless.py, no graph code of its own
sessions.py SessionRegistry: the list of resumable sessions (title, stage, gate) next to the checkpoints; record keeps a thread's row in step with its checkpoint (the UI and the CLI both call it)
nodes/ One module per pipeline concern: research (the optional research step), panel (the panel subgraph), discussion (one speaker turn), blueprint_graph (the blueprint subgraph) with its node functions in blueprint, summary, architecture, strategy, gates (all interrupt() gates and their routers), blueprint, implement, verify (the verify / verify_lane / verdict / fix steps), report, iterate (the iterate gate and change_planner), reflect (the reflect node and route_to_reflect), acceptance (the acceptance_author node and lanes_for, the lanes of a round), harness_tuning (the harness tuning subgraph and route_after_acceptance); common holds helpers shared with the UI, preferences_block (the one prompt section that carries the user's project preferences), and structured_with_repair (a structured call checked by a function, with one repair attempt; harness tuning and the reflection use it)
llm/ Model access: providers.py (vendor SDK construction and quirks), runtime.py (get_runtime(role_key)), invoke.py (invoke_text, and invoke_grounded for a web-search call, which also returns the URLs the provider cited), structured.py (invoke_structured); providers.web_search_tool and runtime.search_runtime bind a provider's native search tool
schemas.py Pydantic models exchanged between agents (ModeratorDecision, QuestionSet, ArchitectureProposal, ExecutionStrategy) and their markdown renderers, plus ProjectPreferences (user input, not a model output)
prompts_common.py The prompt blocks the judging and changing agents share (ideas from Harness²; imports nothing from the package): EVIDENCE_BOUNDARY, ANSWER_FREE, RUBRIC_ORDER / RUBRIC_CRITERIA, NO_CHANGE_REVISION, TEST_INTEGRITY (see Prompt hardening)
roles.py RoleSpec registry: system prompts and provider/model/token wiring per agent; resolve_role_model(settings, role) is the one place that decides which provider and model a role runs on (an explicit *_PROVIDER / *_MODEL wins over the profile, known through model_fields_set; llm.get_runtime, doctor, and the UI all use it); resolve_agent_model(settings, kind) does the same for an agent session (its own *_MODEL, else a pinned IMPLEMENTER_MODEL, else the profile)
blueprints.py Blueprint document specs (prompt, dependency wave, upstream needs, revisable), prompt_for(), and write_bundle() (LLM-free)
templates/ The stack starter templates (see Starter templates): one folder each with template.toml and the scaffold in files/; the package code is load_templates / get_template / normalize_template, template_files and apply_template (lay a scaffold into a workspace), pack_template (the choice recorded in a pack's STRATEGY.json), catalog_text and prompt_block (what the strategy step and the blueprint documents are told), with_template_commands, and missing_tools (for doctor); imports only plan and harness_pack
library.py The experience library (see Experience library): the reflector's Reflection / EditRow / Lesson schemas and reflection_problems, domain_for, the entry files (write_entry, load_entries, forget, list_domains), render_index (with how later projects judged each lesson), snapshot and reference_block (what a run reads), and the leak check (forbidden_for, leaks; write_entry refuses an entry that quotes an acceptance suite or holds a secret); LLM-free
harness_tuning.py Harness tuning's pure helpers (see Harness tuning): the HarnessEdit and Composition schemas, pick_pilot, session_budget, edit_problems (an edit checked against the harness validator and the rules of an edit), edit_diff, the proposal and composition prompts, unsafe_choice (an edit whose run delivered nothing is not adopted over a base run that delivered), and tuning_identity (the ledger count); LLM-free
pilot_selection.py Blind selection of harness tuning's pilot build (see Harness tuning): the Selection / BuildScore schemas, candidates, anonymize (seeded shuffle to A/B/C), redact, build_section and selection_prompt, selection_problems, score_key (rubric order), and overrule (a clean build wins over one whose tests failed or were weakened); LLM-free
harness_pack.py The generated project's agent harness (see The agent harness): HarnessSpec (the harness writer's answer), render_harness / fallback_harness, validate_harness (the deterministic validator, also meant for proposed harness edits), read_harness / write_harness / refresh_commands on disk, and ensure_project_settings (the fixed .claude/settings.json restored before a session loads it); LLM-free
plan.py The typed execution plan (Plan, PlanTask, contracts, commands), validate_plan, execution_waves, render_plan_markdown, fallback_plan, parse_plan_markdown (an edited plan.md back into a Plan); iterations: ChangePlan, append_iteration_tasks, iteration_of, fallback_change_tasks (LLM-free)
delivery.py make_delivery_zip (project zip without dependencies, secrets, symlinks) and tag_iteration (v0.<n> git tag); LLM-free
blueprint_review.py CritiqueReport/Issue and the pure helpers that pick revision targets and render REVIEW.md (LLM-free)
implementer.py Claude Agent SDK sessions: the lead/team implementation modes and iter_agent_messages, the one place a session is streamed (options and workspaces come from implementation/)
implementation/ executor.py (task-by-task engine, BudgetTracker, conflict resolver), scheduler.py (ready tasks, blocked tasks, DAG width), merge.py (worktrees, task commits, merges), events.py (live ImplEvents from SDK messages), trajectory.py (SessionLog: every session's stream as a file, and the console rebuilt from those files), ledger.py (one row per session, plus harness tuning's model calls, and the check against usage), reports.py (the JUnit / coverage files of the tests lane parsed into evidence that overrules its claim; with cases=, the same pass also lists each test case with its assertion message, never the failure body), acceptance.py (the held-out suite: AcceptanceSuite, suite_dir outside the workspace, save_suite / load_suite, make_scratch (the throwaway copy the lane runs in), requirement_status, acceptance_failures, and the FIX_NOTE a fix session gets with acceptance failures), integrity.py (the test-integrity guard: SessionWatch snapshots the test files around a session, compare, count_finding, review, blocking), fixes.py (the contrastive fix loop: classify_failures, the <notes> contract (parse_notes, notes_problem), the attempt folders (write_attempt, write_after, evidence_block), and the attempt history (history_entry, close_entry, history_markdown)), progress.py (resumable per-task results), executor.run_pilot_rollout (harness tuning's pilot sessions), options.py (build_agent_options: the one place that sets cwd, model (from the session's kind: task, verifier lane, or escalation), budget, OS sandbox, guard hook, scrubbed env, and which settings load: the project harness for every session but a verifier's), guard.py (PreToolUse denylist), verify.py (the verification lanes, the acceptance lane's runner (_run_acceptance), LaneReport parsing and merging over the round's expected lanes, the fix session), workspace.py (copy bundle without node_modules/.venv/…, git init, orchestrator commits, workspace_tree); threat model in SECURITY.md
evals.py The opt-in blueprint eval behind scripts/eval_blueprint.py: judge_pack scores a pack's PRD, architecture, and plan on a three-criterion rubric (JudgeScores; no fallback, so a failed judge call is an error, never an invented score), generate_pack runs the pipeline in autopilot up to the implement gate, render_table prints the result. Needs --live; the offline structural check of the same packs is tests/test_golden_blueprints.py
exporter.py Full-session exports (build_session_markdown, build_session_json, save_session_export): built from the derived transcript, so they reproduce the whole run (panel, summary, questions, answers, architecture, strategy, blueprint file list, implementation log, verification lanes, delivery report, decisions) in Markdown and JSON
demo/ Offline demo mode: DemoChatModel + fixtures.py (canned, idea-aware output per role) and a stand-in implementation stage and verification lanes
text_utils.py normalize_content() shared by the LLM layer and the UI service
ui/app.py Gradio entrypoint (make_ui(), main()), started by idea-to-mvp / python -m idea_to_mvp
ui/service.py SubmitService: async generator bridge between Gradio and the graph; renders every response from checkpointed state
ui/view.py Pure projection of graph state to the UI: transcript_from_state, mode_from_state, status and stage helpers, and the panel streaming helpers (panel_token, LiveTurns, TurnInfo) (no Gradio)
ui/render.py HTML helpers for chat cards (thinking_block, turn_block, openings_row, moderator_banner, research_card, tuning_card, ...)
ui/components.py Pure HTML components: stage_stepper (steps with status and elapsed time), usage_badge, stage_header (the sticky bar), model_profile_markdown, the example ideas
ui/console.py Pure renderers for the implementation tab: render_task_board (pending / running / done / failed), render_console (the live log), render_cost_meter, running_tasks
ui/dashboard.py render_dashboard: the delivery dashboard (lane verdict cards, requirements table, cost/time, how to run)
ui/library.py The Experience library panel's text (library_markdown: a stack's index and every entry's edit rows) and its entry list (entry_choices); the service's library_panel / forget_library_entry drive it
ui/artifacts.py The read-only file viewer (read_workspace_file, confined to the workspace), the blueprint zip, and the key that tells when the artifacts panel must refresh
ui/gates.py GateSpec / GATES: the form of every gate (widgets, render, build_resume, validate, echo, next_step), the blueprint editor's save_blueprint_file, and the layout helpers that map the flat Gradio inputs/outputs to a gate
ui/theme.py build_theme() and the CSS (all colours are variables, defined for light and dark)

State contract

IdeaDiscussionState (state.py) carries: user_idea, discussion_history (LangChain messages, add_messages reducer), summary, questions + generated_questions (the MvpQuestion dumps and their numbered-line rendering), user_answers, architecture_proposal + architecture (the ArchitectureProposal dump and its markdown rendering), arch_choice, execution_strategy (an ExecutionStrategy dump, with the template name), plan_decision, implement_decision ({implement, notes, parallel, harness_tuning}: parallel is the parallelism picked at the gate, 0 = the setting; harness_tuning whether to tune the harness first, absent in a decision recorded before the choice existed, which then follows HARNESS_TUNING), blueprint_docs (path → generated document, filled in parallel), blueprint_review (the critic's latest {approved, revisions, issues}), project_bundle_dir/files/summary, workspace_dir, implementation_log, task_results (plan task id → TaskResult, merged by a dict reducer), lane_reports (verification lane → LaneReport dump, filled by the parallel lanes through a dict-merge reducer), finished_tasks (sessions awaiting their merge in the parallel engine), verification ({passed, attempts, report, lanes, integrity, history, environment}; integrity is the TEST_INTEGRITY mode the verdict was given under, history has one row per fix attempt of this version, and environment is set when the loop stopped because no change to the project could fix what is left), integrity_findings (finding id → IntegrityFinding: what a task, resolver, or fix session did to the tests, or a drop in the test count, with its status open / restored / justified; a dict-merge reducer, kept across versions), integrity_test_count (the tests the last test report listed, None before one), acceptance (the held-out suite of the version being built: {iteration, dir, files, covers, note}; {} when ACCEPTANCE_TESTS is off), harness_tuning (the tuning record, filled by its parallel branches through a dict-merge reducer: status (running / done / skipped with a note), pilot, budget_usd, base (a ProbeResult), inv / dom (each edit with its probe), compose ({decision, proposed, overruled, notes, rationale, files}), selection ({status, builds, proposed, choice, arm, overruled, scores, rationale, called, note, landed, task_commit}: status is chosen / none / skipped, builds maps a build id to the harness that made it), adopted, commit, changed_files, ledger; {} until the stage runs), library (the experience library as read before the blueprint, library.snapshot: {domain, index, lessons, entries}; {} when it is off), reflection (what the latest delivery's reflection recorded: {status, domain, entry, lesson, edits, dropped, rationale, note}, status one of recorded / no_entry / skipped / failed / refused), delivery_report, delivery_zip, publication (where the delivery was published, {repo, url, visibility, branch, commit, tags, files, backend, published_at}, {} until it is), iteration (the version being built: 1 = v0.1), change_requests (the feedback of each later iteration), iterate_decision, no_change ({request, reason} when the change planner found nothing to build, else {}), spent_before_iteration (agent cost of earlier versions, so each has its own budget), cost_estimate (the implement gate's CostRange for the first version, kept for the dashboard), research (a ResearchBrief dump, {} when off or empty), preferences (a ProjectPreferences dump: platform, stack hints, deploy target, must use, must avoid; set once by make_initial_state), stage, next_speaker, max_rounds (the panel's turn budget: rounds × speakers), turn_count, panel_mode, opening_turns (speaker → opening statement; filled by parallel branches through a dict-merge reducer), convergence (the moderator's latest {converged, reason}). Gate decisions are small TypedDicts (ArchChoice, PlanDecision, ImplementDecision).

The panel

nodes/panel.py builds the panel as a LangGraph subgraph, mounted in the parent graph as the single node panel:

  • Openings in parallel. The start edge fans out with Send("opening_turn", ...), one per speaker, so the three opening statements cost one call latency instead of three. A speaker's opening sees only the idea (the others are being written at the same time). merge_openings then appends them to the transcript in canonical PM, Tech Lead, Skeptic order whichever finished first.
  • Moderated debate. From then on moderator → speaker_turn alternate. The moderator (role moderator, a cheap structured ModeratorDecision call) picks the next speaker and may declare the debate converged; its reason is shown in the chat as the convergence note. Code, not the prompt, enforces the hard rules: nobody converges before every speaker has had two turns, nobody speaks twice in a row (the least-heard speaker is used instead), and max_rounds is a hard cap on turns. If the moderator's output stays invalid, the deterministic fallback keeps the panel in rotation.
  • Round robin. With panel_mode="round_robin" the start edge goes straight to speaker_turn, which loops in the fixed PM → Tech Lead → Skeptic order until the cap; no moderator, no parallelism.
  • State across the boundary. The subgraph shares IdeaDiscussionState with the parent but declares a narrower input schema (PanelInput) that leaves out usage and opening_turns. Without it the parent's accumulating usage channel would receive its own records back from the subgraph and count them twice. The LLM nodes inside the subgraph carry LLM_RETRY; the panel node itself does not (a retry would redo every turn), and because the subgraph inherits the parent checkpointer, a crash mid-panel resumes from the last finished turn.
  • Streaming in the chat. SubmitService adds "messages" to the stream modes; view.panel_token keeps only the tokens of the two turn nodes (opening_turn, speaker_turn) and names the speaker from the role that llm.get_runtime puts in every chat model's metadata (the three parallel openings interleave, and a token carries no other speaker). view.LiveTurns accumulates them per speaker into live bubbles (re-rendered at most every _TOKEN_INTERVAL_SECONDS); a finished opening stays as it is until merge_openings makes the three of them part of the checkpoint, and any other committed step clears the buffer. The buffer is a transient overlay like the progress indicator: it never enters state. The demo model implements _stream, so demo runs stream like real ones. In the chat the openings render as one row of three cards, the moderator's convergence note as a slim banner, and turns older than the last round are collapsed.
  • Concurrency cap. graph.run_config(thread_id, max_concurrency=...) (from LLM_MAX_CONCURRENCY) bounds how many model calls parallel branches keep in flight.

The research step

nodes/research.py is one node in front of the panel; route_research sends the run to it from START only when ENABLE_RESEARCH is on (otherwise straight to panel, as before). It makes two calls because providers cannot combine web search with structured output: the researcher runs with its provider's own search tool bound (web_search_tool: Anthropic's versioned web_search, OpenAI's built-in web_search, Gemini's Google Search grounding; the provider runs the searches, nothing in this repo executes a tool) and invoke_grounded returns its notes plus the URLs it cited; then a plain invoke_structured call, with no tools, condenses the notes into a ResearchBrief.

  • Untrusted by construction. The notes are quoted to the extraction call as fenced data, the extraction call has no tools, and the brief is validated (schemas.ResearchBrief): competitors without an http(s) URL are dropped, fields are clipped, lists are capped, and sources keep only http(s) links (cited URLs are merged in). nodes.common.research_block hands the brief to the panel's prompts as reference data, not instructions; the chat card (ui.render.research_card) escapes everything and links with rel="noopener noreferrer".
  • Optional means optional. A transient error is retried by LLM_RETRY like any model node; any other failure logs a warning and leaves research empty, so the run goes on. doctor checks the researcher only when research is enabled.
  • Demo mode. The demo model ignores the bound tool and answers from demo/fixtures.py (researcher, ResearchBrief), so ENABLE_RESEARCH=true DEMO_MODE=true runs offline.

The blueprint pack

nodes/blueprint_graph.py builds the pack as a second subgraph, mounted as the parent's plan_bundle node. It is an evaluator-optimizer pipeline:

  • Dependency waves. Every document is generated from the shared context block plus the upstream documents it needs (BundleFileSpec.needs, injected by blueprints.prompt_for under ## Upstream document: <path> headings, each truncated at a line break with a [truncated] marker), so the plan is written from the real PRD and architecture and the subagent definitions from the real plan. A wave starts when the previous one is done and its documents are written concurrently: (1) PRD.md, ARCHITECTURE.md; (2) README.md, AGENTS.md and the contracts/, application/, quality/ guides, and the plan; (3) .claude/agents/<workstream>.md (none when the strategy has no workstreams) and the agent harness (harness_writer, see The agent harness). Each wave_n node is a no-op that fans out with Send, one task per document; the static edge out of the workers fires once the whole wave is done. A worker stores {path: text} in blueprint_docs (an empty reply becomes the document's fallback right there, so later documents read what will really be written).
  • The plan is typed data. The plan_writer node (role plan_writer) produces a plan.Plan through invoke_structured: contracts, tasks (T01…, depends_on, requirement_ids, contracts in/out, acceptance, tests, coverage, handoff), and the project commands. plan.validate_plan then checks it deterministically: duplicate or malformed ids, unknown dependencies, cycles, unknown workstreams or contracts, requirement ids missing from the PRD, P0 requirements no task covers, workstreams with no tasks, an empty test command. Any findings are fed back for one repair attempt (kept only if it leaves fewer problems). If the model never produces a valid Plan, a deterministic fallback_plan is used. plan.execution_waves turns the task graph into topological layers for the parallel execution to come. plan.json is the source of truth; plan.md is rendered from it by render_plan_markdown. Scope budget. The plan writer's prompt sizes the build, never its quality: it plans every P0 requirement (all requirements when none is marked P0) in full, adds no feature or tooling the PRD does not require, groups the work into normally 3 to 5 coherent tasks, and asks for a test per acceptance criterion (one test file per module, no duplicate tests of one behaviour) with coverage_target kept at 80. It exists because a live run planned a one-screen log as 4 tasks that wrote 37 test files and took 37 minutes in one serial session (tests/test_blueprints.py::test_the_plan_writer_is_given_a_small_mvp_scope_budget).
  • Critic and revise loop. After the last wave the review node cross-checks PRD ↔ ARCHITECTURE ↔ plan ↔ subagent prompts: the deterministic plan problems that survived the repair become blockers, and a critic model (role blueprint_critic, a structured CritiqueReport) adds its own issues, each a blocker or a warning on a named file. A report is approved exactly when it has no blockers, whatever the model claimed. While blockers name a regenerable document (every document but the harness, which its own validator guards) and MAX_BLUEPRINT_REVISIONS allows, revise regenerates only those documents, with the issues and their previous version appended to the prompt, and the pack is reviewed again. A stale dependent (subagents of a revised plan) is not regenerated automatically; the next review reports it. When no more revisions are possible, the remaining notes are written to REVIEW.md in the bundle, listed in the pack summary, and shown at the implement gate (the plan gate comes before the pack exists, so the implement gate is where the user first approves it).
  • Writing. The final write node calls the deterministic blueprints.write_bundle(). As with the panel, the subgraph takes a narrower input schema (no usage, blueprint_docs, or blueprint_review), the retry policy sits on the model nodes, and a crash mid-pack resumes at the failed step without regenerating finished ones. The pack lands in a timestamped folder in blueprints_dir: README.md, PRD.md (numbered requirements), ARCHITECTURE.md, AGENTS.md plus scoped contracts/, application/, quality/ guides, plan.json (the validated task graph, source of truth) with plan.md (rendered from it), .claude/agents/*.md (one subagent per workstream), the agent harness (CLAUDE.md, the check script, .claude/settings.json, .claude/skills/*/SKILL.md, and the guardrails section of AGENTS.md), STRATEGY.json, and REVIEW.md when review notes remain. Each document has its own system prompt, wave, and upstream needs in blueprints.py.

The agent harness

The documents say what to build; the harness gives every agent session the same tools for how (the harness components of Harness², arXiv:2610.14224: guardrails, tool guidance, skills, deterministic scripts; the code and prompts are this project's own). harness_pack.py owns it:

  • What a pack carries. CLAUDE.md (deterministic: points to AGENTS.md, lists the plan's commands between markers, the skills with their triggers, and the tool guidance), check.sh under scripts/ (deterministic, from plan.commands: install, lint, then the test report command or the plain test command; a failed install stops, a failed lint does not stop the tests so the report is always written, and named steps run alone: bash scripts/check.sh install test), .claude/skills/<name>/SKILL.md (frontmatter name / description plus numbered steps), a marked Guardrails section appended to AGENTS.md (six fixed rules plus up to a few stack rules), and the fixed .claude/settings.json (PROJECT_SETTINGS: no hooks, no permissions, project MCP servers not approved).
  • The harness writer. Wave 3's harness_writer node (role harness_writer, on the architect's model, PLAN_MAX_TOKENS) reads the architecture and the rendered plan (not plan.json, which only supplies the commands to check against) and returns a HarnessSpec: skills, tool guidance, and stack guardrails. Its answer is rendered and validated; problems go back once as a repair prompt, and an answer that still fails (or a failed call) is replaced by fallback_harness, a check skill and, with a run command, run-the-app. The answer is kept in blueprint_docs under harness.json and never written into the pack; write_bundle renders it for the final plan (a revised plan may have changed the commands) and falls back if it no longer validates. Editing plan.md at the implement gate re-renders the check script and the commands section of CLAUDE.md (refresh_commands).
  • The validator. validate_harness(files) reads text only: every file in the harness surface (CLAUDE.md, the four AGENTS.md, top-level scripts, .claude/settings.json, .claude/skills/<kebab-name>/SKILL.md, .claude/agents/*.md; no .., no absolute path), the required files present, the settings exactly PROJECT_SETTINGS, one to MAX_SKILLS skills, each with a frontmatter name equal to its folder and a description that names a trigger ("Use when ..."), every script a skill or CLAUDE.md invokes present, the guardrails section under GUARDRAILS_BUDGET and the always-on text (CLAUDE.md, the guardrails, every skill description) under ALWAYS_ON_BUDGET characters. tests/test_golden_blueprints.py validates the harness of every golden pack.
  • Who loads it. Task, fix, and merge-resolver sessions run with setting_sources=["project"] and skills="all", so Claude Code loads the workspace's CLAUDE.md and skills; build_agent_options first restores an existing .claude/settings.json (ensure_project_settings), and the guard refuses agent writes to .claude/settings*.json and .mcp.json, so a task cannot grant the next session a hook or a permission. Verification lanes (verifier) load nothing: they judge the work, and text an agent may have rewritten must not become a judge's instructions. The task and fix prompts ask for bash scripts/check.sh before finishing; with the script present, the tests lane runs bash scripts/check.sh install test and the quality lane bash scripts/check.sh lint. The orchestrator never runs the script itself.

Harness tuning

The harness a pack ships is the harness writer's best guess before any agent has worked in the project. HARNESS_TUNING=pilot (or the implement gate's checkbox) tunes it on one real task first: Harness²'s Behavioral Contrast, task-level Propose–Probe–Compose (Google Research, arXiv:2610.14224, Apache-2.0; the code and prompts are this project's own). The harness_tuning subgraph (nodes/harness_tuning.py, helpers in harness_tuning.py) runs between acceptance_author and the engines, only for the first version and only once (route_after_acceptance):

pilot ─Send×2→ propose → probe_wave ─Send×2→ probe ─┬→ compose ─┬→ adopt
  │                                                 └→ select ──┘
  └─ skipped (no git, no plan, no budget) → END
  • Pilot and base run. pick_pilot takes the first-wave task with the most dependents (direct and indirect; ties go to more direct dependents, then plan order). The base run builds it under the pack's harness in a worktree (pilot-base, made like a parallel task's) with the task prompt, then a tests lane runs there (run_lane(work_dir=...), judged by its JUnit report as usual). A run that changed no file "delivered nothing" and gets no lane. Sessions are pilot / pilot_lane ledger rows with trajectories pilot-<arm>.md / pilot-<arm>-tests.md, and usage records with the role pilot; their events show as pilot:<arm> in the console, never as the plan task.
  • Propose. Two structured calls in parallel (role harness_editor, on the architect's model), one per kind: INV (how the agent works: workflow order, tool use, a helper script under scripts/, stop conditions) and DOM (what a practitioner of the stack knows: skills, conventions, contracts). Each reads the current harness, the pilot task, what the base run delivered, and its trajectory (head and tail kept within a budget, fenced as data), plus the stack's experience library as reference data when it has entries (see Experience library), and returns a HarnessEdit: whole-file contents of at most four harness files (an empty content removes a file) with the trajectory moments that motivate it, or no files when nothing points to a better harness. edit_problems checks the edited harness with validate_harness (problems the base already had do not count), refuses the check script (the verdict's script) and .claude/settings.json, and keeps every base guardrail; one repair attempt with the problems, else the candidate inherits the base harness and says so.
  • Probe. The pilot task is built again under each candidate in its own worktree (pilot-inv, pilot-dom; the candidate's files are committed there first, so the run's diff is its own work, and a candidate that cannot be committed fails the step instead of being counted as the session's work), in parallel, each with its tests lane. Worktree creation and removal take a lock, since both probes reach git at once. Harness files are never written through a symbolic link: such a path is skipped with a warning.
  • Compose. One structured call (role harness_composer) gets both edits as diffs against the base and the three runs (delivery, tests lane, cost, turns, trajectory) and returns a Composition: keep_base, adopt_inv, adopt_dom, or merge (with the composed files), notes in the kept | revised | dropped -> edit -> evidence shape, and a rationale. Keeping the base is a valid answer. The orchestrator overrules to keep_base when the decision adopts an edit whose run delivered nothing while the base run delivered (unsafe_choice; the prompt allows "overwhelming evidence", the code does not), when a merge still fails edit_problems after one repair, or when the adopted edit changes nothing.
  • Select (Harness²'s blind selection, beside the composer: both run once the probes are in, and adopt waits for both). The three builds are not thrown away. The ones that delivered are shuffled with a seed made from the workspace, the pilot, and their commits (so a retried or resumed step names them the same way) and named A, B, C (pilot_selection.anonymize); one structured call (role pilot_selector, on the architect's model) gets the task, PRD.md, and per build the files it changed, its diff against its own parent commit (so a candidate's harness commit is not part of it), its tests-lane verdict, and what its session did to the tests, with every pilot worktree path and pilot-<arm> name replaced by [hidden] (redact); never its trajectory, its summary, its cost, or its harness. It returns a Selection: scores of 1 to 5 per rubric criterion (delivery, conformance, fidelity, consistency, operational fitness, finish) for every build, a choice (none is valid), and a rationale; an answer that chooses an unknown build or scores a build not exactly once gets one repair, else no build is selected. The orchestrator overrules a choice whose tests did not pass, or whose session weakened the tests (the pilot sessions are watched by the integrity guard like task sessions), when another build is clean: the best-scored clean build is taken, compared criterion by criterion in rubric order (overrule). No call is made when no run delivered, or when strategy subagents builds the plan with one lead session, which takes no task's result.
  • Adopt. The chosen files are written into the workspace and committed as harness: tuned (pilot T0x), before T01 (changed_files lists what was written). Then the selected build is applied on top as the pilot task's commit, T01: <title> (pilot build B, selected) (merge.apply_commit: a cherry-pick of the build's own commit, refused on a dirty tree and undone on a conflict, which happens when the session edited a harness file the tuned harness also changed), and the task is recorded done in progress.json with its turns, its integrity findings, and a cost of $0 (its cost is the tuning's, already deducted, so the budget never counts it twice). Both engines skip a done task, so the pilot task is not built again; when no build was selected or it does not apply, the engine builds it as before. Then the worktrees are removed. The ledger must hold exactly three pilot rows, one pilot_lane per run that delivered, two proposal rows, one compose row, and one select row when the selector was called (tuning_identity), and their cost must equal the usage the stage recorded; otherwise the evidence is not trusted: the base is kept and no build is used (a run resumed after a crash in the middle of a probe can add a row and land here).
  • Budget. Each of the six sessions may spend min(IMPLEMENTER_MAX_TASK_USD, IMPLEMENTER_MAX_TOTAL_USD / 2 / 6) (session_budget); below $0.25 the stage is skipped with a note. What they spent counts against the whole-run budget: verification sees it in usage, and every engine (the task engines and the lead session of strategy subagents) deducts ledger.tuning_spend from what it may spend; the engines emit no cost event of their own for it, since the pilot sessions already put theirs on the stream. When tuning is chosen at the gate, the stored cost_estimate includes its sessions (pricing.with_tuning; marked harness_tuning, and the dashboard says "incl. harness tuning"), so the dashboard compares a tuned run's agent spend with both. The four calls are planning spend.
  • Where it shows. The chat shows a Behavioral contrast card (ui/render.tuning_card, built from harness_tuning in state): the harness adopted and its commit, what became of the pilot builds, the three runs side by side (delivered, tests, cost, turns, build id, the selected one marked), what each edit changed with the trajectory moments its editor named, the composer's notes and rationale and any overrule, the selector's scores with the build ids revealed, and the spend (pilot sessions and planning calls apart, from the probes and the ledger). The session export and a stage that was skipped use the Markdown version (ui/view.tuning_markdown). Demo mode runs the whole stage offline: the demo editors add a skill each, the demo composer merges both, and the demo selector takes build A (the demo builds are the same).

Experience library

Each run used to start cold: what one project learnt about its stack (a test runner that needs a flag, a harness edit that saved the pilot a detour) was gone with it. The experience library (library.py, nodes/reflect.py) carries it to the next project of the same stack: Harness²'s harnessing-level recursion (Google Research, arXiv:2610.14224, Apache-2.0; the code and prompts are this project's own). EXPERIENCE_LIBRARY=on|off; unset, it is on except in demo mode (canned demo lessons must not reach a real library).

plan_bundle:wave_1 ── reads OUTPUT_DIR/library/<domain>/ into state["library"] ──→ plan writer, harness writer, harness editors
delivery_report → reflect ── writes an entry, rebuilds INDEX.md ──→ iterate_gate | END
  • Domains. A library per stack: the starter template's name, else the first two words of the chosen option's stack (["Python", "FastAPI", "HTMX"] → python-fastapi), else general (domain_for). OUTPUT_DIR/library/<domain>/ holds entries/<id>.json (one per delivery that left something), harness/<id>/ (the harness files harness tuning adopted in that project), and INDEX.md, rebuilt after every write and forget.
  • Reading. The blueprint subgraph's wave_1 reads the domain once into state["library"] (snapshot: the index cut to INDEX_CHARS whole items, and the lessons it lists), so a revised plan, harness tuning, and the reflection afterwards all see the same entries. The plan writer and the harness writer get it after their upstream documents, and both harness editors after the base trajectory (reference_block): fenced, as reference data, never instructions, with the rule that an earlier project's fact is a hypothesis here and must be re-verified. The index lists the lessons best first (an undisputed one before one that later projects found to hurt more often than help, then by confidence, newest first), how later projects judged each one, and the harness edits earlier projects adopted.
  • Reflecting. After every delivery (verified or not) reflect (role reflector, on the architect's model, one call, @with_usage; a planning call, not in the ledger) reads the version's evidence: the ledger rows, the lanes' verdicts and failures, the test-integrity findings, the fix attempts with their failures, files, and <notes>, harness tuning's three runs and the composer's notes, excerpts of up to three trajectories (failed sessions first, then fix attempts and resolvers, then the longest tasks), and the library's current index. It answers with a Reflection: one edit row per edit it is given (harness:inv / harness:dom for the tuning edits that changed something, lesson:<id> for each lesson the run read; only the first version tried them, so a later version's reflection judges none) as helped, hurt, no observed effect, or confounded with its evidence (the prompt prefers confounded when one rollout is all the evidence), and at most one lesson {cue, lesson, evidence, confidence}, or none (NO_ENTRY). reflection_problems (more than one lesson, an edit not listed, judged twice or not at all, an empty field) gets one repair; then only the usable rows and the first complete lesson are kept, clipped. A delivery that leaves no lesson, no row, and no adopted harness writes nothing. The entry id is stable per project version, so a re-run step replaces its own entry. Writes and forgets hold a per-domain lock (a thread lock plus flock on the domain's .lock file), so a UI and a headless run delivering projects of one stack at once do not rebuild the index over each other. A failure that is not transient is logged and the run goes on.
  • Never acceptance content, never a secret. The reflector is not shown the acceptance lane's failures or summary (only its counts), the [acceptance] failures of fix attempts, or the verification report, and the whole prompt is redacted before the call (redact): a fix session was told the acceptance failures, so its notes and trajectory may name a hidden test, and every acceptance test name, acceptance line, and secret in it becomes a marker. What it answers is checked anyway (value_leaks, string by string, never on a JSON dump, which would escape the quotes of a line of test code; whitespace runs are compared as one space): a lesson, its rationale, a row, or an adopted harness file that holds a configured provider key, the value of any environment variable named like a key, token, secret, or password, something shaped like a key or private key, a line (40 characters or longer) of one of the project's acceptance suites, or one of their test names is dropped (the chat says what was dropped, never the text), and write_entry re-checks the whole entry and raises LibraryLeak before writing anything. tests/test_library.py asserts both.
  • Where it shows. The chat says when the planner was given lessons, and after the dashboard what the reflection recorded (ui/view.reflection_markdown). The Experience library panel lists a stack's lessons and edit rows and forgets an entry (its harness files go with it and the index is rebuilt). Demo mode answers with confounded for every edit and one lesson about the demo's report-writing test runner, unless the index already holds it, so two demo projects show the loop end to end.

Starter templates

Every project used to start from an empty directory, which cost the first task its turns on boilerplate and made verification flaky (no test runner yet, no report). src/idea_to_mvp/templates/ holds a small library of deterministic scaffolds: python-cli, python-fastapi, node-ts-express, react-vite, and nextjs. Each has a test runner, a linter, a test command that writes the JUnit report the tests lane reads, a .gitignore, a first passing test, and check.sh.

  • Choosing. The strategy step is given the list (catalog_text: each template's description and when to pick it, plus none) and records its pick in ExecutionStrategy.template, from the chosen architecture's stack and the preferences; the prompt forbids overriding the user's stack. A name that is not a template becomes none (normalize_template), as does a strategy from before templates existed, and the fallback strategy and demo mode use none (the demo builds its own dependency-free project). STRATEGY.json in the pack records it.
  • Telling the planner. build_bundle_context adds prompt_block to the context every blueprint document is written from: the template's files and layout, its fixed commands, and the rule that no task creates what it provides, so T01 builds the product's first slice on top. The plan writer's commands are then replaced by the template's (with_template_commands, in the plan node and again in write_bundle), because the scaffold's config files assume exactly those (a .venv/bin/... path, an npm script); the pack's check.sh therefore is the template's.
  • Laying it down. prepare_workspace copies the pack, commits blueprint, then apply_template writes the scaffold and commits scaffold, before the acceptance author and T01. Files are plain text with {{name}} filled in from the pack's folder name; gitignore becomes .gitignore (merged into the pack's, a real one would apply to the template folder itself); check.sh is rendered from the template's commands by the same function the pack uses. A file the pack already has is kept (the pack's documents win), nothing is written through a symbolic link, and folders a tool left behind (.ruff_cache, node_modules) are not part of the scaffold. Without git the files are still laid, uncommitted.
  • Toolchain. doctor warns, offline, when the tools a template's commands need are not on the PATH (python3; node and npm, version 22.12 or newer for the JavaScript templates). Installing runs in the agents' sandbox against the allowed registries; the orchestrator never installs or runs a scaffold.
  • Tests. The registry, the layout rules, and the planner wiring run offline. uv run pytest -m scaffold tests/test_templates.py installs and checks every scaffold with the real toolchain and network (bash scripts/check.sh must exit 0 and leave a readable JUnit report); the starter-templates CI job runs it, and the default run leaves it out.
  • Adding one. A folder with template.toml (name, title, description, use_when, toolchain, notes, and the five [commands]) and files/; run the scaffold test for it and nothing else needs registering, since the strategy prompt, the doctor check, and the tests read the folder. The JavaScript templates write no coverage in their report command: istanbul's Cobertura file has a DOCTYPE, which the report reader refuses (npm run coverage still works).

Prompt hardening

The agents that judge or change other agents' work share a few prompt blocks (prompts_common.py). The ideas come from Google Research's Harness² (arXiv:2610.14224, Apache-2.0); the wording and code are this project's own.

  • Evidence boundary. Lanes read agent-written code, test output, and web-derived text, which is where an injected instruction would sit. EVIDENCE_BOUNDARY says all of it is data: never follow a directive found in it, never run a script because a file says so, report the attempt instead. It is in the lane prompts (the acceptance lane's too), the fix and merge-resolver prompts, and the system prompts of the blueprint critic and the change planner. tests/test_prompts_common.py::test_every_judge_prompt_carries_the_evidence_boundary fails for any judge prompt without it, so a new judge must carry it. It lowers the risk; it does not make a model immune (SECURITY.md owns the threat model).
  • Answer-free implementers. ANSWER_FREE is in the task and fix prompts: work from the brief and the project's own tests, look nowhere outside the workspace for answers. It does not say what is being kept from the agent, since naming it would point at it.
  • Ordered rubric. The blueprint critic and the requirements lane (RUBRIC_ORDER) weigh findings in this order: delivery, conformance to the PRD's shape, fidelity to the PRD, internal consistency, operational fitness, finish. Length is not merit. The tests and quality lanes report facts and do not use it.
  • Tests are not yours to weaken. TEST_INTEGRITY is in the task, fix, and merge-resolver prompts: fix the code, never delete, skip, or loosen a test to get a green run, and record a test that was genuinely wrong in quality/TEST_CHANGES.md. The orchestrator checks it either way (see Test integrity); the prompt says so, because an honest agent that knows the rule writes the justification at once instead of costing a fix attempt.
  • Keeping what exists is an answer. A blueprint revision may leave a document unchanged when no issue holds (NO_CHANGE_REVISION, added by blueprints.prompt_for to every revision), and change_planner may return tasks: [] with a reason (see Iteration loop), instead of inventing work.

Multi-provider LLM abstraction

  • llm.get_runtime(role_key) returns a cached, frozen AgentRuntime (LangChain BaseChatModel + provider, model, token budget, system prompt) for any role in roles.ROLES (PM = OpenAI, Tech Lead / Summarizer / Architect = Anthropic, Skeptic = Google by default). The provider is always the configured one; warn_on_provider_mismatch() only logs an obviously wrong pairing.
  • Nodes call llm.invoke_text(runtime, messages) and get plain text back ('' when the model produced none). It is the single owner of retries: Google output truncated by MAX_TOKENS is retried with a larger max_output_tokens, and an empty reply is retried once with an instruction to answer visibly.
  • Agents that hand structure to other agents use llm.invoke_structured(runtime, messages, Schema, fallback=...) and get a validated pydantic instance. It asks the provider for schema-constrained output (Anthropic: native json_schema, because newer Claude models reject forced tool use), retries once with the validation error appended, then uses the deterministic fallback (logged) or raises StructuredOutputError. Schemas are kept provider-safe: all fields required, and counts/lengths enforced by Python validators rather than JSON-schema keywords. State stores model_dump() dicts; prompts do not describe output formats, the schema does.
  • Newer models reject or discourage sampling parameters, so sampling_kwargs() only forwards TEMPERATURE to models that accept it.

Model choices

What each role runs on in the default balanced profile and why, checked 2026-10-19 against the providers' model and pricing pages (Anthropic, OpenAI, Google), with public benchmarks only as a hint. Prices are $ per million tokens, input / output; models.toml holds the cached-input prices, sources, and the other two profiles. A test keeps this table equal to the catalog.

Role Model Why $ in / out
moderator claude-haiku-5-5 A small structured call after every panel turn: the cheapest current tier is enough, and the same in every profile. $0.10 / $0.50
pm gpt-6.1-sol OpenAI's mid tier, close to gpt-6-astra at a fifth of the price; keeps a third provider in the panel. $2.00 / $10.00
tech_lead claude-sonnet-5-5 A mid-tier panel voice; Anthropic's view in the debate. $2.00 / $10.00
skeptic gemini-3.8-flash Google's most capable Flash at a Flash price; the third provider. $0.75 / $3.75
summarizer claude-sonnet-5-5 One mid-length synthesis; mid tier is enough. $2.00 / $10.00
architect (also strategy, plan writer, harness writer, change planner, blueprint critic, acceptance author, harness editor, harness composer, build selector, reflector) claude-opus-5-5 Planning mistakes are paid for again in every agent session, so these calls get the strongest affordable model (was Sonnet). $4.00 / $20.00
research claude-sonnet-5-5 Searching and condensing with Anthropic's web search tool; good value, no deep reasoning needed. $2.00 / $10.00
implementer claude-sonnet-5-5 Task sessions are most of a run's spend. Sonnet 5.5 is within a few points of Opus 5.5 on agentic coding benchmarks (ahead on Terminal-Bench) at half the price (was Opus for every session). $2.00 / $10.00
verifier claude-sonnet-5-5 The read-mostly lanes decide the verdict, so a false pass is costly; Haiku 5.5 trails far behind on agentic benchmarks. $2.00 / $10.00
escalation claude-opus-5-5 Merge conflicts and fix attempts after the first: the cases the task model already failed get the strongest model. $4.00 / $20.00

The other profiles: fast puts every role and session on the cheapest current models (claude-haiku-5-5, gpt-6-luna) and escalates to claude-sonnet-5-5; the Skeptic stays on gemini-3.8-flash, so the debate keeps three providers (Google's older Flash-Lite models trail Haiku 5.5 and gpt-6-luna and are not used). Haiku 5.5 costs five times as much on prompts over 100K tokens, which agent sessions reach, so its agent estimate is low. quality puts Opus 5.5 on the Tech Lead, the summarizer, the architect, and every agent session, and escalates to claude-fable-5-1. Fable 5.1 serves only escalation: the Agent SDK tolerates its minutes-long turns, while a planning call would hit LLM_TIMEOUT_SECONDS. Orgs on zero data retention cannot use it without Anthropic's approval. Considered and not used: gpt-6-astra (a short panel turn gains little at five times the price of gpt-6.1-sol, and it can spend the turn's small token budget on reasoning) and gemini-4-argon (listed as stable at launch prices, but a launch report says API access is still restricted; try it with idea-to-mvp models --check). idea-to-mvp models prints the estimated cost of a typical run per profile; idea-to-mvp bench --compare measures the profiles end to end (see Benchmark).

Demo mode

DEMO_MODE=true makes llm.get_runtime() return runtimes backed by demo.models.DemoChatModel, which answers from demo/fixtures.py (RESPONSES[role]); blueprint documents are told apart by their system prompt. implementer.run_implementation and the lane/fix sessions of implementation/verify.py dispatch to demo/implementer.py, which writes a tiny dependency-free project (with a small test runner in its tests folder that writes the JUnit report, the plan fixture's test_report command) and verifies it with real checks (its unittest suite run through that runner, byte-compilation plus a python -m demo_app smoke probe, and P0 requirement coverage from plan.json). The UI shows a banner. The demo strategy picks no starter template. tests/test_e2e_demo.py drives the real graph and SubmitService through every gate this way, offline, in CI. Acceptance tests are off in demo mode unless ACCEPTANCE_TESTS=on; then the demo author returns a small unittest suite over the demo project's public functions, run in the throwaway copy with the demo's report runner (demo_run_acceptance).

Demo-parity rule: any new LLM call, structured schema, or SDK agent session needs a fixture in demo/ so the offline pipeline keeps working end to end.

Persistence, resume, and the state-derived UI

  • Checkpoints: CHECKPOINTER=sqlite (default) stores every graph checkpoint in OUTPUT_DIR/sessions.db through AsyncSqliteSaver; memory keeps them for the life of the process. Gates are interrupt() pauses, so a checkpointer is always required. The aiosqlite worker thread is made a daemon so an open connection can never keep the process alive after Ctrl+C.
  • Async runtime: the UI drives the graph with graph.astream(..., stream_mode=["updates", "custom", "messages"], subgraphs=True) (committed steps, live implementation events, panel tokens); sync nodes run in worker threads. GraphProvider opens the graph lazily inside the event loop that will use it (Gradio builds the UI synchronously but serves from its own loop).
  • The UI is a projection of state. After every graph update SubmitService re-reads the thread's checkpoint (with subgraphs=True, and graph.merged_values folds the running panel's own checkpoint in, because a subgraph node only commits to the parent when it finishes) and derives the chat (transcript_from_state), the UI mode (mode_from_state: idea → answers → arch choice → plan gate → implement gate → done, plus interrupted for a run that stopped mid-step), the status line, and the stage tracker from it. The browser session only remembers the thread id, so a session can be rebuilt after a restart and no copy of pipeline state can drift. Transient overlays (the message just sent, the panel turns being written, the step in progress, an error) are added on top of the derived transcript and vanish on the next render.
  • Resume: the Saved sessions panel lists SessionRegistry rows; Resume selected re-renders that thread at whatever gate it was waiting at. A run that crashed between gates shows a Continue button, which calls astream(None, config) to carry on from the last checkpoint instead of restarting.

Headless runs

idea-to-mvp run "<idea>" and idea-to-mvp resume <thread> (cli.py → headless.py) drive the same compiled graph on the same checkpointer as the UI, read threads with the same graph.read_thread, and record them with the same SessionRegistry.record, so a session started on the command line opens in the UI's Saved sessions and the other way round. Nothing is kept outside the checkpoint.

  • Gates from flags. After every stretch of astream the driver reads the thread: at a gate, decide turns the flags into exactly the resume value the UI form would send (--answers FILE, else with --autopilot the questions' suggested answers; --arch 1|2, else with --autopilot the recommendation; the pack with --autopilot or --implement; the iterate gate with --feedback and --implement, used once). The suggested answers and the recommendation come from the same helpers the autopilot nodes use (nodes.gates.suggested_answers, recommended_option). The state's autopilot stays off for a headless run, so the flags decide every gate and --arch wins over the recommendation.
  • Spending needs --implement. The implement gate is passed only with that flag, never by --autopilot; without it the run stops there and prints the gate's dollar estimate. Building another version also needs it.
  • Stops are resumable. A gate the flags do not answer leaves the thread waiting there; resume answers it with new flags. A failed step exits 1 and leaves the last checkpoint, so resume continues it (astream(None, ...)), as the UI's Continue does. --max-total-usd is applied as IMPLEMENTER_MAX_TOTAL_USD for that process only, so pass it again on resume.
  • Output. Progress (committed steps, agent sessions starting and ending) goes to stderr; the RunSummary (outcome, gate, verdict, workspace, delivery zip, blueprint folder, planning and agent cost, the estimate, the questions or architecture options at those gates, and the next command) goes to stdout, as JSON with --json. Exit codes: 0 delivered and verified, 2 delivered with failures, 3 stopped at a gate (or ended before anything was built), 1 error or interrupted.

MCP server

idea-to-mvp mcp (cli.py → mcp_server.py) serves the pipeline to other agents (Claude Code, Claude Desktop, any MCP client) over stdio, with the mcp 2.x SDK (MCPServer; the mcp extra in pyproject.toml, which claude-agent-sdk pulls in anyway). It adds no graph code: like the bench it is a client of headless.py (run_idea, drive) on the app's own checkpointer, so a session started through MCP opens in the UI and the other way round, and idea-to-mvp resume <session> continues one the server was stopped in.

  • Five tools. start_run(idea, autopilot), get_status(thread_id), answer_gate(thread_id, gate, ...), list_sessions(limit), get_delivery(thread_id). The last three plus get_status are annotated read-only. Failures the caller can fix (an unknown session, a missing argument, a wrong gate) are ToolErrors, so their text reaches the client; any other exception is withheld by the SDK.
  • Runs go on in the background. A run takes minutes, so start_run and answer_gate return at once and the work continues as a task in the server's event loop (Orchestrator._launch), one at a time per session; get_status says running, and once the task has stopped reports the gate the thread waits at with its payload (questions, architecture options, the implement gate's cost estimate; the delivery report and the publish options are left out, get_delivery serves the report) and how to answer it. The task's last progress lines (the same lines the CLI prints to stderr) are kept in memory. A task that raises is reported as state: error with the hint headless.drive would print; a server that exits cancels its tasks and leaves the checkpoint, so the session shows interrupted with the resume command.
  • Answers name their gate. answer_gate reads the thread, refuses a gate that is not the one it waits at, and turns the arguments into exactly the resume value the UI form sends (build_resume: answers or use_suggested_answers; option; generate; implement / parallel / harness_tuning; feedback). The resumed run uses HeadlessOptions() with no flags, so it stops at the next gate; only start_run(autopilot=True) rides several gates (answers, architecture, pack) and stops at the implement gate.
  • Spending needs confirm_spend. Starting agent sessions, implement_gate with implement=true and iterate_gate with a change request, is refused unless the call carries confirm_spend: true; the tool descriptions and the server's instructions tell the caller to show the user the gate's cost estimate first. Declining (implement=false) needs no confirmation. This is the MCP counterpart of the CLI's --implement; see SECURITY.md for what it does and does not guard.
  • Stdout is the protocol. Logs go to stderr; the SDK claims stdin / stdout for the transport, so a stray print in the pipeline cannot corrupt a message. tests/test_mcp_server.py::test_the_server_speaks_mcp_over_stdio runs the real command in a subprocess, and the other tests drive a whole demo run (start, the gates, implement with and without confirm_spend, a second version, the delivery) through an in-memory client.

Benchmark

idea-to-mvp bench (cli.py → bench.py) runs the golden ideas (src/idea_to_mvp/golden_ideas.json, eight ideas across web, mobile, CLI, and API stacks) through the headless layer with autopilot and --implement and records what a README can quote. It adds no graph code: each idea is headless.run_idea on the bench's own checkpointer, so a bench thread opens in the UI like any other. The experiment discipline is Harness²'s.

  • A run is a folder. <OUTPUT_DIR>/bench/<name>/ holds config.json (the snapshot), results.json (one IdeaResult per idea, rewritten atomically after each idea, so a killed bench loses at most the idea in flight), and output/, the run's own OUTPUT_DIR (sessions database, workspaces, held-out suites, experience library). Two configurations never share an output root, so one cannot learn from the other's library; within a run the library does accumulate across ideas of a stack, in the order of the ideas file.
  • The snapshot refuses a different experiment. It records the mode, the --set overrides, the idea ids with a fingerprint of each idea's text and preferences, and a flat view of the effective settings (the profile, the model every role and kind of agent session resolves to, harness tuning, the library and acceptance switches, the fix and budget limits, the turn limits, the sandbox). Calling the same --name again with anything different exits 1 and names each difference; the global --max-total-usd is not part of it, so a run that ran out of budget can be continued with more.
  • Scored or unscored. An idea that was delivered is scored: verified is the verdict, with the lanes passed (acceptance included), the held-out suite's pass rate, integrity flags, fix attempts, planning and agent cost, and wall time. An idea that never reached a delivery (a step that raised, a gate the flags cannot answer, an interruption, the budget) is unscored: it is in no rate, its spend is kept apart (unscored_spend_usd), and calling the bench again retries exactly those ideas (continuing their threads) while keeping the scored ones. A delivery whose verification failed is a real zero.
  • Budgets and modes. --max-usd-per-idea is the idea's IMPLEMENTER_MAX_TOTAL_USD; it must be at least twice IMPLEMENTER_MAX_TASK_USD (check_task_budget), because the parallel engine reserves the per-task cap for every task it starts and a budget that fits one reservation builds only the first task of a plan; --max-total-usd caps everything the run has spent (planning and agents, from every result): each idea gets the smaller of its cap and what is left, and ideas the cap cannot afford stay unscored. Without DEMO_MODE=true the bench needs --live and --max-total-usd; with it, --live is refused. --dry-run prints the settings and the catalog's typical-run estimate and writes nothing.
  • Configurations are flags. --profile, --harness-tuning, --library, and --set KEY=VALUE become environment overrides of the settings for that run only (the bench owns OUTPUT_DIR, CHECKPOINT_DB, DEMO_MODE, and the per-idea budget).
  • --compare runA runB ... aligns the runs on the ideas every run scored and whose text is the same in all, lists the settings that differ, and folds each run's results on that common set into the same totals: verified rate, verified deliveries per dollar and cost per verified delivery (spend on scored ideas), lanes and acceptance tests passed, fix attempts, integrity flags, wall time. Every idea left out is named with the reason. Verified deliveries per dollar is the number that says which models are worth their price.
  • Exit codes. 0 every idea verified, 2 a delivery failed verification, 3 some ideas unscored (call again to retry them), 1 error. tests/test_bench.py runs the whole bench in demo mode as the CI smoke test; scripts/eval_blueprint.py stays as the cheap, pack-only judge.

Resilience, usage, and tracing

  • Cut-off answers. llm.invoke.invoke_text asks again with a larger output budget when the provider reports that the cap ended the answer (finish_reason / stop_reason read as MAX_TOKENS) and the text does not look complete: Google once (to at most 8192 tokens), Anthropic up to twice (3x or +4096, at most 16384). Anthropic's cap includes thinking, and Opus 5.5 can spend all of it on thinking and return no text (tests/test_llm_invoke.py::test_a_reply_that_is_only_thinking_when_the_budget_ran_out_is_retried_larger). Other providers are not retried.
  • Two retry layers. Provider SDKs retry HTTP-level failures themselves (LLM_MAX_RETRIES, per-request LLM_TIMEOUT_SECONDS). Nodes that call a model (summarizer, architect, strategy, and the panel and blueprint subgraphs' model nodes) also carry LLM_RETRY, so a node that still fails with a transient error (rate limit, timeout, connection reset, 5xx; matched by exception class name and status code, no provider imports) is re-run with backoff instead of failing the stage. Auth, validation, and schema errors are never retried.
  • Usage. Model-calling nodes are wrapped with @with_usage(role=...), which records every model call made during the node (text and structured, retries included) via LangChain's usage callback and appends UsageRecords to the accumulating usage state channel. cost_usd is the call's price from pricing.py (the model catalog, or the MODEL_PRICES_FILE override; input the provider served from its cache is charged at the cached rate, a dated snapshot counts as its model, and a demo run costs nothing), and stays None for a model with no price anywhere; Agent SDK sessions report their own dollar cost. summarize_usage keeps the two apart: planning_cost_usd (panel, research, summary, architecture, blueprint calls; None when none could be priced) and agent_cost_usd (the roles in AGENT_USAGE_ROLES: implementer, resolver, verifier, fixer), which alone counts against the whole-run budget, plus unpriced_calls. The sticky header shows the token total, planning spend ("+ n unpriced", or "planning unpriced", when calls had no price), and agent spend as badges (ui/components.usage_badge). The cache-creation surcharge Anthropic charges is not modelled, so a figure can be slightly low.
  • Tracing. Set LANGSMITH_TRACING=true and LANGSMITH_API_KEY in .env (or the shell). Only LANGSMITH_*/LANGCHAIN_* are exported from .env — provider keys are deliberately not, because agent subprocesses inherit the environment. Runs are named idea-to-mvp and tagged thread:<id> (graph.run_config).
  • idea-to-mvp doctor [--offline] checks every role's key and, unless --offline, makes one tiny real call per distinct provider/model; it also checks the bundled Claude Code CLI. Failures are reported per role; exit code 1 if any check failed.

The implementation engine

For strategy mode agent_team with a runnable plan.json (tasks exist, ids unique, dependencies known, no cycle; otherwise the lead session is used and a warning is logged), the async implementer node calls executor.run_plan, which walks plan.execution_waves one task at a time (parallel execution is the next step):

  • One fresh session per task. run_task builds a prompt from the PlanTask (goal, scope, requirements, acceptance criteria, tests, contracts, the summaries of its dependencies, the project commands), streams the session through implementer.iter_agent_messages, and records the ResultMessage cost, turns, and session id. On success the orchestrator commits T01: <title>; a failed session is never committed. A crashing session becomes a failed task and the run goes on; tasks whose dependencies did not finish are skipped; a missing sandbox is a configuration error and aborts.
  • Resume. Results are written to <workspace>/.idea-to-mvp/progress.json (git-ignored, read-only for agents). Re-running the node after a kill skips done tasks and retries failed and skipped ones in the same workspace.
  • Budgets. One BudgetTracker is shared by all sessions. A session's SDK budget is min(IMPLEMENTER_MAX_TASK_USD, remaining); a task starts only while budget remains; what earlier runs of the workspace already spent is deducted; the verification lanes and fix sessions that follow are paid from what is left of the whole-run cap (see Verification lanes).
  • Live events. The node publishes ImplEvents (task_start, tool, text, cost, task_end) on LangGraph's custom stream; SubmitService subscribes with stream_mode=["updates", "custom"] and shows progress and the running cost (ui/view.implementation_progress, throttled; transient, not part of the checkpoint). The lead session mode emits no events. Each task's cost is also appended to usage as an implementer record.
  • Demo mode simulates each task (demo_task): the first builds the stand-in project, every task writes a note, with the same events and commits.

Trajectories and the run ledger

Every agent session is recorded in the workspace's .idea-to-mvp/ folder (git-ignored, read-only for agents, left out of the delivery zip), whichever engine ran it and whether it ran in a worktree or the main checkout (the files live in the main workspace, which outlives the worktree):

  • Trajectory. trajectories/<label>.md (implementation/trajectory.py, SessionLog) is written while the session runs, one grammar for every kind of session: [ACTION] a tool call with its input as JSON (long values clipped), [OBSERVATION] the truncated result ((error) when the tool failed), [TEXT] what the agent said, [ERROR], and a final [RESULT] with outcome, cost, turns, and session id. Lines of a longer entry are indented, so text an agent or a tool produced can never start an entry of its own; thinking blocks are not kept; a killed run leaves the file up to the point it died. The label is T01 for a task (T01-2 for a second attempt), T03-resolver, lane-tests-1 (the verification round), fix-1, lead / workstream-<name> for the lead and team sessions of implementer.py; a later version's lane and fix labels start with v2-. Demo sessions have no SDK messages: their events are written in the same grammar.
  • Ledger. ledger.json (implementation/ledger.py) gets one row when a session ends: kind (task / resolver / lane / fix, and for harness tuning pilot / pilot_lane, plus a row per model call, proposal / compose / select, with no trajectory), label, task_id, iteration, attempt, model, cost_usd, turns, outcome (success / failed / crashed; a lane that finds failures is still a success), session_id, the trajectory path, and start / end times. A session killed before it ends has a trajectory but no row, since its cost is unknown; one that could not start (no sandbox, no budget) leaves neither.
  • The identity. check_ledger compares the ledger's total with the spend usage reports for what it records (the implementer, resolver, verifier, fixer, and pilot records, and harness tuning's harness_editor / harness_composer / pilot_selector calls); delivery_report logs a warning when they differ. A merge resolver's spend is its own resolver usage record on the model it ran on (split from its task's cost by the ledger), and the lead / workstream sessions of strategy subagents are implementer records taken from the ledger rows the node just added, so they count against the whole-run budget too.
  • Where it shows. After a restart the Implementation console is rebuilt from the ledger and the trajectory files (events_from_trajectories, with the plan's task titles) until the process has live events, and a run continued after a restart keeps those lines in front of its own. A task card on the board names its latest trajectory file, which the user opens in the file explorer.

Cost estimate

The implement gate shows a dollar range (pricing.estimate_run_cost, stored in state as cost_estimate so the dashboard can set it against the actual spend). It is the plan's task count times the cost of one task session, plus one verification round (three lanes, four with acceptance tests); the high end also adds MAX_FIX_ATTEMPTS fix sessions (the first on the task model, later ones on the escalation model, each followed by a verification round); both ends are capped by IMPLEMENTER_MAX_TOTAL_USD. When the plan can be tuned, the gate also shows what harness tuning would add (pricing.estimate_tuning_cost: three task sessions at the same per-task figure and band, three tests lanes, four calls on the harness editor's model at the architect's typical call; the sessions never more than half the whole-run cap). A task session costs the median of earlier projects' finished tasks on the same model (read from their ledgers under projects/, summed over a task's attempts) once there are at least three, with a band of 0.75x to 1.5x; otherwise the catalog's typical session ([typical_run.implementer] of models.toml) with a band of 0.5x to 2x. A session model with no price makes the whole estimate "unpriced" instead of a figure that leaves it out. The range is a guide, not a quote.

Parallel execution

EXECUTION_STRATEGY (default auto) decides whether the strategy model's choice of mode stands. The model tends to pick subagents for small or tightly coupled apps, which builds the whole plan in one serial lead session (the slowest path: 73% of a live run's 51 minutes); agent_team builds one session per task and runs the independent ones in parallel worktrees. nodes/strategy.py::apply_override replaces the mode only (workstreams and template stay) and prefixes the reasoning with the override, so the strategy card never argues for a mode it does not use (tests/test_strategy.py::test_execution_strategy_overrides_the_models_mode_unless_auto). A plan that is not runnable still falls back to the lead session, whatever the setting.

With IMPLEMENTER_MAX_PARALLEL above 1 (default 3), strategy mode agent_team, a runnable plan, and a git workspace, route_after_workspace sends the run to the implement_plan subgraph (nodes/implement_graph.py) instead of the single-node implementer; anything else keeps the sequential engine above, which is exactly the =1 behaviour.

  • Loop. prepare discards worktrees of a killed run; pick_wave skips tasks behind a failed one, takes the ready tasks (dependencies merged, scheduler.next_ready) and creates one worktree per task; run_task_node runs the sessions concurrently; merge_wave merges; back to pick_wave until nothing can start; finish writes the log and usage, commits, and removes leftovers.
  • One worktree per task. merge.create_worktree makes <projects>/.worktrees/<workspace>/<id> on branch task/<id> from the current HEAD, beside the workspace (not inside it). That folder is the session's cwd, sandbox root, and guard root, so a task cannot touch the main checkout or another task. The task prompt says dependencies must be installed there.
  • Bounded parallelism. A node cannot set its own concurrency, so a batch never holds more than IMPLEMENTER_MAX_PARALLEL tasks (max_concurrency/LLM_MAX_CONCURRENCY still caps the run overall).
  • Budget by reservation. Every started task reserves min(IMPLEMENTER_MAX_TASK_USD, whole-run budget); a batch holds only as many tasks as floor(remaining / reservation), so concurrent tasks can never overshoot the whole-run cap; when less than one task's reservation is left, the ready tasks fail as "not started: budget" and their dependents are skipped. A resolver is paid from what is left.
  • Merge, then done. The orchestrator commits the task on its branch (--git-dir pinned to the worktree's admin directory inside the main repository, because an agent can rewrite its worktree's .git file) and merge_wave merges branches in task-id order (T03: <title> (merged); fast-forward when main has not moved). A task is recorded done in progress.json only after its merge, so a kill between session and merge loses nothing recorded; on resume the stale worktree is discarded and the task redone.
  • Conflicts. A conflict leaves the merge in progress and executor.run_merge_resolver runs one bounded session on ESCALATION_MODEL in the main workspace (keep both intents, run the tests, no commit). The orchestrator accepts the result only if no conflict markers remain (merge.complete_merge); otherwise the merge is aborted, the task fails, and its dependents are skipped.
  • Project tests are not run on the host. Running plan.commands.test from the orchestrator would execute agent-written code outside the sandbox. Each task's own session runs its tests, the resolver runs them after a conflict, and the verification stage checks the integrated result.
  • Live view. ui/view.implementation_progress shows every running task; a task's end is announced by the merge step with its final status. The implement gate reports the plan's task_count, dag_width, and max_parallel.

Verification lanes

implement → verify ─Send×3|4→ verify_lane → verdict ─ pass | exhausted ─→ delivery_report
               ↑                              └────── retry ──→ fix ──┘ (back to verify)
  • Three lanes, concurrently. verify fans out with Send to verify_lane, one branch per lane (implementation/verify.py), each a session on VERIFIER_MODEL: tests installs dependencies and runs plan.commands.test (it may write coverage artefacts), quality runs lint / type checks, looks for obvious security problems, and smoke-probes the documented run command (skipped, with a note, for a library), requirements maps every P0 requirement of the PRD (all of them if none is marked P0) to at least one test and reports the uncovered ones. Quality and requirements sessions run with Edit/MultiEdit/Write disallowed; a lane can still create files through the shell, so treat them as read-mostly. The quality lane must not run the install command (the tests lane does, at the same time).
  • Test evidence. The plan's commands.test_report is the test command written to also leave JUnit XML (and coverage) in .idea-to-mvp/reports/ (pytest --junitxml=..., vitest --reporter=junit, gotestsum --junitfile; the plan writer fills it per stack, validate_plan insists on that folder). The tests lane is told to run it, and run_lane empties the folder first, so a report is always from this round. Afterwards implementation/reports.py reads the files (a file read, no agent code; DOCTYPE/entity XML and files over 20 MB are refused) and overrules the lane's claim: no JUnit file, zero tests, only skipped tests, or any failure or error fails the lane with the parsed reason (the failing test names go to the fix session as [tests] failures). A clean report never rescues a lane that listed failures. The counts and coverage ride in the lane's report as evidence (set only by the orchestrator: parse_lane_report drops one an agent sends, and the field is left out of the schema the agent answers), and the dashboard's Tests card shows them. A plan without test_report (written before Task 8) keeps the agent's verdict with a logged warning and a note in the summary; SECURITY.md says what a report does not prove.
  • Structured verdicts, no sentinel. Each session is asked for JSON matching LaneReport (ClaudeAgentOptions.output_format, ResultMessage.structured_output; JSON in the reply text is accepted as a fallback). A missing, non-JSON, schema-invalid, wrong-lane, or error result fails that lane with the reason (parse_lane_report never raises); a lane that lists failures does not pass. passed overall needs every lane of the round (nodes/acceptance.lanes_for: the three, plus acceptance when the current version has a suite); a report of a lane that was not expected (an acceptance report left from an earlier version) is ignored.
  • Graph-level fix loop. verdict folds the lanes into state["verification"] ({passed, attempts, report, lanes}) and routes pass / exhausted (attempts reached MAX_FIX_ATTEMPTS, or no budget for another round) to delivery_report and retry to fix. fix runs one implementation session on the merged failure list ([lane] failure, not raw prose), the first attempt on IMPLEMENTER_MODEL and every later one on ESCALATION_MODEL (verify.fix_role), the orchestrator commits (fix attempt N), and control returns to verify. Every attempt is its own checkpoint and stream event, so the UI shows the live lane progress (verify:tests, ... in the console) and a killed run resumes at the step it stopped at. A retry re-runs every lane (their reports overwrite the previous round's).
  • Held-out acceptance tests. The tests lane runs tests the implementers wrote; the acceptance lane runs tests they never saw (Harness²'s answer-free principle). Before the first task of each version, acceptance_author (role acceptance_author, on the architect's model, ACCEPTANCE_MAX_TOKENS) gets the PRD, the requirements to cover, the plan's public contracts and commands, and the later versions' change requests (which win over the PRD where they conflict), and nothing of the implementation, and returns an AcceptanceSuite: test files for the project's framework, black-box where possible (the run command as a subprocess, the contracts' endpoints), every test named after the requirement it checks (test_R1_...), and a command that runs the acceptance/ folder and writes .idea-to-mvp/reports/acceptance.xml. The suite is validated (relative paths inside the folder, at most 12 files, a command that writes that report; one retry with the error, else no suite) and saved to OUTPUT_DIR/acceptance/<workspace>/v<n>/, beside the projects folder, never inside a workspace; no suite (off, no plan, nothing written, or a suite no longer on disk) means no acceptance lane. The command check wants a word that names the acceptance/ folder besides the report path, so a command that runs the project's own tests is refused. The lane copies the project (without .git, .idea-to-mvp/, dependencies, build output, sockets and pipes, or a top-level acceptance/ of its own; a copy that still fails is a failing lane, not a crash) to <projects>/.worktrees/<workspace>/acceptance-v<n>-<round>, adds the suite, and runs a verifier session there with write tools disallowed: install, run the command once, report. The orchestrator then judges by the JUnit report alone (no report, no tests, or any failure fails the lane) and drops everything the session said, because it has read the tests: the failures are the failing tests' names and assertion messages (the cases reports.read_evidence lists carry a failure's message, never its body, which is a traceback quoting the test), the summary is the orchestrator's, the copy is deleted, and the session's trajectory is kept in OUTPUT_DIR/acceptance/<workspace>/trajectories/ (its ledger row stays in the workspace, so the spend adds up, but with an empty trajectory: agents may read the ledger, and it must not say where the suite is). A fix session that gets [acceptance] failures is also told what they are and to fix the behaviour rather than look for the tests (acceptance.FIX_NOTE, added only then). Each requirement's acceptance verdict comes from the tests whose own names carry its id (requirement_status; not their file or parametrize ids) and fills the Acceptance column of the dashboard's requirements table. ACCEPTANCE_TESTS=on|off; unset, it is on except in demo mode. Hidden from an agent that follows its brief, not secret from one that goes looking (SECURITY.md).
  • Test integrity. The agents that make the tests pass also write them, so implementation/integrity.py checks what each session did to them (Harness²'s answer-free idea: the agent being judged must not shape the verdict). SessionWatch snapshots the test files (named like tests, or under tests/, __tests__/, spec/, ...; dependency folders, .idea-to-mvp/, and symbolic links left out; reading never runs project code) before every task session (in its worktree when parallel), merge resolver, and fix session, and compares afterwards. It flags a deleted or renamed test file, new skip markers (pytest.mark.skip / skipif / xfail, unittest.skip, .skip / .only / xit, t.Skip, #[ignore], @Disabled, ...), and assertion lines removed from a named test (def test_*, it(...) / test(...), func Test*; the whole file otherwise) whose other lines are unchanged; a rewritten test is not flagged. A resolver may lose assertions in the files that conflicted (a side had to win), but may not delete a test file or add markers. After each round with a test report, verdict adds a finding when the report lists fewer tests than the previous round (integrity_test_count). Findings travel in the task results (and progress.json, so a resumed run keeps them), the parallel engine drops those of a branch whose merge was aborted, and the state's integrity_findings is the record. verdict re-reads the workspace: an open finding is restored when the file is back with as many assertions, the markers are gone, or the count is back, and justified when quality/TEST_CHANGES.md has a list item - <path>: <why> (- test-count: <why> for the count) that was not there before the change (a finding keeps what the file said about its path as stale, so an old line cannot clear a new change). A deleted file that holds no named test, assertion, or skip marker (an empty package marker, a conftest file with only fixtures) is not a finding. With TEST_INTEGRITY=block (default) any open finding fails the verdict and reaches the fix session as an [integrity] failure that says how to clear it; warn reports without blocking; off reads nothing. The verification report and the dashboard's Test integrity card list every finding with its status and the agent's justification. SECURITY.md says what it does not catch.
  • Contrastive fix loop. A memoryless fix attempt repeats the one before it, so attempt N reads attempts 1…N-1 (Harness²'s sequential recursion: each round carries the earlier evidence, served as files so nothing is cut to fit a prompt). After every attempt the orchestrator writes <workspace>/.idea-to-mvp/fix/attempt-<n>/ (v<k>-attempt-<n> for version k > 1; implementation/fixes.py; git-ignored, read-only for agents like the rest of .idea-to-mvp/, out of the delivery zip): failures.md (what the attempt was given), diff.patch (what it changed: the diff from the commit before the session to the commit the orchestrator made, cut at 200 KB), trajectory.md (a copy of its trajectory), and, once the next verdict has judged the round that followed, after.md (that round's lane reports). The next fix prompt (build_fix_prompt) names those folders and does not paste them, and FIX_PROMPT requires a <notes> block with one line per hypothesis, kept | revised | dropped -> <hypothesis> -> <the trajectory moment or report line that decided it>, a new -> ... line for the cause being tested now, and a new hypothesis whenever the previous one failed. The orchestrator parses the notes (fixes.parse_notes) and records a missing or non-conforming block as a note on the attempt (notes_problem) without failing it: a prose rule that costs a whole attempt when broken would only teach the agent to pad the block. The notes of the attempt before are what the next one must judge; older ones were judged then.
  • Environment failures end the loop. Before a fix session is paid for, fixes.classify_failures splits the failure list. A lane failure that starts with ENVIRONMENT: (the lane prompts allow it for a cause on the machine, not in the project: a domain the sandbox blocks, a credential nobody has, a tool that cannot be installed here) or that matches one of a few narrow patterns is an environment failure (the patterns are not applied to a failing test's own name and assertion message, an [acceptance] failure or a test case from a report, whose product wording such as "missing credentials" is not a diagnosis); a tool that is merely missing is not, since the project may have to declare it. When every failure is environmental, verdict records verification["environment"] and routes to exhausted with a report that says what the user must provide, instead of burning MAX_FIX_ATTEMPTS. When only some are, the fix session is told which ones are not its to fix. A fix session can also find this out itself: it answers with <environment>what is missing</environment> (FixOutcome.kind == "environment"), the attempt is recorded as stopped, and verify skips the round that would verify an unchanged project. The lane text is an agent's, so a lane that wrongly claims ENVIRONMENT: can only shorten the loop; the report and the dashboard show the reason.
  • Attempt history. verification["history"] has one row per attempt (model, failures it was given, files it changed, notes, cost, and, once judged, passed / failed with the failures left, or stopped). The delivery report has a Fix attempts section and the dashboard a Fix attempts card built from it.
  • Budget. Lane and fix spend is recorded in usage (verifier, fixer). Each lane may spend min(IMPLEMENTER_MAX_TASK_USD, remaining / 3), a fix session min(IMPLEMENTER_MAX_TASK_USD, remaining), where remaining is the whole-run cap minus everything in usage. With nothing left verify skips the round and the report says so.
  • Delivery report. Shows a verdict per lane and the failures each reported.

Iteration loop

delivery_report ─(iteration < MAX_ITERATIONS)→ iterate_gate ─ iterate ─→ change_planner → implement → verify → delivery_report
                └────────────── otherwise ───→ END              └─ done ─→ END
  • Gate. iterate_gate interrupts with {"kind": "iterate_gate", "report", "iteration", ...} and resumes with {"iterate": bool, "feedback": str}; iterating without feedback ends the run. On iterate it appends the feedback to change_requests and moves iteration on (v0.1 → v0.2). After MAX_ITERATIONS versions (default 5) the gate is not offered.
  • change_planner (role change_planner) receives the feedback, the PRD, the existing tasks with their status, the contracts, and the id prefix, and returns a ChangePlan of new tasks (I2-01, ... for iteration 2; they may depend on finished tasks). The result is checked against the extended plan with validate_plan (problems the plan already had are not held against the change, ids must be I<n>-01, I<n>-02, ... and never reuse an existing id); one repair attempt gets the problem list, and a still-invalid plan becomes one deterministic task carrying the request (fallback_change_tasks). A ChangePlan may also be empty with a reason (the request is already satisfied): that is accepted at once, builds nothing, and ends the run at the delivered version (route_after_change_planner; iteration and change_requests go back to what was delivered, and the request and the reason are kept in no_change, which the chat shows). An empty plan without a reason is still rejected. The tasks are appended to the workspace's plan.json/plan.md (finished tasks are never rewritten) and committed (I2: plan), because task worktrees are made from HEAD.
  • Same engine, only new tasks. route_after_workspace sends the run to implementer or implement_plan exactly as for the first version, and an iteration always builds task by task (builds_task_by_task), even when the strategy is subagents; tasks done in progress.json are skipped, so only the new ones run. A lead-session project has no per-task progress, so the planner records its tasks as done first. Verification then starts from scratch (verification is reset).
  • Budget per version. The whole-run cap applies to each version: the engines count only the spend of the current version's tasks (progress.spent_in_iteration), and verification subtracts spent_before_iteration from the run's usage, so a full first build does not starve the second.
  • Delivery. delivery_report tags the workspace v0.<iteration> when verification passed (uncommitted work is committed first, an existing tag moves) and writes deliveries/<workspace>-v0.<iteration>.zip under OUTPUT_DIR, referenced as delivery_zip. The zip leaves out dependency and build directories, .git, orchestrator files, .env* (except .env.example), and symbolic links. In the UI the gate is its own mode: a Request changes / Finish here choice plus the feedback box.

Publishing a delivery

publish.py puts a finished project on GitHub, only when asked and only after a confirmation. It is a side action of the iterate gate (and idea-to-mvp publish <session>), not a node: the gate's decision stays {iterate, feedback}.

  • Plan, then confirm. plan_publish(state, settings, client, repo=, visibility=) reads the thread's state and the workspace's git repository and returns a PublishPlan: the repository (owner/name, the owner from the request, GITHUB_OWNER, or the token's account), the visibility (PUBLISH_VISIBILITY, private unless asked), the branch, its commit, the v0.<n> tags merged into it, every file tracked at the tip, the files only the history holds (removed: pushed with it, so listed), and the commit subjects. The UI shows it as the Review what will be pushed preview; the CLI prints it. plan.fingerprint is a hash of repository, visibility, backend, branch, commit, and tags; publish_plan(plan, client, confirm=...) raises NotConfirmed unless the confirmation quotes it, so the UI's confirm button carries the fingerprint of the plan it showed and the service re-plans and compares before anything is created (SubmitService.publish_review / publish_confirm).
  • What is pushed. The planned commit as the branch and each version tag, as exact refspecs (<commit>:refs/heads/main, refs/tags/v0.1:...), never forced, never other branches. A plan is refused (it lists problems) when the history it would push ever held a path under .idea-to-mvp/, a .git component, or a secret env file (delivery.is_secret_env): the working tree's .gitignore keeps them out of the commits, the plan checks that an agent did not force them in. A session that is already published is refused too; sending a later version is by hand.
  • The credential. make_client picks RestClient when GITHUB_TOKEN is set, else GhClient (the signed-in gh CLI: gh api for GitHub, gh auth token for the push). The token reaches git through git's GIT_CONFIG_* environment variables as an http.https://github.com/.extraheader, so it is scoped to the pushed repository's host and never in an argument list (workspace.run_git(..., env=)); the repository's config and hooks are reset first like every orchestrator git call, and errors are redacted. implementation/options.py blanks GITHUB_TOKEN, GH_TOKEN, GITHUB_PAT, and GH_PAT in agent environments.
  • One at a time. The UI service holds a per-thread slot while a confirmed publish runs: a second confirm, a review, or an iterate decision for that session is refused until it ends. headless.publish_and_record (shared with the CLI) publishes and records.
  • Recording. A success becomes the thread's publication: written with graph.update_thread, which keeps the iterate gate pending (a state update is a checkpoint of its own and drops the gate's interrupt from the snapshot, so the gate's node is run again to raise it from the new state). The delivery dashboard links the repository, and the gate's payload (publish) shows it published.

Implementation sandbox

Every agent session is built by implementation.options.build_agent_options, which combines an OS sandbox for shell commands (IMPLEMENTER_SANDBOX, domains in IMPLEMENTER_ALLOWED_DOMAINS), the guard.py PreToolUse hook bound to the session's workspace (the only path check for file tools), a scrubbed environment (the SDK merges env over the inherited one, so secrets are blanked with empty strings), and settings isolation: no session loads the user's settings, task / fix / resolver sessions load only the workspace's project harness after its settings file was restored, and verification lanes load nothing (see The agent harness). sandbox_status(settings) is what the implement gate reports, so the UI never claims more than is true. Agents never commit: workspace.commit_workspace does, with hardened git. What each layer does and does not protect is in SECURITY.md, its single owner.

Streaming UI

SubmitService.handle_submit() is an async generator that yields one Gradio update tuple per graph update (panel-internal updates included, via astream(..., subgraphs=True)), so the chat streams as nodes and panel turns finish. Gate decisions become Command(resume=...) payloads; interrupts select the next UI mode.

  • Implementation tab. The UI has two tabs: Conversation (chat, idea box, gate forms) and Implementation: a cost meter (agent spend of the current version against IMPLEMENTER_MAX_TOTAL_USD), the task board (plan.json tasks in pending / running / done / failed columns with workstream, branch, cost, turns, commit, and an expandable summary plus git diff --stat of the task's commit; skipped tasks count as failed), the live console (the ImplEvents of the custom stream, latest 200, oldest first, scroll anchored to the bottom, verification lanes included as verify:<lane>) and the artifacts panel. Events are transient by nature: SubmitService keeps them per thread in memory (_events), and after a restart the console is rebuilt from the persisted trajectories (see Trajectories and the run ledger), while the board is derived from what is on disk (plan.json, progress.json, the state's task_results), and a task counts as running only while a run is streaming (_active), so a stopped run never leaves tasks marked running. Diff stats are cached per commit (workspace.diff_stat, hardened git, first parent so a merge shows what it merged). The service selects the implementation tab when a run starts building and the conversation tab when it ends, only when that changes (it reads the state's own stage: the view's derived stage flickers to done between the steps of a subgraph).
  • Artifacts panel. Workspace path with a copy button, download buttons for the delivery zip and the blueprint folder zip (both served from OUTPUT_DIR/deliveries, the only allowed_paths of the app), and a read-only file explorer. A gr.FileExplorer cannot change its root, so it is re-created by @gr.render whenever the workspace-path State changes; its text is shown through SubmitService.view_file → read_workspace_file, which refuses anything outside the workspace (symbolic links that lead out are not followed), .env* files (except .env.example), .git, large (>200 KB) and binary files. The panel is refreshed only when what it shows changes (artifact_key: workspace, delivery zip, newest blueprint file).
  • Delivery dashboard. The chat's delivery entry is render_dashboard(state), not markdown: a verdict card per verification lane (commands, failures; the acceptance card also shows its counts and where the suite is kept), a Test integrity card (BLOCKED / WARNING / CLEAR, every finding with its status and the agent's justification from quality/TEST_CHANGES.md, or one line when nothing was flagged), a Fix attempts card (each attempt's model, files changed, hypotheses with their evidence, and result; the environment problem when the loop stopped for one), a requirements table (each PRD requirement with its priority, covering tasks, and a status: delivered / incomplete / untested when the requirements lane flagged it / uncovered; with an acceptance lane, an Acceptance column: passed / failed / skipped / no test), planning cost and agent cost apart ("unpriced" when calls had no price), the gate's estimate against the agent spend of the first version (under / within / over the range; not shown for later versions), tokens, total time (from the stage timings), tasks done, and How to run (the plan's install and run commands, else the README's run section). It replaces the separate verification entry once the run is delivered; the iterate form sits right below it. The markdown report stays in state (delivery_report) for the iterate gate and the session export.
  • Gate forms. Every gate has its own form (ui/gates.py); none reuses another's widgets. A GateSpec holds: build() (creates the widgets), render(payload) (fills them from the interrupt payload as gr.update kwargs), build_resume(inputs) (form inputs → exactly the value the node's payload parser takes; tests round-trip each through its node), validate(inputs, payload) (refuses a bad submission with a message), echo(inputs) (the decision as a chat message until the graph records it), next_step(resume) (the node that runs next, for the progress indicator) and an optional wire() for the form's own events. SubmitService looks the pending gate up in GATES; the app lists every gate widget in gate_layout() order and each submit button injects its own action name (pack_inputs). Outputs are the shared widgets followed by one visibility update per gate panel and one update per gate widget (only the pending gate's are filled; all forms hide while a decision is being sent or a step runs).
  • answers: five fields prefilled with each question's suggested_answer and labelled with why_it_matters, a Use all suggestions button; the resume is the numbered 1. … lines (blank answers keep their number, trailing blanks drop; an all-blank form is refused).
  • arch_choice: two side-by-side cards (name, style, stack chips, data, trade-offs, limits) with a Recommended badge and the rationale, a radio preselected to the recommendation, and notes.
  • plan_gate: notes plus Generate the execution pack / Skip for now.
  • implement_gate: a summary table (model, sandbox, permission mode, tasks, DAG width, budget, estimated sessions, estimated cost, and harness tuning's extra cost), a red banner when the sandbox is off or the mode is bypassPermissions, the review notes, a harness tuning checkbox (preset from HARNESS_TUNING, sent as harness_tuning only when the gate's payload offered it, so a hidden box, or a gate paused before the choice existed, leaves it to the setting; the service passes the payload to build_resume under PAYLOAD_INPUT), a parallelism selector (Sequential | Parallel N up to the plan's DAG width; sent as parallel and honoured by the routing and the parallel engine through effective_parallel), and the blueprint editor: PRD.md, ARCHITECTURE.md, plan.md in a code editor, saved into the pack before anything is built. A save is validated: empty files are refused; a PRD.md edit is checked against the current plan; a plan.md edit is parsed (parse_plan_markdown) and checked with validate_plan (cycles, unknown ids, ...), and on success plan.json (the source of truth) and a canonical plan.md are written. Only problems the edit introduces block it. Start implementation is refused while the editor holds unsaved changes.
  • iterate_gate: a feedback box with Iterate / Finish.
  • Design system. All colours live in CSS variables (ui/theme.py: :root for light, .dark for Gradio's dark scheme); rules use only var() and color-mix(), so cards are tinted by their accent in both schemes. tests/test_ui_render.py fails on a hard-coded hex colour outside the variable blocks and checks text contrast in both schemes. The theme and CSS are passed to launch(theme=, css=) (Gradio 6).
  • Sticky header. stage_header = the stage stepper (done / active / todo / failed) with the time each stage took, plus the token/$ badge. Elapsed time is derived, not stored: SubmitService reads the thread's checkpoint history and view.stage_elapsed credits each checkpoint with the time since the previous one, skipping time spent waiting at a gate (GATE_NODES); the running step gets the time since the last checkpoint. The marks are re-read only after the graph committed a step.
  • Settings. The header accordion holds rounds, panel mode, autopilot, and a read-only view of the model profile and the models it resolves to (from Settings); a collapsed Project preferences accordion holds the ProjectPreferences fields, which submit_idea passes to handle_submit(..., preferences=...) for a new idea (the chat echoes what was stated); handle_submit(text, rounds, decision, thread, panel_mode, autopilot) receives them. The chat is 70vh tall and example ideas replace the old pre-filled text (they are hidden while a gate is open).
  • Autopilot. state["autopilot"] (set from the checkbox; sent with every resume as Command(update={"autopilot": ...}), or aupdate_state when continuing) makes collect_answers, arch_choice and plan_gate decide without pausing: each question's suggested_answer numbered like a typed answer (the gate still asks if any suggestion is missing), the architect's recommendation, and generate. The implement gate never checks it (it spends money) and the iterate gate keeps asking; the decisions carry an "Autopilot" note in the chat.
  • Stop. The Stop button is wired with cancels=[run_event]: Gradio cancels the running handle_submit, which cancels astream between checkpoints, and SubmitService.stop_run re-renders from the last checkpoint. State stays consistent (a step that was running writes nothing); the run shows as interrupted and Continue redoes that step. A synchronous node already running in a worker thread finishes in the background and its result is discarded.

Output locations

All generated data goes under OUTPUT_DIR (default ~/idea-to-mvp, outside the repository): exports/, blueprints/, projects/, deliveries/ (one zip per delivered version), acceptance/ (the held-out suites), library/ (the experience library, per stack), and sessions.db (checkpoints + session list).

Extending the pipeline

Add an agent

  1. Role. Add a RoleSpec to ROLES in roles.py (system prompt, and the provider/model/max-token settings it reads). A role that needs its own provider and model also needs Settings fields, an entry in every profile of models.toml (PROFILES is built from it) naming a model of the catalog, and commented lines in .env.example (tests/test_config.py and tests/test_model_catalog.py check these). A new model goes into models.toml first, with its prices, capabilities, checked date, and source.
  2. Output. If other agents consume it, define a Pydantic schema in schemas.py (every field required, limits in validators) and call it through llm.invoke_structured(..., fallback=...).
  3. Node. Write nodes/<name>.py: @with_usage(role=...), model access only through llm.*, and preferences_block(state.get("preferences")) in any prompt that shapes the design.
  4. Wire it. Add state fields to IdeaDiscussionState and make_initial_state, register the node in graph.py with retry_policy=LLM_RETRY, and add its edges (inside a subgraph, extend its narrow input schema too). Run uv run python scripts/gen_graph_diagram.py.
  5. Show it. Add its transcript entry to ui/view.py (and a _RUNNING line if it takes a while) and its card to ui/render.py.
  6. Demo fixture. Add the canned answer to demo/fixtures.py (RESPONSES for text, STRUCTURED for a schema); the demo-parity rule and tests/test_e2e_demo.py depend on it.
  7. Tests. Fake llm.get_runtime / llm.invoke_* as tests/test_strategy.py does, and add a golden idea to src/idea_to_mvp/golden_ideas.json if it changes the blueprint pack.

Add a starter template

See Starter templates: a folder under src/idea_to_mvp/templates/ with template.toml and files/, then uv run pytest -m scaffold tests/test_templates.py -k <name> (it needs the toolchain and network).

Add a gate

  1. Node. A function in nodes/gates.py that calls interrupt({"kind": "<kind>", "question": ..., ...}) and normalizes whatever comes back. Honour state["autopilot"] only for decisions that cost nothing; the implement gate never does.
  2. Edges. Route to and from it in graph.py; add the node name to GATE_NODES in ui/view.py so the time spent waiting is not counted as work.
  3. Form. One GateSpec in GATES (ui/gates.py) and its mode in GATE_MODES in ui/view.py. The layout, the service dispatch, and the stop wiring follow from the registry; no handler changes.
  4. Tests. Round-trip the spec's build_resume through the node's parser (tests/test_gates_ui.py shows how) and extend the lifecycle test.

Conventions

  • Imports: absolute (from idea_to_mvp.config import get_settings); no relative or dual-import fallbacks. The package is installed editable by uv sync, so tests and the app import it the same way.
  • Calling the LLM layer: nodes use from idea_to_mvp import llm and call llm.get_runtime(...) / llm.invoke_text(...) / llm.invoke_structured(...) through the package namespace, and use from idea_to_mvp import implementer for SDK sessions, so a test can monkeypatch one attribute for every node.
  • Test isolation: config.clear_settings_cache() resets the lru_cache between tests; point OUTPUT_DIR at tmp_path via monkeypatch.setenv. Graph lifecycle tests fake all LLM/SDK calls by monkeypatching llm.get_runtime, llm.invoke_text, llm.invoke_structured (answer from demo.fixtures.respond_structured), and implementer.prepare_workspace / run_implementation and implementation.verify.run_lane / run_fix — see tests/test_graph_lifecycle.py.
  • Driving the service in tests: use the demo_service fixture (tests/conftest.py: demo models + a real SQLite checkpointer under tmp_path) and tests/service_helpers.py; graph-level tests use build_graph(MemorySaver()).
  • Model-calling nodes: decorate with @with_usage(role=...) and register them with retry_policy=LLM_RETRY (in graph.py, or in the subgraph builder for the panel and blueprint nodes).
  • Agent sessions: build options only through implementation.options.build_agent_options; never construct ClaudeAgentOptions elsewhere, or the sandbox, guard, and environment scrub are skipped.
  • Demo parity: new LLM calls and agent sessions get a demo fixture (see Demo mode); tests/test_e2e_demo.py fails otherwise.
  • Golden packs: src/idea_to_mvp/golden_ideas.json lists the ideas tests/test_golden_blueprints.py and the eval script run through the pipeline; add an idea there to put it under both.
  • Graph diagram: after changing graph topology run uv run python scripts/gen_graph_diagram.py.