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¶
- Research (optional,
ENABLE_RESEARCH) — a researcher model searches the web with its provider's own search tool and a validated, citedResearchBrief(competitors with links, market notes, gaps) is handed to the panel and shown in the chat (see The research step). - 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_robinkeeps the fixed rotation). - Summarizer — executive brief plus exactly 5 clarifying MVP questions.
- 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. - Architect + architecture gate — two options; the graph pauses at
arch_choicefor a structured{option, notes}decision. - Strategy — emits a validated
ExecutionStrategy{mode, reasoning, workstreams, template}choosingsubagentsvsagent_teamand the starter template the project begins from, ornone(deterministic fallback strategy if the model output stays invalid; see Starter templates;EXECUTION_STRATEGY=agent_team|subagentsreplaces the model's mode, and the reasoning then says so, see Parallel execution). - 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). - Implementation gate + implementer — pause at
implement_gatewith 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 isbypassPermissions);{implement, notes}resumes. theprepare_workspacenode 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 asscaffold(its own checkpointed step, so a continued run reuses the same workspace), theacceptance_authorwrites 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 optionalharness_tuningsubgraph 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 modeagent_team, run in parallel git worktrees by theimplement_plansubgraph (or one at a time byimplementerwhenIMPLEMENTER_MAX_PARALLEL=1; see The implementation engine), or one lead session with subagents forsubagents; sessions are configured byimplementation/options.pyand the orchestrator commits. - 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; averdictnode folds them with the test-integrity findings (a session that deleted, skipped, or weakened a test; see Test integrity), failed rounds go to afixnode and back toverify(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 av0.<n>git tag when verification passed) follows. - Reflection (
EXPERIENCE_LIBRARY) —reflectwrites 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). - Iterate gate — after every delivery the graph pauses at
iterate_gatewith{iterate, feedback}: changes loop throughchange_plannerandacceptance_author(a new suite for the new version) back into the same engine; finishing (or reachingMAX_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 -. exhausted .-> delivery_report;
verdict -. retry .-> 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_openingsthen appends them to the transcript in canonical PM, Tech Lead, Skeptic order whichever finished first. - Moderated debate. From then on
moderator → speaker_turnalternate. The moderator (rolemoderator, a cheap structuredModeratorDecisioncall) picks the next speaker and may declare the debate converged; itsreasonis 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), andmax_roundsis 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 tospeaker_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
IdeaDiscussionStatewith the parent but declares a narrower input schema (PanelInput) that leaves outusageandopening_turns. Without it the parent's accumulatingusagechannel would receive its own records back from the subgraph and count them twice. The LLM nodes inside the subgraph carryLLM_RETRY; thepanelnode 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.
SubmitServiceadds"messages"to the stream modes;view.panel_tokenkeeps only the tokens of the two turn nodes (opening_turn,speaker_turn) and names the speaker from therolethatllm.get_runtimeputs in every chat model'smetadata(the three parallel openings interleave, and a token carries no other speaker).view.LiveTurnsaccumulates them per speaker into live bubbles (re-rendered at most every_TOKEN_INTERVAL_SECONDS); a finished opening stays as it is untilmerge_openingsmakes 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=...)(fromLLM_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_blockhands the brief to the panel's prompts as reference data, not instructions; the chat card (ui.render.research_card) escapes everything and links withrel="noopener noreferrer". - Optional means optional. A transient error is retried by
LLM_RETRYlike any model node; any other failure logs a warning and leavesresearchempty, so the run goes on.doctorchecks the researcher only when research is enabled. - Demo mode. The demo model ignores the bound tool and answers from
demo/fixtures.py(researcher,ResearchBrief), soENABLE_RESEARCH=true DEMO_MODE=trueruns 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 byblueprints.prompt_forunder## 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.mdand thecontracts/,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). Eachwave_nnode is a no-op that fans out withSend, one task per document; the static edge out of the workers fires once the whole wave is done. A worker stores{path: text}inblueprint_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_writernode (roleplan_writer) produces aplan.Planthroughinvoke_structured: contracts, tasks (T01…,depends_on,requirement_ids, contracts in/out, acceptance, tests, coverage, handoff), and the project commands.plan.validate_planthen 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 validPlan, a deterministicfallback_planis used.plan.execution_wavesturns the task graph into topological layers for the parallel execution to come.plan.jsonis the source of truth;plan.mdis rendered from it byrender_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) withcoverage_targetkept 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
reviewnode cross-checks PRD ↔ ARCHITECTURE ↔ plan ↔ subagent prompts: the deterministic plan problems that survived the repair become blockers, and a critic model (roleblueprint_critic, a structuredCritiqueReport) adds its own issues, each ablockeror awarningon 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) andMAX_BLUEPRINT_REVISIONSallows,reviseregenerates 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 toREVIEW.mdin 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
writenode calls the deterministicblueprints.write_bundle(). As with the panel, the subgraph takes a narrower input schema (nousage,blueprint_docs, orblueprint_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 inblueprints_dir:README.md,PRD.md(numbered requirements),ARCHITECTURE.md,AGENTS.mdplus scopedcontracts/,application/,quality/guides,plan.json(the validated task graph, source of truth) withplan.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 ofAGENTS.md),STRATEGY.json, andREVIEW.mdwhen review notes remain. Each document has its own system prompt, wave, and upstream needs inblueprints.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 toAGENTS.md, lists the plan's commands between markers, the skills with their triggers, and the tool guidance),check.shunderscripts/(deterministic, fromplan.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(frontmattername/descriptionplus numbered steps), a marked Guardrails section appended toAGENTS.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_writernode (roleharness_writer, on the architect's model,PLAN_MAX_TOKENS) reads the architecture and the rendered plan (notplan.json, which only supplies the commands to check against) and returns aHarnessSpec: 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 byfallback_harness, acheckskill and, with a run command,run-the-app. The answer is kept inblueprint_docsunderharness.jsonand never written into the pack;write_bundlerenders it for the final plan (a revised plan may have changed the commands) and falls back if it no longer validates. Editingplan.mdat the implement gate re-renders the check script and the commands section ofCLAUDE.md(refresh_commands). - The validator.
validate_harness(files)reads text only: every file in the harness surface (CLAUDE.md, the fourAGENTS.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 exactlyPROJECT_SETTINGS, one toMAX_SKILLSskills, each with a frontmatter name equal to its folder and a description that names a trigger ("Use when ..."), every script a skill orCLAUDE.mdinvokes present, the guardrails section underGUARDRAILS_BUDGETand the always-on text (CLAUDE.md, the guardrails, every skill description) underALWAYS_ON_BUDGETcharacters.tests/test_golden_blueprints.pyvalidates the harness of every golden pack. - Who loads it. Task, fix, and merge-resolver sessions run with
setting_sources=["project"]andskills="all", so Claude Code loads the workspace'sCLAUDE.mdand skills;build_agent_optionsfirst restores an existing.claude/settings.json(ensure_project_settings), and the guard refuses agent writes to.claude/settings*.jsonand.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 forbash scripts/check.shbefore finishing; with the script present, the tests lane runsbash scripts/check.sh install testand the quality lanebash 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_pilottakes 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 arepilot/pilot_laneledger rows with trajectoriespilot-<arm>.md/pilot-<arm>-tests.md, andusagerecords with the rolepilot; their events show aspilot:<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 underscripts/, 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 aHarnessEdit: 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_problemschecks the edited harness withvalidate_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 aComposition:keep_base,adopt_inv,adopt_dom, ormerge(with the composed files), notes in thekept | revised | dropped -> edit -> evidenceshape, and a rationale. Keeping the base is a valid answer. The orchestrator overrules tokeep_basewhen 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 failsedit_problemsafter 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
adoptwaits 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 (rolepilot_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 andpilot-<arm>name replaced by[hidden](redact); never its trajectory, its summary, its cost, or its harness. It returns aSelection: scores of 1 to 5 per rubric criterion (delivery, conformance, fidelity, consistency, operational fitness, finish) for every build, a choice (noneis 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 strategysubagentsbuilds 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_fileslists 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 recordeddoneinprogress.jsonwith 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 adonetask, 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 threepilotrows, onepilot_laneper run that delivered, twoproposalrows, onecomposerow, and oneselectrow when the selector was called (tuning_identity), and their cost must equal theusagethe 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 inusage, and every engine (the task engines and the lead session of strategysubagents) deductsledger.tuning_spendfrom 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 storedcost_estimateincludes its sessions (pricing.with_tuning; markedharness_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 fromharness_tuningin 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), elsegeneral(domain_for).OUTPUT_DIR/library/<domain>/holdsentries/<id>.json(one per delivery that left something),harness/<id>/(the harness files harness tuning adopted in that project), andINDEX.md, rebuilt after every write and forget. - Reading. The blueprint subgraph's
wave_1reads the domain once intostate["library"](snapshot: the index cut toINDEX_CHARSwhole 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(rolereflector, 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 aReflection: one edit row per edit it is given (harness:inv/harness:domfor 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) ashelped,hurt,no observed effect, orconfoundedwith its evidence (the prompt prefersconfoundedwhen 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 plusflockon the domain's.lockfile), 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), andwrite_entryre-checks the whole entry and raisesLibraryLeakbefore writing anything.tests/test_library.pyasserts 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 withconfoundedfor 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, plusnone) and records its pick inExecutionStrategy.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 becomesnone(normalize_template), as does a strategy from before templates existed, and the fallback strategy and demo mode usenone(the demo builds its own dependency-free project).STRATEGY.jsonin the pack records it. - Telling the planner.
build_bundle_contextaddsprompt_blockto 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'scommandsare then replaced by the template's (with_template_commands, in the plan node and again inwrite_bundle), because the scaffold's config files assume exactly those (a.venv/bin/...path, annpmscript); the pack'scheck.shtherefore is the template's. - Laying it down.
prepare_workspacecopies the pack, commitsblueprint, thenapply_templatewrites the scaffold and commitsscaffold, before the acceptance author and T01. Files are plain text with{{name}}filled in from the pack's folder name;gitignorebecomes.gitignore(merged into the pack's, a real one would apply to the template folder itself);check.shis 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.
doctorwarns, offline, when the tools a template's commands need are not on the PATH (python3;nodeandnpm, 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.pyinstalls and checks every scaffold with the real toolchain and network (bash scripts/check.shmust exit 0 and leave a readable JUnit report); thestarter-templatesCI 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]) andfiles/; 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 coveragestill 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_BOUNDARYsays 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_boundaryfails 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.mdowns the threat model). - Answer-free implementers.
ANSWER_FREEis 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_INTEGRITYis 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 inquality/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 byblueprints.prompt_forto every revision), andchange_plannermay returntasks: []with areason(see Iteration loop), instead of inventing work.
Multi-provider LLM abstraction¶
llm.get_runtime(role_key)returns a cached, frozenAgentRuntime(LangChainBaseChatModel+ provider, model, token budget, system prompt) for any role inroles.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 byMAX_TOKENSis retried with a largermax_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: nativejson_schema, because newer Claude models reject forced tool use), retries once with the validation error appended, then uses the deterministicfallback(logged) or raisesStructuredOutputError. Schemas are kept provider-safe: all fields required, and counts/lengths enforced by Python validators rather than JSON-schema keywords. State storesmodel_dump()dicts; prompts do not describe output formats, the schema does. - Newer models reject or discourage sampling parameters, so
sampling_kwargs()only forwardsTEMPERATUREto 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 inOUTPUT_DIR/sessions.dbthroughAsyncSqliteSaver;memorykeeps them for the life of the process. Gates areinterrupt()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.GraphProvideropens 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
SubmitServicere-reads the thread's checkpoint (withsubgraphs=True, andgraph.merged_valuesfolds 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, plusinterruptedfor 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
SessionRegistryrows; Resume selected re-renders that thread at whatever gate it was waiting at. A run that crashed between gates shows a Continue button, which callsastream(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
astreamthe driver reads the thread: at a gate,decideturns the flags into exactly the resume value the UI form would send (--answers FILE, else with--autopilotthe questions' suggested answers;--arch 1|2, else with--autopilotthe recommendation; the pack with--autopilotor--implement; the iterate gate with--feedbackand--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'sautopilotstays off for a headless run, so the flags decide every gate and--archwins 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;
resumeanswers it with new flags. A failed step exits 1 and leaves the last checkpoint, soresumecontinues it (astream(None, ...)), as the UI's Continue does.--max-total-usdis applied asIMPLEMENTER_MAX_TOTAL_USDfor that process only, so pass it again onresume. - 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 plusget_statusare annotated read-only. Failures the caller can fix (an unknown session, a missing argument, a wrong gate) areToolErrors, 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_runandanswer_gatereturn at once and the work continues as a task in the server's event loop (Orchestrator._launch), one at a time per session;get_statussaysrunning, 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_deliveryserves 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 asstate: errorwith the hintheadless.drivewould print; a server that exits cancels its tasks and leaves the checkpoint, so the session showsinterruptedwith theresumecommand. - Answers name their gate.
answer_gatereads the thread, refuses agatethat is not the one it waits at, and turns the arguments into exactly the resume value the UI form sends (build_resume:answersoruse_suggested_answers;option;generate;implement/parallel/harness_tuning;feedback). The resumed run usesHeadlessOptions()with no flags, so it stops at the next gate; onlystart_run(autopilot=True)rides several gates (answers, architecture, pack) and stops at the implement gate. - Spending needs
confirm_spend. Starting agent sessions,implement_gatewithimplement=trueanditerate_gatewith a change request, is refused unless the call carriesconfirm_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; seeSECURITY.mdfor 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
printin the pipeline cannot corrupt a message.tests/test_mcp_server.py::test_the_server_speaks_mcp_over_stdioruns the real command in a subprocess, and the other tests drive a whole demo run (start, the gates, implement with and withoutconfirm_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>/holdsconfig.json(the snapshot),results.json(oneIdeaResultper idea, rewritten atomically after each idea, so a killed bench loses at most the idea in flight), andoutput/, the run's ownOUTPUT_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
--setoverrides, 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--nameagain with anything different exits 1 and names each difference; the global--max-total-usdis 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:
verifiedis 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-ideais the idea'sIMPLEMENTER_MAX_TOTAL_USD; it must be at least twiceIMPLEMENTER_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-usdcaps 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. WithoutDEMO_MODE=truethe bench needs--liveand--max-total-usd; with it,--liveis refused.--dry-runprints the settings and the catalog's typical-run estimate and writes nothing. - Configurations are flags.
--profile,--harness-tuning,--library, and--set KEY=VALUEbecome environment overrides of the settings for that run only (the bench ownsOUTPUT_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.pyruns the whole bench in demo mode as the CI smoke test;scripts/eval_blueprint.pystays as the cheap, pack-only judge.
Resilience, usage, and tracing¶
- Cut-off answers.
llm.invoke.invoke_textasks again with a larger output budget when the provider reports that the cap ended the answer (finish_reason/stop_reasonread asMAX_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-requestLLM_TIMEOUT_SECONDS). Nodes that call a model (summarizer,architect,strategy, and the panel and blueprint subgraphs' model nodes) also carryLLM_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 appendsUsageRecords to the accumulatingusagestate channel.cost_usdis the call's price frompricing.py(the model catalog, or theMODEL_PRICES_FILEoverride; 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_usagekeeps the two apart:planning_cost_usd(panel, research, summary, architecture, blueprint calls; None when none could be priced) andagent_cost_usd(the roles inAGENT_USAGE_ROLES:implementer,resolver,verifier,fixer), which alone counts against the whole-run budget, plusunpriced_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=trueandLANGSMITH_API_KEYin.env(or the shell). OnlyLANGSMITH_*/LANGCHAIN_*are exported from.env— provider keys are deliberately not, because agent subprocesses inherit the environment. Runs are namedidea-to-mvpand taggedthread:<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_taskbuilds a prompt from thePlanTask(goal, scope, requirements, acceptance criteria, tests, contracts, the summaries of its dependencies, the project commands), streams the session throughimplementer.iter_agent_messages, and records theResultMessagecost, turns, and session id. On success the orchestrator commitsT01: <title>; a failed session is never committed. A crashing session becomes afailedtask and the run goes on; tasks whose dependencies did not finish areskipped; 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 skipsdonetasks and retriesfailedandskippedones in the same workspace. - Budgets. One
BudgetTrackeris shared by all sessions. A session's SDK budget ismin(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;SubmitServicesubscribes withstream_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 tousageas animplementerrecord. - 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 isT01for a task (T01-2for a second attempt),T03-resolver,lane-tests-1(the verification round),fix-1,lead/workstream-<name>for the lead and team sessions ofimplementer.py; a later version's lane and fix labels start withv2-. 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 tuningpilot/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 asuccess),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_ledgercompares the ledger's total with the spendusagereports for what it records (theimplementer,resolver,verifier,fixer, andpilotrecords, and harness tuning'sharness_editor/harness_composer/pilot_selectorcalls);delivery_reportlogs a warning when they differ. A merge resolver's spend is its ownresolverusage record on the model it ran on (split from its task's cost by the ledger), and the lead / workstream sessions of strategysubagentsareimplementerrecords 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.
preparediscards worktrees of a killed run;pick_waveskips tasks behind a failed one, takes the ready tasks (dependencies merged,scheduler.next_ready) and creates one worktree per task;run_task_noderuns the sessions concurrently;merge_wavemerges; back topick_waveuntil nothing can start;finishwrites the log and usage, commits, and removes leftovers. - One worktree per task.
merge.create_worktreemakes<projects>/.worktrees/<workspace>/<id>on branchtask/<id>from the current HEAD, beside the workspace (not inside it). That folder is the session'scwd, 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_PARALLELtasks (max_concurrency/LLM_MAX_CONCURRENCYstill 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 asfloor(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-dirpinned to the worktree's admin directory inside the main repository, because an agent can rewrite its worktree's.gitfile) andmerge_wavemerges branches in task-id order (T03: <title> (merged); fast-forward when main has not moved). A task is recordeddoneinprogress.jsononly 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_resolverruns one bounded session onESCALATION_MODELin 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.testfrom 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_progressshows every running task; a task's end is announced by the merge step with its final status. The implement gate reports the plan'stask_count,dag_width, andmax_parallel.
Verification lanes¶
implement → verify ─Send×3|4→ verify_lane → verdict ─ pass | exhausted ─→ delivery_report
↑ └────── retry ──→ fix ──┘ (back to verify)
- Three lanes, concurrently.
verifyfans out withSendtoverify_lane, one branch per lane (implementation/verify.py), each a session onVERIFIER_MODEL: tests installs dependencies and runsplan.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 withEdit/MultiEdit/Writedisallowed; 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_reportis 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_planinsists on that folder). The tests lane is told to run it, andrun_laneempties the folder first, so a report is always from this round. Afterwardsimplementation/reports.pyreads 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 asevidence(set only by the orchestrator:parse_lane_reportdrops 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 withouttest_report(written before Task 8) keeps the agent's verdict with a logged warning and a note in the summary;SECURITY.mdsays 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_reportnever raises); a lane that lists failures does not pass.passedoverall 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.
verdictfolds the lanes intostate["verification"]({passed, attempts, report, lanes}) and routespass/exhausted(attempts reachedMAX_FIX_ATTEMPTS, or no budget for another round) todelivery_reportandretrytofix.fixruns one implementation session on the merged failure list ([lane] failure, not raw prose), the first attempt onIMPLEMENTER_MODELand every later one onESCALATION_MODEL(verify.fix_role), the orchestrator commits (fix attempt N), and control returns toverify. 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(roleacceptance_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 anAcceptanceSuite: 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 theacceptance/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 toOUTPUT_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 theacceptance/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-levelacceptance/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 casesreports.read_evidencelists carry a failure'smessage, 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 inOUTPUT_DIR/acceptance/<workspace>/trajectories/(its ledger row stays in the workspace, so the spend adds up, but with an emptytrajectory: 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.pychecks what each session did to them (Harness²'s answer-free idea: the agent being judged must not shape the verdict).SessionWatchsnapshots the test files (named like tests, or undertests/,__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,verdictadds a finding when the report lists fewer tests than the previous round (integrity_test_count). Findings travel in the task results (andprogress.json, so a resumed run keeps them), the parallel engine drops those of a branch whose merge was aborted, and the state'sintegrity_findingsis the record.verdictre-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 whenquality/TEST_CHANGES.mdhas 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 asstale, 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. WithTEST_INTEGRITY=block(default) any open finding fails the verdict and reaches the fix session as an[integrity]failure that says how to clear it;warnreports without blocking;offreads nothing. The verification report and the dashboard's Test integrity card list every finding with its status and the agent's justification.SECURITY.mdsays 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 nextverdicthas 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, andFIX_PROMPTrequires a<notes>block with one line per hypothesis,kept | revised | dropped -> <hypothesis> -> <the trajectory moment or report line that decided it>, anew -> ...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_failuressplits the failure list. A lane failure that starts withENVIRONMENT:(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,verdictrecordsverification["environment"]and routes toexhaustedwith a report that says what the user must provide, instead of burningMAX_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, andverifyskips the round that would verify an unchanged project. The lane text is an agent's, so a lane that wrongly claimsENVIRONMENT: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/failedwith the failures left, orstopped). 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 spendmin(IMPLEMENTER_MAX_TASK_USD, remaining / 3), a fix sessionmin(IMPLEMENTER_MAX_TASK_USD, remaining), whereremainingis the whole-run cap minus everything inusage. With nothing leftverifyskips 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_gateinterrupts 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 tochange_requestsand movesiterationon (v0.1 → v0.2). AfterMAX_ITERATIONSversions (default 5) the gate is not offered. change_planner(rolechange_planner) receives the feedback, the PRD, the existing tasks with their status, the contracts, and the id prefix, and returns aChangePlanof new tasks (I2-01, ... for iteration 2; they may depend on finished tasks). The result is checked against the extended plan withvalidate_plan(problems the plan already had are not held against the change, ids must beI<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). AChangePlanmay also be empty with areason(the request is already satisfied): that is accepted at once, builds nothing, and ends the run at the delivered version (route_after_change_planner;iterationandchange_requestsgo back to what was delivered, and the request and the reason are kept inno_change, which the chat shows). An empty plan without a reason is still rejected. The tasks are appended to the workspace'splan.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_workspacesends the run toimplementerorimplement_planexactly as for the first version, and an iteration always builds task by task (builds_task_by_task), even when the strategy issubagents; tasksdoneinprogress.jsonare 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 (verificationis 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 subtractsspent_before_iterationfrom the run'susage, so a full first build does not starve the second. - Delivery.
delivery_reporttags the workspacev0.<iteration>when verification passed (uncommitted work is committed first, an existing tag moves) and writesdeliveries/<workspace>-v0.<iteration>.zipunderOUTPUT_DIR, referenced asdelivery_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 aPublishPlan: 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, thev0.<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.fingerprintis a hash of repository, visibility, backend, branch, commit, and tags;publish_plan(plan, client, confirm=...)raisesNotConfirmedunless 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 listsproblems) when the history it would push ever held a path under.idea-to-mvp/, a.gitcomponent, or a secret env file (delivery.is_secret_env): the working tree's.gitignorekeeps 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_clientpicksRestClientwhenGITHUB_TOKENis set, elseGhClient(the signed-inghCLI:gh apifor GitHub,gh auth tokenfor the push). The token reaches git through git'sGIT_CONFIG_*environment variables as anhttp.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.pyblanksGITHUB_TOKEN,GH_TOKEN,GITHUB_PAT, andGH_PATin 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 withgraph.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.jsontasks in pending / running / done / failed columns with workstream, branch, cost, turns, commit, and an expandable summary plusgit diff --statof the task's commit; skipped tasks count as failed), the live console (theImplEvents of the custom stream, latest 200, oldest first, scroll anchored to the bottom, verification lanes included asverify:<lane>) and the artifacts panel. Events are transient by nature:SubmitServicekeeps 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'stask_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 ownstage: the view's derived stage flickers todonebetween 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 onlyallowed_pathsof the app), and a read-only file explorer. Agr.FileExplorercannot change its root, so it is re-created by@gr.renderwhenever the workspace-pathStatechanges; its text is shown throughSubmitService.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 fromquality/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. AGateSpecholds:build()(creates the widgets),render(payload)(fills them from the interrupt payload asgr.updatekwargs),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 optionalwire()for the form's own events.SubmitServicelooks the pending gate up inGATES; the app lists every gate widget ingate_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_answerand labelled withwhy_it_matters, a Use all suggestions button; the resume is the numbered1. …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 fromHARNESS_TUNING, sent asharness_tuningonly 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 tobuild_resumeunderPAYLOAD_INPUT), a parallelism selector (Sequential | Parallel Nup to the plan's DAG width; sent asparalleland honoured by the routing and the parallel engine througheffective_parallel), and the blueprint editor:PRD.md,ARCHITECTURE.md,plan.mdin a code editor, saved into the pack before anything is built. A save is validated: empty files are refused; aPRD.mdedit is checked against the current plan; aplan.mdedit is parsed (parse_plan_markdown) and checked withvalidate_plan(cycles, unknown ids, ...), and on successplan.json(the source of truth) and a canonicalplan.mdare 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::rootfor light,.darkfor Gradio's dark scheme); rules use onlyvar()andcolor-mix(), so cards are tinted by their accent in both schemes.tests/test_ui_render.pyfails on a hard-coded hex colour outside the variable blocks and checks text contrast in both schemes. The theme and CSS are passed tolaunch(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:SubmitServicereads the thread's checkpoint history andview.stage_elapsedcredits 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 theProjectPreferencesfields, whichsubmit_ideapasses tohandle_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 is70vhtall 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 asCommand(update={"autopilot": ...}), oraupdate_statewhen continuing) makescollect_answers,arch_choiceandplan_gatedecide without pausing: each question'ssuggested_answernumbered like a typed answer (the gate still asks if any suggestion is missing), the architect'srecommendation, 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 runninghandle_submit, which cancelsastreambetween checkpoints, andSubmitService.stop_runre-renders from the last checkpoint. State stays consistent (a step that was running writes nothing); the run shows asinterruptedand 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¶
- Role. Add a
RoleSpectoROLESinroles.py(system prompt, and the provider/model/max-token settings it reads). A role that needs its own provider and model also needsSettingsfields, an entry in every profile ofmodels.toml(PROFILESis built from it) naming a model of the catalog, and commented lines in.env.example(tests/test_config.pyandtests/test_model_catalog.pycheck these). A new model goes intomodels.tomlfirst, with its prices, capabilities,checkeddate, and source. - Output. If other agents consume it, define a Pydantic schema in
schemas.py(every field required, limits in validators) and call it throughllm.invoke_structured(..., fallback=...). - Node. Write
nodes/<name>.py:@with_usage(role=...), model access only throughllm.*, andpreferences_block(state.get("preferences"))in any prompt that shapes the design. - Wire it. Add state fields to
IdeaDiscussionStateandmake_initial_state, register the node ingraph.pywithretry_policy=LLM_RETRY, and add its edges (inside a subgraph, extend its narrow input schema too). Runuv run python scripts/gen_graph_diagram.py. - Show it. Add its transcript entry to
ui/view.py(and a_RUNNINGline if it takes a while) and its card toui/render.py. - Demo fixture. Add the canned answer to
demo/fixtures.py(RESPONSESfor text,STRUCTUREDfor a schema); the demo-parity rule andtests/test_e2e_demo.pydepend on it. - Tests. Fake
llm.get_runtime/llm.invoke_*astests/test_strategy.pydoes, and add a golden idea tosrc/idea_to_mvp/golden_ideas.jsonif 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¶
- Node. A function in
nodes/gates.pythat callsinterrupt({"kind": "<kind>", "question": ..., ...})and normalizes whatever comes back. Honourstate["autopilot"]only for decisions that cost nothing; the implement gate never does. - Edges. Route to and from it in
graph.py; add the node name toGATE_NODESinui/view.pyso the time spent waiting is not counted as work. - Form. One
GateSpecinGATES(ui/gates.py) and its mode inGATE_MODESinui/view.py. The layout, the service dispatch, and the stop wiring follow from the registry; no handler changes. - Tests. Round-trip the spec's
build_resumethrough the node's parser (tests/test_gates_ui.pyshows 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 byuv sync, so tests and the app import it the same way. - Calling the LLM layer: nodes use
from idea_to_mvp import llmand callllm.get_runtime(...)/llm.invoke_text(...)/llm.invoke_structured(...)through the package namespace, and usefrom idea_to_mvp import implementerfor SDK sessions, so a test can monkeypatch one attribute for every node. - Test isolation:
config.clear_settings_cache()resets thelru_cachebetween tests; pointOUTPUT_DIRattmp_pathviamonkeypatch.setenv. Graph lifecycle tests fake all LLM/SDK calls by monkeypatchingllm.get_runtime,llm.invoke_text,llm.invoke_structured(answer fromdemo.fixtures.respond_structured), andimplementer.prepare_workspace/run_implementationandimplementation.verify.run_lane/run_fix— seetests/test_graph_lifecycle.py. - Driving the service in tests: use the
demo_servicefixture (tests/conftest.py: demo models + a real SQLite checkpointer undertmp_path) andtests/service_helpers.py; graph-level tests usebuild_graph(MemorySaver()). - Model-calling nodes: decorate with
@with_usage(role=...)and register them withretry_policy=LLM_RETRY(ingraph.py, or in the subgraph builder for the panel and blueprint nodes). - Agent sessions: build options only through
implementation.options.build_agent_options; never constructClaudeAgentOptionselsewhere, 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.pyfails otherwise. - Golden packs:
src/idea_to_mvp/golden_ideas.jsonlists the ideastests/test_golden_blueprints.pyand 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.