Design-Flow Harness (Gated Lifecycle)
The design-flow harness turns a product goal into reviewable engineering deliverables by walking a gated lifecycle — a sequence of phases with a human gate between each. It is the spine that binds MetaForge's existing run, gate, agent, and twin machinery into a single "design any product" flow.
Per ADR-008, the reasoning inside each phase is delegated to the external harness (the ReAct loop driving MCP tools); MetaForge owns the gated spine — sequencing, gates, and the digital thread.
Flows can also be dependency graphs with parallel and conditional phases, patched while running, and judged by a completion verdict: see Workflow Lifecycle.
Phases and gates
A flow is an ordered list of phases; each phase has an objective (handed to the brain) and an optional gate. Two flows ship today.
Every flow is also preceded by two shared phases from the Engineering Intent &
Requirements Harness epic: Intent (G0, "Intent sign-off") and
Stakeholder Needs (G1, "Needs sign-off") — see
engineering-intent-requirements-harness.md
for the full 9-gate model (G0–G8). The tables below start at Requirements (G2)
onward for brevity; intent and needs always run first. Intent also
settles the deciding questions, once.
design_v1 — the thin mechanical vertical (deterministic handlers drive the
mechanical phases for reliable geometry):
| Phase | Objective (summarised) | Gate |
|---|---|---|
| Requirements | Functional requirements, constraints, primary load/use case → twin | Requirements sign-off |
| Preliminary Feasibility | Mass/cost/power budgets, first-order structural/thermal/geometry feasibility, major risks → twin | Preliminary Feasibility Gate (G3) |
| Detailed Design | Author the critical subsystem geometry/schematic + rationale → twin | Design review (G6) |
| Simulation & V&V | Run FEA / ERC-DRC, extract the key result, record a verdict → twin | V&V sign-off (G7) |
concept_v1 decides what to build and stops before any CAD. It runs
mech_v1's intent (with the deciding questions),
needs, requirements, feasibility, route selection and concept design phases,
copied verbatim (tests/unit/test_concept_flow.py fails if they drift), then
a Verification Plan phase that hands the concept on with its checks named:
for every requirement the method, the load case or measurement, the
acceptance criterion and the phase that will do it, plus how each of the
concept's open items will be closed. A concept approved here is the starting
point for a mech_v1 run.
hardware_v1 — the full hardware/robotics lifecycle. Every phase is driven
by a goal-driven deterministic handler (see below) so each phase reliably
lands its real, typed deliverable in the twin:
| Phase | Objective (summarised) | Gate |
|---|---|---|
| Requirements | Functional reqs, environment, quantified constraints (mass/power/DOF/cost), motion/use cases → twin | Requirements sign-off |
| Preliminary Feasibility | Mass/cost/power budgets, first-order structural/thermal/geometry feasibility, major risks → twin | Preliminary Feasibility Gate (G3) |
| System Architecture | Subsystem decomposition, interfaces, mass/power/compute/cost budgets, actuation/sensing/compute/power selection → twin | Architecture Gate (G4) |
| Concept Selection | Trade study: propose 2-3 concepts satisfying the architecture, select one with alternatives + rationale → twin | Concept Selection Gate (G5) |
| Mechanical Design | Author + commit the load-bearing/motion-critical geometry, material + dimensions → twin | Mechanical design review (G6) |
| Electronics Design | Power budget, schematic topology, component selection, ERC → twin | Electronics review |
| Firmware & Control | Control loop, task/RTOS structure, pin map + drivers → twin | Firmware review |
| Simulation & V&V | FEA / kinematics / ERC-DRC / thermal, pass-fail verdicts vs requirements → twin | V&V sign-off (G7) |
| Manufacturing Prep | BOM + cost, fabrication outputs, assembly + bring-up plan → twin | Manufacturing readiness / Release Gate (G8) |
The Preliminary Feasibility gate's mass/cost/power and risk criteria are
computed for real (not just shown as prose) by
twin_core.consistency.gates.evaluate_g3_feasibility, auto-loading the
project's persisted budget/invariant EngineeringEntity declarations
(twin.record_engineering_entity). The Architecture gate's
"architecture satisfies major constraints" criterion is likewise real, via
evaluate_g4_architecture (reusing the same constraint-evaluation engine the
V&V gate already enforces with). The Concept Selection gate's checks are
real too, via evaluate_g5_concept_selection, reading
twin.record_decision's alternatives/rationale/parent_refs --
GoalDrivenConceptSelectionHandler (the "Decision Agent", spec section
26.12) is what populates them: it proposes 2-3 candidate concepts, picks
one, and records the decision linked back to the architecture decision (see
Concept selection / Decision Agent
below). The Release gate's checks are real too, via evaluate_g8_release
(the Manufacturing Prep phase's gate): real checks against
TwinAPI.list_baselines() and "evidence" entities' staleness status
, plus "waiver"/"release_approval" EngineeringEntity
declarations that only count once approved via
twin.approve_engineering_entity (see
Waiver / release model below), plus
"required verification complete" via the same injected
traceability_coverage accessor G6 uses. evaluate_g6_design_sketch (G6,
Preliminary Design / Design Sketch — reads the existing design_sketch work
product + its approve-sketch REST endpoint, and the system_architecture
work product's component/interface counts, rather than inventing a parallel
checkpoint; its "requirement coverage" criterion is likewise real when a
caller supplies a traceability_coverage accessor) is now mapped
onto each flow's design/"Mechanical Design"/"Detailed Design" phase gate
— the natural preliminary-design checkpoint right after Concept
Selection (G5). evaluate_g7_verification_readiness (G7 —
per-critical-requirement verification-method/ownership checks, reusing the
same metadata["verification_method"]/Constraint.source conventions
TraceabilityAgent already established) is likewise now mapped onto each
flow's simulation/"Simulation & V&V" phase gate, the checkpoint
right before Manufacturing / Release (G8). Neither injects a
traceability_coverage accessor from this checker (same as every other
gate here — none do today), so their requirement-coverage check stays
NOT_EVALUATED until that's wired. See twin_core/consistency/gates.py's
module docstring for exactly which checks each evaluates today vs. still
advisory pending Phase 6 (Evidence Integration).
Select a flow with the flow id in the run request ("flow": "hardware_v1").
A full hardware_v1 run now commits nine real, typed work products —
prd, documentation (architecture budget), cad_model, bom, pinmap,
firmware_source, test_plan, manufacturing_file, and design_decision.
Adding or extending a phase is a data change in
orchestrator/design_flow/spec.py, not new control flow.
Phase tools follow deliverables
A phase's MCP tool set is derived from what it must produce
(mcp_core.profiles.DELIVERABLE_TOOLS), not only from its disciplines. The
live failure: tailoring replaced the simulation phase's disciplines with
['mechanical'], so it had no freecad.generate_mesh or calculix.run_fea
and recorded fail_blocked_no_fea. Now every required and expected
deliverable contributes its tools, always kept, and set_disciplines merges
with (rather than replaces) the template discipline a deliverable depends on.
See context engineering for budget and drop rules.
Goal-driven deterministic handlers
The native ReAct brain reasons well but is unreliable at reliably producing a
specific typed artifact (it may author prose where a cad_model or bom is
required, or claim a result a tool never actually returned). So every
hardware_v1 phase is routed to a goal-driven handler that follows a hybrid
pattern:
the LLM extracts a small structured spec from the goal (its strength — reading intent), then a deterministic step authors the artifact and commits it through a recorder (the reliable path). The artifact is always goal-named, loadable, and consistent.
| Phase | Handler | Produces |
|---|---|---|
| Requirements | GoalDrivenRequirementsHandler | the constraint_set (verifiable constraints, each with an acceptance method, the one home of the values), then the prd prose, then a decision linking CS-...@n by depends_on |
| Architecture | GoalDrivenArchitectureHandler | documentation (per-subsystem numeric mass/power/cost budgets) |
| Concept Selection | GoalDrivenConceptSelectionHandler | design_decision (trade study: alternatives + rationale + link to the architecture decision) |
| Mechanical Design | NativeMechanicalDesignHandler (backstop GoalDrivenMechanicalHandler) | the brain's named multi-part cad_model; the backstop is one primitive |
| Electronics | NativeFirstPhaseHandler (backstop GoalDrivenElectronicsHandler) | KiCad schematic (the module interconnect, or a custom board's circuit with pcb_layout, DRC and Gerbers) and the power budget; the backstop records bom + power budget only |
| Firmware & Control | NativeFirstPhaseHandler (backstop GoalDrivenFirmwareHandler) | firmware_source that was built, statically checked and run on the emulator; the backstop is a pin map + scaffold |
| Simulation & V&V | GoalDrivenVVHandler | test_plan + an honest verdict (deep analyses deferred, never falsely "compliant") |
| Manufacturing Prep | GoalDrivenManufacturingHandler | manufacturing_file + honest readiness (Gerbers deferred to Phase 2) |
Gate feedback reaches scripted handlers. A retry or rework reason arrives as
FlowContext.retry_feedback, which only the ReActPhaseBrain reads. A scripted
handler sees only the goal, so HybridBrain puts the feedback before the goal
for any handler that does not set reads_retry_feedback (the native-first
handlers set it, and pass the feedback on to their own backstop). Before this,
every scripted phase ignored every retry and rework reason (2026-11-15).
Handlers share the pattern in api_gateway/runs/*_handlers.py and persist via
the recorders in api_gateway/twin/ (geometry_recorder, bom_recorder,
document_recorder). A HybridBrain routes each phase to its handler and falls
back to the ReActPhaseBrain for any phase without one (mech_v1 and the older
design_v1 use different handler sets).
mech_v1 design phase. The design phase is driven by the native
ReActPhaseBrain (flow context first in the prompt, FreeCAD session tools,
twin.commit_geometry) through NativeMechanicalDesignHandler. It is told to
build a named multi-part design and to pass the real material and key
dimensions in extra_metadata on the commit. If the phase ends with no loadable
cad_model (or the native turn fails), GoalDrivenMechanicalHandler runs as a
backstop. It is given the flow context and the project's constraint set,
re-asks once if its spec breaks a stated limit, and the phase summary starts
with FALLBACK:. design_v1 routing is unchanged.
hardware_v1 design, electronics and firmware (native first). These three
phases used to run only their scripted handlers, which never call FreeCAD
authoring, KiCad or the firmware build: a run could commit a solid cylinder as
its enclosure and finish with no schematic, board or built firmware
(2026-11-15). The design phase now runs NativeMechanicalDesignHandler as in
mech_v1. Electronics and firmware run NativeFirstPhaseHandler
(api_gateway/runs/native_first.py): the ReActPhaseBrain does the phase with
a rules note naming the tools (kicad.generate_schematic,
kicad.generate_pcb, kicad.autoroute_pcb, kicad.run_erc/run_drc,
twin.record_design_files; firmware.build, firmware.static_check,
firmware.run_emulated), then a probe checks the twin for the phase's work
products since the phase started (schematic for electronics, firmware_source
for firmware). Electronics is told to prefer complete commercial modules and
boards over a custom board; a module build delivers the interconnect schematic,
and only a custom board adds pcb_layout and gerber. If one is missing or the brain fails, the scripted handler
runs and the summary starts with FALLBACK:. The pcb_layout and
firmware_source deliverables now carry the tools that make them in
DELIVERABLE_TOOLS (mcp_core/profiles.py; the board's set includes the
schematic tools), so a phase expected to deliver a board can draw one whatever
discipline it names. schematic alone keeps only the recorder, because
design_v1's CAD phase also expects it and has no room in its tool budget.
Multi-part designs commit an assembly. When a design has more
than one part, the cad_model hint tells the agent to commit each part as its
own named cad_model, then build one assembly (freecad.create_assembly, then
freecad.add_part_to_assembly for each part by name), export it and commit it
as <product> Assembly with twin.commit_geometry and
parts=[{node_id, name, material, position_bbox_mm}] (or part_node_ids). The
recorder checks every part is an existing cad_model in the same project before
creating anything, records the list as metadata.parts, and links the assembly
to each part with a parent_of edge. The geometry check at the gate
(check_assembly in api_gateway/runs/geometry_constraints.py) then fails a
phase window (the same since_ts window the deliverable check uses) that
committed more than one part cad_model and no assembly referencing them
(superseded nodes, and parts from earlier phases, are ignored) (multi-part design has no assembly), and, when an assembly exists, fails
part position boxes that overlap by more than 0.01 mm or an assembly bounding
box that does not enclose its parts.
Coverage is met when any one assembly covers every part, so a sub-assembly
committed after the top-level one no longer flips a covered design to "no
assembly covering" (it used to judge whichever assembly was listed
last). A cad_model committed with model_role: "analysis" (and idealises,
the design part it stands for), such as an FEA idealisation with simplified
supports, is left out of both geometry checks: it is not product geometry, so
it is neither a loose design part nor held to the product's size, stock or
material limits. model_role: "component" marks the same for a bought
component's own 3D model, made so a board's 3D export shows it (a footprint
model): it is part of the board's model, so the release checklist, DFM, the
assembly check and the release package leave it out, and Develop never shows it
as the product (twin_core/model_roles.py).
A size limit is measured on what it names. A metric that names a part
(seat_width_min, leg_height_max) is compared only with the cad_models whose
names contain that word (Chair Seat), and is reported as not evaluated when
no model is named for it, rather than being applied to every part. A
product-level metric (product_envelope_width, overall_height), or one whose
word every model shares, is compared with the assembly when the design has one.
A metric that names nothing still applies to every model. Extents are sorted
largest first: length is the largest, width the middle and height or depth the
smallest, except that a panel's depth (a part whose smallest extent is under a
quarter of its middle one) is its smaller in-plane size, never its thickness.
A revision that a retry or rework turned down is not part of the design
either. When a reviewer retries or reworks a phase, that
attempt's drafts are closed as rejected or abandoned on their
REVISION_OF edge. The geometry checks skip a closed revision and judge the
newest one under the same name that is still open or approved. Before this,
a loose model left by an abandoned attempt kept failing every later
attempt's gate, because the Temporal gate's window is the whole project.
The constraints a gate compares against are scoped the same way. Each
constraint belongs to the constraint_set revision it arrived in
(metadata.constraint_set_wp), and the geometry, analysis and design-record
checks evaluate only constraints of current revisions and of this run's open
drafts. A constraint whose set was closed as rejected or abandoned, or
superseded by a newer revision (a supersedes / revision_of reference, an
incoming SUPERSEDES edge from a revision that is not itself closed, or an
open draft whose REVISION_OF edge names it as its prior_node_id), gets no
vote, so a phase that corrects a limit can relax it as well as tighten it.
A constraint with no set, or whose set's status cannot be read, is still
evaluated: the gate fails toward checking a limit, never toward skipping one.
Where a real analysis needs a capability MetaForge doesn't have in Phase 1 (ERC/DRC on an authored schematic, Gerber export), the handler records the result honestly as deferred rather than asserting a compliance the tools never established.
Eval flywheel and the honest scoreboard
The harness is matured by an eval flywheel (evals/): reference products are
driven through the real gated flow (evals/run_scenarios.py, auto-approving
each gate), and correctness rubrics score the engineering outcome — not
mere presence — of each phase against what a real deliverable must contain. The
rubrics deliberately score correctness, so a phase that records a design_decision
but no real content scores low.
Seven per-phase rubrics (requirements, architecture, mechanical, electronics,
firmware, V&V, manufacturing) plus one cross-phase consistency rubric
(digital-thread integrity — does the same device/interface/power thread through
every phase, and do the artifacts agree?) run over three reference products:
l1_breakout (IMU board), l2_logger (BME280 dual-bus logger), and
l3_balancer (a self-balancing robot controller). All three score identically:
every phase at 1.0 except the electronics erc_or_netlist check — which is a
genuine Phase-2 boundary (real ERC needs an authored schematic, a KiCad-write
capability), not a defect — with the digital thread intact end to end.
A second suite, evals/run_chat_scenarios.py, applies the same
flywheel to the harness-backed chat surface: scripted multi-turn
conversations over /v1/chat scored for needle recall across turns,
project-brief adherence, context-window telemetry honesty, and tool-call
trajectory quality (duplicate/retry discipline, error rates, big-observation
survival). Scenarios declare expected_today for behavior known broken on the
current harness (e.g. facts beyond the 20-turn history slice, until
lands compaction), which reports as xfail and flips to xpass when the fix
ships — so re-running the identical baseline command measures each
context-engineering phase as it lands. See evals/README.md for the scenario
schema and rubric catalog.
Work-product quality (substance, not structure) is scored by an optional
LLM-as-judge pass, evals/judge.py: it grades each run's twin work
products against the scenario's definition_of_done and attaches advisory
judge blocks to the report. Deterministic rubric checks remain authoritative
for pass/fail.
How a run flows
POST /v1/runs {request: {goal, flow: "design_v1", project_id}}
│
▼
DesignFlowExecutor.run(run_id) # orchestrator/design_flow/executor.py
for each phase:
brain.run_phase(...) # ReAct loop + MCP tools → artifacts in twin
if phase.gate:
store.request_approval(...) # run → awaiting_approval (SSE emits it)
decision = await gate # resolved by POST /v1/runs/{id}/approval
approve → next phase
retry → re-run THIS phase (see "Retrying a phase"), same gate again
rework → go back to an EARLIER phase (see "Sending a run back"), re-run from there
reject → run ends (rejected)
store.complete(run_id, result)
The executor drives the existing
InMemoryRunStore state machine, so
the run's status transitions stream over the existing /v1/runs/{id}/events
SSE and /ws surfaces, and pause/resume uses the existing approval endpoint. A
GateCoordinator bridges the async gate wait to the synchronous store
transition triggered by the approval route.
Flow context reaches every phase
The context given to flow.propose (manufacturing route, processes, machines,
stock, quantity, target maturity, loads and use, budget, requirements) is not
only a generator input. FlowContext.render_for_phases() renders it once into a
text block that is stored on the flow version and frozen with it:
FrozenFlow.contextholds the block and is part of the content hash, so it cannot change after approval. A flow with no context hashes exactly as before, and versions saved before the field existed load with an empty context.- The version store persists it in a
flow_contextcolumn, added in place to existing databases. - Temporal:
DesignFlowInput.flow.contextis copied intoPhaseRequest.flow_context. Both fields are optional with an empty default, so workflows already in flight still decode and replay. - In-process: the run record carries
flow_contextandDesignFlowExecutor.runpasses it into the executor'sFlowContext. - Both engines call the same
ReActPhaseBrain, which puts the block at the very start of the prompt under "Flow context", ahead of the per-phase goal. The block is identical for every phase of a run, so the prompt prefix stays stable for prompt caching. With no context the prompt is unchanged.
The requirements phase is expected to turn the stated values (stock, loads, spacing) into typed constraints, and no phase should report them as unknown.
Generation receives the manufacturing context
The frozen flow context is what the requester stated at proposal. The
project's manufacturing context
record (MFC-PROJECT) is the shared, revisioned record every generator
reads, and the two are kept consistent:
- A proposal that states a
manufacturingContextrecords it in the project's context item asuser_stated. A proposal that states none takes the record's confirmed values as its context (never its assumptions, since the flow context is treated as stated), so a route already chosen in Create or decided earlier is not asked for again. - Every phase brain also gets the record's block, read when the phase starts,
among its phase inputs: confirmed values, assumptions and gaps on separate
lines, with the revision (
MFC-PROJECT@n, orunresolved). A route the person changed in Create, or a decision approved at an earlier gate, reaches the next phase this way. - A
manufacturing_routedecision recorded inside a run is an assumption pending that run's gate. When a person approves the gate it becomes adecisionin the record. - The concept tools a phase calls (
twin.render_concept_sketch,twin.render_concept_image,twin.generate_concept_mesh,twin.generate_sketch) read the same record themselves and record themanufacturing_context_refthey used on each output.
Driving it from the CLI
# The friendly way: start a gated flow for a goal and stream transitions
python -m cli.forge_cli design "quadruped robot leg able to carry 5 kg body mass" \
--flow design_v1 --project-id <uuid>
# The explicit equivalent (what `design` wraps)
python -m cli.forge_cli runs create --request-json \
'{"goal": "quadruped robot leg able to carry 5 kg body mass",
"flow": "design_v1",
"project_id": "<uuid>"}'
# Watch phase/gate transitions stream (SSE)
python -m cli.forge_cli runs watch <run_id>
# When the run pauses at a gate, review and pass it
python -m cli.forge_cli runs approve <run_id>
# ...or hold the design
python -m cli.forge_cli runs reject <run_id>
A run is treated as a design flow only when it opts in with a flow id (or
kind: "design_flow"); a bare {goal} keeps the plain run semantics.
Driving it from chat
The chat agent can start a flow itself via the runs MCP adapter:
run.start_design_flow— goal + flow id (validated against the registry, defaulthardware_v1) +project_id; drives the same in-process path asPOST /v1/runsand returns the run id + phase list.run.get_status— run id → lifecycle state, the gate reason it is paused on, error/result — so the agent can report progress in conversation.
Launching is deliberately not pre-gated: the flow pauses at every phase
boundary for human approval, so the gates themselves are the HITL
mechanism — the tool only queues work a human must repeatedly sign off.
Approvals stay where they always were (POST /v1/runs/{id}/approval, the
dashboard, or forge runs approve).
Deliverable enforcement ("no work product silently missing")
Each phase declares required_deliverables — the work-product types it must
record into the twin (e.g. the Design phase requires a cad_model). At the
gate, a GateEvaluator (backed by the same project store the dashboard reads)
checks which of those types the phase actually recorded during its window:
- All present → the gate pauses for human sign-off, showing present/missing.
- Missing and the phase is
enforce_deliverables→ the run fails at the gate with the missing list, rather than silently passing. The Design gate cannot pass without a committed, viewablecad_model.
Each required type gets a specific "which tool, which arguments" hint in the
phase prompt (deliverable_hints in api_gateway/runs/flow_brain.py), keyed by
the same type string the gate counts (WorkProductType value). For example prd
is twin.record_document(document_type='prd'), constraint_set is
twin.record_constraint_set, and simulation_result / load_case are
twin.record_document with that document_type. A type no MCP tool can record
(schematic, pcb_layout, gerber, pick_and_place, manufacturing_file,
test_plan, test_result, verification_report) says so and tells the model
not to substitute another type. twin.record_document is in PHASE_COMMON (mcp_core/profiles.py), so every
phase carries it. A unit test fails when a type a template requires
or expects, or that tailoring can add, has no hint, so a tailored deliverable can
no longer fall back to the generic "record it into the twin" line.
A server-run phase cannot ask. Skills and phase objectives say to ask the
person for anything missing, which is right for an interactive client. A phase
the server runs has no one to answer, so its prompt also says it runs
unattended (UNATTENDED_PHASE_RULE in api_gateway/runs/flow_brain.py): instead
of asking and stopping, it records a deferred decision with its open questions
as the reason where the objective allows one, and otherwise decides with what it
has and states its assumptions. The reviewer answers at the gate, and a retry
carries the answer back. Without this, a route selection phase on a brief with
no manufacturing context asked for the quantity, recorded nothing, asked again
on every retry, and the run failed when the findings stopped changing.
Client-mode runs do not use this prompt, so a connected client still asks.
This makes completeness machine-enforced and quality human-judged: the machine guarantees the deliverable exists in the twin; the human reviews whether it's right.
Retrying a phase from its gate
A gate answers one of three decisions through
POST /v1/runs/{id}/approval:
| Decision | Body | Effect |
|---|---|---|
| approve | {"decision": "approve"} | the run moves to the next phase |
| reject | {"decision": "reject"} | the run ends rejected |
| retry | {"decision": "retry", "reason": "..."} | the same phase runs again and the same gate opens again |
On a retry the phase brain gets the gate's findings (missing deliverables, an
ungrounded reply, constraint violations) and the reviewer's reason as the
first block of its prompt, ahead of the flow context. Every earlier approved
phase is kept; only the retried phase's previous attempt is dropped from the
run's completed list. Nothing before it re-runs and no earlier gate is asked
again.
A gate that is not ready parks instead of failing the run. When an enforcing
phase is missing required deliverables, has an ungrounded reply, or the gate
enforces constraints that are violated, the run moves to awaiting_approval
with a reason that starts NOT READY (retry the phase or reject) and lists the
findings. Such a gate takes retry or reject only: an approve is answered
409 by the route and is ignored by the workflow, because approving work the
system already knows is incomplete is the click-through habit gates exist to
prevent. Reject still ends the run.
Cap. One phase may be retried METAFORGE_DESIGN_FLOW_MAX_PHASE_RETRIES
times (default 3). The cap is read when the run starts and carried into the
workflow as DesignFlowInput.max_phase_retries, so it cannot change mid-run.
A retry past the cap is refused with 409; if one reaches the engine anyway the
run ends failed with the reason.
Visibility. Each attempt is recorded in the run's events
(phase_started with attempt N, gate_not_ready, phase_retry_requested
with the reviewer and reason). GET /v1/runs/{id}/flow-state adds attempt,
retriesLeft, gateReady and gateFindings.
Temporal. The retry travels as an optional retry flag on the
submit_gate_decision signal (GateAnswer.retry, default False), and
PhaseRequest gains optional retry_feedback and attempt, so inputs from
before the change still deserialize. Parking a not-ready gate replaces a
_fail, which changes the workflow's command sequence, so it is guarded by
workflow.patched("forge-495-gate-retry"): a run whose history already holds the
old failure replays it unchanged. The in-process executor behaves the same way
(GateCoordinator.note_retry), so the two engines stay at parity.
What the retried or reworked phase is told. After the gate
decision closes the phase's drafts, both engines read them back and add a block
to the retry or rework feedback: each turned-down revision's ref
(CAD-BRACKET@2), the gate's reason, and a short diff against the revision
before it (bounding box, volume, mass for a part; limit changes for a
requirement set). In-process this is DesignFlowExecutor(revision_notes=...);
on Temporal it is the collect_revision_notes activity, which returns plain
data, guarded by workflow.patched("forge-530-revision-notes"). See
context engineering.
There is no MCP run-approval tool: a gate is answered by a human on the dashboard or the approval endpoint, never by the agent.
Sending a run back to an earlier phase
A retry re-runs the phase a gate belongs to. That cannot fix a verdict that is really about earlier work: a verification gate that fails on a safety factor needs a design change, and the design phase is behind it. A fourth decision, rework, names an earlier phase:
| Decision | Body | Effect |
|---|---|---|
| rework | {"decision": "rework", "to_phase": "design", "reason": "..."} | the run goes back to to_phase, re-runs it and every later phase in order, and re-opens each of their gates |
The target phase's brain gets, as the first block of its prompt, the
reviewer's reason, the findings of the gate that sent the run back, and the
summary of the phase that failed. Later phases get no special block; they see the
reworked phase's new summary in the thread so far. Phases before to_phase
keep their completed entries and their approvals and are not asked again. A
rework is accepted at a gate that is not ready as well as at one that is.
Validation. to_phase must be an earlier phase of this run's own frozen
flow. A missing id, an id that is not part of the flow, or the current or a
later phase is refused with 422 and a reason that names the problem (naming the
current phase points at retry). Rework on a run that is not a design flow is
422 too.
Cap. One run may be sent back METAFORGE_DESIGN_FLOW_MAX_REWORK_CYCLES
times (default 3), counted across the whole run. It is read when the run starts
and carried in DesignFlowInput.max_rework_cycles; the count survives a
continue-as-new. A rework past the cap is refused with 409; if one reaches the
engine anyway the run ends failed with the reason. Each phase keeps its own
retry budget on every pass.
Visibility. Each cycle is a phase_rework_requested run event carrying
from, to and cycle (and the reviewer and reason in detail).
GET /v1/runs/{id}/flow-state adds reworkCycles, maxReworkCycles and
reworksLeft; phases after the target read pending until they run again.
Temporal. The target travels as an optional rework_to field on the
submit_gate_decision signal (GateAnswer.rework_to, default empty), and
DesignFlowInput gains max_rework_cycles and rework_cycles, so inputs from
before the change still deserialize. Handling a rework adds commands that older
histories do not contain, so it is guarded by
workflow.patched("forge-500-rework"), which is consulted only after a rework
answer has arrived. A run parked at a gate before the deploy, including one
parked at its last gate, therefore replays exactly as before and accepts a rework
as new history. A rework signal with an invalid target is recorded as
gate_decision_ignored and the gate stays open. The in-process executor behaves
the same way (GateCoordinator.note_rework), so the two engines stay at parity.
There is still no MCP tool for this: like approve and retry, only a human answers
a gate.
A run's change set: drafts until the gate
Every definition a run writes (parts, assemblies, constraint sets, intent,
needs, objectives, BOMs, component selections: the definition types in
twin_schema.md section 2.30)
is a draft revision in the run's change set. Nothing new is asked of the
agent or the reviewer: the tools are the same, and the write knows its run from
the MCP call context (run_id and phase, set by the Temporal worker's phase
scope and, for the in-process engine, by the executor's injected phase_scope).
- During the run a draft never moves its item's head. The run's own reads
(
twin.item_history,twin.get_nodewithitem_key) see its drafts over the head; the dashboard, other runs andGET /v1/twin/itemssee only approved heads. The phase's own gate is evaluated over its drafts, so the reviewer sees exactly what an approval would commit. - Approve commits the change set before the run moves on: every drafted
item's head moves to the run's latest draft, the drafts become
approvedwith the gate's name and the gate's reason aschange_reason, andSUPERSEDESlinks each one to the revision it replaced (with staleness propagation, spec section 21). All of a gate's items move or none do. - Reject, retry and rework close the change set: its drafts become
rejected(reject) orabandoned(retry, rework) with the reviewer's reason. No head moves. The drafts stay in each item's history; they never reach the current view. A retried or reworked phase is told that what it recorded was discarded, and records its work again on top of the current heads. - The run ends any other way: a completed run commits what phases after its last human gate drafted (an ungated or auto-approved phase rides along with the next human gate otherwise); a failed or canceled run abandons its drafts; a gate that timed out rejects them.
Optimistic concurrency (spec sections 40 and 41). When a run first drafts an
item, the change set records that item's head as its base. At approval, if any
base head has moved since (another run's approval, or a direct write outside any
run), the whole approval is refused with 409 and a PATCH_CONFLICT message
naming each item, its base and its current head, for example
CAD-LEG was @1 when this run drafted CAD-LEG@3, and is now @2. Nothing is
committed and the run stays parked at its gate. A retry of that gate is the
rebase: it closes the stale drafts, and the conflict message is appended to the
retry reason, so the phase redoes its work on the current revisions. Revision
numbers are never reused, so two runs drafting one item get distinct numbers
(@2 and @3 above) and a closed draft's number stays its own.
Both engines. Gate decisions from either engine go through
routes.decide_run_gate (shared by /v1/runs/{id}/approval and
/v1/approvals/gate:{id}/decision), which settles the change set before the run
record moves, so a resumed phase never writes into a change set that is being
closed. Terminal states reach api_gateway/runs/change_sets.py through the run
store's transition observer, which on Temporal is fed by the reconcile loop.
Not a branch. The change set has no node of its own and no branch or merge
vocabulary: it is the items whose Item.drafts names the run plus the
REVISION_OF edges stamped change_set=<run id>. It does not go through
TransactionEngine, whose Patch carries field edits: here the
revisions already exist as immutable nodes and committing is a head move. It
shares that engine's discipline instead: check every precondition, then write,
and since GraphEngine has no multi-write transaction, a commit that fails
part-way restores the heads it already moved and reports 503.
Observability. item_revision_drafted, run_change_set_committed,
run_change_set_refused, run_change_set_closed and
run_change_set_commit_failed log events; the
metaforge_twin_change_set_total{outcome} counter (committed, refused,
rejected, abandoned, failed); the TwinChangeSetApprovalsRefused alert.
Known limits: the gate's deliverable check (present_types) reads the project's
work products, so two runs on one project at the same time can each count the
other's drafts as present; the check at approval still refuses a commit whose
base moved.
Exact CAD at the release gate
Exact geometry is built on commit, not per edit. twin.build_exact_cad
(or POST /v1/twin/items/{key}/exact-build) runs as a job on an explicit
commit or on demand: it lowers the design IR in the CadQuery adapter, checks
the B-Rep, and moves the item head only when the check passes; a failure is
recorded on the revision it started from and the last valid revision stays
the head. While it runs, the last valid exact revision stays current, and a
result whose base moved ends stale and is not applied. A parametric
sketch is built only once its required inputs (depth or angle, and material)
are supplied; nothing is assumed for them.
A phase whose gate is G8 (the spine flow's manufacturing gate) requires
every CAD item in the project to be at a validated exact revision with a STEP
exported from that revision whose re-import round trip passed. Until then the
gate lists exact CAD incomplete: <item>@<n>: <reason> as missing, and the
G8 consistency check exact_cad_validated is incomplete (the gate is
not_ready). A project with no CAD items is not held to this rule. No other
gate changes. See the twin schema.
Stale evidence at the gate
A simulation_result, a design_decision and an evidence entity are pinned,
when they are written, to the item revisions they are about: a simulation to the
geometry it analysed (CAD-BRACKET@1), and to a constraint set
(CS-BRACKET-REQS@1) only when the call names it or the requirements it
verifies; evidence also to the project's constraint sets. See
records pinned to revisions.
When an item's head moves (a write outside any run, or this run's gate approving
its drafts), every record pinned to an older revision of that item becomes
stale. An open draft stales nothing: a gate that rejects or abandons it leaves
the old records current, and marks records made on the draft itself invalid.
The gate reads the same flag the agent does, so stale evidence never satisfies a criterion:
- Analysis constraints. The analysis check finds a model's results by the
derives_fromlink or by the model's item key in the result's pins, so a result recorded on an older revision of the same part is found even though it names the old node. The latest current result is used. When only a stale one exists, every analysis constraint on that model gets a finding (a violation at error severity) naming the record and the revision it was for, for examplemax stress: 'Bracket FEA' is stale: it was for CAD-BRACKET@1, and CAD-BRACKET is now @2; re-run it on the current revision. - Deliverables. A stale, superseded or invalid
simulation_resultorverification_reportdoes not count towardrequired_deliverables. - G8 release. "Stale evidence resolved" now covers
simulation_resultwork products as well as evidence entities, and its detail names each stale record with the same text.
A re-run on the new revision is current, and it marks the older run of the
same analysis superseded (when its gate approves, for a re-run made inside a
run), so the gate passes once the analysis is redone. Nothing extra is asked of
the agent: the pins are inferred from what the record already names.
Phase summaries are not decisions. When a phase that requires a
design_decision ended without recording one, the native brain used to record
its own phase summary as "<phase> - phase summary". It no longer does: the
summary is kept on the run record (completed[].summary, shown as
phases[].summary in the run status), and a phase that decided nothing shows a
missing design_decision at its gate. Existing phase-summary decisions are left
in place and are not migrated.
Phase step budget, blob storage and tool visibility
Step budget. Each native phase has its own tool-use budget instead of one
hard-coded 24. A phase whose required or expected deliverables include
cad_model or simulation_result is "heavy" and gets a larger budget, because
building several sketch-based parts takes many CAD calls.
| Variable | Default | Applies to |
|---|---|---|
METAFORGE_FLOW_PHASE_MAX_STEPS | 24 | every other phase |
METAFORGE_FLOW_PHASE_MAX_STEPS_HEAVY | 60 | phases that need cad_model / simulation_result |
An invalid or non-positive value falls back to the default with a
flow_phase_budget_env_invalid warning. The budget is logged per phase in
design_flow_brain_phase (max_steps, heavy), and a phase that runs out
logs design_flow_phase_exhausted and ends its summary with the budget it used.
Blob storage in the worker. design-flow-worker carries the same MINIO_*
variables as gateway (a test keeps them in step). The deterministic commit
paths, GoalDrivenMechanicalHandler and MechanicalDesignHandler, call the
geometry recorder with require_blob_store=True: if the STEP blob cannot be
stored, the commit raises and the phase reports the failure instead of creating
a cad_model with no stored geometry. The optional path is unchanged:
twin.commit_geometry called over MCP and the /v1/twin/import route still keep
the node and log geometry_blob_store_skipped when storage is down.
Tool visibility. Every search_tools call logs search_tools_query with the
query and the tools it matched, registered, found already available, could not
register (phase cap) or found unavailable (service-refused), so a phase hunting
for a missing tool shows up in the logs. The search covers the whole
MCP catalog and matches each query word against a tool's id, name and
description, so a multi-word query such as freecad assembly finds
freecad.create_assembly; the result lists every match with a one-line
description and says plainly when a match exists but cannot be registered.
freecad.create_body and freecad.create_sketch now return the body or sketch
id, its label, and the next call to make, so a phase does not re-create the body.
Constraint-as-gate-criteria
Gate criteria were previously prose shown to the approver but never
evaluated. Now every gate also evaluates the project's recorded constraints
through the twin's constraint engine (TwinConstraintChecker in
api_gateway/runs/gate_eval.py):
- Every gate appends the real constraint state to its approval reason —
Constraints: OK (N evaluated)or the violation/warning list — so the reviewer sees data, not just prose. - Gates with
enforce_constraints(the final gate of each built-in flow: V&V sign-off ondesign_v1/mech_v1, Manufacturing readiness onhardware_v1) fail-fast when any ERROR-severity violation applies to the run's project, with the same contract as a missing required deliverable. - Best-effort: a broken or absent constraint engine reads as "unchecked" and never blocks or crashes a run.
- Scoping: the engine evaluates the branch, not the project — violations
citing
work_product_idsare filtered to the run's project; violations citing none are treated as global and always count.
Geometry constraints. A structured requirement (metric +
limit) carries the placeholder expression True, so the engine alone can
never fail it. TwinConstraintChecker therefore also compares those
constraints to the project's current cad_model (latest per name) through
api_gateway/runs/geometry_constraints.py, and adds the result to the same
violation list. Covered: envelope and size metrics (envelope, length,
width, height, depth, size, dimension) against the sorted bounding-box
extents read from metadata.dimensions_mm, bbox_mm or
geometry_features.properties.bounding_box; thickness or stock metrics against
the smallest extent (per part for an assembly whose parts record dimensions);
and a material metric against the recorded material. A requirement that
names a family (wood, metal, plastic, composite) accepts any material of that
family, so "wood or metal" accepts birch plywood; one that names a specific
material ("18 mm birch plywood", "aluminium") needs that word in the recorded
material; one that names no material ("suitable for construction") is reported
as not evaluated. A part that records no material is a violation. Not covered, and
reported as not evaluated rather than passing: assembly parts without recorded
dimensions, per-part printed-size limits (metrics containing print), mass,
deflection and safety factor (these need analysis evidence, see below), and any
metric outside the lists above. A metric that names a load position or a spacing
(a word such as moment, lever, offset, distance, position,
clearance, spacing or stroke) is not a part size even when it also says
length or height: moment_arm_length is where a load acts, so it is reported
as not evaluated instead of being compared with each part's largest extent. The mech_v1 design gate (G6) now sets
enforce_constraints (template version 1.1.0), so a violation fails it.
Analysis constraints. Deflection / displacement, stress and
safety-factor limits are compared to the latest simulation_result linked to
each current cad_model (metadata.source_cad_model_id or a derives_from
edge), by api_gateway/runs/analysis_constraints.py. Values are read from
max_displacement_mm, max_von_mises_mpa and safety_factor (or any
*_sf_* key). The constraint's unit decides what it is: length units
(mm, m) are deflection, pressure units (MPa, Pa, N/mm2) are stress, dimensionless
is safety factor, and force units (N, kN) are load requirements that are skipped
as inputs, not result checks. The name is used only when the unit is absent, and a
unit that contradicts the name is not evaluated with the reason. Every constraint ends as passed, violated (with the numbers) or
not evaluated (with the reason), all shown in the gate reason; a violation on
an enforcing gate marks it not ready. Load-case scaling: a limit that names its
basis (service or factored) is compared after scaling the result linearly
by target load over analysed load (inverse for safety factor), using
service_load_n, factored_load_n and the analysed load; the finding states
the scaling (for example 12.07 mm at 490 N becomes 6.03 mm at the 245 N
service load, which breaks a 5 mm limit). When the result records two
different loads and the limit names neither, or a service limit has no
recorded loads to scale with, the constraint is not evaluated, never passed.
A result linked only to a superseded cad_model is not used. The
simulation_result hint also asks for an optional
metadata.modelling_assumptions (for example bonded versus contact joints,
material approximations), which is shown to the reviewer at the gate.
Design-record constraints. An electronics or firmware
requirement (drc_error_count == 0, board_length_mm <= 40,
build_error_count == 0) has no cad_model to compare against, so before this
every one went unchecked: the engine counted its True placeholder as a pass
and the requirement matrix showed it as no_data. Now:
- The constraint engine skips a placeholder that stands for a
metric+limitbinding (is_placeholder_bound), so it is no longer counted as evaluated. api_gateway/runs/design_fact_constraints.pyreads the numbers the current (head) revision of each design record states about itself:pcb_layout,schematic,firmware_sourceandbom. It compares the one the requirement'smetricnames to the limit. A few tool spellings are accepted for the same fact (erc_errorsforerc_error_count,drc_errors,unrouted,layer_count,build_errors). Bookkeeping numbers (file_count,total_bytes,item_revision) are never facts.TwinConstraintCheckeradds the result to the gate: a broken limit is a violation, and a metric no design record states is listed as not evaluated with the reason. A size metric that a design record states (a board's length) is measured from that record, not reported as "no cad_model".simulation_resultnumbers are not read here. They rest on load cases and assumptions, so they verify a requirement only through a claim or the analysis check above.
Measuring tool results. A sandbox run still left seven
requirements no_data although the emulated boot (7 of 7
checks), the power budget (12.47 mA against 150 mA) and the parts' datasheet
ratings were all on record as evidence. Earlier, a run had passed every
requirement on a claim whose evidence carried no value at all. Now:
- After the design records,
design_fact_constraintsreads the current results (twin.record_evidence) of the tools that measure the design rather than estimate it:kicad.*,firmware.build,firmware.static_check,firmware.run_emulatedandpower.check_budget(a sum of the stated loads), plus anydatasheetevidence (a published rating). It reads the numbers at the top level of the result, newest result first. A design record wins over a result for the same metric, and a result whose verdict isnot_establishedis skipped. - The basis travels with the number: the tool and its version, and the
result's
basis, the inputs'basis,basis_accepted_byandboardwhen they are recorded. A pass from typical currents or from a stand-in board says so in its detail. - The power budget's own names are accepted for the requirement's metric:
vbus_load_mafortotal_supply_currentorvbus_load_current,rail_3v3_load_maforrail_3v3_load_current,rail_3v3_margin_pctforrail_load_margin_pct, andchecks_failedforboot_checks_failed. - Any other tool's result (an FEA or CFD run) is still not read this way; it counts only through a claim that cites it.
- The gate uses the same facts, so a failed boot check or an over-budget supply current is a violation at the gate, not only in the matrix.
- A requirement nothing states is reported with the tool call that would close it, for example "boot with firmware.run_emulated and record its result with twin.record_evidence, with 'boot_checks_failed' in it".
The requirement matrix also grades claims (see docs/twin_schema.md): a claim
against a metric + limit requirement passes only when a number for that
metric, in the evidence it cites or in the facts above, meets the limit. A
claim with nothing comparable is unverified, and the completion verdict does
not count it as passing.
The gate skeleton stays hardcoded (versioned code); the criteria come from the project's own constraint data. The structured constraint-creation tool is what fills that data from the Requirements phase; decision-derived phase applicability is the planned complement.
Consistency-gate status
Six gates carry a real spec G-number in Gate.gate_id — the Preliminary
Feasibility Gate ("G3", design_v1/hardware_v1/mech_v1's
feasibility phase), the Architecture Gate ("G4", hardware_v1's
architecture phase), the Concept Selection Gate ("G5", hardware_v1's
concept_selection phase), the Design review Gate ("G6", every flow's
design phase), the V&V sign-off Gate ("G7", every flow's simulation
phase), and the Manufacturing readiness / Release Gate ("G8",
hardware_v1's manufacturing phase). At those gates,
TwinConsistencyGateChecker (api_gateway/runs/gate_eval.py) calls the
matching twin_core.consistency.gates.evaluate_gN_* evaluator and appends
its real status to the approval reason — e.g. G3: ready_for_review (2 pass, 1 fail, 6 not evaluated).
This is purely informational, unlike enforce_constraints above: there is
no enforce_consistency_gate flag, so a gate never fails automatically on
this checker's result — even a failed G-number status still just pauses for
ordinary human review, same as before this existed. Every other gate (the
shared Intent/Needs phases, Requirements, Electronics, Firmware) has no
gate_id at all, so the checker is never even consulted for them. G0-G2
have no dedicated evaluator module yet — wiring those in, and deciding
whether any of G3-G8 should ever gain real enforcement, is separate, later
work.
Budget/invariant persistence
G3's mass/cost/power budget and runtime-invariant checks
(twin_core.consistency.gates.evaluate_g3_feasibility) used to require a
caller to pass Budget/Invariant objects it already knew about — there
was no per-project "the mass budget for this quadruped is 5kg" persistence
anywhere. An agent now declares one via twin.record_engineering_entity
(entity_type="budget" or "invariant", with metric/unit/
system_total or limit in extra, and a stable title like
"mass_budget"/"INV-MASS" for readable check labels; a budget is
rejected without those three keys, because recording one
without them used to succeed and then be dropped from every rollup, which
read as no budget existing) and it is loaded
automatically on every future G3 evaluation — including the real one
TwinConsistencyGateChecker runs from the executor. A project with none
declared gets a NOT_EVALUATED placeholder (budgets:none-declared/
invariants:none-declared), same never-silently-absent convention as G3's
existing risks:none-recorded check; a declared entity whose metadata
doesn't parse becomes its own NOT_EVALUATED check naming the entity,
never a silently dropped budget. Passing an explicit budgets=[]/
invariants=[] still bypasses the Twin lookup, unchanged, for a caller
evaluating a hypothetical declaration that was never persisted.
Concept selection / Decision Agent
evaluate_g5_concept_selection's checks (viable concept(s), trade study
performed, rationale captured, selected concept linked to
requirements/objectives) already read a project's recorded design_decision
work products, but hardware_v1 had no phase that ever reached G5, and
nothing generated a real trade study — a decision an agent recorded manually
either had no alternatives at all, or invented some without genuinely
weighing them. Concept Selection is now a real phase in hardware_v1
(orchestrator/design_flow/spec.py, between Architecture and Mechanical
Design), gated Gate(gate_id="G5"), driven by
GoalDrivenConceptSelectionHandler (api_gateway/runs/concept_handlers.py)
— the spec's "Decision Agent" (section 26.12): it prompts the LLM for 2-3
distinct concepts/approaches that could satisfy the just-decided
architecture, picks one, and records it through twin.record_decision with
real alternatives ({option, reason_rejected} pairs — the trade study),
rationale, and parent_refs pointing back at the architecture decision
(resolved from PhaseOutcome.artifacts, which GoalDrivenArchitectureHandler
now reports as a real node id rather than a placeholder string). Same
never-fail-the-phase discipline as every other goal-driven handler: an
extraction failure falls back to a generic two-concept default rather than
blocking the run.
Deliberately not built in this pass: scoring candidate concepts against
recorded objective EngineeringEntity nodes via ObjectiveEngine/
objective_from_entity — there is no MCP read tool for
engineering entities today (only twin.record_engineering_entity, the write
side), and IntentInterpreterAgent (Phase 3), the only code that ever
produces entity_type="objective" records, isn't wired into any live
execution path yet — so this handler's selection is the LLM's own reasoning,
not an objective-weighted ranking. Wiring a real read path for engineering
entities is separate, later work.
Deciding questions at intent, and the pick at the concept gate
The questions whose answers change a design most are asked once, in the shared Intent phase, and the design direction is picked at the Concept gate, once the requirements and the manufacturing route are known. Choosing a structure (dowelled legs, slot-together sheets, a cantilever) before the process is chosen would fix it before the facts it depends on exist, so intent records answers and lessons, never a direction.
Deciding questions. Besides its intent entity, the intent phase records
one design_decision whose deciding_questions field holds:
{
"questions": [{"id", "question", "answer", "source"}], // 1 to 8
"lessons": [{"text", "source_run"}]
}
The questions are the few whose answers change the design most (who uses it,
the load, the budget, the quantity, the process available, the style). Each
answer says where it came from: stated (the goal or the flow context),
person, assumed (the agent's stated assumption) or open.
twin.record_decision checks the record with parse_deciding_answers
(orchestrator/design_flow/context.py) and refuses a malformed one: more
than eight questions, repeated ids, or an unanswered question whose source is
not open. Both gate engines (the in-process executor's readiness check and
the Temporal _GateCheckers.evaluate) read the latest record at the intent
gate: without one the gate is not ready. The intent entity stays the phase's
only required deliverable, so an earlier run's intent can still be reused, but
only with its answers: a new flow skips intent only when the project has both
a current intent and a valid deciding-answers record, so an intent recorded
before the questions existed is settled again rather than skipped.
Every later phase is briefed with the answers. ReActPhaseBrain reads
the project's latest deciding answers before each phase after intent and puts
them in the brief under "do not ask them again", so nothing is asked twice.
The concept gate is the "pick a direction" card. The concept phase
proposes two or three concepts and records them as concept_options with one
selected. Its gate reason lists every concept with its summary, the selected
one, and how to change it: approving accepts the selected concept; a retry
naming another, or saying "you choose", sends the phase back with that
answer. When the person leaves the choice to the agent, the agent chooses and
records why. The reason is the same text the dashboard and the plugin already
show at a gate; there is no separate dashboard card yet.
Earlier runs are reused. The intent and concept briefs also list what
earlier runs on the same project learned, collected by
api_gateway/runs/prior_lessons.py with the pure helpers in
orchestrator/design_flow/prior_lessons.py:
- gate rejections: the reason on every reject, retry or rework logged on an earlier run's decisions;
- reviewer findings: the reasons of a reviewer's retry, rework or reject, and every concern it raised;
- recorded lessons: the latest deciding answers' own lessons and the twin's rejected item revisions with their gate reasons.
They are newest first, deduplicated on their text and capped at eight. The
current run is left out. The gateway reads runs from its run store; the
Temporal worker, whose store is empty, reads the run ledger file the gateway
writes, read-only, from the ~/.metaforge volume the two share. A source that
cannot be read costs its lessons, never the phase. Intent carries the lessons
that bear on the design into its record, so a later run finds them there too.
Concept design in mech_v1 and illustrative sketches
mech_v1 now carries the same Concept Selection phase (use: concept_selection, titled "Concept Design"), placed after the process
choice (route_selection) and before industrial_design, so a product's
structure and joints are decided before anyone authors CAD. The phase asks
for two or three concepts, one labelled sketch per concept committed with
twin.commit_design_sketch (self-contained SVG, each label marked
intended, assumption or open), and a design_decision that names the
selected assembly (parts, connections, joint types), the rejected
alternatives and any candidate standard or bought parts. Both
design_sketch and design_decision are required deliverables, the gate is
G5, and the objective says outright that no CAD is authored in this phase.
A concept's sketch does not have to be hand-written SVG.
twin.render_concept_sketch draws it from a block layout: named boxes and
cylinders, each with a size and position in mm and a provenance tag
(verified, intended, assumption or open), and the connections
between them with their joint types. The renderer
(tool_registry/tools/twin/concept_sketch.py) is pure standard library and
deterministic, so the same layout always gives the same bytes. It draws
front, side and top orthographic views with dimension lines (sketch type B),
an isometric view (C) and an exploded isometric view with leader-line
labels (D), styles every label by its tag, and closes with a title block
that reads "Illustrative concept sketch, not a design record". The result is
committed through the same recorder as twin.commit_design_sketch, so it is
just as illustrative. A part may be given as bbox_mm, the two corners of
its bounding box, which is what a CAD assembly reports per part: a sketch
drawn from CAD (type E, later work) can feed the same renderer.
A block layout is accurate and dry, so a concept can also get an appealing
picture that stays honest about what it is (sketch type A).
twin.render_concept_image takes either the layout_node_id of a sketch
drawn by twin.render_concept_sketch (which now keeps its layout in
metadata.concept_layout) or an inline layout in the same schema, plus a
short visual_brief from the model: the product, its materials, its style.
The layout is drawn as a grey isometric block image, the same projection as
the sketch's isometric view, and sent with the brief to an image model, which
is told to keep the proportions and arrangement and to render the finished
product. The result is a render work product with
metadata.authority = "illustrative", linked generated_from to its sketch.
It records what conditioned it in metadata.conditioned_on (the layout's
source, its content hash, the sketch node when there is one, and
image_conditioning: layout_png when the layout image reached the model,
none when only the brief and the part list did), along with the brief, the
exact prompt, the provider and the model. The label "AI concept image,
illustrative only" is drawn as a banner into the pixels and kept in the PNG's
text chunk; where Pillow is missing the image is wrapped in an SVG whose text
element carries the label instead, and no layout image is sent. Like every
sketch and render it can never back a requirement claim. Generation is opt-in
because each image is a paid call. METAFORGE_IMAGE_PROVIDER=openrouter
uses the OpenRouter key the deployment already has (OPENROUTER_API_KEY,
OPEN_ROUTER_API_KEY, or METAFORGE_LLM_API_KEY when OpenRouter is the LLM
provider), and the compose file passes the METAFORGE_IMAGE_* settings to the
gateway and the MCP sidecar: the layout image and the
prompt go to OpenRouter's chat completions with the image output modality,
and the picture comes back in the reply, so any image model on OpenRouter is
a METAFORGE_IMAGE_MODEL slug (default google/gemini-2.5-flash-image;
GPT Image models work the same way). METAFORGE_IMAGE_PROVIDER=openai calls
OpenAI's images API directly instead (default gpt-image-1, which takes the
layout through its edits endpoint) on OPENAI_API_KEY.
METAFORGE_IMAGE_TIMEOUT_S (default 120) bounds the call either way. With no provider configured the tool fails at once with a message
saying what to set, a provider that does not answer in time is a timeout
error, and neither writes anything. Outcomes are counted in
metaforge_concept_image_total{outcome}, and ConceptImageGenerationUnavailable
warns when most requests in an hour fail.
Image models drift: they add parts, drop parts and draw joints the concept
does not have. So once a concept image exists, a vision model checks it
against the concept's selected assembly, the assembly on the project's
latest concept decision (or the decision named by decision_ref, or an
inline assembly). It is asked whether every made part is visible, whether
each connection and joint looks as the decision says, and whether anything
major is drawn that the concept does not have, and it answers in strict JSON:
parts_seen (name, present, note), joints (the two parts, whether they
match, note), extras, a verdict of consistent, inconsistent or
unclear, and a summary. The verdict is held to its own findings, so a
"consistent" reply that reports a missing made part is stored as
inconsistent, and a made part it never mentions makes it unclear. The result
is stored on the render as metadata.critique with the provider and model
that judged and the decision it was compared with. It uses the same vision
path as sketch reading (api_gateway/twin/image_critique.py). It is
advisory and best-effort: with no assembly on record, no vision model, a
model that does not answer, or a reply that does not fit the schema, the
critique is {"verdict": "unchecked", "reason": ...} and the image is still
returned. An image is of one concept, so the project's concept decision is
used only when it selects that concept (or names no options). Otherwise, and
before any decision is recorded (the concept phase makes its images first),
the image is checked against its own sketch layout: the parts and joints the
concept's block layout names, recorded as assembly_source.kind = "sketch_layout". The MCP sidecar gets the gateway's METAFORGE_LLM_*
provider settings, so these vision calls use the deployment's model provider
and key rather than an unconfigured default. The image prompt asks for
exactly the layout's parts, joined as laid out, and for anything shown in use
(the bikes on a bike rack) to be whole, correctly built and held the way the
product holds it. twin.critique_concept_image checks an image
already in the twin (its node_id, and optionally decision_ref or
assembly) and stores the result in a new revision, which is how an image
made before the concept decision gets checked. Both gate engines add a note
to the concept gate's reason, for example "concept image check: C
consistent; A inconsistent: Wheel Hook Left not visible". The note never
blocks the gate, and the critique never makes an image evidence: the render
stays illustrative and twin.record_claim still refuses it. Checks are
counted in metaforge_concept_image_critique_total{verdict}, and
ConceptImageCritiqueUnchecked reports when most go unchecked.
A concept image can also be turned into a 3D reference model for concept
review. twin.generate_concept_mesh takes the image_node_id of a render
made by twin.render_concept_image (or, with no image, a text prompt;
exactly one of the two) and sends it to Tripo's image-to-3D API: the image is
uploaded (POST /files), a task is created
(POST /generation/image-to-model, or /generation/text-to-model for a
prompt), the task is polled (GET /tasks/{task_id}) every 5 seconds, and the
GLB at output.model_url is downloaded at once, since Tripo's model links
expire within minutes. The label banner drawn on the concept image is cropped
off before upload so it is not modelled as part of the product. The mesh is a
render work product with format: glb and metadata.authority = "illustrative", linked generated_from the image, recording the provider,
the Tripo task id and model version, and the label "AI 3D reference model,
illustrative only". It is never a cad_model: its dimensions are the
model's guess, not the layout's, and twin.record_claim refuses it like
every render. The twin viewer previews it with its 3D mesh engine. It is off
unless METAFORGE_MESH_PROVIDER=tripo, with the key in TRIPO_API_KEY (a
key alone turns nothing on, since every mesh is paid);
METAFORGE_MESH_TIMEOUT_S (default 600) bounds the whole generation, and
METAFORGE_MESH_MODEL_VERSION picks Tripo's model. A node that is not a
concept image, a missing or oversized prompt, or an unreadable image is
refused before any paid call. A failed, cancelled, banned or expired task is
an error naming its status, a task still running at the deadline is a
timeout, a rejected key is reported without the key, and none of them writes
anything. Outcomes are counted in
metaforge_concept_mesh_total{outcome, mode} (mode is image,
multiview or text), and ConceptMeshGenerationUnavailable warns when
most requests in six hours fail.
A single image leaves the model to guess the sides it cannot see, so a
reference model can instead be made from the concept's own straight-on
views. twin.render_concept_image takes an optional view: isometric (the
default) or front, left, back or right, which draws the block layout
as a flat-shaded orthographic view from that side (boxes, and cylinders seen
side-on, as rectangles; cylinders seen end-on as ellipses; farthest parts
first). The front view stands at y < 0 looking along +y with x to the right;
the back view looks along -y, so x is mirrored; the left view stands at
x < 0 looking along +x, with the product's front on the right; the right view
looks along -x, with the front on the left. All four share one scale, so the
product is the same height in each. The prompt asks for a straight-on
orthographic view of that side with no perspective, and the view is recorded
in conditioned_on.view and in the result; the label banner and the vision
critique are unchanged. twin.generate_concept_mesh then takes
view_images, an object mapping front, left, back and right to such
renders (front required, at least two in all), as the alternative to
image_node_id and prompt. Each image has its banner cropped and is
uploaded, and one POST /generation/multiview-to-model task is created with
inputs in Tripo's view-key form ([{"front": token}, {"left": token}]).
A missing front, a single view, an unknown view, the same image twice, a node
that is not a concept image, an image drawn for a different view than its key,
or images drawn from different layouts are refused before any paid call. The
mesh records view_image_node_ids and is linked generated_from every view.
Every mode takes the generation options auto_size (Tripo scales the model
to metres; default false when the images came from a block layout, since the
fit to the envelope described below replaces it, and true otherwise),
face_limit (default 100000; 500 to 20000, with
a default of 20000, under smart_low_poly), texture (default true),
generate_parts (default false) and smart_low_poly (default false). They
are sent to Tripo, which documents them on all three endpoints, and stored as
metadata.generation_options. generate_parts needs an untextured model, so
it sends texture and pbr false and says so in
generation_options_note; combined with texture: true or smart_low_poly
it is refused before any call. After download the GLB's bounding box is read
from its glTF JSON, without a paid call or a mesh library: each mesh's
POSITION accessor min and max, carried through its node transforms. That is
exact without rotation and a superset with one (bbox_approximate), and a
file with no scene graph falls back to the union of the accessors' boxes. It
is stored as bbox_m in glTF axes (x, y up, z). When the images came from a
block layout, its overall size is stored as envelope_mm (width, depth,
height). Height is glTF y, and the two horizontal axes are paired whichever
way fits better, reported as axis_mapping.
With an envelope the model is then scaled to it (fit_to_envelope, default
true when there is an envelope). One uniform factor is chosen: the one that
minimises the summed squared log ratio of model to envelope over the three
axes, which is the geometric mean of the three ratios, with the horizontal
pairing whose remaining error is smaller. It is applied by giving the scene a
new parent node with that scale in the glTF JSON chunk; no vertex buffer is
rewritten, and every existing node keeps its own transform beneath it (a file
whose scenes do not share one root list has each root's own transform scaled
instead). The stored GLB is the scaled one, and the provider's own file is
kept beside it in the blob store (provider_glb_object_key, with its hash and
size). The record carries scale_factor, the box before and after
(bbox_m_before in the provider's units, bbox_m in metres) and
proportion_error_pct, what no uniform scale can remove: a model that came
out 14% too deep for its width and height reads about +9% depth and -4% on
the other two once fitted. A real run returned 763 x 720 x 500 mm with
auto_size for a microwave whose envelope is 490 x 395 x 290 mm, so a fit is
the norm rather than the exception. With fit_to_envelope false, or with no
envelope, the file is stored as the provider made it and deviation_pct
compares it with the envelope: absolute with auto_size, and of proportions
only without it, the model then being scaled to the envelope's largest axis
for the comparison (deviation_basis).
A generation takes about 150 seconds, longer than a client waits for one MCP
call (Claude Code gives up at 120 and showed an error for a mesh the server
went on to store). So a client's call returns at once with a job:
{"job_id", "status": "running", "poll": "twin.job_status", "expected_seconds": 150}. The paid generation runs as a background task, and
its result (the node_id and the rest) is stored on the job, which the
read-only twin.job_status returns; the next reply to the same session after
the job finishes also says so, once. Everything that would refuse the call is
still checked before it returns, so a bad call fails at once and pays nothing.
An identical call (same arguments, session and project) while the job runs,
or within 10 minutes of its success, returns the same job rather than paying
for a second mesh. The design-flow worker, a call claiming a run and an
in-process caller still wait for the mesh itself, and wait chooses
explicitly. Jobs are stored in SQLite per process; a restart marks the jobs it
left running as interrupted. See MCP specification for the
job protocol.
An accepted 3D concept can then be split into parts and worked on one part at
a time, in three more paid steps held and run as jobs the same way
(api_gateway/twin/concept_parts.py). twin.segment_concept_mesh calls
Tripo's POST /mesh/segment with the concept's own Tripo task id when it has
one, else its GLB uploaded through POST /files, else a URL; model is
v1.0-20250506 (geometry, the default) or v2.0-20260430 (semantic labels,
beta, which alone takes segmentation_granularity and
split_by_connectivity). Tripo does not document whether parts come back as
separate nodes or where a label is carried, so the parser
(api_gateway/twin/glb_parts.py) reads every mesh-drawing node of the default
scene as a candidate part and looks for a label in node and mesh extras
(label, semantic_label, part_label, category, class), then in a
name that is not generic (tripo_part_3 and Mesh are generic). Fewer than
two mesh nodes, even one mesh with several primitives, is recorded as
not_segmented: no part could be addressed by name, so none is guessed. The
result is fitted to the source's envelope and stored as a new revision of the
concept (still L0 and illustrative).
Each part is proposed a component of the concept assembly from its label,
then its relative size and position against the L1 block layout (the eight
ways the layout can sit in glTF axes are tried and the best kept), then the
order, with a confidence. A part is proposed only when one component is at
least 0.6 and 0.1 ahead of the next; a mirror-symmetric pair that only a
label could tell apart, and every other unclear part, is a question for the
person. Only parts a person confirms get component_id in their node
extras, in our stored copy.
twin.regenerate_concept_part makes one part again through the same text or
image to model path (the image is one the person supplies, never an automatic
crop), and twin.complete_concept_part calls POST /mesh/complete with the
segmentation task, part_names set to that part and completion_mode
quick_cap (seal) or ai_completion. Either result replaces only that node:
its mesh is dropped and a child node draws the new part, fitted uniformly to
the part's own box with the same least squares log rule as the envelope fit
and centred on it, so the node's pose, name and extras stay. The new data is
appended after the existing binary chunk, so every other node's accessors,
buffer views and bytes are unchanged, and the step checks that before
storing. A part redone after the split is no longer in Tripo's segmentation,
so sealing it is refused.
The concept decision carries what it selects as data, not prose.
twin.record_decision takes an assembly (each part with its source, made,
bought or standard, plus material, process, quantity and a provenance tag,
and each connection between two named parts with its joint and fasteners)
and concept_options (every concept considered, with its sketch and exactly
one selected). Both are checked when recorded: a connection to a part that is
not listed, or one with no joint, is refused. The G5 gate gains a "Selected
assembly recorded" check that passes when the latest assembly joins its parts
with stated joints, and is not evaluated when no decision carries one. The
standard and bought parts the joints rely on are recorded with
twin.record_component_selection and selection: "candidate"; the BOM view
reports that state, so a candidate never reads as a chosen part.
Design then builds to the concept. The mech_v1 design phase is told to
read the selected assembly and author one CAD part per made part, named as in
the concept, joined as decided. Its gate (G6) reads the latest assembly on
record and is not ready while a made part has no committed CAD part carrying
its name (a "Leg" is covered by "Leg 1" or "Chair Leg"). Bought and standard
parts are not required to be modelled. If the design has to depart from the
concept, the phase records a revised concept decision with its assembly, and
the gate compares against that one. With no assembly on record the gate
behaves as before.
Industrial design hands mechanical design constraints, not prose. The
shared industrial design phase now also decides the joint and edge language
(how joints show and with which fixings; which edges get which radius or
chamfer) and records it with twin.record_constraint_set. Its decision
carries an industrial_design field: joint_language, edge_treatment,
ergonomics (a verdict with the source of its limits, or the reason nobody
handles the product), finishes (each part's appearance and whether
check_cmf_compatibility passed) and open_decisions. Both gate engines
read the latest one, and the gate is not ready while a decision is still
open, the ergonomics check failed, a finish clashes with its material, or no
finish is chosen.
Each concept is shown two ways. The concept phase first draws its block
layout with twin.render_concept_sketch (the dimensioned, tagged views), then
makes the concept's AI image from that sketch with twin.render_concept_image,
so a person can judge the direction at a glance. The image is an expected,
not required, artifact: with no image provider configured, or a provider
that fails, the phase says so in its decision and the gate still reads the
sketches. Inside a claimed concept task the image call is a client-task
write, so it is not held for approval like a call outside any task.
A sketch shows intent and is never evidence. Sketches and renders are
committed with metadata.authority = "illustrative", the gate review brief
reports each work product's authority (illustrative for a sketch, render
or image, otherwise the recorded authority), and twin.record_claim refuses
a claim whose artefact is illustrative: a requirement is satisfied by the
CAD model, analysis or test that shows it, not by a drawing of the idea.
Reading a person's sketch
A person can start the concept from their own hand sketch or reference
image. twin.interpret_sketch sends it to a vision model, which proposes
the parts it sees, the connections and joint types between them, rough
proportions and the questions it cannot answer from the picture. The reply
must be strict JSON in that schema; anything else is refused and nothing is
stored. The module is api_gateway/twin/sketch_reading.py, and the model
call is injected, so tests run against a fake.
The reading is a proposal, not a record:
- The image is stored as an
imagework product withmetadata.authority = "illustrative", so it can never back a claim. - Every proportion carries
tag: "assumption", whatever the model said. A size read off a drawing is neververified. - The reading sits in
metadata.sketch_readingwithstatus: "proposed". A person moves it toconfirmedorrejectedwithtwin.confirm_sketch_reading, a human-authority tool: the call is always held, and the decider recorded is whoever approved it, never a name in the arguments. An agent cannot confirm its own reading.
Only confirmed readings reach the concept phase. When concept_selection
starts, the phase brain lists the project's confirmed readings and adds them
to the phase prompt, labelled as intent: proportions as assumptions and open
questions as still open. A proposed or rejected reading is never offered.
The vision model is the gateway's configured provider chain, with
METAFORGE_VISION_MODEL as its model when set, less the families whose
adapter cannot carry an image (Gemini, Bedrock and Codex). The call is shared
in api_gateway/twin/vision.py so any other image reader uses the same
chain and the same setting. If
none is left, or none answers within METAFORGE_SKETCH_READING_TIMEOUT_S
(120 s by default), the tool fails with a message saying so. Outcomes are
counted in metaforge_sketch_reading_total, and the
SketchReadingUnavailable alert fires when most readings in an hour fail.
Generating a freeform concept sketch
twin.generate_sketch (and Generate a concept in Create's Imagine sketch, which calls the
same service over /v1/twin/projects/{id}/sketch-generations) draws a
freeform concept sketch through the same image providers as
twin.render_concept_image. The module is
api_gateway/twin/sketch_generation.py. Three modes: text (intent,
constraints and a style), reference (the project's active references, each
sent for its role: an inspiration image for mood, a geometry image for
shape, a specification's stated values as constraints in words; verification
evidence is never sent) and sketch (a saved sketch_strokes revision
drawn to a PNG here and refined; the strokes are never written). Left out,
the mode follows from a sketch, then active references, then text.
The providers now take an ImageRequest (several conditioning images and an
optional mask) and say what they can do in ProviderCapabilities, read from
the adapter code:
| Provider | Mask | Images per call | Partial images |
|---|---|---|---|
openai (images.edit) | yes | 16 | no (not called with streaming) |
openrouter (chat completions) | no | 4 | no |
A region edit sends the mask to a provider that takes one; otherwise the
output is composited back outside the mask. The pixels outside the mask and
inside locked regions are compared with the input either way, and a proposal
under METAFORGE_SKETCH_PRESERVATION_THRESHOLD (0.9) is flagged for review.
With no provider streaming partial images, generation reports only real
stages: queued, started, a milestone when the image arrives, a
review_required event when preservation fails, and completed.
Generation runs as a job on its target (SKT-X:full or
SKT-X:region-<hash>, CONCEPT:full without a sketch): a newer request on
the same target supersedes an older one, identical requests within 30 s
coalesce, and a result that arrives after another concept was accepted ends
stale, stored as history and never accepted. n_variants defaults to 1.
Each output is a proposal; only a person's accept moves the accepted concept
(see generated concept sketches). The
tool is held for approval and counted against the image spend cap like
twin.render_concept_image.
Models per step
Each step of the concept pipeline names its model in one place. Every setting is optional; unset, the step uses the default in the last column.
| Step | Setting | Format | Default |
|---|---|---|---|
| Concept phase reasoning (server mode) | the phase's model in the flow, or a phase_brain route | provider:model | the gateway's chat model |
Reading a sketch (twin.interpret_sketch) | METAFORGE_VISION_MODEL | a model id for the chat provider (on OpenRouter a vendor/model slug) | the gateway's chat model |
Concept image (twin.render_concept_image) | METAFORGE_IMAGE_MODEL (with METAFORGE_IMAGE_PROVIDER) | an image model slug | google/gemini-2.5-flash-image on OpenRouter, gpt-image-1 on OpenAI; off until a provider is set |
Concept sketch (twin.generate_sketch, Create Generate) | METAFORGE_IMAGE_MODEL (with METAFORGE_IMAGE_PROVIDER) | an image model slug | the same as the concept image |
Concept reference mesh (twin.generate_concept_mesh) | METAFORGE_MESH_MODEL_VERSION (with METAFORGE_MESH_PROVIDER=tripo) | a Tripo model version | v3.1-20260211; off until the provider is set |
| Gate review (server reviewer) | the policy's reviewer_model, then METAFORGE_REVIEWER_MODEL | provider:model, or a model id for the chat provider | a gate_check route, else the gateway's chat model |
The gateway's chat model is METAFORGE_LLM_MODEL on METAFORGE_LLM_PROVIDER,
or the durable harness selection when one is stored.
The concept phase's own model. A flow phase carries an optional model
(provider:model) that its phase brain runs on, ahead of every route (see
per-role model routing).
In a template, set it beside the use line, for example model: anthropic:claude-opus-4-8 under - use: concept_selection; a
generated flow sets it with the set_model operation. A
phase_brain:<discipline> route applies to every phase with that
discipline, so it is the wider choice: in mech_v1 the concept phase shares
the manufacturing discipline with the route selection phase. In client mode
the connected client runs the phase, so the client's own model reasons and
these settings do not apply to it.
The reviewer. The policy's reviewer_model wins, then
METAFORGE_REVIEWER_MODEL, then the default. Each stored review records the
provider:model that wrote it and model_source (policy, env or
default); see the approvals page.
The compose file passes METAFORGE_REVIEWER_MODEL to the gateway, the MCP
sidecar and the design-flow worker (which runs the reviewer), and
METAFORGE_VISION_MODEL to the gateway and the MCP sidecar, next to the
METAFORGE_IMAGE_* settings.
Waiver / release model
evaluate_g8_release's "waivers approved" and "build/manufacturing release
approved" checks used to always come back NOT_EVALUATED — there was no
"waiver" concept in the graph at all (HITLEngine's "waiver" was only ever
a transient approval-classification category, never persisted), and nothing
ever advanced an EngineeringEntity's authority past proposed except
create_baseline (straight to baselined) — so a "waiver" or "release"
record could never be genuinely approved versus merely proposed, even
if one existed.
"waiver" and "release_approval" now join EngineeringEntityType, the
same home "budget"/"invariant" got — an agent declares one via the
existing twin.record_engineering_entity tool (a waiver should parent_refs
the requirement/constraint it excepts). The new part is
twin.approve_engineering_entity (api_gateway/twin/ engineering_entity_approval.py): a real approval step, generic across every
EngineeringEntityType, advancing authority from proposed to
reviewed/approved (never baselined — that stays exclusively
create_baseline's job). evaluate_g8_release reads both back for real:
- Waivers approved: zero waivers recorded is a real PASS — nothing outstanding needs one, the same vacuous-pass exception G4's "architecture satisfies major constraints" already documents for zero recorded constraints. A recorded-but-unapproved waiver FAILS — a raised exception can't silently count as resolved just because a node exists.
- Build/manufacturing release approved: the opposite default — a
missing
release_approvalFAILS, notNOT_EVALUATED, since release-to-manufacture is an unconditionally required sign-off (spec section 63; HITL Level 4 Mandatory Authority), the same posture the baseline check already takes for a missing baseline.
The CAD design loop
A component with a parametric plan (a PSK item) can be refined
automatically. twin.design_cad_loop (api_gateway/twin/cad_design_loop.py)
runs as a background job: a model writes CadQuery, the result is built,
checked, rendered in a real headless browser and reviewed by a vision critic,
and the model revises until it is satisfied or a cap is reached. Every tool
call goes through MCP: scripts run only inside the CadQuery adapter
container, never in the gateway.
Context, gathered once per run. The brief and its measurements, the
component, the active references with their roles and extracted facts, the
IFC-CAD-EDA interface contract's parameters, the component's own envelope
from its manufacturing context, the parametric plan's features and inputs,
the proposed feature history (FHP-<component>) when reconstruction made
one, the manufacturing context block (stated, assumed and unknown, through
manufacturing_context_block()) and the component's current DFM findings.
When every input of the plan's first feature is known, the plan is compiled
into a seed script (compile_design_ir_cadquery) the first iteration starts
from.
Unknown dimensions are never invented. A plan input with no value and no
answer, and a contract parameter whose basis is unknown, is listed to the
model as UNKNOWN. The model asks for it, or, when allow_working_values is on
(the default), uses a value it labels as an assumption with the same name; the
assumption is recorded and shown to the person as an open issue to confirm. A
reply that does neither for a required unknown is turned into a question and
the run stops needs_input before anything is built. A later run takes the
person's numbers in answers.
Each iteration.
- The author model (the chat provider chain) returns one JSON object: the whole script, a one-line summary, a few words of focus ("fixing wall thickness"), assumptions and questions.
cadquery.execute_script, thencadquery.validate_shape. A build error or a validity finding goes back to the model in the next prompt.- Measurements: the bounding box, size and volume; under a process whose
rule profile names exact checks (FDM),
cadquery.dfm_measureand the profile's exact checks on the candidate; under any other profile, its heuristic rules on the measured extents; with no process,not_assessed. - The STEP is converted to GLB by the OCCT converter, and
render.model_viewsrenders iso, front, side and top views (with the measured size as the dimension overlay) and a contact sheet. - The vision critic (
METAFORGE_VISION_MODEL) gets the sheet, the measured numbers, the intent and the DFM findings, and returns issues (severity, view, feature, suggested change) and asatisfiedverdict with reasons. A satisfied verdict that still lists a blocking or major issue counts as not satisfied.
Stop rules. The run stops satisfied only when all four hold: the critic
is satisfied, validity is pass, no blocking DFM finding remains, and every
stated overall size (target_dimensions, and the component's own envelope as
a maximum) is within tolerance_mm (default 0.5 mm). It stops
iteration_cap after max_iterations (default 5, at most 8) and spend_cap
when the run's budget is used: max_model_calls (default twice the
iterations) and max_spend_usd (default METAFORGE_CAD_LOOP_MAX_SPEND_USD,
1.0). Priced calls count against the USD limit through the usage store;
unpriced calls count as calls. It stops needs_input on a question and
failed when a model, the OCCT converter or the render adapter cannot be
reached (nothing is judged that nobody saw). The reason is always recorded
with its detail.
Records and acceptance. A run is one cad_design_loop record (see
CAD design loop records). Its
result is the last iteration that built and passed validity, proposed and
bound to the CAD item's head when the run started. Nothing is applied. A
person's Use this version (POST /v1/twin/projects/{id}/cad-loops/{node_id}/decision) builds the script
through the exact CAD path (twin.build_exact_cad): the head moves only when
that build passes its own validity check, and a head that moved since the run
started is refused with 409. Keep the previous one records the decision
and changes nothing. The critic's verdict never sets validated or
verified.
Spend and approval. From Create, a run past the project's hourly cap
(METAFORGE_AUTO_APPROVE_CAD_LOOP_PER_HOUR, 3) answers 409 spend_confirmation_required until the person confirms, and an agent caller
is refused. Over MCP, twin.design_cad_loop is additive and open world, so
it is held for approval like other paid tools, and only the project's auto
policy (within the same cap) approves it.
Progress. Each iteration publishes an operation event on the job's
operation: "Iteration 2: fixing wall thickness" when it starts, then the
contact sheet as an image artifact and the stop rule's open parts. The run
ends with a review_required event when a version is proposed.
The render adapter
render.model_views (tool_registry/tools/render/) renders a GLB in headless
Chromium through Playwright. The page is a local three.js (r169) viewer: the
image fetches three.js from the npm registry at build time, checks its
SHA-256 and keeps it, and every page request is answered from local files
(page.route), so a render needs no network. Views are iso, front,
side, back, left, top, bottom and section (a cut along a CAD axis
at a fraction of the extent, seen from the side cut away). Directions are
given in CAD axes (Z up) and converted to the page's Y-up frame; a GLB from
the STEP converter is Z-up and is turned upright. Flat views are orthographic
with a floor grid, a scale bar and an optional dimension overlay from the
caller's measured extents, labelled with their source; the iso view is in
perspective under a neutral studio environment. The tool returns one PNG per
view, a contact sheet, the view metadata and the mesh's bounding box in mm,
inline, and keeps nothing (read-only). The page-building half
(tool_registry/tools/render/page.py) is pure and unit-tested without a
browser.
What's built vs. planned
Built (Phase 1): the design_v1, mech_v1, and full 7-phase hardware_v1
gated flows; the executor + gate coordinator wired into /v1/runs; goal-driven
deterministic handlers for every hardware_v1 phase, committing nine typed work
products via the twin recorders; per-phase deliverable enforcement via
GateEvaluator (including a loadable cad_model gate); the ReAct phase brain
as fallback; SSE/CLI drive; and the evals/ flywheel with eight correctness
rubrics over three reference products.
Planned (Phase 2+): real ERC/DRC and Gerber export on an authored schematic
(KiCad-write) to close the electronics erc_or_netlist gap; real CalculiX FEA on
a load-bearing part inside hardware_v1 (today only mech_v1 runs FEA;
hardware_v1 V&V honestly defers it); weighted gate-readiness scoring via
twin_core/gate_engine (EVT/DVT/PVT); phase/gate linkage stored on twin nodes;
and a dedicated forge design CLI wrapper.
Key modules
| Module | Role |
|---|---|
orchestrator/design_flow/spec.py | Phase / Gate / FlowDefinition / DeliverableSlot, built-in flows |
orchestrator/design_flow/slots.py | Deliverable slots: default slots, key binding, write-to-slot matching |
orchestrator/design_flow/{contract,fragments,compose,checks,coupling}.py | Composable flows: task contract, domain fragments, composition, stage-gate checks, coupled blocks (Composable Design Flows) |
orchestrator/design_flow/templates/spine/spine_v1.yaml | The shared spine the templates extends |
orchestrator/design_flow/executor.py | DesignFlowExecutor, GateCoordinator, PhaseBrain |
api_gateway/runs/flow_brain.py | ReActPhaseBrain fallback; keeps the phase summary on the run record |
api_gateway/runs/{req,arch,mech,elec,fw,vv,mfg}_handlers.py | Goal-driven deterministic phase handlers |
api_gateway/twin/{geometry,bom,document}_recorder.py | Persist typed artifacts loadably (blob + content_hash + project link) |
api_gateway/runs/gate_eval.py | ProjectGateEvaluator — deliverable enforcement (loadable cad_model) |
api_gateway/runs/prior_lessons.py, orchestrator/design_flow/prior_lessons.py | Earlier runs' gate rejections, reviewer findings and recorded lessons for the intent and concept briefs |
api_gateway/runs/routes.py | Per-flow handler routing; launches the executor on a design-flow POST /v1/runs |
evals/run_scenarios.py, evals/*_rubric.py | Eval flywheel: scenario runner + correctness rubrics |
evals/run_chat_scenarios.py, evals/chat_*_rubric.py | Chat context-engineering evals: multi-turn scenarios + trajectory rubrics |
Version view exposes the frozen context
GET /v1/design-flows/versions/{id} returns context: the frozen flow context
string that is part of the version's content hash, so a reviewer
sees exactly what the phase brain will be handed. The G6 geometry-constraint
check likewise considers only cad_models committed in the phase window, with
superseded parts excluded, the same scoping as the assembly check.
Deliverable slots carry item keys
Every definition write gets an item (see Items and revisions), but the item was still found by name, and the model chooses the name. A slot fixes the identity before the run starts: each deliverable a phase declares gets one, with the item key every write of it lands on.
Where slots come from.
- Declared: a template phase's
slotslist ({type, name, key?}), a tailoring'sdeclare_itemsoperation (value: [{"type": "cad_model", "name": "left bracket"}, ...], or bare names when the phase produces exactly one definition type), or an edited version'sslotsper phase. Two brackets are two slots. - Default: one slot per singleton definition type a phase requires or
expects and no declared slot covers (
intent,constraint_set,bom,assembly), named after the phase: the requirements phase's constraint set isCS-REQUIREMENTS, the intent phase's intentINT-INTENT. Parts, stakeholder needs and objectives get no default slot, because a phase usually writes several and one shared slot would turn four parts into four revisions of one item; they are declared by name or resolved by name as in.
Keys. A slot's key is the item key for its type and name
(derive_key, e.g. CAD-LEFT-BRACKET). The project part of an item's identity
is the item's project scope, not a prefix in the key: keys are already unique
per project, a key cannot contain / (it sits in the
/v1/twin/items/{key}/revisions path), and a project can be renamed while its
id cannot. So the same deliverable in the same project has the same key in
every version, and a part a run before slots already recorded as
CAD-LEFT-BRACKET is the slot's item from the first slotted run.
A slot of a one-per-project type (intent, constraint_set, bom,
assembly) whose own key names no item yet revises the project's existing
item of that type when there is exactly one. A project migrated from legacy
nodes keeps its requirements under a key derived from their old
title, such as CS-WALL-SHELF-DERIVED-MECHANICAL-SIZING-CONSTRAINTS; the
requirements phase's CS-REQUIREMENTS slot writes the next revision of that
item rather than opening a second one. With two or more candidates nothing is
guessed and the slot key stands. The write counts as the slot's, so it is not
flagged as undeclared (flow_slot_bound_to_existing_item is logged).
Frozen at save. FlowVersionStore.save binds the declared slots
(slots.bind_slots fills in their keys) before freezing, so they and their
keys are part of the version's content hash and an approval approves them.
Default slots are never stored: they are a pure function of the frozen phase,
derived at run time (slots.effective_slots), and shown in the API with
derived: true. A flow that declares no slots (every built-in template, a
version saved before slots existed) therefore hashes exactly as before, because an
empty slots list is left out of the hash like an unset model: an approved
version still verifies, and a new version of the same content gets the same
hash. diff_flows reports declared items (phase 'design' declares cad_model 'left bracket' (item CAD-LEFT-BRACKET)), never the derived defaults.
During a run. The phase brain puts the phase's slots on the MCP call
context (McpCallContext.item_slots, carried to the sidecar in the
X-MetaForge-Item-Slots header next to X-MetaForge-Run) and lists them in
the phase brief, so the agent knows its item keys without having to pass them.
A definition write with no explicit item_key / supersedes, in a phase that
declares slots of its type, resolves to a slot (slots.match_slot):
- the slot with the same name or key;
- else the slot whose name shares the most meaningful words, when one is
clearly best ("Bracket, left side v2" is
CAD-LEFT-BRACKET); - else the only slot of that type, unless this same run already wrote that item under a different name (a second name in one run is a second part);
- else no slot.
An explicit item_key or supersedes always wins. A write whose final item is
not one of the phase's slots for that type is still recorded, as its own item,
and flagged: metadata.undeclared_item, undeclared_phase,
declared_item_keys; undeclared_item: true plus a note in the tool result;
a flow_undeclared_item log event; and the
metaforge_flow_item_slot_total{item_type, outcome="undeclared"} counter
(outcome="slot" for writes that landed on a slot). A write of a type the
phase declares no slot for is not judged and resolves as.
At the gate. TwinConstraintChecker lists undeclared items in the
report's undeclared_items, rendered in the gate reason as Undeclared items (n): .... They are findings for the reviewer (a real new part, or a renamed
declared one), never violations, so they never fail a gate. The in-process
engine scopes them to the phase window; the Temporal gate check, like its
deliverable check, looks at the whole project. There is no alert on the
counter: an undeclared item is a review item, and the reviewer already sees it.
API. Every phase in GET /v1/design-flows, GET /v1/design-flows/{id}
and GET /v1/design-flows/versions/{id} carries slots
([{itemType, name, itemKey, derived}], derived for a default slot that is
computed rather than stored), and POST /v1/design-flows/versions accepts
slots per phase (itemKey optional). A slot the editor sends back with
derived: true is dropped rather than turned into a declared one, so
round-tripping a flow through the editor does not change its hash.
Run supervisor
The run supervisor drives a design run to a verified result, like a loop over
the run (api_gateway/runs/supervisor.py). It is started per run with
POST /v1/runs/{id}/supervise (optional budgets max_actions,
max_restarts, max_model_calls, max_hours), the flow.supervise MCP tool,
the plugin's /metaforge:drive, or the Supervise this run button on the
run page. Every 30 seconds the gateway ticks each supervised run:
| Run state | What the supervisor does |
|---|---|
| Queued or running | Watches. |
| At a gate | Lets the gate be reviewed and decided under the project's approval policy; it never decides a gate itself. A gate that has no review (it opened while the policy was off, or its review failed) gets one asked for, once per gate, once it has been open three minutes without one (the worker's own review, as the gate opens, comes first), while the policy is not off. When a person has to, it records that it is waiting. When the gate is failing in a way the agent cannot fix (the reviewer judges the work sound while the checks fail, or the same findings return after a retry), it stops and reports a platform issue instead of spending retries. |
| Failed | Diagnoses the failure from the run's failure class. A design failure restarts the run as a new run, linked by supervised_from, whose flow_context says why the last attempt stopped and what the reviewer said. A tooling failure restarts after a two-minute pause. A missing capability or an authorisation failure stops it for a person. |
| Completed | Reads the completion verdict. COMPLETED_VERIFIED ends the supervision as verified; anything else restarts with the unmet requirements in the brief. |
| Rejected, cancelled or timed out | Stops: a person, or the clock, ended the run. |
Starting supervision again on a run whose supervision stopped (a budget used, or a person stopped it) begins a fresh budget window: the clock and the action and restart counters start over, while the chain of runs and the log carry on.
A restart carries the run's goal, flow, project, intelligence and flow context
and nothing of its decisions, reviews or engine state. The supervision record
(request["supervision"]: status, budgets, counters, the chain of runs and a
log of its actions) moves to the new run, so GET /v1/runs/{id}/supervision
on any run in the chain shows where it went, and a gateway restart resumes it.
Budgets default to 20 actions, 3 restarts, 600 model calls across the chain
and 12 hours; when one is used the supervisor stops and says which.
metaforge_run_supervisor_action_total counts its actions, and
RunSupervisorFoundPlatformIssue fires when it stopped on something only a
code change can fix.