Official Codebase of 3DCodeVerse
Python
tracks: the planner owns its brief/budgets/examples; graphics is one module (28→23 files)
gaoypeng6894849e6bb8
diff --git a/harness/bench/_fixed_eval.py b/harness/bench/_fixed_eval.pyindex b982083d..43b4a750 100644--- a/harness/bench/_fixed_eval.py+++ b/harness/bench/_fixed_eval.py@@ -174,7 +174,7 @@ class FixedEvaluator:"""Graphics: the judged frames + the gl_frames gate + the frame metrics, as the loop does."""from codeverse.judges.base import JudgeInputfrom codeverse.languages._gl_common import read_metrics- from codeverse.tracks.graphics_steps import frame_stats_text, frames_render_set+ from codeverse.tracks.graphics import frame_stats_text, frames_render_settry:out.renders = frames_render_set(ws, out.build, 0)diff --git a/harness/bench/ab_plan.py b/harness/bench/ab_plan.pyindex 3dc23e06..b7f2bf11 100644--- a/harness/bench/ab_plan.py+++ b/harness/bench/ab_plan.py@@ -11,7 +11,7 @@ planner, the in-loop judge, the rounds and dollars, and the fixed judge that prothe reported score (``bench/_fixed_eval.py``, ``n_samples`` 2).Why each arm is a child PROCESS rather than a thread: the switches under test are read-from the environment (``codeverse.tracks.brief.brief_enabled`` reads ``os.environ`` at+from the environment (``codeverse.tracks.planner.brief_enabled`` reads ``os.environ`` atcall time; anything under ``Settings`` is read once through an ``lru_cache``), so twothreads in one interpreter cannot hold different values of them. A child gets exactlythe env its arm needs and nothing leaks across. Each child owns a key pool, so thediff --git a/harness/bench/judge_calib_graphics.py b/harness/bench/judge_calib_graphics.pyindex 7aa62465..d10ba322 100644--- a/harness/bench/judge_calib_graphics.py+++ b/harness/bench/judge_calib_graphics.py@@ -34,7 +34,7 @@ from codeverse.contracts.spec import Specfrom codeverse.judges.base import JudgeInputfrom codeverse.judges.replay_input import plan_digestfrom codeverse.judges.vlm_judge import VlmJudge-from codeverse.tracks.graphics_steps import frame_stats_text+from codeverse.tracks.graphics import frame_stats_textfrom codeverse.workspace import WorkspaceOUT_ROOT = Path(__file__).resolve().parent / "out"diff --git a/harness/bench/refs_ab_readout.py b/harness/bench/refs_ab_readout.pyindex b2449b2b..f25c8507 100644--- a/harness/bench/refs_ab_readout.py+++ b/harness/bench/refs_ab_readout.py@@ -25,7 +25,7 @@ from codeverse.contracts.spec import ReferenceImage, Specfrom codeverse.judges.base import JudgeInputfrom codeverse.judges.reference import LikenessJudgefrom codeverse.judges.replay_input import plan_digest-from codeverse.tracks.graphics_steps import frame_stats_text+from codeverse.tracks.graphics import frame_stats_textfrom codeverse.workspace import WorkspaceSUFFIXES = (".png", ".jpg", ".jpeg", ".webp")diff --git a/harness/codeverse/tracks/brief.py b/harness/codeverse/tracks/brief.pydeleted file mode 100644index c81ab892..00000000--- a/harness/codeverse/tracks/brief.py+++ /dev/null@@ -1,201 +0,0 @@-"""Brief expansion: the "input prompt" lever, upstream of the planner.--One cheap structured call turns "a hand-crank coffee grinder" into an-:class:`~codeverse.contracts.plan.EngineeringBrief`: the real-world reference instance-and its dimensions, the sub-assemblies a real one has, the mechanism, what is visible-from outside, what it does NOT have, and 3-6 *signature features* a viewer uses to-recognise it. Optional (``CV3D_PLAN_BRIEF``), cached on disk by prompt hash, and never-fatal — any failure returns ``None`` and the planner runs exactly as it did before.--What the planner then DOES with the brief — the derived plan budget, the re-plan quality-gate and the fold back into the plan — lives in ``tracks/plan_budget.py``.-"""--from __future__ import annotations--import hashlib-import json-import logging-import os-from pathlib import Path-from typing import Any--from pydantic import ValidationError--from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart-from codeverse.contracts.common import Track, Usage-from codeverse.contracts.plan import EngineeringBrief-from codeverse.contracts.spec import Spec-from codeverse.models.schema_utils import parse_json_lenient-from codeverse.prompts import load_text, prompt_hash, render--log = logging.getLogger(__name__)--#: env switch: ``off``/``0``/``false`` disables brief expansion for the run-BRIEF_ENV = "CV3D_PLAN_BRIEF"-#: tracks the object-shaped brief applies to (graphics/scene get budgets only)-BRIEF_TRACKS = (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT)-BRIEF_TEMPLATE = "tracks/brief_object.j2"-BRIEF_MAX_TOKENS = 65_536---# ----------------------------------------------------------------------------- brief-def brief_enabled(spec: Spec, *, default: bool = True) -> bool:- """Whether to expand the brief for this spec (env switch wins; object tracks only)."""- raw = (os.environ.get(BRIEF_ENV) or "").strip().lower()- on = default if not raw else raw not in ("0", "off", "false", "no")- return on and spec.track in BRIEF_TRACKS---def brief_cache_dir() -> Path:- root = os.environ.get("CV3D_CACHE_DIR") or (Path.home() / ".cache" / "codeverse")- return Path(root) / "briefs"---def _reference_digest(spec: Spec) -> list[dict[str, str]]:- """Identify the reference images by path AND content hash.-- ``--reference`` synthesises a NEW image per run under the same spec fields, so- the path alone does not separate two runs; the bytes do. An unreadable file- still contributes its path, so it can never collapse onto "no references"."""- out: list[dict[str, str]] = []- for r in spec.references:- try:- digest = _sha256_file(Path(r.path))- except OSError:- digest = "(unreadable)"- out.append({"path": r.path, "role": r.role, "note": r.note, "sha256": digest})- return out---def _sha256_file(path: Path) -> str:- h = hashlib.sha256()- with path.open("rb") as fh:- for chunk in iter(lambda: fh.read(1 << 20), b""):- h.update(chunk)- return h.hexdigest()---def brief_cache_key(spec: Spec, model_id: str) -> str:- """Every input to the call must be in the key.-- ``expand_brief`` attaches ``spec.references`` to the request and tells the model- to read the dimensions and features off them, so a key that omits them lets an- ``--image`` run drink a brief generated WITHOUT the image (and vice versa) —- silently, from the machine-wide ~/.cache/codeverse/briefs, with cached=True in- events.jsonl."""- c = spec.constraints- payload = json.dumps({- "prompt": spec.prompt.strip(), "track": spec.track.value, "language": spec.language.value,- "must_have": list(c.must_have), "must_not": list(c.must_not), "style": c.style,- "dimensions_m": c.dimensions_m or {}, "model": model_id,- "references": _reference_digest(spec),- "template": prompt_hash(load_text(BRIEF_TEMPLATE)),- }, sort_keys=True)- return hashlib.sha256(payload.encode()).hexdigest()[:20]---def expand_brief(spec: Spec, model_id: str, *, model: Any | None = None, events: Any | None = None,- cache_dir: Path | None = None) -> tuple[EngineeringBrief | None, Usage]:- """One cheap structured call → :class:`EngineeringBrief`, cached by prompt hash.-- Never raises and never blocks planning: any failure returns ``(None, usage)`` and the- planner runs exactly as it did before."""- usage = Usage()- cdir = cache_dir if cache_dir is not None else brief_cache_dir()- key = brief_cache_key(spec, model_id)- path = cdir / f"{key}.json"- if path.is_file():- try:- brief = EngineeringBrief.model_validate_json(path.read_text())- if not brief.is_useful:- raise ValueError("cached brief has nothing to plan from")- if events is not None:- events.emit("plan.brief", cached=True, key=key, n_sub=len(brief.sub_assemblies),- n_signature=len(brief.signature_features), cost_usd=0.0)- return brief, usage- except (ValidationError, ValueError, OSError) as e: # a stale/corrupt cache entry is not fatal- log.warning("brief cache %s unusable (%s); regenerating", path, e)- if model is None:- from codeverse.models import get_chat_model-- model = get_chat_model(model_id)- system = render(BRIEF_TEMPLATE, track=spec.track.value, language=spec.language.value)- images = [ImagePart(path=r.path, label=f"{r.role}: {r.note}".strip(": ")) for r in spec.references]- user = f"REQUEST: {spec.prompt.strip()}"- if spec.constraints.must_have:- user += "\n\nThe user also requires:\n" + "\n".join(f"- {m}" for m in spec.constraints.must_have)- if spec.constraints.dimensions_m:- user += "\n\nStated dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in spec.constraints.dimensions_m.items())- if images:- user += f"\n\n{len(images)} reference image(s) are attached — read the dimensions and features off them."- try:- resp = model.generate(ChatRequest(- messages=[ChatMessage.user(user, images=images or None)], system=system,- response_schema=EngineeringBrief.model_json_schema(), temperature=0.3, thinking="low",- max_output_tokens=BRIEF_MAX_TOKENS, max_wait_s=900.0, label="planner-brief"))- usage = usage + resp.usage- # parse_json_lenient, not json.loads: it tolerates fences/prose AND strips the- # C0 controls a model can emit, which json.loads would carry into the brief.- raw = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text or "{}")- brief = EngineeringBrief.model_validate(raw)- if not brief.is_useful:- raise ValueError(f"brief has {len(brief.sub_assemblies)} sub-assemblies and "- f"{len(brief.signature_features)} signature features — nothing to plan from")- except Exception as e: # noqa: BLE001 — the brief is an optional accelerator, never a failure mode- log.warning("brief expansion failed (%s: %s); planning without it", type(e).__name__, e)- if events is not None:- events.emit("plan.brief_failed", error=f"{type(e).__name__}: {e}"[:300])- return None, usage- try:- cdir.mkdir(parents=True, exist_ok=True)- path.write_text(brief.model_dump_json(indent=1))- except OSError as e:- log.warning("could not cache brief at %s: %s", path, e)- if events is not None:- events.emit("plan.brief", cached=False, key=key, n_sub=len(brief.sub_assemblies),- n_signature=len(brief.signature_features), cost_usd=round(usage.cost_usd, 5))- return brief, usage---def brief_block(brief: EngineeringBrief | None) -> str:- """The brief as a prompt block for the planner's user message ("" when absent)."""- if brief is None:- return ""- out = ["ENGINEERING BRIEF (researched for this request — treat it as ground truth about the real object):",- f"- it is: {brief.one_line or brief.object_name}"]- if brief.reference:- out.append(f"- reference instance the numbers come from: {brief.reference}")- if brief.dimensions_m:- out.append("- real-world dimensions (m): " + ", ".join(f"{d.name} {d.meters:.3f}" for d in brief.dimensions_m))- if brief.mechanism:- out.append(f"- how it works: {brief.mechanism}")- if brief.sub_assemblies:- out.append(f"- sub-assemblies a real one has ({len(brief.sub_assemblies)}):")- for s in brief.sub_assemblies:- bits = f" · {s.name}"- if s.purpose:- bits += f" — {s.purpose}"- if s.parts:- bits += f"; made of: {', '.join(s.parts)}"- if s.material:- bits += f" [{s.material}]"- out.append(bits)- if brief.visible_from_outside:- out.append("- visible from outside (model these): " + "; ".join(brief.visible_from_outside))- if brief.hidden_inside:- out.append("- inside, NOT visible (do not model): " + "; ".join(brief.hidden_inside))- if brief.not_present:- out.append("- it does NOT have: " + "; ".join(brief.not_present))- if brief.materials:- out.append("- materials: " + "; ".join(brief.materials))- if brief.signature_features:- out.append(f"- SIGNATURE FEATURES ({len(brief.signature_features)}) — a viewer recognises the object by these; "- "every one of them must be a part, a sub-part or a named detail in your plan:")- out += [f" {i}. {f}" for i, f in enumerate(brief.signature_features, 1)]- return "\n".join(out)----__all__ = ["BRIEF_ENV", "BRIEF_TEMPLATE", "BRIEF_TRACKS", "brief_block", "brief_cache_dir",- "brief_cache_key", "brief_enabled", "expand_brief"]diff --git a/harness/codeverse/tracks/depth.py b/harness/codeverse/tracks/depth.pyindex b4935bbb..fd14c7dd 100644--- a/harness/codeverse/tracks/depth.py+++ b/harness/codeverse/tracks/depth.py@@ -24,7 +24,7 @@ on eight objective axes — is ``codeverse/spatial/complexity.py`` + ``docs/COMPThis module is the *target* side: what THIS plan should be allowed and asked to spend.Hence: :func:`depth_budget` (how many triangles / how much build time this *plan*-deserves — how many PARTS a prompt deserves is ``tracks.brief.plan_budget``,+deserves — how many PARTS a prompt deserves is ``tracks.planner.plan_budget``,which also owns the thin-plan re-ask), and :func:`scope_groups` (how to split one plan into sessions smallenough that each part gets real attention) with :func:`interfaces_text` handingeach session the exact numbers of the parts it must touch but may not edit.diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.pyindex 44aa32d5..30174e7d 100644--- a/harness/codeverse/tracks/graphics.py+++ b/harness/codeverse/tracks/graphics.py@@ -12,37 +12,49 @@ Refinement is always one whole-program task.from __future__ import annotationsimport logging+import re+import shutil+from dataclasses import dataclass+from pathlib import Pathfrom typing import Any-from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet-from codeverse.contracts.common import TRACK_INFO, Language, Track-from codeverse.contracts.plan import GraphicsPlan, Plan+from codeverse.config import seed_recipes_enabled+from codeverse.contracts.artifacts import (+ BuildResult,+ GateReport,+ Measurement,+ RenderSet,+ RenderView,+ Severity,+)+from codeverse.contracts.common import HARNESS_OWNED_SRC, TRACK_INFO, Language, Track+from codeverse.contracts.plan import AcceptanceItem, GraphicsPlan, Planfrom codeverse.contracts.run import RoundRecordfrom codeverse.contracts.spec import Spec-from codeverse.languages._gl_common import read_metrics+from codeverse.languages._gl_common import SHEET_NAME, read_metrics+from codeverse.languages.glsl_shader.lint import FUNC_DEF+from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL+from codeverse.languages.glsl_shader.wrap import strip_commentsfrom codeverse.orchestrator.rounds import TaskGroupfrom codeverse.prompts import render+from codeverse.spatial.cookbook_tool import Section, split_sectionsfrom codeverse.tracks.common import RunContext-from codeverse.tracks.generation import GenerationTask-from codeverse.tracks.graphics_recipes import seed_recipes-from codeverse.tracks.graphics_steps import (- PLAN_MAX_OUTPUT_TOKENS,- PLAN_TEMPERATURE,- PLAN_TEMPLATE,- ensure_graphics_acceptance,- frame_stats_text,- frames_render_set,- graphics_event_stats,- graphics_expected_files,- graphics_prompt_context,-)-from codeverse.tracks.graphics_steps import plan_example as graphics_plan_example+from codeverse.tracks.generation import SINGLE_SHOT_FORMAT, GenerationTaskfrom codeverse.tracks.lifecycle import BaseTrack, StageRunner+from codeverse.tracks.planner import add_acceptance_item, build_system_prompt+from codeverse.tracks.planner import plan as run_plannerfrom codeverse.tracks.prompting import (+ AGENT_OUTPUT_RULES,+ acceptance_lines,+ constraints_text,current_files,+ is_always_chapter,judge_digest,judged_sheet,reference_images,+ reference_note,+ select_cookbook_chapters,+ select_cookbook_excerpt,skeleton_files,)from codeverse.workspace import Workspace@@ -50,6 +62,384 @@ from codeverse.workspace import Workspacelog = logging.getLogger(__name__)+# ===================================================================== recipe seeding+# (merged from codeverse/tracks/graphics_recipes.py, 2026-08-28 — its two importers+# were this track and graphics_steps. Original module rationale:+# Seed the cookbook's verified GLSL recipes into the HARNESS-OWNED ``src/recipes.glsl`` BEFORE the session.+#+# Measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash api-agent, shader_v2 judge): the+# baseline prompt carried the cookbook's "Light phenomena" chapter — five mentions of ``curtain(`` in+# ``trajectories/baseline_r00/prompt.md`` — and the agent called none of them (``grep -c "curtain("+# src/shader.frag`` = 0 in both finished runs): round 0 was again a comb of bars (``comb_artefact``, 0.33).+# Showing flash a recipe is not the same as flash using it, so the recipes go ON DISK.+# ... see git history of graphics_recipes.py for the full measured writeup.)+#: the harness-owned recipe file (``contracts.common.HARNESS_OWNED_SRC``; ``AgentJob.read_only``)+RECIPES_REL = HARNESS_OWNED_SRC[Language.GLSL_SHADER][0]+#: the agent's helper file — never written by this module, except :func:`trim_skeleton_common`+COMMON_REL = "src/common.glsl"+HEADER = ("// harness-owned: verified cookbook recipes matched to this brief — READ-ONLY (the harness pastes this "+ "above src/common.glsl); call these functions from shader.frag")+RESUME_HEADER = "// ---- appended on resume (recipes this file did not define yet) ----"+TRIM_NOTE = "// {names}: provided by src/recipes.glsl (harness-owned, pasted above this file) — call them, do not redefine them"+#: ``ctx.extra`` key → the prompt block (``[{name, signature, purpose}, …]``, every seeded recipe on disk)+EXTRA_KEY = "seeded_recipes"+#: chapters whose code is a TEMPLATE to adapt, not a library to call: the raymarching ``map()`` is the+#: agent's own scene, and a seeded ``map`` / ``calcNormal`` would collide with the one it must write+NOT_SEEDED: tuple[str, ...] = ("Raymarching",)++#: what each recipe is for — one line in the header comment and in the prompt block+PURPOSES: dict[str, str] = {+ "curtain": "ONE organic aurora / drapery / flame-sheet ribbon (folded lower edge, rays in bundles, gaps; "+ "k = 0 at the lower edge .. 1 at the top) — never a comb of bars",+ "auroraCol": "green-low → violet-crown aurora colour for the k that curtain() writes",+ "aurora": "the whole aurora: three curtains at different depths, nearest brightest "+ "(then col += au * 1.7 + au * au * 0.5 for bloom)",+ "stars": "dense sub-pixel star field on a grid (density 160 / 70, keep 0.2–0.3); add two layers",+ "bokehSoft": "soft gaussian city-light discs ADDED on a dark ground, three depth layers, pulsing",+ "dropsLayer": "rain on glass: (drop mask, trail) per grid cell scrolling down; refract the background with .x",+ "skyGrad": "dusk sky gradient by p.y", "sun": "sun disc with a soft halo",+ "waterHeight": "water surface height (waves + noise) for reflections / normals",+ "warped": "domain-warped fbm: billowy clouds, smoke, marble",+ "hash11": "1D hash 0..1", "hash12": "2D → float hash 0..1", "hash22": "2D → vec2 hash", "hash33": "3D → vec3 hash",+ "noise": "smooth 2D value noise 0..1", "noise3": "3D value noise (volumes, time as z)",+ "fbm": "6-octave rotated fbm", "ridged": "ridged fbm (mountains, veins)",+ "palette": "IQ cosine palette", "tonemapACES": "ACES tonemap", "gamma": "gamma 2.2",+ "sdCircle": "2D circle SDF", "sdBox": "2D box SDF", "sdSegment": "2D segment SDF", "sdStar": "2D star SDF",+ "fill": "1-px anti-aliased fill of an SDF", "stroke": "anti-aliased outline of an SDF",+ "glow": "exponential glow around an SDF", "rot2": "2D rotation matrix",+}++_FENCE = re.compile(r"```glsl[ \t]*\n(.*?)^```", re.S | re.M)+_CALL = re.compile(r"\b([A-Za-z_]\w*)\s*\(")+_KEYWORDS = frozenset({"for", "if", "while", "switch", "return"})+_DEFINE = re.compile(r"^[ \t]*#\s*define\s+(\w+)", re.M)+#: top-level comment lines that are usage examples (``// usage: …``, ``// sunset: palette(…)``, a+#: statement ending in ``;``), not documentation of the function that follows+_USAGE = re.compile(r"^//\s*(?:usage|e\.g\.)\b|^//\s*[\w .-]+?:\s+\w+\(|;\s*(?://.*)?$", re.I)+++@dataclass(frozen=True)+class Recipe:+ name: str+ signature: str+ text: str # doc comment lines + the complete definition+ calls: frozenset[str]+ chapter: str++ @property+ def purpose(self) -> str:+ return PURPOSES.get(self.name, f'from the cookbook chapter "{self.chapter}"')++ def entry(self) -> dict[str, str]:+ return {"name": self.name, "signature": self.signature, "purpose": self.purpose}+++def parse_functions(code: str, chapter: str = "") -> list[Recipe]:+ """Top-level function definitions in a GLSL text (``mainImage`` / ``main`` excluded), each with+ the documentation comment lines directly above it; usage comments and bare statements dropped."""+ lines = code.splitlines()+ out: list[Recipe] = []+ pending: list[str] = []+ i = 0+ while i < len(lines):+ raw = lines[i]+ s = raw.strip()+ if s.startswith("//"):+ pending = [] if _USAGE.search(s) else pending + [raw]+ i += 1+ continue+ m = FUNC_DEF.match(raw)+ if not s or not m: # blank, #define, or a bare statement snippet+ pending, i = [], i + 1+ continue+ depth, opened, j = 0, False, i+ while j < len(lines):+ code_only = strip_comments(lines[j])+ depth += code_only.count("{") - code_only.count("}")+ opened = opened or "{" in code_only+ j += 1+ if opened and depth <= 0:+ break+ body = lines[i:j]+ head = strip_comments(body[0])+ signature = (head[: head.index(")") + 1] if ")" in head else head).strip()+ text = "\n".join(pending + body)+ if m.group(1) not in ("mainImage", "main"):+ calls = frozenset(_CALL.findall(strip_comments(text))) - _KEYWORDS - {m.group(1)}+ out.append(Recipe(m.group(1), signature, text, calls, chapter))+ pending, i = [], j+ return out+++def chapter_functions(section: Section) -> list[Recipe]:+ return [r for block in _FENCE.findall(section.body) for r in parse_functions(block, section.title)]+++def cookbook_functions(md: str) -> dict[str, Recipe]:+ """Every function the cookbook defines, by name, in cookbook order (first definition wins)."""+ out: dict[str, Recipe] = {}+ for sec in split_sections(md):+ for r in chapter_functions(sec):+ out.setdefault(r.name, r)+ return out+++def defined_names(glsl: str) -> set[str]:+ """Function and ``#define`` names a GLSL file already defines (what a seed must not repeat)."""+ names = set(_DEFINE.findall(glsl))+ names.update(m.group(1) for line in strip_comments(glsl).splitlines() if (m := FUNC_DEF.match(line)))+ return names+++def with_helpers(wanted: list[Recipe], known: dict[str, Recipe]) -> list[Recipe]:+ """``wanted`` plus every cookbook function they call (transitively), callees before callers."""+ order: list[Recipe] = []+ seen: set[str] = set()++ def visit(r: Recipe) -> None:+ if r.name in seen:+ return+ seen.add(r.name)+ for dep in (n for n in known if n in r.calls):+ visit(known[dep])+ order.append(r)++ for r in wanted:+ visit(known.get(r.name, r))+ return order+++def graphics_brief(ctx: RunContext) -> str:+ """The text the cookbook selection (prompt excerpt AND seeded recipes) is matched against."""+ plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None+ return ctx.spec.prompt + " " + " ".join(plan.key_visuals if plan else [])+++def recipe_chapters(ctx: RunContext) -> list[Section]:+ """The brief's cookbook chapters minus the always-on ones and the templates (``NOT_SEEDED``)."""+ return [s for s in select_cookbook_chapters(ctx, graphics_brief(ctx))+ if s.level >= 2 and not is_always_chapter(s.title) and not is_always_chapter(s.title, NOT_SEEDED)]+++def seeded_on_disk(glsl: str, known: dict[str, Recipe]) -> list[Recipe]:+ """The cookbook recipes a ``src/recipes.glsl`` carries, in file order (a file without the harness+ header is not a seed; only cookbook names count)."""+ if HEADER not in glsl:+ return []+ return [known[r.name] for r in parse_functions(glsl) if r.name in known]+++def is_skeleton_common(text: str) -> bool:+ """Is this ``src/common.glsl`` still the harness skeleton — untouched, or only ever trimmed by+ :func:`trim_skeleton_common`? (Every function it defines is the skeleton's own, verbatim.)"""+ if text == COMMON_GLSL:+ return True+ skeleton = {r.name: r.text for r in parse_functions(COMMON_GLSL)}+ return (text.startswith(COMMON_GLSL.splitlines()[0])+ and defined_names(text) <= defined_names(COMMON_GLSL)+ and all(skeleton.get(r.name) == r.text for r in parse_functions(text)))+++def trim_skeleton_common(path: Path, provided: set[str]) -> list[str]:+ """Drop from the SKELETON's ``src/common.glsl`` the helpers ``src/recipes.glsl`` now provides — it is+ pasted first, so a second ``hash12`` in common.glsl is a redefinition and the first build would fail+ before the agent wrote a line. Acts only while the file is still the harness's own skeleton text+ (the agent has not seen it yet); once the agent owns common.glsl a duplicate is its own to remove,+ and the lint names it. Returns the names dropped."""+ if not path.is_file():+ return []+ text = path.read_text(errors="replace")+ if not is_skeleton_common(text):+ return []+ dropped = [r for r in parse_functions(text) if r.name in provided]+ if not dropped:+ return []+ for r in dropped:+ text = text.replace(r.text + "\n", "", 1)+ text = re.sub(r"\n{3,}", "\n\n", text)+ first, rest = text.split("\n", 1)+ note = TRIM_NOTE.format(names=", ".join(r.name for r in dropped))+ path.write_text(f"{first}\n{note}\n{rest}")+ return [r.name for r in dropped]+++def seed_recipes(ctx: RunContext) -> list[str]:+ """Write the brief's verified recipes (+ their helpers) to the harness-owned ``src/recipes.glsl``+ (a resume appends only names the file does not define yet); return the names written THIS call.+ ``ctx.extra["seeded_recipes"]`` lists every seeded recipe on disk (for the prompt block);+ ``recipes.seeded`` is emitted with both. No-op unless glsl_shader and enabled."""+ if ctx.language is not Language.GLSL_SHADER or not seed_recipes_enabled():+ return []+ known = cookbook_functions(ctx.cookbook_text or "")+ chapters = recipe_chapters(ctx)+ wanted = [r for s in chapters for r in chapter_functions(s)]+ path: Path = ctx.ws.root / RECIPES_REL+ existing = path.read_text(errors="replace") if path.is_file() else ""+ have = defined_names(existing)+ new = [r for r in with_helpers(wanted, known) if r.name not in have]+ trimmed: list[str] = []+ if new:+ head = [HEADER] if not existing else [RESUME_HEADER]+ block = [*head, *(f"// {r.signature} — {r.purpose}" for r in new), "", *(r.text for r in new)]+ lead = "" if not existing else ("" if existing.endswith("\n") else "\n") + "\n"+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(existing + lead + "\n".join(block) + "\n")+ existing = path.read_text(errors="replace")+ trimmed = trim_skeleton_common(ctx.ws.root / COMMON_REL, defined_names(existing))+ present = seeded_on_disk(existing, known)+ ctx.extra[EXTRA_KEY] = [r.entry() for r in present]+ ctx.events.emit("recipes.seeded", file=RECIPES_REL, names=[r.name for r in new], present=[r.name for r in present],+ chapters=[s.title for s in chapters], trimmed=trimmed)+ return [r.name for r in new]+++# ===================================================================== planner hooks + prompt context + frames+# (merged from codeverse/tracks/graphics_steps.py, 2026-08-28 — single production importer)+PLAN_TEMPLATE = "tracks/plan_graphics.j2"+PLAN_TEMPERATURE = 0.5+PLAN_MAX_OUTPUT_TOKENS = 65_536 # the model's declared output ceiling; unused tokens cost nothing+EXPECTED_FILES: dict[Language, list[str]] = {+ Language.GLSL_SHADER: ["src/shader.frag", "src/common.glsl"],+ Language.OPENGL_PYTHON: ["src/program.py"],+}+++# ----------------------------------------------------------------------------- planner+def plan_example() -> dict[str, Any]: # the graphics worked example (planner hook)+ return {+ "title": "Neon rain on a window", "summary": "Looking through a rain-streaked window at a neon-lit street at night; "+ "drops run down the glass, city lights turn into coloured bokeh discs that pulse.",+ "style": "cyberpunk night: deep indigo/black base, magenta + cyan neon accents, warm sodium highlights; soft, filmic",+ "resolution": [1280, 720], "duration_s": 8.0,+ "passes": [+ {"name": "CityBokeh", "kind": "fullscreen", "description": "background: 40-60 blurred bokeh discs (hash-placed, 3 depth layers, cyan/magenta/amber), slow horizontal parallax, pulsing brightness"},+ {"name": "RainDrops", "kind": "fullscreen", "description": "grid-cell drops with hash offsets, running trails (fract(t) per cell), refraction offset applied when sampling the background"},+ {"name": "Grade", "kind": "postprocess", "description": "vignette, slight chromatic aberration, tonemap + gamma"},+ ],+ "uniforms": ["u_time", "u_resolution"],+ "motion": "drops slide down with gravity and wobble; bokeh drifts left 0.02/s and pulses at 0.5-1 Hz; no hard cuts",+ "key_visuals": ["rain drops with trails on glass", "blurred neon bokeh discs", "dark night street behind", "magenta/cyan palette"],+ "acceptance": [+ {"id": "a1", "text": "Raindrops with trails visibly run down the glass (compare t=0 and t=1)", "how": "visual", "priority": "must"},+ {"id": "a2", "text": "Blurred coloured bokeh lights are visible in the background", "how": "visual", "priority": "must"},+ {"id": "a3", "text": "Frames change over time (no static image)", "how": "probe", "priority": "must"},+ ],+ }+++def build_plan_system_prompt(spec: Spec, *, runtime: Any | None = None) -> str:+ """The graphics plan system prompt = the shared builder with the graphics+ template + worked example (``plan_graphics.j2`` references no 3D frame)."""+ return build_system_prompt(spec, GraphicsPlan, runtime=runtime, template=PLAN_TEMPLATE, example=plan_example())+++def ensure_graphics_acceptance(plan: GraphicsPlan, spec: Spec) -> GraphicsPlan:+ """Spec must_have / must_not → visual items; planned motion → a probe item (never 'ground contact')."""+ items: list[AcceptanceItem] = list(plan.acceptance)+ for m in spec.constraints.must_have:+ add_acceptance_item(items, "must", f"Includes: {m}", "visual")+ for m in spec.constraints.must_not:+ add_acceptance_item(items, "not", f"Does NOT include: {m}", "visual")+ if plan.motion.strip() and not any("static" in a.text.lower() or "motion" in a.text.lower() or "change over time" in a.text.lower() for a in items):+ add_acceptance_item(items, "motion", "Frames change over time as planned (not a static image)", "probe")+ plan.acceptance = items+ return plan+++def graphics_event_stats(plan: GraphicsPlan) -> dict[str, Any]:+ """``plan.done`` payload for graphics (passes, not parts/zones)."""+ return {"n_passes": len(plan.passes), "n_acceptance": len(plan.acceptance)}+++def plan_graphics(spec: Spec, model_id: str, ws: Workspace, *, model: Any | None = None, events: Any | None = None,+ budget: Any | None = None, runtime: Any | None = None) -> GraphicsPlan:+ """Structured planner call → validated GraphicsPlan: the ONE planner loop+ (``tracks/planner.plan``) parameterised with the graphics hooks."""+ return run_planner(spec, model_id, GraphicsPlan, ws, model=model, events=events, budget=budget, runtime=runtime,+ template=PLAN_TEMPLATE, example=plan_example(), temperature=PLAN_TEMPERATURE,+ max_output_tokens=PLAN_MAX_OUTPUT_TOKENS,+ finalise=lambda p: ensure_graphics_acceptance(p, spec), event_stats=graphics_event_stats)+++# ----------------------------------------------------------------------------- prompt context+def graphics_expected_files(ctx: RunContext) -> list[str]:+ return list(EXPECTED_FILES.get(ctx.language, ["src/shader.frag"]))+++def passes_table(plan: GraphicsPlan | None) -> str:+ if plan is None or not plan.passes:+ return "(no passes)"+ rows = ["| pass | kind | what it draws / computes |", "|---|---|---|"]+ rows += [f"| {p.name} | {p.kind} | {p.description} |" for p in plan.passes]+ return "\n".join(rows)+++def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:+ """Every variable the graphics templates may reference (StrictUndefined)."""+ plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None+ res = plan.resolution if plan else (1280, 720)+ d: dict[str, Any] = {+ "track": ctx.track.value, "language": ctx.language.value, "contract": ctx.contract_text,+ "cookbook_rel": ctx.cookbook_rel, "cookbook_excerpt": select_cookbook_excerpt(ctx, graphics_brief(ctx)), "tool_cards": ctx.tool_cards,+ # the recipes tracks/graphics_recipes.py put in the harness-owned src/recipes.glsl before the session ([] = no block)+ "seeded_recipes": list((getattr(ctx, "extra", None) or {}).get(EXTRA_KEY) or []),+ "single_shot": ctx.single_shot, "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,+ "spec_prompt": ctx.spec.prompt, "constraints": constraints_text(ctx.spec),+ "title": plan.title if plan else "Untitled effect", "plan_summary": plan.summary if plan else "",+ "style": plan.style if plan else "", "resolution": f"{res[0]}x{res[1]}", "duration": f"{plan.duration_s:g}" if plan else "8",+ "passes_table": passes_table(plan), "motion": plan.motion if plan else "", "key_visuals": list(plan.key_visuals) if plan else [],+ "uniforms": ", ".join(plan.uniforms) if plan and plan.uniforms else "u_time, u_resolution",+ "acceptance": acceptance_lines(plan), "entry_files": ", ".join(getattr(ctx.runtime, "entry_globs", ()) or ()),+ "expected_files": graphics_expected_files(ctx), "reference_note": reference_note(ctx),+ "judge_times": "0, 1, 2.5, 4, 6 s",+ }+ d.update(extra)+ return d+++# ----------------------------------------------------------------------------- renders / gates+def frames_render_set(ws: Workspace, build: BuildResult, round_index: int) -> RenderSet:+ """Copy the judged frames + sheet into renders/rNN and describe them as a RenderSet (views ``t=<s>s``)."""+ out = ws.renders_dir(round_index)+ out.mkdir(parents=True, exist_ok=True)+ frames_dir = Path(build.extra_paths.get("frames", ws.artifacts / "frames"))+ metrics = read_metrics(ws)+ stats = metrics[0] if metrics else None+ views: list[RenderView] = []+ frames = stats.frames if stats else []+ for f in frames:+ src = Path(f.path)+ if not src.is_file():+ continue+ dst = out / f"frame_t{f.time:05.2f}.png"+ shutil.copy2(src, dst)+ views.append(RenderView(name=f"t={f.time:g}s", path=str(dst), time_s=f.time))+ if not views and frames_dir.is_dir(): # metrics missing: fall back to the raw frame files+ for p in sorted(frames_dir.glob("f*_t*.png")):+ dst = out / p.name+ shutil.copy2(p, dst)+ views.append(RenderView(name=p.stem.split("_t", 1)[-1] + "s", path=str(dst)))+ sheet_src = Path(build.extra_paths.get("sheet", ws.artifacts / SHEET_NAME))+ sheet = None+ if sheet_src.is_file():+ sheet = out / "sheet.png"+ shutil.copy2(sheet_src, sheet)+ renderer = str(build.census.get("renderer", "")) if isinstance(build.census, dict) else ""+ return RenderSet(views=views, contact_sheet=str(sheet) if sheet else None, renderer=renderer or "moderngl",+ duration_ms=build.duration_ms)+++def frame_stats_text(ws: Workspace) -> str:+ m = read_metrics(ws)+ if m is None:+ return "(no frame metrics)"+ stats, gate = m+ lines = stats.summary_lines()+ for f in gate.findings:+ lines.append(f"- GATE gl_frames {f.as_line(with_severity=True, with_hint=f.severity is not Severity.INFO)}")+ return "\n".join(lines)++class GraphicsPipeline:"""No measurement; gates = gl_frames (from artifacts/metrics.json); render = the frames."""@@ -97,7 +487,7 @@ class GraphicsTrack(BaseTrack):# ------------------------------------------------------------------ planner hooksdef plan_example(self, spec: Spec) -> dict[str, Any]:- return graphics_plan_example()+ return plan_example()def finalise_plan(self, plan_obj: Any, spec: Spec) -> Any:return ensure_graphics_acceptance(plan_obj, spec)diff --git a/harness/codeverse/tracks/graphics_recipes.py b/harness/codeverse/tracks/graphics_recipes.pydeleted file mode 100644index 4102f769..00000000--- a/harness/codeverse/tracks/graphics_recipes.py+++ /dev/null@@ -1,267 +0,0 @@-"""Seed the cookbook's verified GLSL recipes into the HARNESS-OWNED ``src/recipes.glsl`` BEFORE the session.--Measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash api-agent, shader_v2 judge): the-baseline prompt carried the cookbook's "Light phenomena" chapter — five mentions of ``curtain(`` in-``trajectories/baseline_r00/prompt.md`` — and the agent called none of them (``grep -c "curtain("-src/shader.frag`` = 0 in both finished runs): round 0 was again a comb of bars (``comb_artefact``, 0.33).-Showing flash a recipe is not the same as flash using it, so the recipes go ON DISK.--Measured again 2026-08-26 (bench/out/seed_v1, same brief / model, seeding ON into ``src/common.glsl``):-``recipes.seeded`` fired, and the finished run's ``src/common.glsl`` carried NO seeded block and no-``curtain(`` — the agent overwrote common.glsl with its own helpers — and ``src/shader.frag`` called-neither ``aurora(`` nor ``curtain(`` nor ``stars(``. Seeding into a file the agent owns is not sticky.-So the file is now ``src/recipes.glsl`` (:data:`RECIPES_REL`), which the harness owns:--* the agent cannot write it — ``AgentJob.read_only`` → ``FileTools`` refuses ``write_file`` /- ``edit_file`` (``read_file`` still works); the prompt says "call these, do not redefine them";-* ``wrap.compose`` pastes it ABOVE ``src/common.glsl`` (harness header < recipes < common < shader),- so it is self-contained: every ``hash12`` / ``noise`` / ``fbm`` helper a recipe calls is IN the- file and nothing the agent does to common.glsl can break a recipe;-* a name it defines is reserved: defining it again in shader.frag / common.glsl / buffer_a.frag is- the ``lint:glsl_shader`` ERROR ``redefines_recipe`` ("… is already provided by src/recipes.glsl");-* the skeleton's ``src/common.glsl`` is the only file this module ever edits, and only while it is- still the untouched harness skeleton: the helpers recipes.glsl now provides are dropped from it- (:func:`trim_skeleton_common`), otherwise the very first build would fail on ``hash12`` twice.--What is seeded: the chapters :func:`select_cookbook_chapters` picks for the brief (minus the always-on-helper / grading / pitfalls chapters and the raymarching template), their ``glsl`` code blocks reduced to-function definitions (no usage comments, no ``mainImage``), plus exactly the helpers those functions-call. A resume appends only the names recipes.glsl does not define yet. Gate:-``Settings.limits.seed_recipes`` / ``CV3D_SEED_RECIPES`` (:func:`seed_recipes_enabled`). glsl_shader-only — ``opengl_python`` programs own their shader strings, nothing is seeded there.-"""--from __future__ import annotations--import re-from dataclasses import dataclass-from pathlib import Path--from codeverse.config import seed_recipes_enabled-from codeverse.contracts.common import HARNESS_OWNED_SRC, Language-from codeverse.contracts.plan import GraphicsPlan-from codeverse.languages.glsl_shader.lint import FUNC_DEF-from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL-from codeverse.languages.glsl_shader.wrap import strip_comments-from codeverse.spatial.cookbook_tool import Section, split_sections-from codeverse.tracks.common import RunContext-from codeverse.tracks.prompting import is_always_chapter, select_cookbook_chapters--#: the harness-owned recipe file (``contracts.common.HARNESS_OWNED_SRC``; ``AgentJob.read_only``)-RECIPES_REL = HARNESS_OWNED_SRC[Language.GLSL_SHADER][0]-#: the agent's helper file — never written by this module, except :func:`trim_skeleton_common`-COMMON_REL = "src/common.glsl"-HEADER = ("// harness-owned: verified cookbook recipes matched to this brief — READ-ONLY (the harness pastes this "- "above src/common.glsl); call these functions from shader.frag")-RESUME_HEADER = "// ---- appended on resume (recipes this file did not define yet) ----"-TRIM_NOTE = "// {names}: provided by src/recipes.glsl (harness-owned, pasted above this file) — call them, do not redefine them"-#: ``ctx.extra`` key → the prompt block (``[{name, signature, purpose}, …]``, every seeded recipe on disk)-EXTRA_KEY = "seeded_recipes"-#: chapters whose code is a TEMPLATE to adapt, not a library to call: the raymarching ``map()`` is the-#: agent's own scene, and a seeded ``map`` / ``calcNormal`` would collide with the one it must write-NOT_SEEDED: tuple[str, ...] = ("Raymarching",)--#: what each recipe is for — one line in the header comment and in the prompt block-PURPOSES: dict[str, str] = {- "curtain": "ONE organic aurora / drapery / flame-sheet ribbon (folded lower edge, rays in bundles, gaps; "- "k = 0 at the lower edge .. 1 at the top) — never a comb of bars",- "auroraCol": "green-low → violet-crown aurora colour for the k that curtain() writes",- "aurora": "the whole aurora: three curtains at different depths, nearest brightest "- "(then col += au * 1.7 + au * au * 0.5 for bloom)",- "stars": "dense sub-pixel star field on a grid (density 160 / 70, keep 0.2–0.3); add two layers",- "bokehSoft": "soft gaussian city-light discs ADDED on a dark ground, three depth layers, pulsing",- "dropsLayer": "rain on glass: (drop mask, trail) per grid cell scrolling down; refract the background with .x",- "skyGrad": "dusk sky gradient by p.y", "sun": "sun disc with a soft halo",- "waterHeight": "water surface height (waves + noise) for reflections / normals",- "warped": "domain-warped fbm: billowy clouds, smoke, marble",- "hash11": "1D hash 0..1", "hash12": "2D → float hash 0..1", "hash22": "2D → vec2 hash", "hash33": "3D → vec3 hash",- "noise": "smooth 2D value noise 0..1", "noise3": "3D value noise (volumes, time as z)",- "fbm": "6-octave rotated fbm", "ridged": "ridged fbm (mountains, veins)",- "palette": "IQ cosine palette", "tonemapACES": "ACES tonemap", "gamma": "gamma 2.2",- "sdCircle": "2D circle SDF", "sdBox": "2D box SDF", "sdSegment": "2D segment SDF", "sdStar": "2D star SDF",- "fill": "1-px anti-aliased fill of an SDF", "stroke": "anti-aliased outline of an SDF",- "glow": "exponential glow around an SDF", "rot2": "2D rotation matrix",-}--_FENCE = re.compile(r"```glsl[ \t]*\n(.*?)^```", re.S | re.M)-_CALL = re.compile(r"\b([A-Za-z_]\w*)\s*\(")-_KEYWORDS = frozenset({"for", "if", "while", "switch", "return"})-_DEFINE = re.compile(r"^[ \t]*#\s*define\s+(\w+)", re.M)-#: top-level comment lines that are usage examples (``// usage: …``, ``// sunset: palette(…)``, a-#: statement ending in ``;``), not documentation of the function that follows-_USAGE = re.compile(r"^//\s*(?:usage|e\.g\.)\b|^//\s*[\w .-]+?:\s+\w+\(|;\s*(?://.*)?$", re.I)---@dataclass(frozen=True)-class Recipe:- name: str- signature: str- text: str # doc comment lines + the complete definition- calls: frozenset[str]- chapter: str-- @property- def purpose(self) -> str:- return PURPOSES.get(self.name, f'from the cookbook chapter "{self.chapter}"')-- def entry(self) -> dict[str, str]:- return {"name": self.name, "signature": self.signature, "purpose": self.purpose}---def parse_functions(code: str, chapter: str = "") -> list[Recipe]:- """Top-level function definitions in a GLSL text (``mainImage`` / ``main`` excluded), each with- the documentation comment lines directly above it; usage comments and bare statements dropped."""- lines = code.splitlines()- out: list[Recipe] = []- pending: list[str] = []- i = 0- while i < len(lines):- raw = lines[i]- s = raw.strip()- if s.startswith("//"):- pending = [] if _USAGE.search(s) else pending + [raw]- i += 1- continue- m = FUNC_DEF.match(raw)- if not s or not m: # blank, #define, or a bare statement snippet- pending, i = [], i + 1- continue- depth, opened, j = 0, False, i- while j < len(lines):- code_only = strip_comments(lines[j])- depth += code_only.count("{") - code_only.count("}")- opened = opened or "{" in code_only- j += 1- if opened and depth <= 0:- break- body = lines[i:j]- head = strip_comments(body[0])- signature = (head[: head.index(")") + 1] if ")" in head else head).strip()- text = "\n".join(pending + body)- if m.group(1) not in ("mainImage", "main"):- calls = frozenset(_CALL.findall(strip_comments(text))) - _KEYWORDS - {m.group(1)}- out.append(Recipe(m.group(1), signature, text, calls, chapter))- pending, i = [], j- return out---def chapter_functions(section: Section) -> list[Recipe]:- return [r for block in _FENCE.findall(section.body) for r in parse_functions(block, section.title)]---def cookbook_functions(md: str) -> dict[str, Recipe]:- """Every function the cookbook defines, by name, in cookbook order (first definition wins)."""- out: dict[str, Recipe] = {}- for sec in split_sections(md):- for r in chapter_functions(sec):- out.setdefault(r.name, r)- return out---def defined_names(glsl: str) -> set[str]:- """Function and ``#define`` names a GLSL file already defines (what a seed must not repeat)."""- names = set(_DEFINE.findall(glsl))- names.update(m.group(1) for line in strip_comments(glsl).splitlines() if (m := FUNC_DEF.match(line)))- return names---def with_helpers(wanted: list[Recipe], known: dict[str, Recipe]) -> list[Recipe]:- """``wanted`` plus every cookbook function they call (transitively), callees before callers."""- order: list[Recipe] = []- seen: set[str] = set()-- def visit(r: Recipe) -> None:- if r.name in seen:- return- seen.add(r.name)- for dep in (n for n in known if n in r.calls):- visit(known[dep])- order.append(r)-- for r in wanted:- visit(known.get(r.name, r))- return order---def graphics_brief(ctx: RunContext) -> str:- """The text the cookbook selection (prompt excerpt AND seeded recipes) is matched against."""- plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None- return ctx.spec.prompt + " " + " ".join(plan.key_visuals if plan else [])---def recipe_chapters(ctx: RunContext) -> list[Section]:- """The brief's cookbook chapters minus the always-on ones and the templates (``NOT_SEEDED``)."""- return [s for s in select_cookbook_chapters(ctx, graphics_brief(ctx))- if s.level >= 2 and not is_always_chapter(s.title) and not is_always_chapter(s.title, NOT_SEEDED)]---def seeded_on_disk(glsl: str, known: dict[str, Recipe]) -> list[Recipe]:- """The cookbook recipes a ``src/recipes.glsl`` carries, in file order (a file without the harness- header is not a seed; only cookbook names count)."""- if HEADER not in glsl:- return []- return [known[r.name] for r in parse_functions(glsl) if r.name in known]---def is_skeleton_common(text: str) -> bool:- """Is this ``src/common.glsl`` still the harness skeleton — untouched, or only ever trimmed by- :func:`trim_skeleton_common`? (Every function it defines is the skeleton's own, verbatim.)"""- if text == COMMON_GLSL:- return True- skeleton = {r.name: r.text for r in parse_functions(COMMON_GLSL)}- return (text.startswith(COMMON_GLSL.splitlines()[0])- and defined_names(text) <= defined_names(COMMON_GLSL)- and all(skeleton.get(r.name) == r.text for r in parse_functions(text)))---def trim_skeleton_common(path: Path, provided: set[str]) -> list[str]:- """Drop from the SKELETON's ``src/common.glsl`` the helpers ``src/recipes.glsl`` now provides — it is- pasted first, so a second ``hash12`` in common.glsl is a redefinition and the first build would fail- before the agent wrote a line. Acts only while the file is still the harness's own skeleton text- (the agent has not seen it yet); once the agent owns common.glsl a duplicate is its own to remove,- and the lint names it. Returns the names dropped."""- if not path.is_file():- return []- text = path.read_text(errors="replace")- if not is_skeleton_common(text):- return []- dropped = [r for r in parse_functions(text) if r.name in provided]- if not dropped:- return []- for r in dropped:- text = text.replace(r.text + "\n", "", 1)- text = re.sub(r"\n{3,}", "\n\n", text)- first, rest = text.split("\n", 1)- note = TRIM_NOTE.format(names=", ".join(r.name for r in dropped))- path.write_text(f"{first}\n{note}\n{rest}")- return [r.name for r in dropped]---def seed_recipes(ctx: RunContext) -> list[str]:- """Write the brief's verified recipes (+ their helpers) to the harness-owned ``src/recipes.glsl``- (a resume appends only names the file does not define yet); return the names written THIS call.- ``ctx.extra["seeded_recipes"]`` lists every seeded recipe on disk (for the prompt block);- ``recipes.seeded`` is emitted with both. No-op unless glsl_shader and enabled."""- if ctx.language is not Language.GLSL_SHADER or not seed_recipes_enabled():- return []- known = cookbook_functions(ctx.cookbook_text or "")- chapters = recipe_chapters(ctx)- wanted = [r for s in chapters for r in chapter_functions(s)]- path: Path = ctx.ws.root / RECIPES_REL- existing = path.read_text(errors="replace") if path.is_file() else ""- have = defined_names(existing)- new = [r for r in with_helpers(wanted, known) if r.name not in have]- trimmed: list[str] = []- if new:- head = [HEADER] if not existing else [RESUME_HEADER]- block = [*head, *(f"// {r.signature} — {r.purpose}" for r in new), "", *(r.text for r in new)]- lead = "" if not existing else ("" if existing.endswith("\n") else "\n") + "\n"- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(existing + lead + "\n".join(block) + "\n")- existing = path.read_text(errors="replace")- trimmed = trim_skeleton_common(ctx.ws.root / COMMON_REL, defined_names(existing))- present = seeded_on_disk(existing, known)- ctx.extra[EXTRA_KEY] = [r.entry() for r in present]- ctx.events.emit("recipes.seeded", file=RECIPES_REL, names=[r.name for r in new], present=[r.name for r in present],- chapters=[s.title for s in chapters], trimmed=trimmed)- return [r.name for r in new]diff --git a/harness/codeverse/tracks/graphics_steps.py b/harness/codeverse/tracks/graphics_steps.pydeleted file mode 100644index f9566fcf..00000000--- a/harness/codeverse/tracks/graphics_steps.py+++ /dev/null@@ -1,181 +0,0 @@-"""Graphics-track helpers: planner hooks (GraphicsPlan), prompt context, frame RenderSet.--The shared planner assumes a 3D frame in its acceptance fixups-(``ensure_acceptance`` adds a ground-contact item); shaders have none, so the-graphics track supplies its own template / example / acceptance hooks to the-ONE planner loop in ``tracks/planner.py`` and reuses everything else from-``tracks/lifecycle.py`` + ``tracks/steps.py`` unchanged.-"""--from __future__ import annotations--import logging-import shutil-from pathlib import Path-from typing import Any--from codeverse.contracts.artifacts import BuildResult, RenderSet, RenderView, Severity-from codeverse.contracts.common import Language-from codeverse.contracts.plan import AcceptanceItem, GraphicsPlan-from codeverse.contracts.spec import Spec-from codeverse.languages._gl_common import SHEET_NAME, read_metrics-from codeverse.tracks.common import RunContext-from codeverse.tracks.generation import SINGLE_SHOT_FORMAT-from codeverse.tracks.graphics_recipes import EXTRA_KEY as SEEDED_KEY-from codeverse.tracks.graphics_recipes import graphics_brief-from codeverse.tracks.planner import add_acceptance_item, build_system_prompt-from codeverse.tracks.planner import plan as run_planner-from codeverse.tracks.prompting import (- AGENT_OUTPUT_RULES,- acceptance_lines,- constraints_text,- reference_note,- select_cookbook_excerpt,-)-from codeverse.workspace import Workspace--log = logging.getLogger(__name__)--PLAN_TEMPLATE = "tracks/plan_graphics.j2"-PLAN_TEMPERATURE = 0.5-PLAN_MAX_OUTPUT_TOKENS = 65_536 # the model's declared output ceiling; unused tokens cost nothing-EXPECTED_FILES: dict[Language, list[str]] = {- Language.GLSL_SHADER: ["src/shader.frag", "src/common.glsl"],- Language.OPENGL_PYTHON: ["src/program.py"],-}---# ----------------------------------------------------------------------------- planner-def plan_example() -> dict[str, Any]:- return {- "title": "Neon rain on a window", "summary": "Looking through a rain-streaked window at a neon-lit street at night; "- "drops run down the glass, city lights turn into coloured bokeh discs that pulse.",- "style": "cyberpunk night: deep indigo/black base, magenta + cyan neon accents, warm sodium highlights; soft, filmic",- "resolution": [1280, 720], "duration_s": 8.0,- "passes": [- {"name": "CityBokeh", "kind": "fullscreen", "description": "background: 40-60 blurred bokeh discs (hash-placed, 3 depth layers, cyan/magenta/amber), slow horizontal parallax, pulsing brightness"},- {"name": "RainDrops", "kind": "fullscreen", "description": "grid-cell drops with hash offsets, running trails (fract(t) per cell), refraction offset applied when sampling the background"},- {"name": "Grade", "kind": "postprocess", "description": "vignette, slight chromatic aberration, tonemap + gamma"},- ],- "uniforms": ["u_time", "u_resolution"],- "motion": "drops slide down with gravity and wobble; bokeh drifts left 0.02/s and pulses at 0.5-1 Hz; no hard cuts",- "key_visuals": ["rain drops with trails on glass", "blurred neon bokeh discs", "dark night street behind", "magenta/cyan palette"],- "acceptance": [- {"id": "a1", "text": "Raindrops with trails visibly run down the glass (compare t=0 and t=1)", "how": "visual", "priority": "must"},- {"id": "a2", "text": "Blurred coloured bokeh lights are visible in the background", "how": "visual", "priority": "must"},- {"id": "a3", "text": "Frames change over time (no static image)", "how": "probe", "priority": "must"},- ],- }---def build_plan_system_prompt(spec: Spec, *, runtime: Any | None = None) -> str:- """The graphics plan system prompt = the shared builder with the graphics- template + worked example (``plan_graphics.j2`` references no 3D frame)."""- return build_system_prompt(spec, GraphicsPlan, runtime=runtime, template=PLAN_TEMPLATE, example=plan_example())---def ensure_graphics_acceptance(plan: GraphicsPlan, spec: Spec) -> GraphicsPlan:- """Spec must_have / must_not → visual items; planned motion → a probe item (never 'ground contact')."""- items: list[AcceptanceItem] = list(plan.acceptance)- for m in spec.constraints.must_have:- add_acceptance_item(items, "must", f"Includes: {m}", "visual")- for m in spec.constraints.must_not:- add_acceptance_item(items, "not", f"Does NOT include: {m}", "visual")- if plan.motion.strip() and not any("static" in a.text.lower() or "motion" in a.text.lower() or "change over time" in a.text.lower() for a in items):- add_acceptance_item(items, "motion", "Frames change over time as planned (not a static image)", "probe")- plan.acceptance = items- return plan---def graphics_event_stats(plan: GraphicsPlan) -> dict[str, Any]:- """``plan.done`` payload for graphics (passes, not parts/zones)."""- return {"n_passes": len(plan.passes), "n_acceptance": len(plan.acceptance)}---def plan_graphics(spec: Spec, model_id: str, ws: Workspace, *, model: Any | None = None, events: Any | None = None,- budget: Any | None = None, runtime: Any | None = None) -> GraphicsPlan:- """Structured planner call → validated GraphicsPlan: the ONE planner loop- (``tracks/planner.plan``) parameterised with the graphics hooks."""- return run_planner(spec, model_id, GraphicsPlan, ws, model=model, events=events, budget=budget, runtime=runtime,- template=PLAN_TEMPLATE, example=plan_example(), temperature=PLAN_TEMPERATURE,- max_output_tokens=PLAN_MAX_OUTPUT_TOKENS,- finalise=lambda p: ensure_graphics_acceptance(p, spec), event_stats=graphics_event_stats)---# ----------------------------------------------------------------------------- prompt context-def graphics_expected_files(ctx: RunContext) -> list[str]:- return list(EXPECTED_FILES.get(ctx.language, ["src/shader.frag"]))---def passes_table(plan: GraphicsPlan | None) -> str:- if plan is None or not plan.passes:- return "(no passes)"- rows = ["| pass | kind | what it draws / computes |", "|---|---|---|"]- rows += [f"| {p.name} | {p.kind} | {p.description} |" for p in plan.passes]- return "\n".join(rows)---def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:- """Every variable the graphics templates may reference (StrictUndefined)."""- plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None- res = plan.resolution if plan else (1280, 720)- d: dict[str, Any] = {- "track": ctx.track.value, "language": ctx.language.value, "contract": ctx.contract_text,- "cookbook_rel": ctx.cookbook_rel, "cookbook_excerpt": select_cookbook_excerpt(ctx, graphics_brief(ctx)), "tool_cards": ctx.tool_cards,- # the recipes tracks/graphics_recipes.py put in the harness-owned src/recipes.glsl before the session ([] = no block)- "seeded_recipes": list((getattr(ctx, "extra", None) or {}).get(SEEDED_KEY) or []),- "single_shot": ctx.single_shot, "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,- "spec_prompt": ctx.spec.prompt, "constraints": constraints_text(ctx.spec),- "title": plan.title if plan else "Untitled effect", "plan_summary": plan.summary if plan else "",- "style": plan.style if plan else "", "resolution": f"{res[0]}x{res[1]}", "duration": f"{plan.duration_s:g}" if plan else "8",- "passes_table": passes_table(plan), "motion": plan.motion if plan else "", "key_visuals": list(plan.key_visuals) if plan else [],- "uniforms": ", ".join(plan.uniforms) if plan and plan.uniforms else "u_time, u_resolution",- "acceptance": acceptance_lines(plan), "entry_files": ", ".join(getattr(ctx.runtime, "entry_globs", ()) or ()),- "expected_files": graphics_expected_files(ctx), "reference_note": reference_note(ctx),- "judge_times": "0, 1, 2.5, 4, 6 s",- }- d.update(extra)- return d---# ----------------------------------------------------------------------------- renders / gates-def frames_render_set(ws: Workspace, build: BuildResult, round_index: int) -> RenderSet:- """Copy the judged frames + sheet into renders/rNN and describe them as a RenderSet (views ``t=<s>s``)."""- out = ws.renders_dir(round_index)- out.mkdir(parents=True, exist_ok=True)- frames_dir = Path(build.extra_paths.get("frames", ws.artifacts / "frames"))- metrics = read_metrics(ws)- stats = metrics[0] if metrics else None- views: list[RenderView] = []- frames = stats.frames if stats else []- for f in frames:- src = Path(f.path)- if not src.is_file():- continue- dst = out / f"frame_t{f.time:05.2f}.png"- shutil.copy2(src, dst)- views.append(RenderView(name=f"t={f.time:g}s", path=str(dst), time_s=f.time))- if not views and frames_dir.is_dir(): # metrics missing: fall back to the raw frame files- for p in sorted(frames_dir.glob("f*_t*.png")):- dst = out / p.name- shutil.copy2(p, dst)- views.append(RenderView(name=p.stem.split("_t", 1)[-1] + "s", path=str(dst)))- sheet_src = Path(build.extra_paths.get("sheet", ws.artifacts / SHEET_NAME))- sheet = None- if sheet_src.is_file():- sheet = out / "sheet.png"- shutil.copy2(sheet_src, sheet)- renderer = str(build.census.get("renderer", "")) if isinstance(build.census, dict) else ""- return RenderSet(views=views, contact_sheet=str(sheet) if sheet else None, renderer=renderer or "moderngl",- duration_ms=build.duration_ms)---def frame_stats_text(ws: Workspace) -> str:- m = read_metrics(ws)- if m is None:- return "(no frame metrics)"- stats, gate = m- lines = stats.summary_lines()- for f in gate.findings:- lines.append(f"- GATE gl_frames {f.as_line(with_severity=True, with_hint=f.severity is not Severity.INFO)}")- return "\n".join(lines)diff --git a/harness/codeverse/tracks/plan_budget.py b/harness/codeverse/tracks/plan_budget.pydeleted file mode 100644index 3d9b7df2..00000000--- a/harness/codeverse/tracks/plan_budget.py+++ /dev/null@@ -1,307 +0,0 @@-"""Plan budgets, the re-plan quality gate, and brief → plan enrichment.--Two levers on the COMPLEXITY CEILING that live between the brief and the planner:--* **Plan budgets** (:func:`plan_budget`) — a target part count derived from the REQUEST- (checklist size; sub-assemblies × signature features when a brief exists) and capped by- the language's practical limit, instead of the flat "6 to 14 parts" the template used to- ask for regardless of difficulty. Measured motivation: on the hard static battery the- plan came back with FEWER parts than the prompt had checklist items (0.91 parts per item,- vs 1.71 on the easy battery) — the constant bound exactly where the request was hardest.-* **The quality gate** (:func:`plan_quality_complaint`) — one re-ask when the plan is- boxes-at-different-sizes *relative to that budget*. Absolute boxiness is not a defect- (a cabinet door really is three boxes: boxy 1.00, scored 0.964), so every threshold here- is relative to what the request asked for.--:func:`enrich_plan` then folds what only the brief knows back into the plan's own fields.-"""--from __future__ import annotations--import re-from dataclasses import dataclass-from typing import Any--from codeverse.contracts.common import Language, Track-from codeverse.contracts.plan import AcceptanceItem, EngineeringBrief-from codeverse.contracts.spec import Spec--#: practical ceiling on TOP-LEVEL plan parts per language. Blender/three.js own one-#: file per part so they scale; cadquery is one file; urdf links cost a joint each and-#: the collision sweep is O(links² × poses), so depth there goes into sub-parts.-PART_CAP: dict[str, int] = {- Language.BLENDER.value: 20,- Language.THREEJS.value: 20,- Language.CADQUERY.value: 14,- Language.URDF_BLENDER.value: 10,-}-DEFAULT_PART_CAP = 14-MIN_PARTS = 6-#: a checklist this long (or a brief) is EVIDENCE that the request really needs the target-#: part count; below it the target is an aspiration the gate must not enforce-EVIDENCE_MIN_CHECKLIST = 4--# --------------------------------------------------------------------- "is this a box?"-#: construction verbs / counted repeated features that make a part description more than-#: "a box of size X". Stems, not bare words: `taper` alone never matches "tapered", which-#: is how every real plan writes it (measured — the un-stemmed version fired the gate on-#: 77 % of the recorded plans instead of 43 %).-_CRAFT = re.compile(- r"\b(bevel\w*|chamfer\w*|fillet\w*|round(?:ed)?[- ](?:edge|corner|over)\w*|bullnose\w*|taper\w*|groove\w*"- r"|flute\w*|thread(?:ed|s)?|helix|helical|spline\w*|loft\w*|revolv\w*|extrud\w*|bezier|swept|sweep\w*"- r"|profile[ds]?|inset\w*|boolean\w*|subdivi\w*|smooth[- ]shad\w*|array\w*|lattice\w*|slot(?:s|ted)?"- r"|notch\w*|ribs?|louvre\w*|louver\w*|knurl\w*|serrat\w*|scallop\w*|hollow\w*|shell(?:ed)?|cut-?out\w*"- r"|recess\w*|emboss\w*|moulding\w*|molding\w*|curv\w*|arc\b|arch\w*|spiral\w*|dome[ds]?|domed|ogee"- r"|scroll\w*|pierc\w*|perforat\w*|crown\w*|swage\w*|bulg\w*|waist\w*|concave|convex|rebate[ds]?|dovetail\w*"- r"|mortise\w*|tenon\w*|splay\w*|conical|tapering|beading|reeded|turned|rounded|radius|radii)\b"- r"|\br\s*=\s*\d", # "bullnose r=10 mm" — a stated radius is construction, not a box- re.I)-_COUNTED = re.compile(- r"\b\d+\s*(x|×)?\s*(slats?|spokes?|teeth|dentils?|panes?|rafters?|bolts?|screws?|rivets?|holes?|segments?"- r"|facets?|ribs?|flutes?|turns?|steps?|rings?|wires?|bars?|louvres?|louvers?|vents?|grooves?|studs?|pads?)\b",- re.I)-#: the graphics analogue of :data:`_CRAFT`: a PASS is not "a box" when it names a real-#: technique. Object craft words (bevel, taper, flute) never appear in a shader plan, so-#: the object vocabulary would flag every pass ever written.-_GFX_CRAFT = re.compile(- r"\b(fbm|noise|hash|sdf|raymarch|ray[- ]?march|march|domain[- ]?warp|voronoi|worley|curl|advect|feedback"- r"|parallax|refract|reflect|fresnel|bokeh|blur|bloom|vignette|aberration|tonemap|gamma|dither|grain"- r"|particle|instanc|scatter|caustic|godray|god[- ]ray|volumetric|shadow|ao\b|ambient occlusion|palette"- r"|gradient|dissolve|erosion|turbulen|flow[- ]?map|displac|tessell|subsurface|halftone|posteris|posteriz)\b",- re.I)-#: two or more numeric literals make a pass description a recipe rather than an adjective-_NUMBER = re.compile(r"\d+(?:\.\d+)?")---def has_real_detail(text: str) -> bool:- """True when a part description says something a box cannot say."""- return bool(_CRAFT.search(text) or _COUNTED.search(text))---def has_pass_detail(text: str) -> bool:- """True when a graphics pass description names a technique or carries a recipe."""- return bool(_GFX_CRAFT.search(text)) or len(_NUMBER.findall(text)) >= 2---@dataclass(frozen=True)-class PlanBudget:- """What this request is worth, in plan units. ``target_parts`` is what the prompt- asks the planner for; ``min_parts`` is what the quality gate insists on."""-- target_parts: int- min_parts: int- cap_parts: int- target_leaves: int- min_detail_parts: int- min_assemblies: int- reason: str = ""- #: is there EVIDENCE that this request needs ``target_parts``? A checklist of four or- #: more items, or a brief. Without it ``target_parts`` is an aspiration the prompt- #: states and the quality gate must not enforce: "a stool" is allowed to be four parts.- evidence: bool = False-- def as_dict(self) -> dict[str, int | str | bool]:- return {"target_parts": self.target_parts, "min_parts": self.min_parts, "cap_parts": self.cap_parts,- "target_leaves": self.target_leaves, "min_detail_parts": self.min_detail_parts,- "min_assemblies": self.min_assemblies, "budget_evidence": self.evidence, "reason": self.reason}---#: the graphics track counts PASSES, not parts: a fragment shader is a stack of layers and-#: more than ~6 stops being a plan and starts being a wish-list. Recorded mean was 3.1 on-#: graphics_v2 (0.530 / 12% pass) and pass count is the ONE complexity metric that-#: correlates positively with the judge there (visual_richness +0.40).-GRAPHICS_CAP = 6-GRAPHICS_MIN = 3---def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget:- """Derive the plan's size budget from the REQUEST, not from a constant.-- Drivers: the user's own checklist (``must_have``), and — when a brief exists — the- sub-assemblies × signature features a real one has. Capped by the language's- practical limit (:data:`PART_CAP`)."""- if spec.track is Track.GRAPHICS:- return _graphics_budget(spec)- cap = PART_CAP.get(spec.language.value, DEFAULT_PART_CAP)- n_must = len(spec.constraints.must_have)- reasons = []- want = MIN_PARTS- if n_must:- # one part (or sub-part) per checklist item is PARITY, not padding: the measured- # ratio on the hard battery was 0.91 parts per checklist item, and the runs with the- # highest ratio scored best on intent_fidelity (+0.26).- want = max(want, n_must)- reasons.append(f"{n_must} checklist items")- n_visible = 0- if brief is not None:- n_sub, n_sig = len(brief.sub_assemblies), len(brief.signature_features)- if n_sub + n_sig:- want = max(want, n_sub + n_sig)- reasons.append(f"{n_sub} sub-assemblies + {n_sig} signature features")- # externally visible features drive the LEAF budget, not the top-level part count:- # "six vertical flutes on the body" is a sub-part of the body, not a part of its own.- n_visible = len(brief.visible_from_outside)- target = max(MIN_PARTS, min(cap, int(want)))- min_assemblies = 0- if brief is not None:- min_assemblies = min(3, sum(1 for s in brief.sub_assemblies if len(s.parts) >= 3))- elif target >= 10:- min_assemblies = 1- return PlanBudget(- target_parts=target,- min_parts=max(MIN_PARTS, int(round(0.85 * target))),- cap_parts=cap,- target_leaves=max(target + 4, int(round(1.8 * target)), n_visible + 2 * min_assemblies),- min_detail_parts=max(2, int(round(0.35 * target))),- min_assemblies=min_assemblies,- reason="; ".join(reasons) or "no checklist — default floor",- evidence=n_must >= EVIDENCE_MIN_CHECKLIST or brief is not None,- )---def _graphics_budget(spec: Spec) -> PlanBudget:- """Pass budget for the graphics track (see :data:`GRAPHICS_CAP`)."""- n_must = len(spec.constraints.must_have)- target = max(GRAPHICS_MIN, min(GRAPHICS_CAP, GRAPHICS_MIN + (n_must + 1) // 3))- return PlanBudget(- target_parts=target, min_parts=max(GRAPHICS_MIN, target - 1), cap_parts=GRAPHICS_CAP,- target_leaves=4 * target, min_detail_parts=max(2, target - 1), min_assemblies=max(2, target - 2),- reason=f"{n_must} checklist items" if n_must else "no checklist — default floor",- evidence=n_must >= EVIDENCE_MIN_CHECKLIST)---def budget_block(budget: PlanBudget, *, unit: str = "parts") -> str:- """The budget as a prompt block for the planner's user message."""- return "\n".join([- f"PLAN BUDGET (derived from this request: {budget.reason}):",- f"- aim for {budget.target_parts} top-level {unit} (hard floor {budget.min_parts}, hard ceiling "- f"{budget.cap_parts}); a plan under the floor will be rejected and re-asked.",- f"- at least {budget.min_detail_parts} of them must carry detail a plain primitive cannot express "- + ("(named elements with their own counts, sizes and speeds)." if unit == "passes" else- "(a taper, a bevel radius, a groove, a counted repeat: '7 slats', '24 spokes')."),- (f"- at least {budget.min_assemblies} of them must use "- + ("`elements` (3-6 named things the pass draws)." if unit == "passes"- else "`children` (3-6 sub-parts) because they are ASSEMBLIES, not shapes.")- if budget.min_assemblies else- "- use `children` for any part a fitter would call an assembly rather than a shape."),- f"- total named shapes across {unit} and their sub-parts should reach about {budget.target_leaves}.",- ])---# ----------------------------------------------------------------------------- quality gate-def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "parts") -> str:- """"" when the plan is worth building; otherwise the SPECIFIC complaint to re-ask with.-- Two classes of complaint. **Hard** ones fire on their own because they mean the plan- cannot carry the request: too few parts for the checklist, or boxes-at-different-sizes- (too few parts saying anything a primitive cannot). **Soft** ones — no assemblies- nested, one material for the whole object — ride along with a hard one but never- trigger a re-ask by themselves, because each is routinely correct on its own (a- wrought-iron arch really is all one material).-- Never absolute: every threshold comes from ``budget``, which comes from the request.- Measured retro-fire rate on the 86 recorded runs is in the wave report."""- parts: list[Any] = list(getattr(plan_obj, "parts", None) or getattr(plan_obj, "passes", None) or [])- if not parts:- return ""- nest = "elements" if unit == "passes" else "children"- hard: list[str] = []- soft: list[str] = []- if budget.evidence and len(parts) < budget.min_parts:- hard.append(- f"Only {len(parts)} {unit} for a request that needs about {budget.target_parts} "- f"({budget.reason}). Split the ones that are really assemblies and add the features you skipped — "- f"do NOT pad with duplicates.")- detector = has_pass_detail if unit == "passes" else has_real_detail- detailed = [p for p in parts if detector(f"{p.description} {getattr(p, 'detail_hint', '')}")- or getattr(p, "children", None) or getattr(p, "elements", None)]- if len(detailed) < budget.min_detail_parts:- plain = [p.name for p in parts if p not in detailed][:8]- hard.append(- f"This plan is boxes at different sizes: only {len(detailed)} of {len(parts)} {unit} describe anything a "- f"plain primitive cannot express, and at least {budget.min_detail_parts} must. Rewrite "- f"{', '.join(plain)} with real construction: profile (tapered / fluted / bevelled r=…), counted repeats "- f"('7 slats at 12 mm pitch'), edge treatment, and the sub-shapes each one is actually made of.")- if budget.min_assemblies:- n_nested = sum(1 for p in parts if len(getattr(p, nest, None) or []) >= 2)- if n_nested < budget.min_assemblies:- soft.append(- f"{n_nested} of the {unit} use `{nest}`, but this request has at least {budget.min_assemblies} real "- f"sub-assemblies. Give each of them 3-6 `{nest}`" +- ("" if unit == "passes" else " with their own bboxes (inside the parent's) and materials") +- f"; leave the simple {unit} alone.")- materials = {(getattr(p, "material", "") or "").strip().lower() for p in parts} - {""}- if unit == "parts" and len(parts) >= 5 and len(materials) <= 1:- soft.append("Every part has the same material (or none). Real objects mix materials — give each part its "- "own material with a colour.")- if not hard:- return ""- return ("Your plan is valid but not worth building yet. Fix EXACTLY these problems and return the full corrected "- "plan JSON again (same schema), keeping everything that was already good:\n- " + "\n- ".join(hard + soft))---# ----------------------------------------------------------------------------- enrichment-def _fold_pass(ps: Any) -> None:- """Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``.-- ``graphics_steps.passes_table`` prints ``| name | kind | description |`` — one markdown- row — so the fold must stay on a single line and must be idempotent."""- if not (ps.elements or ps.detail_hint) or " · " in ps.description:- return- bits = [ps.description.rstrip().rstrip(".")]- if ps.elements:- bits.append("draws: " + " · ".join(e.strip() for e in ps.elements))- if ps.detail_hint:- bits.append(f"what makes it real: {ps.detail_hint.strip()}")- ps.description = " · ".join(bits).replace("\n", " ").replace("|", "/")---def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None, budget: PlanBudget | None = None) -> Any:- """Fold what the BRIEF knows back into the plan's own fields, after validation.-- A part's own depth needs no folding: ``tracks/prompting.py`` renders- ``PartPlan.children`` and ``PartPlan.detail_hint`` straight from the typed fields, so- copying them into ``description`` would print every sub-part twice. A graphics PASS is- the exception — ``graphics_steps.passes_table`` renders only ``description`` — so- ``elements`` are folded there, on ONE line because that table is markdown.-- * the brief's signature features become ``should`` acceptance items — ``should``, not- ``must``: a flash brief's private wishes must never trip ``missing_must_acceptance``,- which caps a finished object at 0.60 (the lesson ``ensure_acceptance`` already- records for the scene track);- * ``style_notes`` gains the reference instance and what the object does NOT have —- the two brief facts that change how the whole object is built rather than one part.- """- for ps in getattr(plan_obj, "passes", None) or []:- _fold_pass(ps)- if brief is None:- return plan_obj- items: list[AcceptanceItem] = list(getattr(plan_obj, "acceptance", None) or [])- known = {a.text.strip().lower() for a in items}- ids = {a.id for a in items}- n = 1- for feature in brief.signature_features:- text = f"Signature feature visible: {feature.strip()}"- if text.lower() in known:- continue- while f"sig{n}" in ids:- n += 1- items.append(AcceptanceItem(id=f"sig{n}", text=text, how="visual", priority="should"))- ids.add(f"sig{n}")- known.add(text.lower())- if hasattr(plan_obj, "acceptance"):- plan_obj.acceptance = items- notes = getattr(plan_obj, "style_notes", "")- extra = []- if brief.reference and brief.reference.lower() not in notes.lower():- extra.append(f"Reference instance: {brief.reference}.")- if brief.not_present:- extra.append("Does NOT have: " + "; ".join(brief.not_present) + ".")- if extra and hasattr(plan_obj, "style_notes"):- plan_obj.style_notes = " ".join([notes.strip(), *extra]).strip()- return plan_obj---__all__ = ["DEFAULT_PART_CAP", "EVIDENCE_MIN_CHECKLIST", "GRAPHICS_CAP", "GRAPHICS_MIN", "MIN_PARTS",- "PART_CAP", "PlanBudget", "budget_block", "enrich_plan", "has_pass_detail", "has_real_detail",- "plan_budget", "plan_quality_complaint"]diff --git a/harness/codeverse/tracks/plan_examples.py b/harness/codeverse/tracks/plan_examples.pydeleted file mode 100644index 40cb22cc..00000000--- a/harness/codeverse/tracks/plan_examples.py+++ /dev/null@@ -1,92 +0,0 @@-"""Worked plan examples — one compact, valid plan per track for the planner's system-prompt. Concrete beats abstract (design law 2): the example is what actually teaches-the model the shape of ``children`` and ``detail_hint``, so the chair carries a nested-Backrest and the drawer unit a four-sub-part Drawer.-"""--from __future__ import annotations--from typing import Any--from codeverse.contracts.common import Track---def plan_example(track: Track) -> dict[str, Any]:- """Compact, valid worked example per track (concrete beats abstract)."""- if track is Track.SCENE:- return {- "title": "Harbour at dusk", "summary": "Small fishing harbour: quay, two boats, lighthouse, calm water.",- "setting": "Breton coast, 1960s, clear dusk", "mood": "calm, warm low sun",- "bounds": {"center": [0, 5, 0], "extents": [120, 30, 120]},- "environment": "Sky gradient orange→indigo, sun at azimuth 250° elevation 8°, light fog density 0.004, flat sea plane y=0, stone quay at y=1.2.",- "zones": [- {"name": "Quay", "description": "L-shaped granite quay with bollards and crates", "bbox": {"center": [-20, 1.2, 0], "extents": [40, 3, 60]}, "contents": ["Bollard", "Crate"]},- {"name": "Water", "description": "calm harbour basin with two moored boats", "bbox": {"center": [20, 0, 0], "extents": [60, 1, 80]}, "contents": ["FishingBoat"]},- ],- "assets": [- {"name": "FishingBoat", "kind": "threejs", "description": "8 m wooden boat, wheelhouse aft, red hull", "approx_size_m": [8, 3.5, 3], "instances_hint": 2},- {"name": "Bollard", "kind": "threejs", "description": "cast-iron mooring bollard", "approx_size_m": [0.3, 0.5, 0.3], "instances_hint": 6},- {"name": "Crate", "kind": "blender_glb", "description": "wooden fish crate, slatted", "approx_size_m": [0.6, 0.3, 0.4], "instances_hint": 8},- ],- "effects": [{"name": "WaterRipple", "kind": "glsl_material", "description": "animated normal ripples on the sea plane", "target": "Water"}],- "animation": ["boats bob ±0.05 m at 0.3 Hz", "water ripples scroll"],- "cameras": [{"name": "Overview", "position": [45, 18, 55], "look_at": [0, 1, 0], "fov": 50, "purpose": "establishing shot"},- {"name": "QuayEye", "position": [-5, 2.8, 25], "look_at": [15, 1, -10], "fov": 60, "purpose": "eye level along the quay"}],- "acceptance": [{"id": "a1", "text": "Two boats float on the water inside the basin", "how": "visual", "priority": "must"},- {"id": "a2", "text": "Quay top at y≈1.2 m, boats' waterline at y≈0", "how": "probe", "priority": "must"}],- }- parts = [- {"name": "Seat", "role": "horizontal seat board", "description": "solid oak board, 40 mm thick, rounded front edge (r=10 mm)",- "bbox": {"center": [0, 0, 0.43], "extents": [0.42, 0.40, 0.04]}, "material": "oiled oak", "attach_to": None, "symmetry": "mirror_x", "instances": 1,- "children": [], "detail_hint": "the eye lands here first — keep the 10 mm bullnose and the 3 mm chamfer under the front edge"},- {"name": "FrontLeg", "role": "front leg", "description": "tapered round leg 35→25 mm, splayed 6° outward",- "bbox": {"center": [0.17, -0.16, 0.205], "extents": [0.035, 0.035, 0.41]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "mirror_x", "instances": 2,- "children": [], "detail_hint": ""},- {"name": "Backrest", "role": "slatted back assembly", "description": "three vertical slats in a curved top rail and a lower rail",- "bbox": {"center": [0, 0.19, 0.66], "extents": [0.40, 0.03, 0.42]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "none", "instances": 1,- "detail_hint": "an assembly, not a panel: the gaps between the slats must be visible from the front and the side",- "children": [- {"name": "TopRail", "role": "curved crest rail", "description": "60 mm deep rail bowed 18 mm back on a 0.9 m radius, ends rounded r=8 mm",- "bbox": {"center": [0, 0.19, 0.85], "extents": [0.40, 0.03, 0.06]}, "material": "oiled oak", "instances": 1},- {"name": "Slat", "role": "vertical back slat", "description": "12 mm thick slat, 55 mm wide, 4 mm chamfer both faces, 30 mm gap to its neighbour",- "bbox": {"center": [0, 0.19, 0.66], "extents": [0.055, 0.012, 0.34]}, "material": "oiled oak", "instances": 3},- {"name": "LowerRail", "role": "rail the slats seat into", "description": "40 mm rail with three 12 × 55 mm mortises on 85 mm centres",- "bbox": {"center": [0, 0.19, 0.48], "extents": [0.40, 0.03, 0.04]}, "material": "oiled oak", "instances": 1},- ]},- ]- base: dict[str, Any] = {- "object_name": "DiningChair", "summary": "Mid-century oak dining chair, 0.45 × 0.50 × 0.82 m.",- "overall_bbox": {"center": [0, 0, 0.41], "extents": [0.45, 0.50, 0.82]},- "style_notes": "Danish mid-century: tapered legs, thin spindles, warm oak, no ornament.",- "parts": parts,- "acceptance": [{"id": "a1", "text": "Seat top at 0.45 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},- {"id": "a2", "text": "Four legs, all touching the ground, splayed outward", "how": "visual", "priority": "must"}],- }- if track is Track.ARTICULATED_OBJECT:- base["object_name"] = "DeskDrawerUnit"- base["parts"] = [- {"name": "Cabinet", "role": "fixed carcass", "description": "18 mm carcass, 6 mm rebated back, 3 mm shadow gap round the drawer opening",- "bbox": {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]}, "material": "painted MDF", "attach_to": None, "symmetry": "none", "instances": 1,- "children": [], "detail_hint": "the opening's shadow gap is what makes the drawer read as a drawer"},- {"name": "Drawer", "role": "sliding drawer (ONE link, four sub-parts)", "description": "drawer box running on side runners",- "bbox": {"center": [0, -0.02, 0.45], "extents": [0.36, 0.46, 0.2]}, "material": "painted MDF", "attach_to": "Cabinet", "symmetry": "none", "instances": 1,- "detail_hint": "one rigid body, but never one box",- "children": [- {"name": "Front", "role": "drawer face", "description": "18 mm face, 4 mm bullnose, overhangs the box 8 mm on every side",- "bbox": {"center": [0, -0.24, 0.45], "extents": [0.36, 0.018, 0.19]}, "material": "painted MDF", "instances": 1},- {"name": "Box", "role": "drawer body", "description": "12 mm sides, 8 mm base set into a 6 mm groove, open top",- "bbox": {"center": [0, 0.0, 0.45], "extents": [0.33, 0.42, 0.17]}, "material": "birch ply", "instances": 1},- {"name": "Knob", "role": "pull", "description": "turned knob 32 mm dia, 22 mm proud, on a 10 mm neck",- "bbox": {"center": [0, -0.26, 0.45], "extents": [0.032, 0.032, 0.032]}, "material": "brushed steel", "instances": 1},- {"name": "Runner", "role": "side runner", "description": "10 × 10 mm strip along each side, full depth",- "bbox": {"center": [0.17, 0.0, 0.40], "extents": [0.01, 0.42, 0.01]}, "material": "birch ply", "instances": 2},- ]},- ]- base["root_link"] = "Cabinet"- base["joints"] = [{"name": "DrawerSlide", "type": "prismatic", "parent": "Cabinet", "child": "Drawer", "axis": [0, -1, 0],- "pivot": [0, -0.02, 0.45], "lower": 0.0, "upper": 0.35, "rest": 0.0, "motion": "drawer pulls out towards -Y"}]- base["acceptance"].append({"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"})- return base---__all__ = ["plan_example"]diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.pyindex c7a05cad..a424b6b9 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -61,7 +61,7 @@ def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:#: Plan-loop switches the tree ACTUALLY reads, name → the module that reads it. Kept#: honest by tests/orchestrator_tracks/test_plan_features.py, which greps the tree.LIVE_SWITCHES: dict[str, str] = {- "CV3D_PLAN_BRIEF": "codeverse/tracks/brief.py",+ "CV3D_PLAN_BRIEF": "codeverse/tracks/planner.py", # brief.py merged in, 2026-08-28"CV3D_SCOPED_PARTS": "codeverse/tracks/depth.py","CV3D_DETAIL_ROUNDS": "codeverse/tracks/lifecycle.py","CV3D_REFERENCE_DIFF": "codeverse/judges/reference.py",diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex 527a5540..7dce7d2a 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -16,34 +16,558 @@ weak links — framework-owned requirements never rely on the model rememberingfrom __future__ import annotations+import hashlibimport jsonimport logging+import os+import refrom collections.abc import Callable+from dataclasses import dataclass+from pathlib import Pathfrom typing import Any, TypeVarfrom pydantic import BaseModel, ValidationErrorfrom codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePartfrom codeverse.contracts.common import Language, Track, Usage-from codeverse.contracts.plan import AcceptanceItem+from codeverse.contracts.plan import AcceptanceItem, EngineeringBrieffrom codeverse.contracts.spec import Specfrom codeverse.conventions import LANGUAGE_FRAME, frame_doc, to_pascal-from codeverse.prompts import prompt_hash, render-from codeverse.tracks.brief import brief_block, brief_enabled, expand_brief+from codeverse.models.schema_utils import parse_json_lenient+from codeverse.prompts import load_text, prompt_hash, renderfrom codeverse.tracks.common import language_contract, load_prompt_or-from codeverse.tracks.plan_budget import (- PlanBudget,- budget_block,- enrich_plan,- plan_budget,- plan_quality_complaint,-)-from codeverse.tracks.plan_examples import plan_examplefrom codeverse.tracks.prompting import constraints_textfrom codeverse.workspace import Workspacelog = logging.getLogger(__name__)++# ===================================================================== the brief+# (merged from codeverse/tracks/brief.py, 2026-08-28 — this module was its only+# production importer; three files described one hand-off)+#: env switch: ``off``/``0``/``false`` disables brief expansion for the run+BRIEF_ENV = "CV3D_PLAN_BRIEF"+#: tracks the object-shaped brief applies to (graphics/scene get budgets only)+BRIEF_TRACKS = (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT)+BRIEF_TEMPLATE = "tracks/brief_object.j2"+BRIEF_MAX_TOKENS = 65_536+++# ----------------------------------------------------------------------------- brief+def brief_enabled(spec: Spec, *, default: bool = True) -> bool:+ """Whether to expand the brief for this spec (env switch wins; object tracks only)."""+ raw = (os.environ.get(BRIEF_ENV) or "").strip().lower()+ on = default if not raw else raw not in ("0", "off", "false", "no")+ return on and spec.track in BRIEF_TRACKS+++def brief_cache_dir() -> Path:+ root = os.environ.get("CV3D_CACHE_DIR") or (Path.home() / ".cache" / "codeverse")+ return Path(root) / "briefs"+++def _reference_digest(spec: Spec) -> list[dict[str, str]]:+ """Identify the reference images by path AND content hash.++ ``--reference`` synthesises a NEW image per run under the same spec fields, so+ the path alone does not separate two runs; the bytes do. An unreadable file+ still contributes its path, so it can never collapse onto "no references"."""+ out: list[dict[str, str]] = []+ for r in spec.references:+ try:+ digest = _sha256_file(Path(r.path))+ except OSError:+ digest = "(unreadable)"+ out.append({"path": r.path, "role": r.role, "note": r.note, "sha256": digest})+ return out+++def _sha256_file(path: Path) -> str:+ h = hashlib.sha256()+ with path.open("rb") as fh:+ for chunk in iter(lambda: fh.read(1 << 20), b""):+ h.update(chunk)+ return h.hexdigest()+++def brief_cache_key(spec: Spec, model_id: str) -> str:+ """Every input to the call must be in the key.++ ``expand_brief`` attaches ``spec.references`` to the request and tells the model+ to read the dimensions and features off them, so a key that omits them lets an+ ``--image`` run drink a brief generated WITHOUT the image (and vice versa) —+ silently, from the machine-wide ~/.cache/codeverse/briefs, with cached=True in+ events.jsonl."""+ c = spec.constraints+ payload = json.dumps({+ "prompt": spec.prompt.strip(), "track": spec.track.value, "language": spec.language.value,+ "must_have": list(c.must_have), "must_not": list(c.must_not), "style": c.style,+ "dimensions_m": c.dimensions_m or {}, "model": model_id,+ "references": _reference_digest(spec),+ "template": prompt_hash(load_text(BRIEF_TEMPLATE)),+ }, sort_keys=True)+ return hashlib.sha256(payload.encode()).hexdigest()[:20]+++def expand_brief(spec: Spec, model_id: str, *, model: Any | None = None, events: Any | None = None,+ cache_dir: Path | None = None) -> tuple[EngineeringBrief | None, Usage]:+ """One cheap structured call → :class:`EngineeringBrief`, cached by prompt hash.++ Never raises and never blocks planning: any failure returns ``(None, usage)`` and the+ planner runs exactly as it did before."""+ usage = Usage()+ cdir = cache_dir if cache_dir is not None else brief_cache_dir()+ key = brief_cache_key(spec, model_id)+ path = cdir / f"{key}.json"+ if path.is_file():+ try:+ brief = EngineeringBrief.model_validate_json(path.read_text())+ if not brief.is_useful:+ raise ValueError("cached brief has nothing to plan from")+ if events is not None:+ events.emit("plan.brief", cached=True, key=key, n_sub=len(brief.sub_assemblies),+ n_signature=len(brief.signature_features), cost_usd=0.0)+ return brief, usage+ except (ValidationError, ValueError, OSError) as e: # a stale/corrupt cache entry is not fatal+ log.warning("brief cache %s unusable (%s); regenerating", path, e)+ if model is None:+ from codeverse.models import get_chat_model++ model = get_chat_model(model_id)+ system = render(BRIEF_TEMPLATE, track=spec.track.value, language=spec.language.value)+ images = [ImagePart(path=r.path, label=f"{r.role}: {r.note}".strip(": ")) for r in spec.references]+ user = f"REQUEST: {spec.prompt.strip()}"+ if spec.constraints.must_have:+ user += "\n\nThe user also requires:\n" + "\n".join(f"- {m}" for m in spec.constraints.must_have)+ if spec.constraints.dimensions_m:+ user += "\n\nStated dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in spec.constraints.dimensions_m.items())+ if images:+ user += f"\n\n{len(images)} reference image(s) are attached — read the dimensions and features off them."+ try:+ resp = model.generate(ChatRequest(+ messages=[ChatMessage.user(user, images=images or None)], system=system,+ response_schema=EngineeringBrief.model_json_schema(), temperature=0.3, thinking="low",+ max_output_tokens=BRIEF_MAX_TOKENS, max_wait_s=900.0, label="planner-brief"))+ usage = usage + resp.usage+ # parse_json_lenient, not json.loads: it tolerates fences/prose AND strips the+ # C0 controls a model can emit, which json.loads would carry into the brief.+ raw = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text or "{}")+ brief = EngineeringBrief.model_validate(raw)+ if not brief.is_useful:+ raise ValueError(f"brief has {len(brief.sub_assemblies)} sub-assemblies and "+ f"{len(brief.signature_features)} signature features — nothing to plan from")+ except Exception as e: # noqa: BLE001 — the brief is an optional accelerator, never a failure mode+ log.warning("brief expansion failed (%s: %s); planning without it", type(e).__name__, e)+ if events is not None:+ events.emit("plan.brief_failed", error=f"{type(e).__name__}: {e}"[:300])+ return None, usage+ try:+ cdir.mkdir(parents=True, exist_ok=True)+ path.write_text(brief.model_dump_json(indent=1))+ except OSError as e:+ log.warning("could not cache brief at %s: %s", path, e)+ if events is not None:+ events.emit("plan.brief", cached=False, key=key, n_sub=len(brief.sub_assemblies),+ n_signature=len(brief.signature_features), cost_usd=round(usage.cost_usd, 5))+ return brief, usage+++def brief_block(brief: EngineeringBrief | None) -> str:+ """The brief as a prompt block for the planner's user message ("" when absent)."""+ if brief is None:+ return ""+ out = ["ENGINEERING BRIEF (researched for this request — treat it as ground truth about the real object):",+ f"- it is: {brief.one_line or brief.object_name}"]+ if brief.reference:+ out.append(f"- reference instance the numbers come from: {brief.reference}")+ if brief.dimensions_m:+ out.append("- real-world dimensions (m): " + ", ".join(f"{d.name} {d.meters:.3f}" for d in brief.dimensions_m))+ if brief.mechanism:+ out.append(f"- how it works: {brief.mechanism}")+ if brief.sub_assemblies:+ out.append(f"- sub-assemblies a real one has ({len(brief.sub_assemblies)}):")+ for s in brief.sub_assemblies:+ bits = f" · {s.name}"+ if s.purpose:+ bits += f" — {s.purpose}"+ if s.parts:+ bits += f"; made of: {', '.join(s.parts)}"+ if s.material:+ bits += f" [{s.material}]"+ out.append(bits)+ if brief.visible_from_outside:+ out.append("- visible from outside (model these): " + "; ".join(brief.visible_from_outside))+ if brief.hidden_inside:+ out.append("- inside, NOT visible (do not model): " + "; ".join(brief.hidden_inside))+ if brief.not_present:+ out.append("- it does NOT have: " + "; ".join(brief.not_present))+ if brief.materials:+ out.append("- materials: " + "; ".join(brief.materials))+ if brief.signature_features:+ out.append(f"- SIGNATURE FEATURES ({len(brief.signature_features)}) — a viewer recognises the object by these; "+ "every one of them must be a part, a sub-part or a named detail in your plan:")+ out += [f" {i}. {f}" for i, f in enumerate(brief.signature_features, 1)]+ return "\n".join(out)+++# ===================================================================== plan budgets+# (merged from codeverse/tracks/plan_budget.py, 2026-08-28 — same reason)+#: practical ceiling on TOP-LEVEL plan parts per language. Blender/three.js own one+#: file per part so they scale; cadquery is one file; urdf links cost a joint each and+#: the collision sweep is O(links² × poses), so depth there goes into sub-parts.+PART_CAP: dict[str, int] = {+ Language.BLENDER.value: 20,+ Language.THREEJS.value: 20,+ Language.CADQUERY.value: 14,+ Language.URDF_BLENDER.value: 10,+}+DEFAULT_PART_CAP = 14+MIN_PARTS = 6+#: a checklist this long (or a brief) is EVIDENCE that the request really needs the target+#: part count; below it the target is an aspiration the gate must not enforce+EVIDENCE_MIN_CHECKLIST = 4++# --------------------------------------------------------------------- "is this a box?"+#: construction verbs / counted repeated features that make a part description more than+#: "a box of size X". Stems, not bare words: `taper` alone never matches "tapered", which+#: is how every real plan writes it (measured — the un-stemmed version fired the gate on+#: 77 % of the recorded plans instead of 43 %).+_CRAFT = re.compile(+ r"\b(bevel\w*|chamfer\w*|fillet\w*|round(?:ed)?[- ](?:edge|corner|over)\w*|bullnose\w*|taper\w*|groove\w*"+ r"|flute\w*|thread(?:ed|s)?|helix|helical|spline\w*|loft\w*|revolv\w*|extrud\w*|bezier|swept|sweep\w*"+ r"|profile[ds]?|inset\w*|boolean\w*|subdivi\w*|smooth[- ]shad\w*|array\w*|lattice\w*|slot(?:s|ted)?"+ r"|notch\w*|ribs?|louvre\w*|louver\w*|knurl\w*|serrat\w*|scallop\w*|hollow\w*|shell(?:ed)?|cut-?out\w*"+ r"|recess\w*|emboss\w*|moulding\w*|molding\w*|curv\w*|arc\b|arch\w*|spiral\w*|dome[ds]?|domed|ogee"+ r"|scroll\w*|pierc\w*|perforat\w*|crown\w*|swage\w*|bulg\w*|waist\w*|concave|convex|rebate[ds]?|dovetail\w*"+ r"|mortise\w*|tenon\w*|splay\w*|conical|tapering|beading|reeded|turned|rounded|radius|radii)\b"+ r"|\br\s*=\s*\d", # "bullnose r=10 mm" — a stated radius is construction, not a box+ re.I)+_COUNTED = re.compile(+ r"\b\d+\s*(x|×)?\s*(slats?|spokes?|teeth|dentils?|panes?|rafters?|bolts?|screws?|rivets?|holes?|segments?"+ r"|facets?|ribs?|flutes?|turns?|steps?|rings?|wires?|bars?|louvres?|louvers?|vents?|grooves?|studs?|pads?)\b",+ re.I)+#: the graphics analogue of :data:`_CRAFT`: a PASS is not "a box" when it names a real+#: technique. Object craft words (bevel, taper, flute) never appear in a shader plan, so+#: the object vocabulary would flag every pass ever written.+_GFX_CRAFT = re.compile(+ r"\b(fbm|noise|hash|sdf|raymarch|ray[- ]?march|march|domain[- ]?warp|voronoi|worley|curl|advect|feedback"+ r"|parallax|refract|reflect|fresnel|bokeh|blur|bloom|vignette|aberration|tonemap|gamma|dither|grain"+ r"|particle|instanc|scatter|caustic|godray|god[- ]ray|volumetric|shadow|ao\b|ambient occlusion|palette"+ r"|gradient|dissolve|erosion|turbulen|flow[- ]?map|displac|tessell|subsurface|halftone|posteris|posteriz)\b",+ re.I)+#: two or more numeric literals make a pass description a recipe rather than an adjective+_NUMBER = re.compile(r"\d+(?:\.\d+)?")+++def has_real_detail(text: str) -> bool:+ """True when a part description says something a box cannot say."""+ return bool(_CRAFT.search(text) or _COUNTED.search(text))+++def has_pass_detail(text: str) -> bool:+ """True when a graphics pass description names a technique or carries a recipe."""+ return bool(_GFX_CRAFT.search(text)) or len(_NUMBER.findall(text)) >= 2+++@dataclass(frozen=True)+class PlanBudget:+ """What this request is worth, in plan units. ``target_parts`` is what the prompt+ asks the planner for; ``min_parts`` is what the quality gate insists on."""++ target_parts: int+ min_parts: int+ cap_parts: int+ target_leaves: int+ min_detail_parts: int+ min_assemblies: int+ reason: str = ""+ #: is there EVIDENCE that this request needs ``target_parts``? A checklist of four or+ #: more items, or a brief. Without it ``target_parts`` is an aspiration the prompt+ #: states and the quality gate must not enforce: "a stool" is allowed to be four parts.+ evidence: bool = False++ def as_dict(self) -> dict[str, int | str | bool]:+ return {"target_parts": self.target_parts, "min_parts": self.min_parts, "cap_parts": self.cap_parts,+ "target_leaves": self.target_leaves, "min_detail_parts": self.min_detail_parts,+ "min_assemblies": self.min_assemblies, "budget_evidence": self.evidence, "reason": self.reason}+++#: the graphics track counts PASSES, not parts: a fragment shader is a stack of layers and+#: more than ~6 stops being a plan and starts being a wish-list. Recorded mean was 3.1 on+#: graphics_v2 (0.530 / 12% pass) and pass count is the ONE complexity metric that+#: correlates positively with the judge there (visual_richness +0.40).+GRAPHICS_CAP = 6+GRAPHICS_MIN = 3+++def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget:+ """Derive the plan's size budget from the REQUEST, not from a constant.++ Drivers: the user's own checklist (``must_have``), and — when a brief exists — the+ sub-assemblies × signature features a real one has. Capped by the language's+ practical limit (:data:`PART_CAP`)."""+ if spec.track is Track.GRAPHICS:+ return _graphics_budget(spec)+ cap = PART_CAP.get(spec.language.value, DEFAULT_PART_CAP)+ n_must = len(spec.constraints.must_have)+ reasons = []+ want = MIN_PARTS+ if n_must:+ # one part (or sub-part) per checklist item is PARITY, not padding: the measured+ # ratio on the hard battery was 0.91 parts per checklist item, and the runs with the+ # highest ratio scored best on intent_fidelity (+0.26).+ want = max(want, n_must)+ reasons.append(f"{n_must} checklist items")+ n_visible = 0+ if brief is not None:+ n_sub, n_sig = len(brief.sub_assemblies), len(brief.signature_features)+ if n_sub + n_sig:+ want = max(want, n_sub + n_sig)+ reasons.append(f"{n_sub} sub-assemblies + {n_sig} signature features")+ # externally visible features drive the LEAF budget, not the top-level part count:+ # "six vertical flutes on the body" is a sub-part of the body, not a part of its own.+ n_visible = len(brief.visible_from_outside)+ target = max(MIN_PARTS, min(cap, int(want)))+ min_assemblies = 0+ if brief is not None:+ min_assemblies = min(3, sum(1 for s in brief.sub_assemblies if len(s.parts) >= 3))+ elif target >= 10:+ min_assemblies = 1+ return PlanBudget(+ target_parts=target,+ min_parts=max(MIN_PARTS, int(round(0.85 * target))),+ cap_parts=cap,+ target_leaves=max(target + 4, int(round(1.8 * target)), n_visible + 2 * min_assemblies),+ min_detail_parts=max(2, int(round(0.35 * target))),+ min_assemblies=min_assemblies,+ reason="; ".join(reasons) or "no checklist — default floor",+ evidence=n_must >= EVIDENCE_MIN_CHECKLIST or brief is not None,+ )+++def _graphics_budget(spec: Spec) -> PlanBudget:+ """Pass budget for the graphics track (see :data:`GRAPHICS_CAP`)."""+ n_must = len(spec.constraints.must_have)+ target = max(GRAPHICS_MIN, min(GRAPHICS_CAP, GRAPHICS_MIN + (n_must + 1) // 3))+ return PlanBudget(+ target_parts=target, min_parts=max(GRAPHICS_MIN, target - 1), cap_parts=GRAPHICS_CAP,+ target_leaves=4 * target, min_detail_parts=max(2, target - 1), min_assemblies=max(2, target - 2),+ reason=f"{n_must} checklist items" if n_must else "no checklist — default floor",+ evidence=n_must >= EVIDENCE_MIN_CHECKLIST)+++def budget_block(budget: PlanBudget, *, unit: str = "parts") -> str:+ """The budget as a prompt block for the planner's user message."""+ return "\n".join([+ f"PLAN BUDGET (derived from this request: {budget.reason}):",+ f"- aim for {budget.target_parts} top-level {unit} (hard floor {budget.min_parts}, hard ceiling "+ f"{budget.cap_parts}); a plan under the floor will be rejected and re-asked.",+ f"- at least {budget.min_detail_parts} of them must carry detail a plain primitive cannot express "+ + ("(named elements with their own counts, sizes and speeds)." if unit == "passes" else+ "(a taper, a bevel radius, a groove, a counted repeat: '7 slats', '24 spokes')."),+ (f"- at least {budget.min_assemblies} of them must use "+ + ("`elements` (3-6 named things the pass draws)." if unit == "passes"+ else "`children` (3-6 sub-parts) because they are ASSEMBLIES, not shapes.")+ if budget.min_assemblies else+ "- use `children` for any part a fitter would call an assembly rather than a shape."),+ f"- total named shapes across {unit} and their sub-parts should reach about {budget.target_leaves}.",+ ])+++# ----------------------------------------------------------------------------- quality gate+def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "parts") -> str:+ """"" when the plan is worth building; otherwise the SPECIFIC complaint to re-ask with.++ Two classes of complaint. **Hard** ones fire on their own because they mean the plan+ cannot carry the request: too few parts for the checklist, or boxes-at-different-sizes+ (too few parts saying anything a primitive cannot). **Soft** ones — no assemblies+ nested, one material for the whole object — ride along with a hard one but never+ trigger a re-ask by themselves, because each is routinely correct on its own (a+ wrought-iron arch really is all one material).++ Never absolute: every threshold comes from ``budget``, which comes from the request.+ Measured retro-fire rate on the 86 recorded runs is in the wave report."""+ parts: list[Any] = list(getattr(plan_obj, "parts", None) or getattr(plan_obj, "passes", None) or [])+ if not parts:+ return ""+ nest = "elements" if unit == "passes" else "children"+ hard: list[str] = []+ soft: list[str] = []+ if budget.evidence and len(parts) < budget.min_parts:+ hard.append(+ f"Only {len(parts)} {unit} for a request that needs about {budget.target_parts} "+ f"({budget.reason}). Split the ones that are really assemblies and add the features you skipped — "+ f"do NOT pad with duplicates.")+ detector = has_pass_detail if unit == "passes" else has_real_detail+ detailed = [p for p in parts if detector(f"{p.description} {getattr(p, 'detail_hint', '')}")+ or getattr(p, "children", None) or getattr(p, "elements", None)]+ if len(detailed) < budget.min_detail_parts:+ plain = [p.name for p in parts if p not in detailed][:8]+ hard.append(+ f"This plan is boxes at different sizes: only {len(detailed)} of {len(parts)} {unit} describe anything a "+ f"plain primitive cannot express, and at least {budget.min_detail_parts} must. Rewrite "+ f"{', '.join(plain)} with real construction: profile (tapered / fluted / bevelled r=…), counted repeats "+ f"('7 slats at 12 mm pitch'), edge treatment, and the sub-shapes each one is actually made of.")+ if budget.min_assemblies:+ n_nested = sum(1 for p in parts if len(getattr(p, nest, None) or []) >= 2)+ if n_nested < budget.min_assemblies:+ soft.append(+ f"{n_nested} of the {unit} use `{nest}`, but this request has at least {budget.min_assemblies} real "+ f"sub-assemblies. Give each of them 3-6 `{nest}`" ++ ("" if unit == "passes" else " with their own bboxes (inside the parent's) and materials") ++ f"; leave the simple {unit} alone.")+ materials = {(getattr(p, "material", "") or "").strip().lower() for p in parts} - {""}+ if unit == "parts" and len(parts) >= 5 and len(materials) <= 1:+ soft.append("Every part has the same material (or none). Real objects mix materials — give each part its "+ "own material with a colour.")+ if not hard:+ return ""+ return ("Your plan is valid but not worth building yet. Fix EXACTLY these problems and return the full corrected "+ "plan JSON again (same schema), keeping everything that was already good:\n- " + "\n- ".join(hard + soft))+++# ----------------------------------------------------------------------------- enrichment+def _fold_pass(ps: Any) -> None:+ """Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``.++ ``graphics_steps.passes_table`` prints ``| name | kind | description |`` — one markdown+ row — so the fold must stay on a single line and must be idempotent."""+ if not (ps.elements or ps.detail_hint) or " · " in ps.description:+ return+ bits = [ps.description.rstrip().rstrip(".")]+ if ps.elements:+ bits.append("draws: " + " · ".join(e.strip() for e in ps.elements))+ if ps.detail_hint:+ bits.append(f"what makes it real: {ps.detail_hint.strip()}")+ ps.description = " · ".join(bits).replace("\n", " ").replace("|", "/")+++def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None, budget: PlanBudget | None = None) -> Any:+ """Fold what the BRIEF knows back into the plan's own fields, after validation.++ A part's own depth needs no folding: ``tracks/prompting.py`` renders+ ``PartPlan.children`` and ``PartPlan.detail_hint`` straight from the typed fields, so+ copying them into ``description`` would print every sub-part twice. A graphics PASS is+ the exception — ``graphics_steps.passes_table`` renders only ``description`` — so+ ``elements`` are folded there, on ONE line because that table is markdown.++ * the brief's signature features become ``should`` acceptance items — ``should``, not+ ``must``: a flash brief's private wishes must never trip ``missing_must_acceptance``,+ which caps a finished object at 0.60 (the lesson ``ensure_acceptance`` already+ records for the scene track);+ * ``style_notes`` gains the reference instance and what the object does NOT have —+ the two brief facts that change how the whole object is built rather than one part.+ """+ for ps in getattr(plan_obj, "passes", None) or []:+ _fold_pass(ps)+ if brief is None:+ return plan_obj+ items: list[AcceptanceItem] = list(getattr(plan_obj, "acceptance", None) or [])+ known = {a.text.strip().lower() for a in items}+ ids = {a.id for a in items}+ n = 1+ for feature in brief.signature_features:+ text = f"Signature feature visible: {feature.strip()}"+ if text.lower() in known:+ continue+ while f"sig{n}" in ids:+ n += 1+ items.append(AcceptanceItem(id=f"sig{n}", text=text, how="visual", priority="should"))+ ids.add(f"sig{n}")+ known.add(text.lower())+ if hasattr(plan_obj, "acceptance"):+ plan_obj.acceptance = items+ notes = getattr(plan_obj, "style_notes", "")+ extra = []+ if brief.reference and brief.reference.lower() not in notes.lower():+ extra.append(f"Reference instance: {brief.reference}.")+ if brief.not_present:+ extra.append("Does NOT have: " + "; ".join(brief.not_present) + ".")+ if extra and hasattr(plan_obj, "style_notes"):+ plan_obj.style_notes = " ".join([notes.strip(), *extra]).strip()+ return plan_obj+++# ===================================================================== worked examples+# (merged from codeverse/tracks/plan_examples.py, 2026-08-28 — same reason)+def plan_example(track: Track) -> dict[str, Any]:+ """Compact, valid worked example per track (concrete beats abstract)."""+ if track is Track.SCENE:+ return {+ "title": "Harbour at dusk", "summary": "Small fishing harbour: quay, two boats, lighthouse, calm water.",+ "setting": "Breton coast, 1960s, clear dusk", "mood": "calm, warm low sun",+ "bounds": {"center": [0, 5, 0], "extents": [120, 30, 120]},+ "environment": "Sky gradient orange→indigo, sun at azimuth 250° elevation 8°, light fog density 0.004, flat sea plane y=0, stone quay at y=1.2.",+ "zones": [+ {"name": "Quay", "description": "L-shaped granite quay with bollards and crates", "bbox": {"center": [-20, 1.2, 0], "extents": [40, 3, 60]}, "contents": ["Bollard", "Crate"]},+ {"name": "Water", "description": "calm harbour basin with two moored boats", "bbox": {"center": [20, 0, 0], "extents": [60, 1, 80]}, "contents": ["FishingBoat"]},+ ],+ "assets": [+ {"name": "FishingBoat", "kind": "threejs", "description": "8 m wooden boat, wheelhouse aft, red hull", "approx_size_m": [8, 3.5, 3], "instances_hint": 2},+ {"name": "Bollard", "kind": "threejs", "description": "cast-iron mooring bollard", "approx_size_m": [0.3, 0.5, 0.3], "instances_hint": 6},+ {"name": "Crate", "kind": "blender_glb", "description": "wooden fish crate, slatted", "approx_size_m": [0.6, 0.3, 0.4], "instances_hint": 8},+ ],+ "effects": [{"name": "WaterRipple", "kind": "glsl_material", "description": "animated normal ripples on the sea plane", "target": "Water"}],+ "animation": ["boats bob ±0.05 m at 0.3 Hz", "water ripples scroll"],+ "cameras": [{"name": "Overview", "position": [45, 18, 55], "look_at": [0, 1, 0], "fov": 50, "purpose": "establishing shot"},+ {"name": "QuayEye", "position": [-5, 2.8, 25], "look_at": [15, 1, -10], "fov": 60, "purpose": "eye level along the quay"}],+ "acceptance": [{"id": "a1", "text": "Two boats float on the water inside the basin", "how": "visual", "priority": "must"},+ {"id": "a2", "text": "Quay top at y≈1.2 m, boats' waterline at y≈0", "how": "probe", "priority": "must"}],+ }+ parts = [+ {"name": "Seat", "role": "horizontal seat board", "description": "solid oak board, 40 mm thick, rounded front edge (r=10 mm)",+ "bbox": {"center": [0, 0, 0.43], "extents": [0.42, 0.40, 0.04]}, "material": "oiled oak", "attach_to": None, "symmetry": "mirror_x", "instances": 1,+ "children": [], "detail_hint": "the eye lands here first — keep the 10 mm bullnose and the 3 mm chamfer under the front edge"},+ {"name": "FrontLeg", "role": "front leg", "description": "tapered round leg 35→25 mm, splayed 6° outward",+ "bbox": {"center": [0.17, -0.16, 0.205], "extents": [0.035, 0.035, 0.41]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "mirror_x", "instances": 2,+ "children": [], "detail_hint": ""},+ {"name": "Backrest", "role": "slatted back assembly", "description": "three vertical slats in a curved top rail and a lower rail",+ "bbox": {"center": [0, 0.19, 0.66], "extents": [0.40, 0.03, 0.42]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "none", "instances": 1,+ "detail_hint": "an assembly, not a panel: the gaps between the slats must be visible from the front and the side",+ "children": [+ {"name": "TopRail", "role": "curved crest rail", "description": "60 mm deep rail bowed 18 mm back on a 0.9 m radius, ends rounded r=8 mm",+ "bbox": {"center": [0, 0.19, 0.85], "extents": [0.40, 0.03, 0.06]}, "material": "oiled oak", "instances": 1},+ {"name": "Slat", "role": "vertical back slat", "description": "12 mm thick slat, 55 mm wide, 4 mm chamfer both faces, 30 mm gap to its neighbour",+ "bbox": {"center": [0, 0.19, 0.66], "extents": [0.055, 0.012, 0.34]}, "material": "oiled oak", "instances": 3},+ {"name": "LowerRail", "role": "rail the slats seat into", "description": "40 mm rail with three 12 × 55 mm mortises on 85 mm centres",+ "bbox": {"center": [0, 0.19, 0.48], "extents": [0.40, 0.03, 0.04]}, "material": "oiled oak", "instances": 1},+ ]},+ ]+ base: dict[str, Any] = {+ "object_name": "DiningChair", "summary": "Mid-century oak dining chair, 0.45 × 0.50 × 0.82 m.",+ "overall_bbox": {"center": [0, 0, 0.41], "extents": [0.45, 0.50, 0.82]},+ "style_notes": "Danish mid-century: tapered legs, thin spindles, warm oak, no ornament.",+ "parts": parts,+ "acceptance": [{"id": "a1", "text": "Seat top at 0.45 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},+ {"id": "a2", "text": "Four legs, all touching the ground, splayed outward", "how": "visual", "priority": "must"}],+ }+ if track is Track.ARTICULATED_OBJECT:+ base["object_name"] = "DeskDrawerUnit"+ base["parts"] = [+ {"name": "Cabinet", "role": "fixed carcass", "description": "18 mm carcass, 6 mm rebated back, 3 mm shadow gap round the drawer opening",+ "bbox": {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]}, "material": "painted MDF", "attach_to": None, "symmetry": "none", "instances": 1,+ "children": [], "detail_hint": "the opening's shadow gap is what makes the drawer read as a drawer"},+ {"name": "Drawer", "role": "sliding drawer (ONE link, four sub-parts)", "description": "drawer box running on side runners",+ "bbox": {"center": [0, -0.02, 0.45], "extents": [0.36, 0.46, 0.2]}, "material": "painted MDF", "attach_to": "Cabinet", "symmetry": "none", "instances": 1,+ "detail_hint": "one rigid body, but never one box",+ "children": [+ {"name": "Front", "role": "drawer face", "description": "18 mm face, 4 mm bullnose, overhangs the box 8 mm on every side",+ "bbox": {"center": [0, -0.24, 0.45], "extents": [0.36, 0.018, 0.19]}, "material": "painted MDF", "instances": 1},+ {"name": "Box", "role": "drawer body", "description": "12 mm sides, 8 mm base set into a 6 mm groove, open top",+ "bbox": {"center": [0, 0.0, 0.45], "extents": [0.33, 0.42, 0.17]}, "material": "birch ply", "instances": 1},+ {"name": "Knob", "role": "pull", "description": "turned knob 32 mm dia, 22 mm proud, on a 10 mm neck",+ "bbox": {"center": [0, -0.26, 0.45], "extents": [0.032, 0.032, 0.032]}, "material": "brushed steel", "instances": 1},+ {"name": "Runner", "role": "side runner", "description": "10 × 10 mm strip along each side, full depth",+ "bbox": {"center": [0.17, 0.0, 0.40], "extents": [0.01, 0.42, 0.01]}, "material": "birch ply", "instances": 2},+ ]},+ ]+ base["root_link"] = "Cabinet"+ base["joints"] = [{"name": "DrawerSlide", "type": "prismatic", "parent": "Cabinet", "child": "Drawer", "axis": [0, -1, 0],+ "pivot": [0, -0.02, 0.45], "lower": 0.0, "upper": 0.35, "rest": 0.0, "motion": "drawer pulls out towards -Y"}]+ base["acceptance"].append({"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"})+ return base++P = TypeVar("P", bound=BaseModel)#: re-ask budgets — a plan the SCHEMA rejects and a plan the QUALITY gate rejects arediff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex b829cb74..88e43e22 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -164,18 +164,16 @@ codeverse/common.py (RunContext, Services), static_object.py (+ the detail round and thereference-image gates), articulated_object.py (+ the planned-motion gate),scene.py, scene_assets.py (+ cheap single-shot asset generation),- graphics.py + graphics_steps.py,- graphics_recipes.py (the brief's verified cookbook recipes + their helpers written into- the harness-owned, read-only src/recipes.glsl before the session — measured: flash calls- a recipe on disk, not one it is shown, and overwrites one seeded into its own common.glsl;- AgentJob.read_only, CV3D_SEED_RECIPES, docs/GRAPHICS_LOOP.md §3),- brief.py (cached EngineeringBrief: one cheap call turns a one-line prompt into- real dimensions / sub-assemblies / signature features; never fatal, CV3D_PLAN_BRIEF),- plan_budget.py (plan size derived from the request, capped per language),+ graphics.py (the whole graphics track: planner hooks, prompt context, frame+ RenderSet, and recipe seeding into the harness-owned, read-only+ src/recipes.glsl — measured: flash calls a recipe on disk, not one it is+ shown; AgentJob.read_only, CV3D_SEED_RECIPES, docs/GRAPHICS_LOOP.md §3),+ planner.py (the ONE planner loop + the cached EngineeringBrief+ (CV3D_PLAN_BRIEF), plan budgets and the worked examples),plan_features.py (CV3D_PLAN_FEATURES: one switch per plan-loop change, so eachcan be A/B'd alone, + pin_plan_blockers() deciding when two arms may shareone plan — docs/PLAN_LOOP.md, docs/EVAL.md §8.1),- plan_examples.py (worked plans shown to the planner), depth.py,+ depth.py,skills_hook.py (the round's view of codeverse/skills: attach before generating,probe reads after — a no-op unless CV3D_SKILLS is on)flywheel/ record.py, export.py, pack.py, sample.py, pairs.py, migrate.py (schema moves),diff --git a/harness/tests/compare_bench/test_fixed_eval_language.py b/harness/tests/compare_bench/test_fixed_eval_language.pyindex fade6860..aee4ee8c 100644--- a/harness/tests/compare_bench/test_fixed_eval_language.py+++ b/harness/tests/compare_bench/test_fixed_eval_language.py@@ -43,7 +43,7 @@ def test_graphics_cells_are_judged_on_their_frames(monkeypatch, tmp_path):ev = FixedEvaluator("fake:judge", n_samples=1)ev._runtimes[Language.GLSL_SHADER] = SimpleNamespace(lint=lambda ws: GateReport(gate="lint", passed=True), build=lambda ws, timeout_s: build)import bench._fixed_eval as fe- import codeverse.tracks.graphics_steps as gs+ import codeverse.tracks.graphics as gsmonkeypatch.setattr(gs, "frames_render_set", lambda ws, b, i: RenderSet(views=[RenderView(name="t=0s", path=str(png))], renderer="fake"))monkeypatch.setattr(gs, "frame_stats_text", lambda ws: "frames=1")diff --git a/harness/tests/graphics/test_live.py b/harness/tests/graphics/test_live.pyindex 8065603c..83ae4124 100644--- a/harness/tests/graphics/test_live.py+++ b/harness/tests/graphics/test_live.py@@ -12,8 +12,8 @@ from codeverse.judges.base import JudgeInputfrom codeverse.judges.vlm_judge import VlmJudgefrom codeverse.languages.glsl_shader.runtime import GlslShaderRuntimefrom codeverse.tracks.generation import generate_files-from codeverse.tracks.graphics import GraphicsTrack-from codeverse.tracks.graphics_steps import (+from codeverse.tracks.graphics import (+ GraphicsTrack,frames_render_set,graphics_prompt_context,plan_graphics,diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.pyindex ffdaee6c..ea278232 100644--- a/harness/tests/graphics/test_track.py+++ b/harness/tests/graphics/test_track.py@@ -24,8 +24,9 @@ from codeverse.languages.glsl_shader.skeleton import write_skeletonfrom codeverse.prompts import renderfrom codeverse.spatial.gl_render import GlFrame, GlResultfrom codeverse.tracks import get_track-from codeverse.tracks.graphics import GraphicsPipeline, GraphicsTrack-from codeverse.tracks.graphics_steps import (+from codeverse.tracks.graphics import (+ GraphicsPipeline,+ GraphicsTrack,build_plan_system_prompt,ensure_graphics_acceptance,graphics_prompt_context,diff --git a/harness/tests/models/test_control_chars.py b/harness/tests/models/test_control_chars.pyindex af6ba2cb..0ead279b 100644--- a/harness/tests/models/test_control_chars.py+++ b/harness/tests/models/test_control_chars.py@@ -114,7 +114,7 @@ def test_the_brief_text_fallback_is_sanitised(tmp_path):from codeverse.contracts.common import Language, Track, Usagefrom codeverse.contracts.plan import EngineeringBrief, RefDimension, SubAssemblyfrom codeverse.contracts.spec import Spec- from codeverse.tracks.brief import expand_brief+ from codeverse.tracks.planner import expand_briefclean = EngineeringBrief(object_name="Grinder", reference="Peugeot 1920s box grinder",diff --git a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.pyindex 28f885c7..0cba5023 100644--- a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py+++ b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py@@ -91,7 +91,7 @@ def test_budget_never_cuts_a_chapter() -> None:def test_graphics_prompt_context_uses_the_selector(monkeypatch) -> None:- from codeverse.tracks import graphics_steps+ from codeverse.tracks import graphics as graphics_stepsseen: dict[str, str] = {}diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.pyindex 98f9db9c..051a5898 100644--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py@@ -29,21 +29,22 @@ from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL, write_skeletonfrom codeverse.languages.glsl_shader.wrap import HEADER as WRAP_HEADERfrom codeverse.languages.glsl_shader.wrap import compose, first_error, parse_glsl_logfrom codeverse.prompts import load_text, render-from codeverse.tracks import graphics_recipes as gr-from codeverse.tracks.graphics_recipes import (+from codeverse.tracks import graphics as gr+from codeverse.tracks.graphics import (HEADER,NOT_SEEDED,RECIPES_REL,RESUME_HEADER,cookbook_functions,defined_names,+ graphics_prompt_context,is_skeleton_common,parse_functions,+ plan_example,recipe_chapters,seed_recipes,seeded_on_disk,)-from codeverse.tracks.graphics_steps import graphics_prompt_context, plan_examplefrom codeverse.workspace import WorkspaceAURORA = "Aurora borealis over a mountain ridge with a frozen lake, dense stars, green and violet curtains"diff --git a/harness/tests/orchestrator_tracks/test_planner_depth.py b/harness/tests/orchestrator_tracks/test_planner_depth.pyindex 0b08bdea..b57c6b9b 100644--- a/harness/tests/orchestrator_tracks/test_planner_depth.py+++ b/harness/tests/orchestrator_tracks/test_planner_depth.py@@ -24,8 +24,8 @@ from codeverse.contracts.plan import (SubPartPlan,)from codeverse.contracts.spec import Constraints, ReferenceImage, Spec-from codeverse.tracks import brief as BR-from codeverse.tracks import plan_budget as B+from codeverse.tracks import planner as B+from codeverse.tracks import planner as BRfrom codeverse.tracks.planner import (MAX_QUALITY_REASKS,build_system_prompt,@@ -370,7 +370,7 @@ def test_graphics_pass_elements_are_folded_into_the_one_markdown_row_that_render"""``graphics_steps.passes_table`` prints only ``description`` — and it is a markdowntable row, so the fold must be single-line and idempotent."""from codeverse.contracts.plan import PassPlan- from codeverse.tracks.graphics_steps import passes_table+ from codeverse.tracks.graphics import passes_tableplan = GraphicsPlan(title="T", summary="s", style="st", passes=[PassPlan(name="Gears", kind="fullscreen", description="meshing gear train",diff --git a/harness/tests/orchestrator_tracks/test_refactor_batch2.py b/harness/tests/orchestrator_tracks/test_refactor_batch2.pyindex d93571f7..4dd7db3d 100644--- a/harness/tests/orchestrator_tracks/test_refactor_batch2.py+++ b/harness/tests/orchestrator_tracks/test_refactor_batch2.py@@ -154,7 +154,7 @@ def test_graphics_planner_hooks_charge_budget_on_planning_error(tmp_ws):from codeverse.contracts.spec import Budgetfrom codeverse.orchestrator.budget import BudgetGuard- from codeverse.tracks.graphics_steps import plan_graphics+ from codeverse.tracks.graphics import plan_graphicsfrom codeverse.tracks.planner import PlanningErrorspec = make_spec(Track.GRAPHICS, Language.GLSL_SHADER)diff --git a/harness/tests/skills/test_delivery_reaches_the_session.py b/harness/tests/skills/test_delivery_reaches_the_session.pyindex 0e2ffbab..26484cdc 100644--- a/harness/tests/skills/test_delivery_reaches_the_session.py+++ b/harness/tests/skills/test_delivery_reaches_the_session.py@@ -125,7 +125,7 @@ def test_round_zero_of_a_scene_run_has_no_generation_task() -> None:@pytest.fixturedef scene_run(tmp_path, monkeypatch):from codeverse.config import Settings- from codeverse.tracks.plan_examples import plan_example+ from codeverse.tracks.planner import plan_examplefrom codeverse.tracks.scene import SceneTrackfrom tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import FakeAgent, FakeJudge, FakeRuntime, FakeServices