Official Codebase of 3DCodeVerse
Python
Delete the per-model prompt/skill variant overlay, the argon tuning loop and run_bench --variant; drop skills_max/skills_unverified
gaoypeng8384913bbc9a
diff --git a/eval/README.md b/eval/README.mdindex 7c7362da..62772b68 100644--- a/eval/README.md+++ b/eval/README.md@@ -24,15 +24,6 @@ pip install -e ../harness # once; both evaluations import copython -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator agy:gemini-4-argonpython -m bench.report bench/out/static_objects_v1 # rebuild report.md + report.htmlpython bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:agy:gemini-4-argon,oneshot:gemini:gemini-3.8-flash --out bench/out/compare_v1-python -m bench.run_bench bench/prompts/scenes_v2.yaml --variant argon --judge gemini:gemini-4-argon # a per-model prompt/skill variant (D105) on every run-python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon --languages scene_threejs,scene_blender \- --generator agy:gemini-4-argon --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 --rounds 2 --max-minutes 90-python -m bench.loop generate --out bench/out/loop_argon --iter 0 [--n 30] [--rung 1] # the tuning loop (docs/EVAL.md §10)-python -m bench.loop run --out bench/out/loop_argon --iter 0 [--resume] # one run_bench child per language-python -m bench.loop diagnose --out bench/out/loop_argon --iter 0 # diagnosis.md: numbers + recommendations-python -m bench.loop compare --out bench/out/loop_argon --iter 1 --against 0 # keep / revert / inconclusive per language-python -m bench.loop judge-calib --out bench/out/loop_argon --iter 1 [--n 3] # the judge arm: within / between σ-python -m bench.loop accept --out bench/out/loop_argon --iter 1 --note "…" # or rollback; status prints the ledgerpython -m llm.config # doctor for the LLM evaluation: tools and assets it can / cannot findpython -m pytest # the bench tests (offline)ruff check .diff --git a/eval/bench/_loop_diag.py b/eval/bench/_loop_diag.pydeleted file mode 100644index 95d40fff..00000000--- a/eval/bench/_loop_diag.py+++ /dev/null@@ -1,794 +0,0 @@-"""What an iteration's run records say (private: ``bench.loop diagnose / compare / judge-calib``).--One :class:`RunDigest` per run, read off the things a run leaves behind — the bench row-(``results.jsonl``), the typed ``record.json`` (``codeverse3d.record.record.load_record``), the-picked round's gates / verdict / skills, and the deliverable's source — and three readers over a-battery of them:--* :func:`diagnose_dir` — the numbers and a RECOMMENDATIONS list produced by deterministic rules- (:data:`RULES`, one table, each rule naming the tracks it reads): a rate crosses its threshold →- one named lever. No model reads the diagnosis; a person does, before editing the variant.-* :func:`compare_dirs` — iteration N against M, paired by prompt id: ``bench.stats.decide`` on the- picked score (the one paired rule every report uses, EVAL.md §8) PLUS the deterministic-gate veto- (:data:`VETOES`) — on the scene track the floating + sunken + interpenetration ERROR count per run,- on the object tracks the connectivity + contract ERROR count (+ the joint sweep and wrong-direction- joints on articulated; capped per run, :data:`OBJECT_VETO_CAP`), must not rise by more than- :data:`VETO_RISE` on average, whatever the judge says (the owner's stricter contact standards,- 2026-10-14, are measured by the gate, not perceived by the VLM).-* :func:`calib_summary` — the judge arm: within-run σ (the re-judge noise), between-run σ (the- spread the judge is asked to resolve), their ratio, and the gate-score correlations.--Gate findings are counted by their TYPED kind (``skills.registry.finding_kind`` →-``"scene_placement/floating"``), never by message text (Law 4). The scene track's metrics are-its own (placement, frames, library reach); the object tracks read ``contract`` / ``connectivity``-(+ ``joint_sweep`` / ``motion_direction`` / the URDF lint on articulated), graphics ``gl_frames``-(:data:`GATE_METRICS`); lint, budget, outages, verdicts, skills and the must-have cap are shared.-"""--from __future__ import annotations--import ast-import json-import math-import re-import statistics-from collections import Counter-from collections.abc import Iterable, Sequence-from dataclasses import dataclass-from pathlib import Path-from typing import Any--from pydantic import BaseModel, Field--from bench._jsonl import latest, read_jsonl-from bench._records import records-from bench.paired_compare import PairedStats, paired, paired_rows-from bench.run_bench import BenchItemResult-from bench.stats import correlation, decide-from codeverse3d.addons.calibration import CalibrationRow, CalibrationTable-from codeverse3d.addons.select import summarise-from codeverse3d.contracts.artifacts import LintKind, Severity-from codeverse3d.contracts.common import Track-from codeverse3d.contracts.run import RoundRecord, RunRecord-from codeverse3d.conventions import CONTACT_GAP_M-from codeverse3d.record.record import RecordError, load_record, stop_reason-from codeverse3d.skills.registry import finding_kind, gate_family, kind_matches-from codeverse3d.spatial.connectivity import GATE as CONNECTIVITY-from codeverse3d.spatial.contract import GATE as CONTRACT-from codeverse3d.spatial.frame_stats import GATE as GL_FRAMES-from codeverse3d.spatial.joints_sweep import SWEEP_GATE-from codeverse3d.tracks.articulated_object import MOTION_GATE, MOTION_WRONG--#: the gate kinds the owner's contact standards are about (spatial/scene_placement.py data.kind)-PLACEMENT_KINDS: tuple[str, ...] = ("scene_placement/floating", "scene_placement/sunken",- "scene_placement/interpenetration")-#: the veto: a variant whose runs gain more than this many placement ERRORs each, on average, is-#: reverted whatever its score — one more floater per run is inside the gate's own run-to-run swing-#: (the same prompt re-run moves 0-1 findings), two is a change in behaviour-VETO_RISE = 1.0--OBJECT_TRACKS: tuple[Track, ...] = (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT)-ALL_TRACKS: tuple[Track, ...] = tuple(Track)-NON_SCENE: tuple[Track, ...] = tuple(t for t in Track if t is not Track.SCENE)-SCENE: tuple[Track, ...] = (Track.SCENE,)---#: the object vetoes count at most this many ERRORs per run: connectivity reports one penetration per-#: PART PAIR (a real bicycle run: 14 in one round), so one noisy prompt going 0 → 14 would add 0.93 per-#: run at n = 15 and revert the iteration on its own; capped, it adds 0.2 and the veto needs several-#: prompts to move. The scene veto is uncapped (the scene gate already caps its findings per scene).-OBJECT_VETO_CAP = 3---@dataclass(frozen=True)-class Veto:- """The deterministic channel ``compare`` holds beside the score: the ERROR findings of ``kinds``- (``skills.registry.kind_matches`` patterns) per run — at most ``per_run_cap`` of them — must not- rise by more than :data:`VETO_RISE`."""-- label: str # what the verdict's reason names- short: str # what the comparison table names- kinds: tuple[str, ...]- per_run_cap: int | None = None-- def count(self, d: RunDigest) -> int:- n = d.errors_of(self.kinds)- return n if self.per_run_cap is None else min(n, self.per_run_cap)---_OBJECT_VETO_KINDS = (f"{CONNECTIVITY}/*", f"{CONTRACT}/*")--#: the veto per track. Graphics has none: its ERRORs are image-level verdicts (black / blown / NaN —-#: at most two per run), so a mean rise above one per run is unreachable, and the shader rubric-#: caps those runs' score already. Articulated adds the pose sweep (capped per pair by the gate,-#: ``MAX_PAIR_FINDINGS``) and a joint that moves the wrong way — the judge caps both-#: (``joint_collision``), the veto must see them too.-VETOES: dict[Track, Veto] = {- Track.SCENE: Veto("floating+sunken+interpenetration", "placement", PLACEMENT_KINDS),- Track.STATIC_OBJECT: Veto("connectivity+contract", "connectivity+contract", _OBJECT_VETO_KINDS, OBJECT_VETO_CAP),- Track.ARTICULATED_OBJECT: Veto("connectivity+contract+joint", "connectivity+contract+joint",- (*_OBJECT_VETO_KINDS, f"{SWEEP_GATE}/*", f"{MOTION_GATE}/{MOTION_WRONG}"),- OBJECT_VETO_CAP),-}--#: `from '../lib/<x>.js'` / `from './lib/<x>.js'` in an agent-written three.js file. A regex over-#: SOURCE TEXT (the import specifier), the way B1's `library_rows` reads the catalog — not over an id.-_JS_LIB_IMPORT = re.compile(r"""from\s+['"](?:\.\./|\./)+lib/([A-Za-z0-9_]+)\.js['"]""")-#: the harness-owned library directory inside ``src/`` — its own files import each other and must-#: not count as the AGENT reaching the library (HARNESS_OWNED_SRC: ``src/lib/``)-_LIB_DIR = "lib"---# --------------------------------------------------------------------------- one run-class RunDigest(BaseModel):- """Everything the diagnosis and the comparison read off one run."""-- id: str- status: str = ""- stop_reason: str = ""- score_baseline: float | None = None- score_picked: float | None = None- picked_round: int | None = None- criteria: dict[str, float] = Field(default_factory=dict, description="the picked verdict's per-criterion scores")- defects: dict[str, bool] = Field(default_factory=dict, description="the picked verdict's defect checklist")- caps: list[str] = Field(default_factory=list, description="cap rules applied on the picked verdict")- gate_errors: dict[str, int] = Field(default_factory=dict, description="typed kind → ERROR findings, picked round")- gate_warns: dict[str, int] = Field(default_factory=dict, description="typed kind → WARN findings, picked round")- issues: list[tuple[str, str]] = Field(default_factory=list, description="(kind, target word) per judge issue")- lib_modules: list[str] = Field(default_factory=list, description="distinct lib modules the agent's files import")- lib_imports: int = Field(default=0, description="import statements of lib modules in the agent's files")- cost_usd: float = 0.0- cost_by_stage: dict[str, float] = Field(default_factory=dict)- minutes: float | None = None- skills_listed: int = 0- skills_surfaced: int = 0- skills_deep: int = 0- deep_read_rate: float | None = Field(default=None, description="mean over the rounds that could measure it")- gates_run: list[str] = Field(default_factory=list, description="the gates the picked round ran "- "(``gate_family`` names, the kinds' prefix): a rate's denominator")- errors: str = ""-- def errors_of(self, kinds: tuple[str, ...]) -> int:- """ERROR findings whose typed kind matches ``kinds`` (exact, or ``family/*``)."""- return sum(n for k, n in self.gate_errors.items() if kind_matches(k, kinds))---def _picked(run_dir: Path, rec: RunRecord) -> RoundRecord | None:- s = summarise(run_dir, record=rec)- idx = s.round- return next((r for r in rec.rounds if r.index == idx), None) if idx is not None else None---def _issue_word(target: str) -> str:- """``ShojiVeranda/ShojiScreen`` → ``ShojiScreen``; ``BlackPine_5`` → ``BlackPine`` (the family, not the- instance): the pairs are counted across runs, where instance numbers only scatter them."""- seg = target.strip().split("/")[-1] or target.strip()- head, _, tail = seg.rpartition("_")- return head if head and tail.isdigit() else seg---def py_lib_modules(path: Path) -> list[str]:- """``lib.<x>`` modules one agent-written python file imports (``ast``, never text)."""- try:- tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))- except SyntaxError:- return []- out: list[str] = []- for node in ast.walk(tree):- if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:- parts = node.module.split(".")- if parts[0] == _LIB_DIR:- out.extend([parts[1]] if len(parts) > 1 else [a.name for a in node.names])- elif isinstance(node, ast.Import):- for a in node.names:- parts = a.name.split(".")- if parts[0] == _LIB_DIR and len(parts) > 1:- out.append(parts[1])- return out---def js_lib_modules(path: Path) -> list[str]:- """``lib/<x>.js`` modules one agent-written three.js file imports (relative specifiers)."""- return _JS_LIB_IMPORT.findall(path.read_text(encoding="utf-8", errors="replace"))---def lib_usage(run_dir: Path) -> tuple[list[str], int]:- """``(distinct modules, import statements)`` over the agent's files under ``deliverable/src`` (the- packaged round) — ``src/`` when nothing was packaged. ``src/lib/`` itself is skipped: the library- importing itself is not the agent using it."""- src = run_dir / "deliverable" / "src"- if not src.is_dir():- src = run_dir / "src"- if not src.is_dir():- return [], 0- found: list[str] = []- for p in sorted(src.rglob("*")):- if not p.is_file() or _LIB_DIR in p.relative_to(src).parts[:-1]:- continue- if p.suffix == ".py":- found.extend(py_lib_modules(p))- elif p.suffix in (".js", ".mjs"):- found.extend(js_lib_modules(p))- return sorted(set(found)), len(found)---def digest_run(run_dir: Path, row: BenchItemResult | None = None) -> RunDigest:- """The digest of one run directory; ``row`` is its bench row when the battery has one."""- d = RunDigest(id=row.id if row is not None else run_dir.name)- if row is not None:- d.status, d.errors = row.status, row.errors- d.score_baseline, d.score_picked, d.picked_round = row.score_baseline, row.score_picked, row.picked_round- d.cost_usd, d.minutes = row.cost_usd, row.minutes- try:- rec = load_record(run_dir)- except RecordError as e:- d.errors = d.errors or str(e)- return d- d.stop_reason = stop_reason(rec)- d.status = d.status or rec.status.value- d.cost_usd = d.cost_usd or rec.total_usage.cost_usd- d.minutes = rec.minutes if rec.minutes is not None else d.minutes- cost = rec.telemetry.cost if rec.telemetry is not None else None- if cost is not None:- d.cost_by_stage = {s.stage: round(s.cost_usd, 6) for s in cost.by_stage}- picked = _picked(run_dir, rec)- if picked is not None:- d.picked_round = picked.index- d.gates_run = sorted({gate_family(g.gate) for g in picked.gates})- for g in picked.gates:- for f in g.findings:- kind = finding_kind(f)- if kind is None:- continue- bucket = d.gate_errors if f.severity == Severity.ERROR else d.gate_warns if f.severity == Severity.WARN else None- if bucket is not None:- bucket[kind] = bucket.get(kind, 0) + 1- j = picked.judgment- if j is not None and not j.degraded:- d.score_picked = j.overall if d.score_picked is None else d.score_picked- d.criteria = dict(j.scores)- d.issues = [(i.kind, _issue_word(i.target)) for i in j.issues]- raw = _raw(j.raw)- d.defects = {k: bool(v) for k, v in (raw.get("defects") or {}).items()}- d.caps = [str(c.get("rule", "")) for c in (raw.get("caps") or {}).get("caps_applied", []) if c.get("rule")]- if d.score_baseline is None:- base = next((r for r in rec.rounds if r.index == 0), None)- if base is not None and base.judgment is not None and not base.judgment.degraded:- d.score_baseline = base.judgment.overall- rates: list[float] = []- for r in rec.rounds:- if r.skills is None:- continue- d.skills_listed += len(r.skills.listed)- d.skills_surfaced += len(r.skills.surfaced)- d.skills_deep += len(r.skills.deep)- if (rate := r.skills.deep_read_rate) is not None:- rates.append(rate)- d.deep_read_rate = round(statistics.fmean(rates), 4) if rates else None- d.lib_modules, d.lib_imports = lib_usage(run_dir)- return d---def _raw(text: str) -> dict[str, Any]:- try:- raw = json.loads(text) if text else {}- except ValueError:- return {}- return raw if isinstance(raw, dict) else {}---def digests_for(out_lang: Path, *, track: Track = Track.SCENE) -> dict[str, RunDigest]:- """prompt id → digest for one ``bench.run_bench`` output directory (its rows + its run dirs,- each run once — ``_records.records``, the loop's ``track`` only)."""- rows: dict[str, BenchItemResult] = {}- jl = out_lang / "results.jsonl"- if jl.is_file():- rows = {r.id: r for r in latest(read_jsonl(jl, BenchItemResult)).values()}- out: dict[str, RunDigest] = {}- runs_root = out_lang / "runs"- if runs_root.is_dir():- for rec_path, data in records(runs_root, track=track.value):- run_dir = rec_path.parent- pid = str((data.get("spec") or {}).get("id", run_dir.name)).split("/")[-1]- # the live run is `runs/<id>`; a redo archives the old tree beside it as `<id>.attemptN`- # (run_bench.archive_attempt) with the SAME spec id, and sorts after it — never the digest- if run_dir.name != pid:- continue- out[pid] = digest_run(run_dir, rows.get(pid))- for pid, row in rows.items(): # a row whose run left no record (an error before the plan) still counts- out.setdefault(pid, digest_run(runs_root / pid, row))- return out---# --------------------------------------------------------------------------- diagnosis-@dataclass(frozen=True)-class Rule:- """A deterministic lever: when ``metric`` crosses ``threshold`` (``above`` or below), say ``text`` —- on the ``tracks`` whose diagnosis computes the metric."""-- name: str- metric: str- threshold: float- text: str- above: bool = True- tracks: tuple[Track, ...] = ALL_TRACKS-- def fires(self, value: float | None) -> bool:- if value is None:- return False- return value >= self.threshold if self.above else value < self.threshold---RULES: tuple[Rule, ...] = (- Rule("floating", "floating_error_rate", 0.25,- "placement recipe + boost the placement skill: seat every placed thing on height_at / its support "- "(lib.place.seat); the gate ERRORs at 0.08 m or > 2 floaters per scene", tracks=SCENE),- Rule("sunken", "sunken_error_rate", 0.25,- "seating recipe: assets are buried, not hovering — seat by the evaluated bbox, never by the origin "- "(sunk ERROR at 0.20 m and 20 % of the height)", tracks=SCENE),- Rule("interpenetration", "interpenetration_error_rate", 0.25,- "clear_of self-check in the zone recipe + spacing in the layout prompt (overlap ERROR at 35 % of the smaller box)",- tracks=SCENE),- Rule("library", "lib_modules_mean", 3.0,- "effects catalog presentation: the agent reaches fewer than three library modules per scene", above=False,- tracks=SCENE),- Rule("lighting", "dark_frame_rate", 0.20,- "lighting recipe: key/fill/exposure numbers per mood + boost the lighting skill (dark_frame caps at 0.55)",- tracks=SCENE),- Rule("budget", "budget_stop_rate", 0.30,- "raise --max-minutes or cut the zone prompt: the clock stops the run before its rounds", tracks=SCENE),- Rule("weather", "infra_failed_rate", 0.20,- "provider weather, not the variant: `bench.loop run --resume` the iteration before reading it"),- Rule("unscored", "unscored_rate", 0.20,- "runs without a verdict: read the errors column (build / render / judge outage) before the scores"),- Rule("skills", "deep_read_rate_mean", 0.20,- "skills are listed but not read: shorten the index, name the chapter in the task text", above=False),- Rule("must", "missing_must_rate", 0.25,- "must-have wording: the contract lines fail the plan's acceptance items — the planner is not carrying them"),- Rule("camera", "camera_error_rate", 0.20,- "camera brief recipe: fit every authored camera to the content box, never inside geometry", tracks=SCENE),- Rule("free_exempt", "free_exempt_rate", 0.20,- "assets tagged placement='free' to dodge the gate: say in the contract that 'free' is for hanging / airborne things only",- tracks=SCENE),- # ---- the other tracks (metrics: GATE_METRICS + the shared ones)- Rule("budget", "budget_stop_rate", 0.30,- "raise --max-minutes or trim the refine instructions: the clock stops the run before its rounds", tracks=NON_SCENE),- Rule("lint", "lint_error_rate", 0.20,- "lint: the agent's code trips the language lint (sandbox, removed API, harness-owned call) — name the rule "- "it breaks in the variant's system prompt", tracks=NON_SCENE),- Rule("connectivity", "conn_floating_error_rate", 0.25,- f"connectivity: contact band — parts stop short of their support; every part must touch the part it attaches "- f"to within {CONTACT_GAP_M * 1000:g} mm (measure the gap before refining; boost the connectivity skill)",- tracks=OBJECT_TRACKS),- Rule("penetration", "conn_penetration_error_rate", 0.25,- "connectivity: contact band — parts sink deep into each other; seat them surface to surface (a hairline "- "overlap is fine), notch or shorten a member that passes through", tracks=OBJECT_TRACKS),- Rule("islands", "conn_islands_rate", 0.25,- "connectivity: islands — stray disconnected pieces inside a part; one part is one solid piece "- "(join or delete the strays)", tracks=OBJECT_TRACKS),- Rule("bbox", "contract_bbox_error_rate", 0.25,- "bbox: dims — the built size / centre / orientation is off the plan's box; measure before refining and "- "keep the planned dimensions (the contract ERRORs past 2× the tolerance)", tracks=OBJECT_TRACKS),- Rule("ground", "contract_ground_error_rate", 0.20,- "bbox: ground — the lowest point is off up = 0; author the object standing on the ground (no wrapper "- "grounds it, Law 7)", tracks=OBJECT_TRACKS),- Rule("parts", "contract_missing_error_rate", 0.20,- "contract: a planned part is missing — name every planned part's object after the plan",- tracks=OBJECT_TRACKS),- Rule("joints", "joint_axis_error_rate", 0.20,- "joints: axis/limits — a joint moves the wrong way or its URDF axis / limits / mimic do not type-check; "- "state the axis-from-pivot rule and the limit units in the variant prompt", tracks=(Track.ARTICULATED_OBJECT,)),- Rule("sweep", "joint_sweep_error_rate", 0.30,- "joints: the pose sweep finds links colliding, buried or detached across the joint range — clearances at "- "the limits, not only at rest", tracks=(Track.ARTICULATED_OBJECT,)),- Rule("black", "frame_black_rate", 0.15,- "black: the frames are black — the final colour assignment, the raymarch hit test and the camera direction",- tracks=(Track.GRAPHICS,)),- Rule("blown", "frame_blown_rate", 0.15,- "blown: the frames are blown out — tone-map into 0..1 and bound accumulated glow", tracks=(Track.GRAPHICS,)),- Rule("no_motion", "frame_no_motion_rate", 0.20,- "no_motion: the frames do not change over time — drive the brief's animation from the time uniform",- tracks=(Track.GRAPHICS,)),- Rule("broken", "frame_broken_rate", 0.10,- "broken: NaN pixels — guard divisions, sqrt/pow/log arguments and normalize() of zero",- tracks=(Track.GRAPHICS,)),-)----@dataclass(frozen=True)-class GateMetric:- """A non-scene rate: the share of the runs whose picked round RAN the kinds' gate(s) that have an- ERROR of ``kinds`` (or a WARN too, ``warn=True``, for a kind the gate never raises to ERROR). A- run whose every build failed falls back to a round without connectivity / contract / gl_frames- reports: it is out of those rates' denominators, not a clean run (it shows in ``unscored_rate``)."""-- metric: str- kinds: tuple[str, ...]- tracks: tuple[Track, ...]- warn: bool = False-- @property- def gates(self) -> frozenset[str]:- """The gate families ``kinds`` belong to (each pattern is ``"<gate>/<kind>"``, our own constants)."""- return frozenset(k.partition("/")[0] for k in self.kinds)---#: the kinds each non-scene rate counts (``finding_kind`` = "<gate>/<data.kind>", lint gates folded to-#: "lint/<LintKind>"). The kind words are the gates' own (spatial/connectivity.py, spatial/contract.py,-#: spatial/joints_sweep.py, spatial/frame_stats.py, tracks/articulated_object.py). Not counted, on-#: purpose: ``contract/footprint_offset`` and ``contract/instance_count`` (the contract gate only ever-#: WARNs them — an ERROR rate would read 0 forever) and ``gl_frames/no_frames`` (``frame_gate`` runs-#: only on a build that produced judged frames, ``_gl_common.finish_build``: a render with none has no-#: gl_frames report at all and shows in ``unscored_rate``).-GATE_METRICS: tuple[GateMetric, ...] = (- GateMetric("lint_error_rate", ("lint/*",), NON_SCENE),- GateMetric("connectivity_error_rate", (f"{CONNECTIVITY}/*",), OBJECT_TRACKS),- GateMetric("conn_floating_error_rate", (f"{CONNECTIVITY}/floating",), OBJECT_TRACKS),- GateMetric("conn_penetration_error_rate", (f"{CONNECTIVITY}/penetration",), OBJECT_TRACKS),- # stray islands are a WARN in the gate (``_island_findings``): counted at WARN, or nothing would ever count- GateMetric("conn_islands_rate", (f"{CONNECTIVITY}/stray_islands",), OBJECT_TRACKS, warn=True),- GateMetric("contract_error_rate", (f"{CONTRACT}/*",), OBJECT_TRACKS),- GateMetric("contract_bbox_error_rate", tuple(f"{CONTRACT}/{k}" for k in ("part_bbox", "instance_bbox", "overall_bbox",- "orientation")), OBJECT_TRACKS),- GateMetric("contract_ground_error_rate", (f"{CONTRACT}/ground_gap",), OBJECT_TRACKS),- GateMetric("contract_missing_error_rate", (f"{CONTRACT}/missing_part",), OBJECT_TRACKS),- GateMetric("joint_sweep_error_rate", (f"{SWEEP_GATE}/*",), (Track.ARTICULATED_OBJECT,)),- GateMetric("joint_axis_error_rate", (f"lint/{LintKind.URDF_JOINT.value}", f"lint/{LintKind.MIMIC.value}",- f"{MOTION_GATE}/{MOTION_WRONG}"), (Track.ARTICULATED_OBJECT,)),- GateMetric("frame_black_rate", (f"{GL_FRAMES}/black",), (Track.GRAPHICS,)),- GateMetric("frame_blown_rate", (f"{GL_FRAMES}/blown",), (Track.GRAPHICS,)),- # a static sequence is a WARN in the gate (``frame_gate``): counted at WARN- GateMetric("frame_no_motion_rate", (f"{GL_FRAMES}/static",), (Track.GRAPHICS,), warn=True),- GateMetric("frame_broken_rate", (f"{GL_FRAMES}/nan",), (Track.GRAPHICS,)),-)---class Recommendation(BaseModel):- rule: str- metric: str- value: float- threshold: float- text: str---class Diagnosis(BaseModel):- """One language of one iteration, diagnosed."""-- language: str- out_dir: str- track: str = Track.SCENE.value- n: int = 0- by_status: dict[str, int] = Field(default_factory=dict)- n_scored: int = 0- baseline: dict[str, float | None] = Field(default_factory=dict, description="mean / median / sd")- picked: dict[str, float | None] = Field(default_factory=dict)- criteria_mean: dict[str, float] = Field(default_factory=dict)- defect_rates: dict[str, float] = Field(default_factory=dict, description="share of scored runs voting the defect")- caps_fired: dict[str, int] = Field(default_factory=dict, description="cap rule → runs it fired on")- gate_error_total: dict[str, int] = Field(default_factory=dict, description="typed kind → ERROR findings over the runs")- gate_error_runs: dict[str, int] = Field(default_factory=dict, description="typed kind → runs with at least one ERROR")- gate_warn_total: dict[str, int] = Field(default_factory=dict)- lib_modules_mean: float | None = None- lib_module_hist: dict[str, int] = Field(default_factory=dict, description="module → runs importing it")- cost_total: float = 0.0- cost_by_stage: dict[str, float] = Field(default_factory=dict)- minutes_mean: float | None = None- minutes_total: float = 0.0- stop_reasons: dict[str, int] = Field(default_factory=dict)- skills: dict[str, float | int | None] = Field(default_factory=dict)- top_issues: list[tuple[str, str, int]] = Field(default_factory=list, description="(kind, target word, n), 12 most frequent")- metrics: dict[str, float | None] = Field(default_factory=dict, description="the rates the rules read")- recommendations: list[Recommendation] = Field(default_factory=list)- runs: list[RunDigest] = Field(default_factory=list)---def _stats(xs: Sequence[float]) -> dict[str, float | None]:- if not xs:- return {"mean": None, "median": None, "sd": None}- return {"mean": round(statistics.fmean(xs), 4), "median": round(statistics.median(xs), 4),- "sd": round(statistics.stdev(xs), 4) if len(xs) > 1 else None}---def _rate(hits: int, n: int) -> float | None:- return round(hits / n, 4) if n else None---def _gate_rate(gated: Sequence[RunDigest], gm: GateMetric) -> float | None:- def hit(d: RunDigest) -> bool:- kinds = [*d.gate_errors, *d.gate_warns] if gm.warn else list(d.gate_errors)- return any(kind_matches(k, gm.kinds) for k in kinds)-- ran = [d for d in gated if gm.gates & set(d.gates_run)]- return _rate(sum(1 for d in ran if hit(d)), len(ran))---def diagnose_digests(language: str, out_dir: Path, digests: Iterable[RunDigest], *,- track: Track = Track.SCENE) -> Diagnosis:- runs = sorted(digests, key=lambda d: d.id)- diag = Diagnosis(language=language, out_dir=str(out_dir), track=track.value, n=len(runs), runs=runs)- diag.by_status = dict(Counter(d.status or "(none)" for d in runs))- evaluated = [d for d in runs if d.status != "infra_failed"]- scored = [d for d in evaluated if d.score_picked is not None]- gated = [d for d in evaluated if d.picked_round is not None]- diag.n_scored = len(scored)- diag.baseline = _stats([d.score_baseline for d in evaluated if d.score_baseline is not None])- diag.picked = _stats([d.score_picked for d in scored])- crit: dict[str, list[float]] = {}- defects: Counter[str] = Counter()- caps: Counter[str] = Counter()- issues: Counter[tuple[str, str]] = Counter()- for d in scored:- for k, v in d.criteria.items():- crit.setdefault(k, []).append(v)- defects.update(k for k, on in d.defects.items() if on)- caps.update(dict.fromkeys(d.caps).keys()) # distinct, in verdict order (a set's order is per-process)- issues.update(d.issues)- diag.criteria_mean = {k: round(statistics.fmean(v), 4) for k, v in sorted(crit.items())}- diag.defect_rates = {k: _rate(n, len(scored)) or 0.0 for k, n in defects.most_common()}- diag.caps_fired = dict(caps.most_common())- diag.top_issues = [(k, w, n) for (k, w), n in issues.most_common(12)]- err_total: Counter[str] = Counter()- err_runs: Counter[str] = Counter()- warn_total: Counter[str] = Counter()- for d in gated:- err_total.update(d.gate_errors)- err_runs.update(d.gate_errors.keys())- warn_total.update(d.gate_warns)- diag.gate_error_total, diag.gate_error_runs = dict(err_total.most_common()), dict(err_runs.most_common())- diag.gate_warn_total = dict(warn_total.most_common())- with_src = [d for d in evaluated if d.lib_modules or d.lib_imports]- diag.lib_modules_mean = round(statistics.fmean(len(d.lib_modules) for d in gated), 3) if gated else None- diag.lib_module_hist = dict(Counter(m for d in with_src for m in d.lib_modules).most_common())- diag.cost_total = round(sum(d.cost_usd for d in runs), 4)- stage: Counter[str] = Counter()- for d in runs:- stage.update(d.cost_by_stage)- diag.cost_by_stage = {k: round(v, 4) for k, v in stage.most_common()}- minutes = [d.minutes for d in evaluated if d.minutes is not None]- diag.minutes_mean = round(statistics.fmean(minutes), 2) if minutes else None- diag.minutes_total = round(sum(minutes), 2)- diag.stop_reasons = dict(Counter(d.stop_reason or "(none)" for d in evaluated).most_common())- rates = [d.deep_read_rate for d in runs if d.deep_read_rate is not None]- diag.skills = {"listed": sum(d.skills_listed for d in runs), "surfaced": sum(d.skills_surfaced for d in runs),- "deep": sum(d.skills_deep for d in runs),- "deep_read_rate_mean": round(statistics.fmean(rates), 4) if rates else None}- n_eval = len(evaluated)- own = (_scene_metrics(diag, gated, err_runs) if track is Track.SCENE- else {gm.metric: _gate_rate(gated, gm) for gm in GATE_METRICS if track in gm.tracks})- diag.metrics = {- **own,- "budget_stop_rate": _rate(sum(1 for d in evaluated if d.stop_reason == "budget"), n_eval),- "infra_failed_rate": _rate(len(runs) - n_eval, len(runs)),- "unscored_rate": _rate(n_eval - len(scored), n_eval),- "deep_read_rate_mean": diag.skills["deep_read_rate_mean"],- "missing_must_rate": _rate(caps["missing_must_acceptance"], len(scored)),- }- diag.recommendations = [- Recommendation(rule=r.name, metric=r.metric, value=v, threshold=r.threshold, text=r.text)- for r in RULES if track in r.tracks and (v := diag.metrics.get(r.metric)) is not None and r.fires(v)- ]- return diag---def _scene_metrics(diag: Diagnosis, gated: Sequence[RunDigest], err_runs: Counter[str]) -> dict[str, float | None]:- """The scene track's own rates (placement, frames, library), in the order its diagnosis has always printed."""- n_gated = len(gated)- return {- "floating_error_rate": _rate(err_runs["scene_placement/floating"], n_gated),- "sunken_error_rate": _rate(err_runs["scene_placement/sunken"], n_gated),- "interpenetration_error_rate": _rate(err_runs["scene_placement/interpenetration"], n_gated),- "free_exempt_rate": _rate(sum(1 for d in gated if "scene_placement/free_exempt" in d.gate_errors- or "scene_placement/free_exempt" in d.gate_warns), n_gated),- "dark_frame_rate": _rate(err_runs["scene_frames/dark_frame"], n_gated),- "camera_error_rate": _rate(sum(1 for d in gated if any(k.startswith("scene_frames/camera_") for k in d.gate_errors)), n_gated),- "lib_modules_mean": diag.lib_modules_mean,- }---def diagnose_dir(language: str, out_lang: Path, *, track: Track = Track.SCENE) -> Diagnosis:- """The diagnosis of one ``bench.run_bench`` output directory (the runs of ``track``)."""- return diagnose_digests(language, out_lang, digests_for(out_lang, track=track).values(), track=track)---def _f(x: float | None, fmt: str = ".3f") -> str:- return "—" if x is None else format(x, fmt)---def _kv_table(title: str, rows: Iterable[tuple[str, Any]], head: tuple[str, str]) -> list[str]:- out = [f"### {title}", "", f"| {head[0]} | {head[1]} |", "|---|---|"]- out += [f"| {k} | {v} |" for k, v in rows]- return out + [""]---def render_diagnosis(d: Diagnosis) -> str:- lines = [f"## {d.language} — {d.n} run(s) under `{d.out_dir}`", "",- "by status: " + ", ".join(f"{k} {n}" for k, n in sorted(d.by_status.items())) + "; "- f"scored {d.n_scored}; stop reasons: " + ", ".join(f"{k} {n}" for k, n in d.stop_reasons.items()), "",- "| score | mean | median | sd |", "|---|---|---|---|",- f"| baseline | {_f(d.baseline.get('mean'))} | {_f(d.baseline.get('median'))} | {_f(d.baseline.get('sd'))} |",- f"| picked | {_f(d.picked.get('mean'))} | {_f(d.picked.get('median'))} | {_f(d.picked.get('sd'))} |", ""]- lines += _kv_table("criteria (mean over scored runs)", ((k, _f(v)) for k, v in d.criteria_mean.items()), ("criterion", "mean"))- lines += _kv_table("defects (vote rate over scored runs)", ((k, format(v, ".0%")) for k, v in d.defect_rates.items()), ("defect", "rate"))- lines += _kv_table("caps fired (runs)", d.caps_fired.items(), ("rule", "runs"))- lines += ["### gates (picked round, typed kind)", "", "| kind | runs with ERROR | ERROR findings | WARN findings |", "|---|---|---|---|"]- kinds = sorted(set(d.gate_error_total) | set(d.gate_warn_total))- lines += [f"| {k} | {d.gate_error_runs.get(k, 0)} | {d.gate_error_total.get(k, 0)} | {d.gate_warn_total.get(k, 0)} |" for k in kinds]- if d.track == Track.SCENE.value:- lines += ["", f"### library: {_f(d.lib_modules_mean, '.2f')} modules per scene", ""]- lines += [f"- {m}: {n}" for m, n in list(d.lib_module_hist.items())[:20]] or ["- (no lib imports found)"]- lines += ["", f"### cost ${d.cost_total:.2f} total; minutes mean {_f(d.minutes_mean, '.1f')}, total {d.minutes_total:.0f}", ""]- lines += [f"- {k}: ${v:.2f}" for k, v in d.cost_by_stage.items()]- s = d.skills- lines += ["", f"### skills: listed {s.get('listed')}, surfaced {s.get('surfaced')}, deep {s.get('deep')}, "- f"deep-read rate {_f(s.get('deep_read_rate_mean'))}", ""]- lines += ["### judge issues (kind, target word)", ""] + [f"- {n:3}× {k} / {w}" for k, w, n in d.top_issues] + [""]- lines += ["### RECOMMENDATIONS", ""]- if d.recommendations:- lines += [f"- **{r.rule}** ({r.metric} = {r.value:.3g} vs {r.threshold:g}): {r.text}" for r in d.recommendations]- else:- lines += ["- (no rule fired)"]- lines += ["", "| metric | value |", "|---|---|"] + [f"| {k} | {_f(v)} |" for k, v in d.metrics.items()] + [""]- return "\n".join(lines)---# --------------------------------------------------------------------------- compare-class Comparison(BaseModel):- """Iteration ``a`` against ``b`` for one language: the score pairs plus the deterministic channels."""-- language: str- name_a: str- name_b: str- track: str = Track.SCENE.value- paired: PairedStats- dropped_ids: list[str] = Field(default_factory=list, description="ids on one side only")- criteria_delta: dict[str, float] = Field(default_factory=dict, description="mean a − b per criterion")- gate_error_delta: dict[str, int] = Field(default_factory=dict, description="kind → Σ(a − b) ERROR findings over the pairs")- placement_rise: float | None = Field(default=None, description="mean a − b of the track's veto ERRORs per run "- "(VETOES: scene floating+sunken+interpenetration, objects connectivity+contract "- "(+ joint sweep / wrong direction on articulated), capped per run; None on a "- "track without a veto). Named for the scene veto it was first: the name keeps "- "every compare_*.json already written loading")- cost_delta: float | None = Field(default=None, description="mean a − b, USD per run")- decision: str = Field(default="", description="keep | revert | inconclusive")- reason: str = ""---def loop_verdict(st: PairedStats, placement_rise: float | None, veto: Veto | None = VETOES[Track.SCENE]) -> tuple[str, str]:- """``(decision, reason)``: ``stats.decide`` on the paired picked scores, then the track's gate veto."""- d = decide(st.deltas)- decision = {"better": "keep", "worse": "revert"}.get(d.outcome, "inconclusive")- reason = d.reason- if veto is not None and placement_rise is not None and placement_rise > VETO_RISE:- decision = "revert"- reason = (f"gate veto: {veto.label} ERRORs rose by {placement_rise:+.2f} per run "- f"(limit {VETO_RISE:+.0f}); score said {d.outcome} — {d.reason}")- return decision, reason---def compare_digests(language: str, name_a: str, name_b: str, st: PairedStats,- da: dict[str, RunDigest], db: dict[str, RunDigest], *, track: Track = Track.SCENE) -> Comparison:- veto = VETOES.get(track)- cmp = Comparison(language=language, name_a=name_a, name_b=name_b, track=track.value, paired=st,- dropped_ids=sorted(set(da) ^ set(db)))- ids = [i for i in st.deltas if i in da and i in db]- crit: dict[str, list[float]] = {}- gates: Counter[str] = Counter()- rises: list[float] = []- costs: list[float] = []- for i in ids:- a, b = da[i], db[i]- for k in set(a.criteria) & set(b.criteria):- crit.setdefault(k, []).append(a.criteria[k] - b.criteria[k])- for k in set(a.gate_errors) | set(b.gate_errors):- gates[k] += a.gate_errors.get(k, 0) - b.gate_errors.get(k, 0)- if veto is not None:- rises.append(veto.count(a) - veto.count(b))- costs.append(a.cost_usd - b.cost_usd)- cmp.criteria_delta = {k: round(statistics.fmean(v), 4) for k, v in sorted(crit.items())}- cmp.gate_error_delta = {k: v for k, v in sorted(gates.items()) if v}- cmp.placement_rise = round(statistics.fmean(rises), 4) if rises else None- cmp.cost_delta = round(statistics.fmean(costs), 4) if costs else None- cmp.decision, cmp.reason = loop_verdict(st, cmp.placement_rise, veto)- return cmp---def compare_dirs(language: str, dir_a: Path, dir_b: Path, *, track: Track = Track.SCENE) -> Comparison:- """Iteration directory ``dir_a`` (the candidate) against ``dir_b`` (the reference), one language."""- cells, name_a, name_b = paired_rows(dir_a, dir_b)- st = paired(cells, name_a, name_b)- return compare_digests(language, name_a, name_b, st, digests_for(dir_a, track=track), digests_for(dir_b, track=track),- track=track)---def render_comparison(c: Comparison) -> str:- st = c.paired- ci = f"[{_f(st.ci95_low, '+.3f')}, {_f(st.ci95_high, '+.3f')}]" if st.ci95_low is not None else "—"- veto = VETOES.get(Track(c.track))- veto_text = (f"{veto.short} ERRORs Δ {_f(c.placement_rise, '+.2f')} per run (veto above {VETO_RISE:+.0f})"- if veto is not None else f"no gate veto on the {c.track} track")- lines = [f"## {c.language}: {c.name_a} − {c.name_b}", "",- f"**{c.decision}** — {c.reason}", "",- f"pairs {st.n} (dropped: outage {st.dropped_infra}, unscored {st.dropped_unscored}, "- f"one side only {len(c.dropped_ids)}); mean picked {_f(st.mean_harness)} vs {_f(st.mean_oneshot)}; "- f"Δ {_f(st.mean_delta, '+.3f')} 95 % t-interval {ci}; W/L/T {st.wins}/{st.losses}/{st.ties}, "- f"sign p {_f(st.sign_p)}; cost Δ {_f(c.cost_delta, '+.2f')} $/run; {veto_text}", ""]- if c.dropped_ids:- lines += ["dropped ids: " + ", ".join(c.dropped_ids), ""]- lines += _kv_table("Δ per criterion (mean a − b)", ((k, _f(v, "+.3f")) for k, v in c.criteria_delta.items()), ("criterion", "Δ"))- lines += _kv_table("Δ gate ERROR findings (Σ a − b over the pairs)", ((k, f"{v:+d}") for k, v in c.gate_error_delta.items()), ("kind", "Δ"))- lines += ["| id | Δ picked |", "|---|---|"] + [f"| {k} | {v:+.3f} |" for k, v in sorted(st.deltas.items())] + [""]- return "\n".join(lines)---# --------------------------------------------------------------------------- judge calibration-class CalibSummary(BaseModel):- """The judge arm of one iteration: is the re-judge noise small against the spread between runs?"""-- language: str- model_id: str- n_samples: int- thinking: str- rounds: int = 0- errors: int = 0- within_sd: float | None = Field(default=None, description="rms of the per-round sample σ: the re-judge noise")- between_sd: float | None = Field(default=None, description="σ of the per-round means: the spread to resolve")- snr: float | None = Field(default=None, description="between_sd / within_sd")- pearson_errors_vs_score: float | None = None- spearman_errors_vs_score: float | None = None- pearson_stored_vs_new: float | None = Field(default=None, description="the in-run verdict against the re-judge")- mean_new: float | None = None- mean_stored: float | None = None- defects: dict[str, int] = Field(default_factory=dict)- caps: dict[str, int] = Field(default_factory=dict)- cost_usd: float = 0.0- latency_s_mean: float | None = None---def calib_summary(language: str, tables: Sequence[CalibrationTable], *, thinking: str) -> CalibSummary:- rows: list[CalibrationRow] = [r for t in tables for r in t.rows]- ok = [r for r in rows if not r.error]- model_id = tables[0].model_id if tables else ""- n_samples = tables[0].n_samples if tables else 0- s = CalibSummary(language=language, model_id=model_id, n_samples=n_samples, thinking=thinking,- rounds=len(rows), errors=len(rows) - len(ok))- if not ok:- return s- s.within_sd = round(math.sqrt(statistics.fmean(r.std ** 2 for r in ok)), 4)- means = [r.mean for r in ok]- s.between_sd = round(statistics.stdev(means), 4) if len(means) > 1 else None- s.snr = round(s.between_sd / s.within_sd, 3) if s.between_sd is not None and s.within_sd else None- gate = [float(r.gate_errors) for r in ok]- s.pearson_errors_vs_score = _r(correlation(gate, means))- s.spearman_errors_vs_score = _r(correlation(gate, means, ranked=True))- stored = [(r.stored_overall, r.mean) for r in ok if r.stored_overall is not None]- s.pearson_stored_vs_new = _r(correlation([a for a, _ in stored], [b for _, b in stored]))- s.mean_new = round(statistics.fmean(means), 4)- s.mean_stored = round(statistics.fmean(a for a, _ in stored), 4) if stored else None- s.defects = dict(Counter(d for r in ok for d in r.defects_present).most_common())- s.caps = dict(Counter(c for r in ok for c in r.caps).most_common())- s.cost_usd = round(sum(r.cost_usd for r in rows), 4)- s.latency_s_mean = round(statistics.fmean(r.duration_s for r in ok), 1)- return s---def _r(v: float | None) -> float | None:- return None if v is None else round(v, 4)---def render_calib(s: CalibSummary) -> str:- lines = [f"## {s.language}: judge {s.model_id}, n_samples {s.n_samples}, thinking {s.thinking}", "",- f"rounds {s.rounds} (errors {s.errors}); within-sd {_f(s.within_sd)} (re-judge noise), "- f"between-sd {_f(s.between_sd)}, SNR {_f(s.snr, '.2f')}; mean new {_f(s.mean_new)} vs stored {_f(s.mean_stored)}; "- f"pearson(gate ERRORs, score) {_f(s.pearson_errors_vs_score, '+.3f')}, spearman {_f(s.spearman_errors_vs_score, '+.3f')}, "- f"pearson(stored, new) {_f(s.pearson_stored_vs_new, '+.3f')}; cost ${s.cost_usd:.2f}, "- f"latency {_f(s.latency_s_mean, '.0f')} s/round", ""]- lines += _kv_table("defects (rounds)", s.defects.items(), ("defect", "rounds"))- lines += _kv_table("caps (rounds)", s.caps.items(), ("rule", "rounds"))- return "\n".join(lines)---__all__ = ["GATE_METRICS", "OBJECT_VETO_CAP", "PLACEMENT_KINDS", "RULES", "VETOES", "VETO_RISE", "CalibSummary", "Comparison", "Diagnosis",- "GateMetric", "Recommendation", "Rule", "RunDigest", "Veto", "calib_summary", "compare_digests", "compare_dirs", "diagnose_digests",- "diagnose_dir", "digest_run", "digests_for", "js_lib_modules", "lib_usage", "loop_verdict",- "py_lib_modules", "render_calib", "render_comparison", "render_diagnosis"]diff --git a/eval/bench/_loop_prompts.py b/eval/bench/_loop_prompts.pydeleted file mode 100644index d1444a50..00000000--- a/eval/bench/_loop_prompts.py+++ /dev/null@@ -1,350 +0,0 @@-"""The rung ladder and the planner-model request behind ``bench.loop generate`` (private).--A loop iteration runs ~15 scene prompts per language (owner, 2026-10-15; was 30 — enough to-pair across iterations, small enough to turn an iteration in hours), and the prompts have to be-two things at once: HARD enough to move (an iteration that scores 0.8 on every prompt has nothing-to learn), and PAIRABLE across iterations (``bench.loop compare`` pairs by prompt id). So the-difficulty lives in a ladder of five rungs, each a set of OBJECTIVE knobs the owner fixed-(zones / asset types / instance cap / lighting / effects), a rung's prompts are generated-ONCE and cached, and an iteration's battery is a mix of the cached rungs up to ``--rung``.--The model does not write the must_have lines. It returns STRUCTURED fields (zones, asset-types with counts, a luminance band, one effect, one animation, a camera brief, ...) and the-loop renders the scenes_v2 composition contract from them (:func:`contract_lines`) — so the-counts always parse, the band is always a band, and the rung rules are checked on typed-fields (:func:`check_prompt`), never by reading numbers back out of prose.--The brief describes a PLACE, never a layout (owner's rule, 2026-10-15): how its zones sit relative-to each other, how high its viewpoint stands and what continues past the detailed area-(``beyond``) are the brief's own choices, and the contract states them as requirements the judge-verifies — not as a shape the builder copies.-"""--from __future__ import annotations--from collections.abc import Sequence-from dataclasses import dataclass-from typing import TYPE_CHECKING, Any, Literal--from pydantic import BaseModel, Field, ValidationError--from codeverse3d.contracts.chat import ChatMessage, ChatRequest-from codeverse3d.contracts.common import Language-from codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient-from codeverse3d.spatial.frame_metrics import DARK_MEAN_LUM--if TYPE_CHECKING:- from bench.run_bench import BenchPrompt--Lighting = Literal["day", "dusk", "night"]-Extra = Literal["interior", "water", "particles"]-Category = Literal["urban", "rural", "nature", "waterfront", "interior", "industrial",- "transport", "fantasy", "historic", "garden"]--#: the four features rungs 4 and 5 count ("two of night+water+interior+particles", "everything")-FEATURE_POOL: tuple[str, ...] = ("night", "water", "interior", "particles")-#: the band every generated luminance band must sit inside — a band outside it asks for a gated-#: scene by construction, and the diagnosis would then blame the variant for the battery. The-#: floor IS the scene_frames gate's threshold (``frame_metrics.DARK_MEAN_LUM``, imported, never a-#: copy that drifts when the gate moves): an authored frame whose mean luminance is below it is a-#: ``dark_frame`` ERROR, capped by the scene rubric. The gate has no ceiling on the mean-#: (``blown_frame`` is a fraction of pure-white pixels, ``frame_metrics.BLOWN_FRAC``), so the-#: ceiling is the loop's own margin under the white point.-LUMINANCE_FLOOR = DARK_MEAN_LUM-LUMINANCE_CEILING = 0.85---@dataclass(frozen=True)-class Rung:- """One difficulty rung: the objective knobs the owner fixed on 2026-10-14."""-- level: int- zones: int # at least this many named zones- asset_types: int # at least this many distinct asset types- instances: int # the counts of every asset type sum to at most this- tier: str # the battery tier the rung's prompts are filed under- require_all: tuple[str, ...] = () # every one of these features- require_any: tuple[str, ...] = () # at least one of these- require_count: int = 0 # at least this many of FEATURE_POOL- forbid: tuple[str, ...] = ()- hero: bool = False # a moving hero asset is named- scale: bool = False # precise scale constraints are stated- brief: str = "" # the one line the generation prompt states---RUNGS: dict[int, Rung] = {- 1: Rung(1, zones=3, asset_types=6, instances=40, tier="medium", require_all=("day",), forbid=("water",),- brief="daylight, no water — a small readable place"),- 2: Rung(2, zones=4, asset_types=8, instances=80, tier="medium", require_any=("dusk", "interior"),- brief="dusk lighting OR an interior"),- 3: Rung(3, zones=5, asset_types=10, instances=150, tier="hard", require_any=("night", "water", "particles"),- brief="night, water or particles"),- 4: Rung(4, zones=6, asset_types=12, instances=250, tier="hard", require_count=2, hero=True,- brief="two of night / water / interior / particles, plus a moving hero"),- 5: Rung(5, zones=6, asset_types=14, instances=400, tier="hard", require_all=FEATURE_POOL, hero=True, scale=True,- brief="night AND water AND an interior AND particles, a moving hero, precise scale constraints"),-}---class AssetCount(BaseModel):- name: str = Field(description="plural noun phrase, e.g. 'market stalls'")- count: int = Field(ge=1, description="how many instances the scene must place")- designs: int = Field(default=1, ge=1, description="distinct designs among them (1 = all alike)")---class GeneratedPrompt(BaseModel):- """What the planner model returns per prompt — typed, so the contract is rendered, not parsed."""-- title: str = Field(description="3-6 words")- category: Category- prompt: str = Field(description="the brief: 2-4 sentences naming the place, its zones, the time of day and one activity")- zones: list[str] = Field(description="named zones, short lowercase phrases; how they relate in space (side by side, "- "nested, stacked, across water, along a road that leaves the frame) is the "- "prompt text's choice")- beyond: str = Field(description="what continues past the detailed area, one clause — the rest of the street, open "- "water to the horizon, more forest, a skyline, farmland, a wall; the place does not "- "stop where its zones stop")- asset_types: list[AssetCount]- lighting: Lighting- features: list[Extra] = Field(default_factory=list)- mood: str = Field(description="the lighting mood in one clause a viewer can verify in a render")- luminance_low: float = Field(ge=0.0, le=1.0, description="mean frame luminance band, low edge")- luminance_high: float = Field(ge=0.0, le=1.0, description="mean frame luminance band, high edge")- effect: str = Field(description="ONE water / weather / particle / shader effect, concrete and visible")- animation: str = Field(description="ONE thing that visibly moves between the sampled times")- camera: str = Field(description="ONE fixed viewpoint — where it stands, what it looks along and its height above "- "the surface it stands on (eye level, 1.6 m, is the usual choice; a balcony, tower, "- "ridge or quay crane is fine when the place has one), e.g. 'at the quay's landward "- "end looking along it at 1.6 m'; a still camera, never a path")- hero: str = Field(default="", description="rungs 4-5: the one hero asset")- hero_motion: str = Field(default="", description="rungs 4-5: how the hero moves")- scale_constraints: list[str] = Field(default_factory=list, description="rung 5: 'the lighthouse is 18 m tall'")-- @property- def feature_set(self) -> frozenset[str]:- return frozenset([self.lighting, *self.features])---class GeneratedBattery(BaseModel):- prompts: list[GeneratedPrompt]---#: one acceptance line per extra feature, fixed wording so every battery states them alike-FEATURE_LINES: dict[str, str] = {- "interior": "interior: the authored cameras are inside the built space — floor, walls and ceiling enclose the view",- "water": "water: a water surface with reflections and visible ripples is in frame from an authored camera",- "particles": "particles: a soft particle effect (dust, steam, sparks, snow, rain) is visible, never hard-edged quads",-}---def check_prompt(gp: GeneratedPrompt, rung: Rung) -> list[str]:- """Every way ``gp`` falls short of ``rung`` — empty when it fits. The loop re-asks with this list."""- problems: list[str] = []- if len(gp.zones) < rung.zones:- problems.append(f"{gp.title!r}: {len(gp.zones)} zones, rung {rung.level} needs at least {rung.zones}")- if len({z.strip().lower() for z in gp.zones}) != len(gp.zones):- problems.append(f"{gp.title!r}: duplicate zone names")- if len(gp.asset_types) < rung.asset_types:- problems.append(f"{gp.title!r}: {len(gp.asset_types)} asset types, rung {rung.level} needs at least {rung.asset_types}")- total = sum(a.count for a in gp.asset_types)- if total > rung.instances:- problems.append(f"{gp.title!r}: {total} instances in total, rung {rung.level} allows at most {rung.instances}")- if not gp.luminance_low < gp.luminance_high:- problems.append(f"{gp.title!r}: luminance band {gp.luminance_low}-{gp.luminance_high} is not low < high")- if gp.luminance_low < LUMINANCE_FLOOR or gp.luminance_high > LUMINANCE_CEILING:- problems.append(f"{gp.title!r}: luminance band must sit inside {LUMINANCE_FLOOR}-{LUMINANCE_CEILING} "- "(the frame gate errors on darker / blown frames)")- have = gp.feature_set- for f in rung.require_all:- if f not in have:- problems.append(f"{gp.title!r}: rung {rung.level} requires {f!r} (has {sorted(have)})")- if rung.require_any and not have & set(rung.require_any):- problems.append(f"{gp.title!r}: rung {rung.level} requires one of {list(rung.require_any)} (has {sorted(have)})")- if rung.require_count and len(have & set(FEATURE_POOL)) < rung.require_count:- problems.append(f"{gp.title!r}: rung {rung.level} requires {rung.require_count} of {list(FEATURE_POOL)} (has {sorted(have)})")- for f in rung.forbid:- if f in have:- problems.append(f"{gp.title!r}: rung {rung.level} forbids {f!r}")- if rung.hero and not (gp.hero.strip() and gp.hero_motion.strip()):- problems.append(f"{gp.title!r}: rung {rung.level} needs a hero and its motion")- if rung.scale and len(gp.scale_constraints) < 2:- problems.append(f"{gp.title!r}: rung {rung.level} needs at least 2 scale constraints")- for field in ("effect", "animation", "camera", "mood", "prompt", "beyond"):- if not getattr(gp, field).strip():- problems.append(f"{gp.title!r}: empty {field}")- return problems---#: The contract's camera line (2026-10-15). Both scene languages render the AUTHORED cameras as stills-#: at t = 0 and t = 1.5 s (``scene_blender.TIMES``, ``scene_threejs`` ``times``) — nothing dollies — so a-#: brief that asked for a tracking camera was a must-have no run could satisfy: the harness planner turns-#: every must_have line into a ``must`` acceptance item, and the judge marked it unverified in 5 of-#: iteration 0's 60 runs ("remains stationary between t=0s and t=1.5s"), which caps the whole score-#: (``missing_must_acceptance``). Every camera line starts with a fixed-form prefix — :func:`migrate_camera_lines`-#: recognises the form by it — and ends with the suffix. ``CAMERA_PREFIX`` is the form written since-#: 2026-10-15: FIXED is interface (stills only), the height is the brief's own (a tower, a balcony, eye level —-#: the harness measures the eye >= 0.3 m above what it stands on and >= 0.5 m from every surface), so the-#: "eye-level" of the first fixed form is no longer baked into an acceptance item the judge verifies.-#: ``LEGACY_CAMERA_PREFIX`` is that first form: the migrated lines of the cached rungs keep it verbatim (they-#: pair iterations), and the migration recognises both forms as already fixed.-CAMERA_PREFIX = "camera: a FIXED camera"-LEGACY_CAMERA_PREFIX = "camera: a FIXED eye-level camera"-CAMERA_SUFFIX = ("; the harness renders still cameras only (nothing dollies or tracks); it never intersects any "- "geometry (no clipping, nothing cut by the near plane)")-FIXED_CAMERA_PREFIXES: tuple[str, ...] = (CAMERA_PREFIX, LEGACY_CAMERA_PREFIX)---def camera_line(camera: str) -> str:- """The must-have line for a viewpoint brief (where it stands, what it looks along, its height)."""- return f"{CAMERA_PREFIX}, {camera.strip()}{CAMERA_SUFFIX}"---def migrate_camera_lines(prompts: Sequence[BenchPrompt]) -> int:- """Rewrite, in place, every ``must_have`` camera line still in the old moving-camera form- (``camera: <route>; the camera never intersects …``) into the fixed form, keeping the route the model- wrote as where the viewpoint stands and looks; returns how many lines changed. Idempotent — a line- already in the fixed form is left alone, as is every non-camera line. The cached rung prompts keep- their ids (they pair iterations), so the line moves and nothing else does."""- n = 0- for p in prompts:- for i, line in enumerate(p.must_have):- if not line.startswith("camera: ") or line.startswith(FIXED_CAMERA_PREFIXES):- continue- route = line.removeprefix("camera: ").split(";", 1)[0].strip()- p.must_have[i] = (f'{LEGACY_CAMERA_PREFIX} standing where this route begins and looking along it — "{route}"'- f"{CAMERA_SUFFIX}")- n += 1- return n---def contract_lines(gp: GeneratedPrompt) -> list[str]:- """The scenes_v2 composition contract rendered from the typed fields (the ``must_have`` list)."""- lines = [f"{len(gp.zones)} zones: {', '.join(z.strip() for z in gp.zones)}",- f"beyond: {gp.beyond.strip()} — the place continues past the detailed zones, visibly, from the authored camera"]- for a in gp.asset_types:- line = f"at least {a.count} {a.name.strip()}"- if a.designs > 1:- line += f" using at least {a.designs} distinct designs"- lines.append(line)- lines.append(f"{gp.lighting} mood: {gp.mood.strip()} (mean luminance roughly "- f"{gp.luminance_low:.2f}-{gp.luminance_high:.2f}, no black or blown-out frames)")- lines.extend(FEATURE_LINES[f] for f in FEATURE_LINES if f in gp.features)- lines.append(f"effect: {gp.effect.strip()}")- lines.append(f"animation: {gp.animation.strip()}")- lines.append(camera_line(gp.camera))- if gp.hero.strip():- lines.append(f"hero: {gp.hero.strip()} — {gp.hero_motion.strip()}")- lines.extend(f"scale: {s.strip()}" for s in gp.scale_constraints if s.strip())- return lines---def instance_total(gp: GeneratedPrompt) -> int:- return sum(a.count for a in gp.asset_types)---# --------------------------------------------------------------------------- the request-SYSTEM = (- "You write evaluation prompts for a procedural 3D scene generator: each prompt describes ONE place "- "that a coding agent builds as a procedural 3D scene (named zones, repeated assets with counts, lighting, "- "one effect, one animation, authored cameras). Prompts are concrete, varied across categories and "- "settings, and buildable procedurally in code (no external models or textures) — no licensed characters, "- "no text-heavy signage, no real people. Describe the place, not a layout: where its zones sit relative to "- "each other, how high its viewpoint stands and what continues past the detailed area are each prompt's own "- "choices, and they should differ from prompt to prompt. Answer ONLY with the JSON the schema describes."-)---def rung_text(rung: Rung) -> str:- lines = [- f"Rung {rung.level} ({rung.tier}): {rung.brief}.",- f"- at least {rung.zones} named zones, each a distinct part of the place the prompt describes; the prompt text "- "says how they sit relative to each other (side by side, nested, stacked, across water, along a road that "- "leaves the frame — the place's own arrangement)",- "- beyond: what continues past the detailed zones (the rest of the street, open water, hills, a skyline, "- "farmland, a wall) — the place does not end where its zones end",- f"- at least {rung.asset_types} distinct asset types, each with an explicit instance count; the counts "- f"must sum to at most {rung.instances} instances in the whole scene",- "- lighting is one of day / dusk / night; extra features are any of interior / water / particles",- f"- a mean-luminance band inside {LUMINANCE_FLOOR:.2f}-{LUMINANCE_CEILING:.2f} that fits the mood "- f"(day ≈ 0.35-0.65, dusk ≈ 0.20-0.45, night ≈ {LUMINANCE_FLOOR:.2f}-0.35)",- "- exactly one effect (water surface, rain, snow, steam, dust, sparks, fog volume, a custom shader material)",- "- exactly one animation (a thing that visibly moves between two sampled times)",- "- a camera brief: ONE fixed viewpoint — where it stands, what it looks along and how high it is (eye level "- "is one option; a tower, balcony, ridge or deck is another when the place has it); the scenes are rendered "- "from still cameras only (nothing dollies or tracks), and the camera never intersects geometry",- ]- if rung.require_all:- lines.append(f"- REQUIRED features: {', '.join(rung.require_all)}")- if rung.require_any:- lines.append(f"- at least one of: {', '.join(rung.require_any)}")- if rung.require_count:- lines.append(f"- at least {rung.require_count} of: {', '.join(FEATURE_POOL)}")- if rung.forbid:- lines.append(f"- FORBIDDEN: {', '.join(rung.forbid)}")- if rung.hero:- lines.append("- name one HERO asset (the thing the scene is about) and how it moves")- if rung.scale:- lines.append("- state at least two PRECISE scale constraints in metres (a named asset's height or span)")- return "\n".join(lines)---def build_request(rung: Rung, n: int, language: Language, *, label: str = "loop:generate",- previous_text: str = "", problems: Sequence[str] = ()) -> ChatRequest:- """The structured request for ``n`` prompts of ``rung``. A re-ask carries the previous answer- (``previous_text``, as the model wrote it) and the typed problems with it, so the model repairs- rather than reinvents."""- user = (- f"Write {n} distinct scene prompts for rung {rung.level}. The scenes will be built in "- f"{'Blender (bpy, Cycles)' if language is Language.SCENE_BLENDER else 'three.js (WebGL)'}; the prompt text "- "itself must stay engine-neutral.\n\n" + rung_text(rung) + "\n\n"- "Spread the prompts over the categories the schema lists (no category more than a quarter of them), "- "vary era, climate and scale, and keep every title unique. Zones are short lowercase phrases; asset "- "type names are plural nouns. A zone named in `zones` must be mentioned in the prompt text."- )- messages = [ChatMessage.user(user)]- if problems:- messages.append(ChatMessage.assistant(previous_text[:60_000] or "(no answer)"))- messages.append(ChatMessage.user(- "Your answer failed these checks — return the FULL corrected list (every prompt, same count), fixing "- "only what the checks name:\n- " + "\n- ".join(problems)))- return ChatRequest(messages=messages, system=SYSTEM, response_schema=GeneratedBattery.model_json_schema(),- temperature=0.9, thinking="medium", max_output_tokens=65_536, max_wait_s=900.0, label=label)---def parse_battery(text: str, parsed: Any = None) -> tuple[GeneratedBattery | None, list[str]]:- """``(battery, problems)``: the model's answer validated against the schema; a parse or validation- failure is a problem the re-ask states, not an exception."""- try:- payload = parsed if parsed is not None else parse_json_lenient(text)- return GeneratedBattery.model_validate(payload), []- except (JsonParseError, ValidationError, TypeError) as e:- return None, [f"the answer did not match the schema: {str(e)[:600]}"]---def check_battery(battery: GeneratedBattery, rung: Rung, n: int) -> list[str]:- """Every problem across the battery: the rung rules per prompt, the count, duplicate titles."""- problems: list[str] = []- if len(battery.prompts) < n:- problems.append(f"{len(battery.prompts)} prompts returned, {n} needed")- titles = [p.title.strip().lower() for p in battery.prompts]- if len(set(titles)) != len(titles):- problems.append("duplicate titles")- for gp in battery.prompts:- problems.extend(check_prompt(gp, rung))- return problems---# --------------------------------------------------------------------------- the mix-def mix_counts(top: int, n: int) -> dict[int, int]:- """How many prompts of each rung 1..``top`` an ``n``-prompt battery takes: an even split, the- remainder to the HARDEST rungs — so a battery at rung 2 keeps half of rung 1's ids (the pairs- ``compare`` needs against the previous iteration) and the other half moves up."""- if top < 1 or top > max(RUNGS):- raise ValueError(f"rung must be 1..{max(RUNGS)}, got {top}")- base, rem = divmod(n, top)- return {r: base + (1 if r > top - rem else 0) for r in range(1, top + 1)}---__all__ = ["CAMERA_PREFIX", "FEATURE_POOL", "LEGACY_CAMERA_PREFIX", "RUNGS", "AssetCount", "GeneratedBattery",- "GeneratedPrompt", "Rung", "build_request", "camera_line", "check_battery", "check_prompt", "contract_lines",- "instance_total", "migrate_camera_lines", "mix_counts", "parse_battery", "rung_text"]diff --git a/eval/bench/_loop_sources.py b/eval/bench/_loop_sources.pydeleted file mode 100644index cf90d0f1..00000000--- a/eval/bench/_loop_sources.py+++ /dev/null@@ -1,182 +0,0 @@-"""Battery selection for the loop's non-scene tracks (private: ``bench.loop generate``).--The scene track writes its own briefs (``_loop_prompts``: a planner model, a rung ladder, cached-ids). The object and graphics tracks already have hand-written batteries under-``bench/prompts/`` whose ids every recorded battery run is keyed by, so the loop SELECTS from-them instead of generating: it pools the source batteries (:func:`pool_sources`), routes each-prompt to the languages it may run in (:func:`route`, :data:`INHERIT_BATTERY_LANGUAGE`), and picks ``n`` per language by the rung's-tier mix (:data:`SOURCE_RUNGS`, :func:`select`). Ids are kept VERBATIM — an iteration's cell is-then the same cell as the recorded battery's, and ``compare`` pairs by id across iterations.--Determinism: the order within a tier is :func:`stable_rank` — sha256 of (loop name, prompt id) —-never file order and never a random draw, so the same rung yields the same ids every iteration-(the pairs) and a prompt added to a source battery later slots in without reshuffling the rest.-"""--from __future__ import annotations--import hashlib-import logging-from collections.abc import Sequence-from dataclasses import dataclass, field-from pathlib import Path-from typing import Literal--from bench.run_bench import Battery, BenchPrompt-from codeverse3d.contracts.common import Language, Track--log = logging.getLogger(__name__)--Order = Literal["hash", "hardest"]---@dataclass(frozen=True)-class TierStep:- """Fill the battery from ``tier``, in ``order``, until it holds ``n`` prompts."""-- tier: str- order: Order = "hash"---#: THE rung table of the non-scene tracks — the tiers a rung draws from, filled in this order-#: until the battery holds ``n``. "hardest" ranks a tier by :func:`demand` (most acceptance items-#: first; :func:`stable_rank` breaks ties); "hash" is :func:`stable_rank` alone. A rung above the-#: table's top uses the top (rung 3+ = hard only). ``easy`` prompts are never drawn: a loop-#: iteration that scores 0.9 everywhere has nothing to learn.-#:-#: ==== ==================================================-#: rung tiers (in fill order)-#: ==== ==================================================-#: 1 medium (hash order), then hard (hash order)-#: 2 hard (hash order), then the hardest medium-#: 3+ hard only (hash order)-#: ==== ==================================================-SOURCE_RUNGS: dict[int, tuple[TierStep, ...]] = {- 1: (TierStep("medium"), TierStep("hard")),- 2: (TierStep("hard"), TierStep("medium", "hardest")),- 3: (TierStep("hard"),),-}---def rung_steps(rung: int) -> tuple[TierStep, ...]:- if rung < 1:- raise ValueError(f"rung must be >= 1, got {rung}")- return SOURCE_RUNGS[min(rung, max(SOURCE_RUNGS))]---def stable_rank(loop_name: str, prompt_id: str) -> str:- """The within-tier order key: sha256 of (loop name, prompt id) — stable across iterations and- machines, different between loops (two loops over one source do not run the same prefix)."""- return hashlib.sha256(f"{loop_name}\0{prompt_id}".encode()).hexdigest()---def demand(p: BenchPrompt) -> int:- """How much a prompt asks for, read off typed fields: its acceptance items (``must_have``, each a- planner acceptance item the judge verifies) plus its stated dimensions (each a contract check)."""- return len(p.must_have) + len(p.dimensions_m or {})---#: the tracks whose source batteries are written for ONE language: a prompt that names no language-#: takes its battery's ``language`` (graphics_v1/v2: "per-prompt `language: opengl_python` marks the-#: raw-OpenGL prompts (battery default is glsl_shader)" — a glsl raymarch brief is not an OpenGL-#: prompt). On the other tracks an unmarked prompt runs in every language of the loop: compare_v4 is-#: a `language: blender` battery whose prompts are blender, three.js and CadQuery prompts alike.-INHERIT_BATTERY_LANGUAGE: frozenset[Track] = frozenset({Track.GRAPHICS})---def normalised_text(text: str) -> str:- return " ".join(text.lower().split())---@dataclass-class Pool:- """Every distinct prompt of the source batteries, in source order (first occurrence wins)."""-- prompts: list[BenchPrompt] = field(default_factory=list)- duplicates: list[str] = field(default_factory=list) # ids dropped: same text as an earlier prompt- id_collisions: list[str] = field(default_factory=list) # ids dropped: an earlier prompt holds the id---def pool_sources(paths: Sequence[Path], track: Track) -> Pool:- """Load every source battery, check it is ``track``'s, and pool its prompts: a prompt whose- normalised text was seen already is a duplicate (the first id wins); a prompt whose id was seen- with OTHER text is a collision (dropped — two cells under one id would never pair). Relative- ``references`` are made absolute: the iteration's battery lives elsewhere. On a track of- :data:`INHERIT_BATTERY_LANGUAGE` an unmarked prompt is stamped with its battery's language."""- pool = Pool()- seen_text: set[str] = set()- seen_id: set[str] = set()- inherit = track in INHERIT_BATTERY_LANGUAGE- for path in paths:- battery = Battery.load(path)- if battery.track != track:- raise ValueError(f"{path}: a {battery.track.value} battery, the loop's track is {track.value}")- base = battery.source_dir or Path(path).resolve().parent- for p in battery.prompts:- key = normalised_text(p.prompt)- if key in seen_text:- pool.duplicates.append(p.id)- continue- if p.id in seen_id:- pool.id_collisions.append(p.id)- log.warning("%s: id %s already names another prompt of the pool: dropped", path, p.id)- continue- seen_text.add(key)- seen_id.add(p.id)- refs = [r if Path(r).is_absolute() else str((base / r).resolve()) for r in p.references]- language = battery.language if inherit and p.language is None else p.language- pool.prompts.append(p.model_copy(update={"references": refs, "language": language}, deep=True))- return pool---def route(prompts: Sequence[BenchPrompt], language: Language) -> list[BenchPrompt]:- """The prompts ``language`` may run: a prompt that names a language goes to that language's- battery only; one that names none goes to every language of the loop (a static prompt is a- blender, three.js and CadQuery prompt alike). Graphics prompts always name one by then- (:func:`pool_sources` stamps the battery's: :data:`INHERIT_BATTERY_LANGUAGE`)."""- return [p for p in prompts if p.language is None or p.language is language]---@dataclass-class Selection:- """What :func:`select` picked: the prompts in battery order, how many per tier, and how many the- rung's tiers held in all (``available`` < ``n`` is a short battery)."""-- prompts: list[BenchPrompt]- tier_counts: dict[str, int]- available: int---def select(prompts: Sequence[BenchPrompt], *, rung: int, n: int, loop_name: str) -> Selection:- """``n`` prompts by the rung's tier mix (:data:`SOURCE_RUNGS`), deterministic. Fewer than ``n``- when the pool's tiers hold fewer — the caller logs it and writes it to generate.json."""- picked: list[BenchPrompt] = []- counts: dict[str, int] = {}- taken: set[str] = set()- steps = rung_steps(rung)- for step in steps:- if len(picked) >= n:- break- tier = [p for p in prompts if p.tier == step.tier and p.id not in taken]- if step.order == "hardest":- tier.sort(key=lambda p: (-demand(p), stable_rank(loop_name, p.id)))- else:- tier.sort(key=lambda p: stable_rank(loop_name, p.id))- chosen = tier[: n - len(picked)]- picked.extend(chosen)- taken.update(p.id for p in chosen)- if chosen:- counts[step.tier] = counts.get(step.tier, 0) + len(chosen)- available = sum(1 for p in prompts if p.tier in {s.tier for s in steps})- return Selection(prompts=picked, tier_counts=counts, available=available)---def rung_table_text() -> str:- """The rung table in one line (written to generate.json beside the rung used)."""- return "; ".join(f"rung {r}{'+' if r == max(SOURCE_RUNGS) else ''}: "- + " then ".join(f"{s.tier}{' (hardest first)' if s.order == 'hardest' else ''}" for s in steps)- for r, steps in SOURCE_RUNGS.items())---__all__ = ["INHERIT_BATTERY_LANGUAGE", "SOURCE_RUNGS", "Pool", "Selection", "TierStep", "demand", "normalised_text", "pool_sources", "route",- "rung_steps", "rung_table_text", "select", "stable_rank"]diff --git a/eval/bench/data/loop/README.md b/eval/bench/data/loop/README.mddeleted file mode 100644index 8faaa9e8..00000000--- a/eval/bench/data/loop/README.md+++ /dev/null@@ -1,39 +0,0 @@-# `bench/data/loop/<name>/ledger.jsonl` — the decisions of a tuning loop--One directory per loop (`bench.loop init --name <name>`), one append-only journal of every-`accept` / `rollback` the loop recorded (`python -m bench.loop accept|rollback --out … --iter N`).-It lives in the repo, not under the ignored `bench/out/`, because an accepted variant version is a-claim about the prompts (`codeverse3d/prompts/variants/<v>/variant.toml` `version`), and a claim-whose evidence is not in the tree is not reproducible. The runs themselves stay under-`bench/out/<loop>/iter_NN/` (big, never committed); the row names what was measured and on what.--Written through `bench/_jsonl.seal_for_append` (a SIGKILL mid-append costs one row, never the file)-and read back as `bench.loop.LedgerRow`, one JSON object per line:--| field | meaning |-|---|---|-| `ts` | ISO-8601 UTC, when the decision was recorded |-| `iteration` | the `iter_NN` the decision is about |-| `languages` | the loop's languages (`scene_threejs`, `scene_blender`) |-| `variant` | the variant name (`argon`) |-| `version_from` → `version_to` | `variant.toml` version before and after: an `accept` bumps it by one; a `rollback` keeps it (working edits discarded) or, when the iteration was itself the latest accept, returns to `version_from` of that accept |-| `variant_hash` | the overlay fingerprint after the decision: `prompts.variants.variant_hash` — the number every run record of the iteration carries (`extra.variant.hash`, `SettingsSnapshot.variant_hash`; `README.md` is left out of it, so a README edit never moves it) — and the same `hash` the snapshot's `snapshot.json` records, so a snapshot pairs with the runs it was measured on. Only an overlay the variant layer does not know (a tmp tree in the tests) falls back to the loop's own sha256[:12] over every file |-| `battery_sha` | sha256[:12] over the iteration's `battery_*.yaml` files — the prompts the verdict was measured on |-| `verdicts` | language → `keep` / `revert` / `inconclusive` from `compare_<lang>.json` (empty when the iteration was never compared: iteration 0, or an accept on diagnosis alone) |-| `decision` | `accept` or `rollback` |-| `cost_usd` | the iteration's spend, summed over its `results.jsonl` rows |-| `tree_commit`, `tree_dirty` | the harness checkout the iteration ran on (`git rev-parse HEAD`; dirty = tracked files modified under `harness/`) |-| `note` | `--note …`, free text: what the iteration changed |--The verdict rule behind `verdicts` is `bench/stats.decide` on the paired picked scores plus the-deterministic-gate veto (`bench/_loop_diag.VETO_RISE`: floating + sunken + interpenetration ERRORs per-run must not rise by more than one on average) — `eval/docs/EVAL.md` §10. The snapshot each accept-takes (`bench/out/<loop>/snapshots/<v>_v<N>/`) is what a later `rollback` restores; `init` snapshots-the version it found so the first rollback has somewhere to go.--Before `accept` (and `init`) bump, snapshot or write anything, the skills overlay is PREFLIGHTED:-`routes.toml` must type-check (`codeverse3d.skills.parse_routes`, the parser `variants_table` runs on-it) and every bundle directory must pass `codeverse3d.skills.validate_bundle`. A run never refuses a-broken overlay — a table that does not type-check is logged and the BASE table routes, an invalid-bundle is skipped — so an iteration whose overlay carries a typo measures nothing about the variant;-the loop is the one place that says no, and a row only ever records an overlay that would route.diff --git a/eval/bench/data/loop/argon_scene/ledger.jsonl b/eval/bench/data/loop/argon_scene/ledger.jsonldeleted file mode 100644index da3a5d92..00000000--- a/eval/bench/data/loop/argon_scene/ledger.jsonl+++ /dev/null@@ -1,3 +0,0 @@-{"ts":"2026-10-15T14:51:19.135961+00:00","iteration":1,"languages":["scene_threejs","scene_blender"],"variant":"argon","version_from":1,"version_to":1,"variant_hash":"eab96d9b3360","battery_sha":"bfacb4b6924b","verdicts":{"scene_threejs":"inconclusive","scene_blender":"inconclusive"},"decision":"rollback","cost_usd":318.9451,"tree_commit":"af4d24ea683eb4891622021e8bbc9bc46e5b8e78","tree_dirty":true,"note":"inconclusive (threejs -0.112±0.168 n=14, blender -0.001±0.188 n=15; blender measured defects fell: interpenetration 0.43→0.13, must-missing 0.33→0.07; threejs lost two zones to build-time crashes and two runs failed at 0 rounds). Superseded by D106 de-templating: the Before-you-return block moves into the iteration-2 overlay."}-{"ts":"2026-10-15T19:40:00.813912+00:00","iteration":3,"languages":["scene_threejs","scene_blender"],"variant":"argon","version_from":1,"version_to":1,"variant_hash":"eab96d9b3360","battery_sha":"e4110fd0cdf7","verdicts":{},"decision":"rollback","cost_usd":246.3576,"tree_commit":"6ab513f1a4400e1ddfab1e47b20e6ceda1cd8002","tree_dirty":true,"note":"it3 vs it2 (same judge): threejs -0.056±0.072, blender -0.013±0.206; driven by hung single-shot asset calls (ladder never passed its timeout: 3/15 threejs and 8/15 blender asset stages ran 32-71 min); runs with a normal asset stage: threejs -0.021, blender +0.071. Fixed in 6ab513f1."}-{"ts":"2026-10-16T09:07:57.343206+00:00","iteration":4,"languages":["scene_threejs","scene_blender"],"variant":"argon","version_from":1,"version_to":2,"variant_hash":"b0efd44507da","battery_sha":"fe55d34261fb","verdicts":{},"decision":"accept","cost_usd":245.1626,"tree_commit":"01415794fe8f1ad03fe7f37ab68fdc04571ceaeb","tree_dirty":true,"note":"it4 vs it0 (same argon judge @medium, n=15): blender 0.755->0.832 +0.077±0.098 (9W/4L), threejs 0.792->0.785 -0.007±0.158; first run with the ladder timeout fix 6ab513f1 (asset stages <=30 min, were up to 71). Overlay empty since D106 (the it1 zone briefs withdrawn); the gain is harness code D106-D108."}diff --git a/eval/bench/loop.py b/eval/bench/loop.pydeleted file mode 100644index 0d18ac4e..00000000--- a/eval/bench/loop.py+++ /dev/null@@ -1,1125 +0,0 @@-"""The argon tuning loop: generate → run → diagnose → compare → judge-calib → accept / rollback.-- cd eval- python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon \\- --languages scene_threejs,scene_blender --generator agy:gemini-4-argon \\- --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 --rounds 2 --max-minutes 90- python -m bench.loop generate --out bench/out/loop_argon --iter 0 [--n 15] [--rung 1]- python -m bench.loop run --out bench/out/loop_argon --iter 0 [--languages scene_threejs] [--resume]- python -m bench.loop diagnose --out bench/out/loop_argon --iter 0- python -m bench.loop compare --out bench/out/loop_argon --iter 1 --against 0- python -m bench.loop judge-calib --out bench/out/loop_argon --iter 1 [--model …] [--thinking medium] [--n 3]- python -m bench.loop accept --out bench/out/loop_argon --iter 1 [--note …]- python -m bench.loop rollback --out bench/out/loop_argon --iter 1- python -m bench.loop status --out bench/out/loop_argon-- # any other track: --track + --source (battery files under bench/prompts/), the rest is the same- python -m bench.loop init --name argon_static --out bench/out/loop_argon_static --variant argon \\- --track static_object --languages blender,threejs,cadquery --source compare_v4.yaml \\- --judge gemini:gemini-4-argon --judge-thinking medium --parallel 8--One iteration = one edit of a per-model prompt/skill VARIANT (``codeverse3d/prompts/variants/<v>/`` +-``codeverse3d/skills/variants/<v>/``, D105) measured on ~15 prompts per language, run in-parallel on the generator under test, judged by ONE fixed judge at ONE thinking level. ``init``-freezes every knob in ``<out>/loop.json``; everything else reads it, so two iterations never differ-in anything but the variant and (when ``--rung`` moves) the prompt mix.--The track decides where the prompts come from: the scene track GENERATES its briefs (a planner-model on a rung ladder, ``_loop_prompts``); every other track SELECTS from its hand-written-batteries (``--source``, ids verbatim, the rung picks the tier mix: ``_loop_sources``). Diagnose-and compare read the track's own gates (``_loop_diag``); the rest of the loop does not care.--Layout of ``<out>``::-- loop.json the fixed configuration (init)- prompts/rung_R_<lang>.yaml a rung's prompts, generated ONCE and reused (stable ids → pairs; scene only)- snapshots/<v>_v<N>/ the overlay dirs as accepted at version N (init writes v<current>)- iter_NN/battery_<lang>.yaml the iteration's battery (a rung mix), generate.json its composition- iter_NN/<lang>/ one ``bench.run_bench`` output per language (runs/, results.jsonl)- iter_NN/run.json child pids, exit codes, wall; run_<lang>.log their stdout- iter_NN/diagnosis.{md,json} diagnose; compare_<lang>.{md,json} compare; judge_calib_<lang>.{md,json}--The ledger of decisions lives IN the repo — ``bench/data/loop/<name>/ledger.jsonl`` (format:-``bench/data/loop/README.md``) — because an accepted variant version is a claim about the prompts,-and a claim whose evidence is under the ignored ``bench/out/`` is not reproducible.-"""--from __future__ import annotations--import argparse-import hashlib-import json-import logging-import os-import shutil-import signal-import subprocess-import sys-import time-import tomllib-from collections.abc import Callable, Sequence-from concurrent.futures import ThreadPoolExecutor-from contextlib import suppress-from dataclasses import dataclass-from datetime import UTC, datetime-from pathlib import Path-from typing import Any, Literal--import yaml-from pydantic import BaseModel, Field, model_validator--for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):- if str(_p) not in sys.path: # this tree's codeverse3d (harness/) + the `bench` package (eval/)- sys.path.insert(0, str(_p))--from bench._jsonl import read_jsonl, seal_for_append # noqa: E402-from bench._loop_diag import ( # noqa: E402- CalibSummary,- Comparison,- Diagnosis,- calib_summary,- compare_dirs,- diagnose_dir,- digests_for,- render_calib,- render_comparison,- render_diagnosis,-)-from bench._loop_prompts import ( # noqa: E402- RUNGS,- GeneratedBattery,- build_request,- check_battery,- contract_lines,- migrate_camera_lines,- mix_counts,- parse_battery,-)-from bench._loop_sources import ( # noqa: E402- pool_sources,- route,- rung_steps,- rung_table_text,- select,-)-from bench.run_bench import Battery, BenchPrompt # noqa: E402-from codeverse3d.config import get_settings # noqa: E402-from codeverse3d.contracts.common import TRACK_LANGUAGES, Language, Track # noqa: E402-from codeverse3d.proc import install_stop_handlers, write_json_atomic # noqa: E402--log = logging.getLogger(__name__)--REPO = Path(__file__).resolve().parents[1] # eval/ — the children run `python -m bench.run_bench` here-HARNESS = REPO.parent / "harness" # the tree whose variant the loop edits-DATA_DIR = REPO / "bench" / "data" / "loop" # the ledgers (in git)-PROMPTS_DIR = REPO / "bench" / "prompts" # where --source names resolve-LOOP_JSON = "loop.json"-VARIANT_TOML = "variant.toml"-#: the machine-wide Cycles slots the children share: 30 parallel runs render on ONE GPU, and-#: `Render.blender_gpu_slots` defaults to 2 for an interactive box (D104 measured 0.21-0.64 s/frame-#: on the GPU vs 2.3 s on the CPU, so a third slot is worth more than a third CPU render; five slots fit the-#: memory the renders measured)-BLENDER_GPU_SLOTS = "5" # 3 → 5 on 2026-10-15: 24 GB of GPU memory sat at 2.7 GB with 30 runs; the owner asked for more parallelism-#: how long a stopped driver waits for a child to record its stop before SIGKILL: the child's own-#: stop handler (`run_bench.main` installs it) unwinds within `proc.STOP_GRACE_S` = 30 s-CHILD_STOP_GRACE_S = 45.0--Thinking = Literal["off", "low", "medium", "high"]---class LoopError(RuntimeError):- """A misconfiguration or a missing prerequisite — exit 2, never a traceback."""---# --------------------------------------------------------------------------- configuration-class LoopConfig(BaseModel):- """Everything an iteration runs with, frozen by ``init`` into ``<out>/loop.json``."""-- schema_version: int = 1- name: str- out: Path- variant: str- languages: list[Language]- generator: str- judge: str- judge_thinking: Thinking = "medium"- planner: str = Field(default="", description="the battery-generation model; '' = Settings.default_planner")- parallel: int = Field(default=15, ge=1, description="run_bench workers PER LANGUAGE (the languages run side by side)")- stagger_s: float = Field(default=40.0, ge=0.0,- description="seconds between the launches of each child's first wave of workers "- "(run_bench --stagger); the children themselves launch stagger_s/2 apart")- rounds: int = Field(default=2, ge=0)- max_minutes: float = Field(default=90.0, gt=0)- n: int = Field(default=15, ge=1, description="prompts per battery") # 30 → 15 (owner, 2026-10-15)- track: Track = Track.SCENE- source: list[str] = Field(default_factory=list,- description="the battery files a non-scene track selects from (relative to eval/, "- "absolute only outside it); the scene track generates its own and takes none")- created_at: str = ""-- @model_validator(mode="after")- def _track_languages(self) -> LoopConfig:- """``--track`` decides: the languages must be that track's, and every track but scene names- its source batteries (a loop.json written before ``source`` existed is a scene loop and loads)."""- allowed = TRACK_LANGUAGES[self.track]- v = self.languages- bad = [x.value for x in v if x not in allowed]- if not v or bad:- raise ValueError(f"languages must be non-empty {self.track.value} languages {[a.value for a in allowed]}, "- f"got {bad or v}")- if len(set(v)) != len(v):- raise ValueError(f"duplicate languages: {[x.value for x in v]}")- if self.track is Track.SCENE and self.source:- raise ValueError("the scene track generates its own briefs: --source is for the other tracks")- if self.track is not Track.SCENE and not self.source:- raise ValueError(f"a {self.track.value} loop selects from battery files: --source is required")- return self-- def iter_dir(self, iteration: int) -> Path:- return self.out / f"iter_{iteration:02d}"-- def save(self) -> Path:- self.out.mkdir(parents=True, exist_ok=True)- write_json_atomic(self.out / LOOP_JSON, self.model_dump(mode="json"))- return self.out / LOOP_JSON-- @classmethod- def load(cls, out: Path | str) -> LoopConfig:- p = Path(out) / LOOP_JSON- if not p.is_file():- raise LoopError(f"no {LOOP_JSON} under {out}: run `bench.loop init --out {out} …` first")- return cls.model_validate_json(p.read_text())---def parse_languages(text: str) -> list[Language]:- try:- return [Language(x.strip()) for x in text.split(",") if x.strip()]- except ValueError as e:- raise LoopError(f"unknown language in {text!r}: {e}") from e---def source_path(entry: str) -> Path:- """A ``LoopConfig.source`` entry on disk (relative entries are relative to eval/)."""- p = Path(entry)- return p if p.is_absolute() else REPO / p---def parse_sources(text: str) -> list[str]:- """``--source a.yaml,bench/prompts/b.yaml,/abs/c.yaml`` → the entries ``LoopConfig.source`` keeps:- a bare name resolves under ``bench/prompts/``, a relative path under eval/; a file under eval/ is- stored relative to it (loop.json stays portable), anything else absolute. A missing file is a- configuration error here, before init writes anything."""- out: list[str] = []- for raw in (x.strip() for x in text.split(",")):- if not raw:- continue- given = Path(raw).expanduser()- candidates = [given] if given.is_absolute() else [REPO / given, PROMPTS_DIR / given]- hit = next((c.resolve() for c in candidates if c.is_file()), None)- if hit is None:- raise LoopError(f"--source {raw!r}: no such battery file (looked at {[str(c) for c in candidates]})")- entry = hit.relative_to(REPO.resolve()).as_posix() if hit.is_relative_to(REPO.resolve()) else str(hit)- if entry not in out:- out.append(entry)- return out---# --------------------------------------------------------------------------- the variant overlay-def _variants_api() -> Any:- """``codeverse3d.prompts.variants`` (Lane V, D105) or a clear error — the loop reads a variant's- root and hash through it, and `run` hands the name to the children."""- try:- from codeverse3d.prompts import variants- except ImportError as e:- raise LoopError("this tree has no codeverse3d.prompts.variants (the D105 variant layer): "- "the loop's variant plumbing needs it") from e- missing = [n for n in ("variant_info", "variant_root", "variant_hash") if not hasattr(variants, n)]- if missing:- raise LoopError(f"codeverse3d.prompts.variants lacks {missing} (the design §0 contract)")- return variants---def _variants_api_or_none() -> Any | None:- try:- return _variants_api()- except LoopError as e:- log.warning("%s", e)- return None---def _check_variant_name(name: str) -> None:- """An unknown variant name is a configuration error (exit 2), caught where the layer is present."""- api = _variants_api_or_none()- if api is None or not name:- return- try:- api.variant_info(name)- except ValueError as e:- raise LoopError(str(e)) from e---@dataclass(frozen=True)-class VariantPaths:- """The two overlay directories of one variant, and the operations the loop does on them.- Injectable (tests point them at a tmp tree); :meth:`default` resolves the real ones."""-- name: str- prompts_root: Path- skills_root: Path-- @classmethod- def default(cls, name: str) -> VariantPaths:- from codeverse3d.prompts import PROMPTS_DIR- from codeverse3d.skills import skills_dir-- api = _variants_api_or_none()- prompts_root = Path(api.variant_root(name)) if api is not None else PROMPTS_DIR / "variants" / name- return cls(name=name, prompts_root=prompts_root, skills_root=skills_dir() / "variants" / name)-- @property- def toml(self) -> Path:- return self.prompts_root / VARIANT_TOML-- def version(self) -> int:- if not self.toml.is_file():- raise LoopError(f"no {VARIANT_TOML} under {self.prompts_root}: is {self.name!r} a variant?")- data = tomllib.loads(self.toml.read_text())- try:- return int(data["variant"]["version"])- except (KeyError, TypeError, ValueError) as e:- raise LoopError(f"{self.toml}: [variant].version is missing or not an integer ({e})") from e-- def set_version(self, new: int) -> None:- """Rewrite ONLY the ``version = N`` line of the ``[variant]`` table (comments and the other keys- stay as the author wrote them), and read it back through tomllib before trusting it."""- out: list[str] = []- table, done = "", False- for line in self.toml.read_text().splitlines(keepends=True):- s = line.strip()- if s.startswith("[") and s.endswith("]"):- table = s[1:-1].strip()- elif table == "variant" and not done and not s.startswith("#") and s.split("=", 1)[0].strip() == "version":- indent = line[: len(line) - len(line.lstrip())]- line = f"{indent}version = {new}\n"- done = True- out.append(line)- if not done:- raise LoopError(f"{self.toml}: no `version = N` line in [variant] to bump")- self.toml.write_text("".join(out))- if self.version() != new:- raise LoopError(f"{self.toml}: wrote version {new} but read back {self.version()}")-- def files(self) -> list[tuple[str, bytes]]:- """``(relpath, bytes)`` of every overlay file, sorted — ``prompts/…`` and ``skills/…``."""- out: list[tuple[str, bytes]] = []- for label, root in (("prompts", self.prompts_root), ("skills", self.skills_root)):- if not root.is_dir():- continue- for p in sorted(root.rglob("*")):- if p.is_file() and "__pycache__" not in p.parts and p.suffix != ".pyc":- out.append((f"{label}/{p.relative_to(root).as_posix()}", p.read_bytes()))- return out-- def overlay_hash(self) -> str:- """sha256[:12] over the sorted (relpath, bytes) of EVERY overlay file — the loop's own- fingerprint, used ONLY as the fallback of :meth:`ledger_hash` for a tree the variant layer- does not know (the tests' tmp overlays). It is not the number a run record carries: Lane V's- ``variant_hash`` leaves ``README.md`` out (documentation, not prompt material), so the two- differ for the shipped overlay by exactly that file."""- h = hashlib.sha256()- for rel, data in self.files():- h.update(rel.encode("utf-8") + b"\0" + data + b"\0")- return h.hexdigest()[:12]-- def ledger_hash(self) -> str:- """THE hash of this overlay: ``prompts.variants.variant_hash`` — what every run record of the- iteration carries (``extra.variant.hash``, ``SettingsSnapshot.variant_hash``) — whenever these- paths are the real overlay; :meth:`overlay_hash` only for a tmp tree. The ledger row and the- snapshot both write this one, so a snapshot can be paired with the runs it was measured on."""- api = _variants_api_or_none()- if api is not None:- try:- if Path(api.variant_root(self.name)).resolve() == self.prompts_root.resolve():- return str(api.variant_hash(self.name))- except Exception as e: # noqa: BLE001 — an unknown name in a tmp tree: fall back- log.debug("variant_hash(%s) unavailable: %s", self.name, e)- return self.overlay_hash()-- def preflight(self) -> None:- """Refuse a broken skills overlay BEFORE it is versioned, snapshotted or written to the ledger.-- At run time the harness degrades silently — ``skills.variants_table`` logs a ``routes.toml``- that does not type-check and routes with the BASE table, ``iter_skills(strict=False)`` skips- an invalid overlay bundle — so an iteration whose overlay carries a typo measures the base- routing, its verdict is about nothing, and nothing would stop ``accept`` recording it as a new- version. This is where the loop says no, with the parsers the run uses: ``skills.parse_routes``- on the overlay's table (what ``variants_table`` calls on that file) and ``skills.validate_bundle``- on every bundle directory under the overlay. The first problem is a :class:`LoopError`."""- from codeverse3d.skills import ROUTES_FILE, bundle_dirs, parse_routes, validate_bundle-- routes = self.skills_root / ROUTES_FILE- if routes.is_file():- try:- parse_routes(routes, variant=self.name)- except ValueError as e:- raise LoopError(f"variant {self.name!r}: {ROUTES_FILE} does not type-check (a run would route "- f"with the base table): {e}") from e- for bundle in bundle_dirs(self.skills_root):- problems = validate_bundle(bundle)- if problems:- raise LoopError(f"variant {self.name!r}: skill bundle {bundle.name} ({bundle}) is invalid (a run "- f"would skip it): " + "; ".join(problems))-- def snapshot_to(self, dest: Path) -> Path:- """Copy both overlay dirs under ``dest/{prompts,skills}`` (replacing an older copy). The- ``snapshot.json`` beside them carries :meth:`ledger_hash` — the same number as the ledger row- and the iteration's run records, never the loop-private :meth:`overlay_hash`."""- if dest.exists():- shutil.rmtree(dest)- for label, root in (("prompts", self.prompts_root), ("skills", self.skills_root)):- if root.is_dir():- shutil.copytree(root, dest / label, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))- (dest / "snapshot.json").write_text(json.dumps({- "variant": self.name, "version": self.version(), "hash": self.ledger_hash(),- "taken_at": datetime.now(UTC).isoformat(), "prompts_root": str(self.prompts_root),- "skills_root": str(self.skills_root)}, indent=2))- return dest-- def restore_from(self, src: Path) -> None:- """Make both overlay dirs equal to the snapshot (a part the snapshot lacks is removed)."""- if not (src / "snapshot.json").is_file():- raise LoopError(f"{src} is not a loop snapshot (no snapshot.json)")- for label, root in (("prompts", self.prompts_root), ("skills", self.skills_root)):- if root.parent.name != "variants" or root.name != self.name:- raise LoopError(f"refusing to replace {root}: not a variants/<{self.name}> overlay directory")- if root.exists():- shutil.rmtree(root)- if (src / label).is_dir():- shutil.copytree(src / label, root)---def snapshot_dir(cfg: LoopConfig, version: int) -> Path:- return cfg.out / "snapshots" / f"{cfg.variant}_v{version}"---# --------------------------------------------------------------------------- init-def init(cfg: LoopConfig, *, paths: VariantPaths | None = None) -> Path:- """Write ``loop.json`` and snapshot the overlay as it stands (``snapshots/<v>_v<current>``), so the- first ``rollback`` has a state to return to. A missing variant layer only costs the snapshot; a- skills overlay that would not route (:meth:`VariantPaths.preflight`) is refused before anything- is written."""- if (cfg.out / LOOP_JSON).is_file():- raise LoopError(f"{cfg.out / LOOP_JSON} exists: one loop per --out (status / iterations read it)")- missing = [s for s in cfg.source if not source_path(s).is_file()]- if missing:- raise LoopError(f"source batteries not found: {missing}")- _check_variant_name(cfg.variant) # before any money is spent- vp = paths or VariantPaths.default(cfg.variant)- vp.preflight()- cfg.created_at = datetime.now(UTC).isoformat()- p = cfg.save()- if vp.toml.is_file():- dest = snapshot_dir(cfg, vp.version())- if not dest.exists():- vp.snapshot_to(dest)- else:- log.warning("no %s under %s: no snapshot taken", VARIANT_TOML, vp.prompts_root)- return p---# --------------------------------------------------------------------------- generate-def rung_cache(cfg: LoopConfig, lang: Language, rung: int) -> Path:- return cfg.out / "prompts" / f"rung_{rung}_{lang.value}.yaml"---def generation_meta(cfg: LoopConfig, iteration: int) -> dict[str, Any] | None:- p = cfg.iter_dir(iteration) / "generate.json"- return json.loads(p.read_text()) if p.is_file() else None---def default_rung(cfg: LoopConfig, iteration: int) -> int:- """No ``--rung``: the previous iteration's (so the pairs are complete), else 1."""- for i in range(iteration - 1, -1, -1):- meta = generation_meta(cfg, i)- if meta is not None:- return int(meta["rung"])- return 1---def rung_prompts(cfg: LoopConfig, lang: Language, rung: int, *, iteration: int,- chat_model: Any = None) -> list[BenchPrompt]:- """The rung's prompts for ``lang`` — from the cache, else generated once (one re-ask on a typed- failure) and cached under ``prompts/rung_R_<lang>.yaml`` with the ids they will keep forever."""- cache = rung_cache(cfg, lang, rung)- if cache.is_file():- data = yaml.safe_load(cache.read_text())- prompts = [BenchPrompt.model_validate(p) for p in data["prompts"]]- migrated = migrate_camera_lines(prompts)- if migrated:- # a cache written before 2026-10-15 carries the moving-camera line (iteration 0 ran with- # it): the ids stay — they pair iterations — and only that line moves, in the file too- data["prompts"] = [p.model_dump(mode="json", exclude_defaults=True) for p in prompts]- data["camera_lines_migrated"] = {"n": migrated, "at": datetime.now(UTC).isoformat()}- _write_cache(cache, data)- log.info("rung %d %s: migrated %d camera line(s) to the fixed-camera form in %s",- rung, lang.value, migrated, cache)- return prompts- r = RUNGS[rung]- if chat_model is None:- from codeverse3d.models.registry import get_chat_model-- chat_model = get_chat_model(cfg.planner or get_settings().backends().planner)- resp = chat_model.generate(build_request(r, cfg.n, lang))- battery, problems = parse_battery(resp.text, resp.parsed)- if battery is not None:- problems = check_battery(battery, r, cfg.n)- if problems:- log.warning("rung %d %s: %d problem(s), re-asking once: %s", rung, lang.value, len(problems), problems[:3])- previous = resp.text or (json.dumps(resp.parsed) if resp.parsed is not None else "")- resp = chat_model.generate(build_request(r, cfg.n, lang, previous_text=previous, problems=problems,- label="loop:generate-reask"))- battery, problems = parse_battery(resp.text, resp.parsed)- if battery is not None:- problems = check_battery(battery, r, cfg.n)- if problems or battery is None:- raise LoopError(f"rung {rung} prompts for {lang.value} failed the rung rules after one re-ask:\n- "- + "\n- ".join(problems))- prompts = _bench_prompts(battery, lang, rung, iteration=iteration, n=cfg.n)- _write_cache(cache, {- "rung": rung, "language": lang.value, "n": len(prompts), "generated_at_iteration": iteration,- "model": str(getattr(chat_model, "id", "")), "generated_at": datetime.now(UTC).isoformat(),- "prompts": [p.model_dump(mode="json", exclude_defaults=True) for p in prompts],- })- return prompts---def _write_cache(cache: Path, data: dict[str, Any]) -> None:- cache.parent.mkdir(parents=True, exist_ok=True)- cache.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))---def _bench_prompts(battery: GeneratedBattery, lang: Language, rung: int, *, iteration: int, n: int) -> list[BenchPrompt]:- r = RUNGS[rung]- return [BenchPrompt(id=f"it{iteration:02d}_{lang.value}_r{rung}_{k:02d}", prompt=" ".join(gp.prompt.split()),- tier=r.tier, category=gp.category, must_have=contract_lines(gp),- tags=[f"rung{rung}", gp.lighting, *gp.features, gp.title])- for k, gp in enumerate(battery.prompts[:n], 1)]---def _write_battery(path: Path, battery: Battery) -> None:- data = battery.model_dump(mode="json")- Battery.model_validate(data) # what the file will load as, not what we built- path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))---def generate_iteration(cfg: LoopConfig, iteration: int, *, rung: int | None = None, n: int | None = None,- chat_model: Any = None) -> dict[Language, Path]:- """Write ``iter_NN/battery_<lang>.yaml`` per language. Scene: a mix of the cached rungs up to- ``rung`` (:func:`bench._loop_prompts.mix_counts`); any other track: a selection from its source- batteries (:func:`generate_from_sources`). Validated through ``Battery`` before it is written."""- rung = default_rung(cfg, iteration) if rung is None else rung- if rung not in RUNGS:- raise LoopError(f"--rung must be one of {sorted(RUNGS)}, got {rung}")- if cfg.track is not Track.SCENE:- return generate_from_sources(cfg, iteration, rung=rung, n=n)- size = n or cfg.n- counts = mix_counts(rung, size)- iter_dir = cfg.iter_dir(iteration)- iter_dir.mkdir(parents=True, exist_ok=True)- out: dict[Language, Path] = {}- ids: dict[str, list[str]] = {}- for lang in cfg.languages:- prompts: list[BenchPrompt] = []- for level, k in counts.items():- cached = rung_prompts(cfg, lang, level, iteration=iteration, chat_model=chat_model)- if len(cached) < k:- log.warning("rung %d %s holds %d prompts, the mix wanted %d", level, lang.value, len(cached), k)- prompts.extend(cached[:k])- battery = Battery(name=f"{cfg.name}_it{iteration:02d}_{lang.value}", track=cfg.track, language=lang,- description=f"loop {cfg.name} iteration {iteration}: {size} scene prompts, rungs "- + ", ".join(f"{lvl}×{c}" for lvl, c in counts.items()),- prompts=prompts)- path = iter_dir / f"battery_{lang.value}.yaml"- _write_battery(path, battery)- out[lang] = path- ids[lang.value] = [p.id for p in prompts]- write_json_atomic(iter_dir / "generate.json", {- "iteration": iteration, "rung": rung, "n": size, "mix": {str(k): v for k, v in counts.items()},- "languages": [x.value for x in cfg.languages], "batteries": {k.value: str(v) for k, v in out.items()},- "ids": ids, "generated_at": datetime.now(UTC).isoformat()})- return out---def generate_from_sources(cfg: LoopConfig, iteration: int, *, rung: int, n: int | None = None) -> dict[Language, Path]:- """A non-scene iteration's batteries: the source batteries pooled (deduped by prompt text, ids- verbatim), routed per language (a prompt naming a language goes to that language only) and- selected by the rung's tier mix (``_loop_sources.SOURCE_RUNGS``, stable-hash order — the same- rung gives the same ids every iteration). A pool too small for ``n`` gives a shorter battery,- logged and written to generate.json (``short``), never silently capped."""- size = n or cfg.n- paths = [source_path(s) for s in cfg.source]- missing = [str(p) for p in paths if not p.is_file()]- if missing:- raise LoopError(f"source batteries not found: {missing}")- try:- pool = pool_sources(paths, cfg.track)- except (OSError, ValueError) as e: # a pydantic ValidationError is a ValueError- raise LoopError(f"cannot pool the source batteries: {e}") from e- if pool.duplicates:- log.info("%d prompt(s) repeat an earlier prompt's text and are dropped: %s", len(pool.duplicates), pool.duplicates)- iter_dir = cfg.iter_dir(iteration)- iter_dir.mkdir(parents=True, exist_ok=True)- tiers = [s.tier for s in rung_steps(rung)]- out: dict[Language, Path] = {}- ids: dict[str, list[str]] = {}- tier_counts: dict[str, dict[str, int]] = {}- short: dict[str, dict[str, int]] = {}- for lang in cfg.languages:- sel = select(route(pool.prompts, lang), rung=rung, n=size, loop_name=cfg.name)- if not sel.prompts:- raise LoopError(f"no {'/'.join(tiers)} prompt of {cfg.source} runs in {lang.value} (rung {rung})")- if len(sel.prompts) < size:- log.warning("%s: the sources hold %d %s prompt(s) for rung %d, n is %d — the battery runs %d",- lang.value, sel.available, "/".join(tiers), rung, size, len(sel.prompts))- short[lang.value] = {"wanted": size, "got": len(sel.prompts)}- battery = Battery(name=f"{cfg.name}_it{iteration:02d}_{lang.value}", track=cfg.track, language=lang,- description=f"loop {cfg.name} iteration {iteration}: {len(sel.prompts)} {cfg.track.value} "- f"prompts selected from {', '.join(cfg.source)}, rung {rung} ("- + ", ".join(f"{t}×{c}" for t, c in sel.tier_counts.items()) + ")",- prompts=sel.prompts)- path = iter_dir / f"battery_{lang.value}.yaml"- _write_battery(path, battery)- out[lang] = path- ids[lang.value] = [p.id for p in sel.prompts]- tier_counts[lang.value] = sel.tier_counts- write_json_atomic(iter_dir / "generate.json", {- "iteration": iteration, "track": cfg.track.value, "rung": rung, "n": size,- "tiers": [[s.tier, s.order] for s in rung_steps(rung)], "rung_table": rung_table_text(),- "sources": list(cfg.source),- "pool": {"size": len(pool.prompts), "duplicates": pool.duplicates, "id_collisions": pool.id_collisions},- "languages": [x.value for x in cfg.languages], "batteries": {k.value: str(v) for k, v in out.items()},- "tier_counts": tier_counts, "short": short, "ids": ids, "generated_at": datetime.now(UTC).isoformat()})- return out---# --------------------------------------------------------------------------- run-def child_argv(cfg: LoopConfig, lang: Language, battery: Path, out_lang: Path, *, resume: bool) -> list[str]:- """The ``python -m bench.run_bench`` command line of one language's child."""- argv = [sys.executable, "-m", "bench.run_bench", str(battery), "--out", str(out_lang),- "--generator", cfg.generator, "--judge", cfg.judge, "--parallel", str(cfg.parallel),- "--rounds", str(cfg.rounds), "--max-minutes", str(cfg.max_minutes), "--no-report"]- if cfg.planner:- argv += ["--planner", cfg.planner]- if cfg.variant:- argv += ["--variant", cfg.variant]- if cfg.stagger_s > 0:- argv += ["--stagger", str(cfg.stagger_s)]- if resume:- argv += ["--redo-status", "infra_failed"]- return argv---def child_env(cfg: LoopConfig, base: dict[str, str] | None = None) -> dict[str, str]:- """The children's environment: the judge's thinking level, the variant (belt and braces beside- ``--variant``: every process of the run reads it), three GPU render slots, unbuffered logs."""- env = dict(os.environ if base is None else base)- env["C3D_JUDGE__THINKING"] = cfg.judge_thinking- if cfg.variant:- env["C3D_VARIANT"] = cfg.variant- else:- env.pop("C3D_VARIANT", None)- env["C3D_RENDER__BLENDER_GPU_SLOTS"] = BLENDER_GPU_SLOTS- env["PYTHONUNBUFFERED"] = "1"- return env---def _terminate(proc: Any) -> None:- """SIGTERM the child's group (its own stop handler records the stop), SIGKILL after the grace."""- try:- os.killpg(proc.pid, signal.SIGTERM)- except (ProcessLookupError, PermissionError, AttributeError, TypeError):- with suppress(Exception):- proc.terminate()- deadline = time.monotonic() + CHILD_STOP_GRACE_S- while time.monotonic() < deadline and proc.poll() is None:- time.sleep(0.2)- if proc.poll() is None:- with suppress(Exception):- os.killpg(proc.pid, signal.SIGKILL)---def run_iteration(cfg: LoopConfig, iteration: int, *, languages: Sequence[Language] = (), resume: bool = False,- popen: Callable[..., Any] = subprocess.Popen) -> dict[str, Any]:- """One child process per language, side by side (``parallel`` runs each), SIGTERM forwarded on a- stop; ``iter_NN/run.json`` carries pids while they run and exit codes + wall after."""- install_stop_handlers()- _check_variant_name(cfg.variant)- iter_dir = cfg.iter_dir(iteration)- langs = list(languages) or cfg.languages- meta: dict[str, Any] = {"iteration": iteration, "started_at": datetime.now(UTC).isoformat(), "resume": resume,- "children": {}}- children: dict[str, tuple[Any, Any]] = {}- t0 = time.monotonic()- try:- for lang in langs:- battery = iter_dir / f"battery_{lang.value}.yaml"- if not battery.is_file():- raise LoopError(f"no {battery.name} under {iter_dir}: run `bench.loop generate --iter {iteration}` first")- out_lang = iter_dir / lang.value- log_path = iter_dir / f"run_{lang.value}.log"- argv = child_argv(cfg, lang, battery, out_lang, resume=resume)- if children and cfg.stagger_s > 0:- # The languages' first waves interleave. agy holds ONE session per key machine-wide- # and there are 30 keys, so 15 + 15 parallel runs plus the harness's own planner /- # asset / judge calls all draw on the same 64-slot pool; two children launched- # together plan and single-shot their assets in the same minute and exhaust it- # (iteration 0: 160 of its 172 `asset.generate_failed` outages fell in the first ten- # minutes). Each child staggers its own first wave by stagger_s (`--stagger`); half- # that between the children puts one language's k-th launch between the other's.- time.sleep(cfg.stagger_s / 2)- fh = log_path.open("a")- fh.write(f"--- {datetime.now(UTC).isoformat()} {' '.join(argv)}\n")- fh.flush()- proc = popen(argv, cwd=str(REPO), env=child_env(cfg), stdout=fh, stderr=subprocess.STDOUT,- start_new_session=True)- children[lang.value] = (proc, fh)- meta["children"][lang.value] = {"argv": argv, "pid": proc.pid, "log": str(log_path), "out": str(out_lang),- "returncode": None}- write_json_atomic(iter_dir / "run.json", meta)- while any(p.poll() is None for p, _ in children.values()):- time.sleep(0.5)- except BaseException: # SystemExit(143) from the stop handler, KeyboardInterrupt, a LoopError mid-launch- for p, _ in children.values():- if p.poll() is None:- _terminate(p)- raise- finally:- for name, (p, fh) in children.items():- meta["children"][name]["returncode"] = p.poll()- fh.close()- meta["finished_at"] = datetime.now(UTC).isoformat()- meta["wall_s"] = round(time.monotonic() - t0, 1)- write_json_atomic(iter_dir / "run.json", meta)- return meta---# --------------------------------------------------------------------------- diagnose / compare / judge-calib-def _present(cfg: LoopConfig, iteration: int, languages: Sequence[Language] = ()) -> list[tuple[Language, Path]]:- out: list[tuple[Language, Path]] = []- for lang in (list(languages) or cfg.languages):- d = cfg.iter_dir(iteration) / lang.value- if d.is_dir():- out.append((lang, d))- else:- log.warning("iteration %d has no %s output (%s)", iteration, lang.value, d)- if not out:- raise LoopError(f"iteration {iteration} has no run output under {cfg.iter_dir(iteration)}")- return out---def diagnose_iteration(cfg: LoopConfig, iteration: int, *, languages: Sequence[Language] = ()) -> dict[str, Diagnosis]:- out: dict[str, Diagnosis] = {}- for lang, d in _present(cfg, iteration, languages):- out[lang.value] = diagnose_dir(lang.value, d, track=cfg.track)- iter_dir = cfg.iter_dir(iteration)- write_json_atomic(iter_dir / "diagnosis.json", {k: v.model_dump(mode="json") for k, v in out.items()})- md = [f"# {cfg.name} — iteration {iteration} diagnosis ({cfg.track.value} track)", "",- f"track `{cfg.track.value}`, variant `{cfg.variant}`, generator `{cfg.generator}`, judge `{cfg.judge}` "- f"@ {cfg.judge_thinking}", ""]- md += [render_diagnosis(v) for v in out.values()]- (iter_dir / "diagnosis.md").write_text("\n".join(md))- return out---def compare_iteration(cfg: LoopConfig, iteration: int, against: int, *,- languages: Sequence[Language] = ()) -> dict[str, Comparison]:- if iteration == against:- raise LoopError("--against must name a different iteration")- out: dict[str, Comparison] = {}- for lang, d in _present(cfg, iteration, languages):- ref = cfg.iter_dir(against) / lang.value- if not ref.is_dir():- log.warning("iteration %d has no %s output to compare against", against, lang.value)- continue- c = compare_dirs(lang.value, d, ref, track=cfg.track)- out[lang.value] = c- iter_dir = cfg.iter_dir(iteration)- (iter_dir / f"compare_{lang.value}.md").write_text(- f"# {cfg.name} — iteration {iteration} vs {against}\n\n" + render_comparison(c))- write_json_atomic(iter_dir / f"compare_{lang.value}.json", c.model_dump(mode="json"))- if not out:- raise LoopError(f"nothing to compare: iteration {against} has no output for {[x.value for x in cfg.languages]}")- return out---def judge_calib(cfg: LoopConfig, iteration: int, *, model_id: str = "", thinking: str = "", n_samples: int = 3,- languages: Sequence[Language] = (), calibrate_fn: Callable[..., Any] | None = None,- workers: int = 4) -> dict[str, CalibSummary]:- """Re-judge every run's PICKED round ``n_samples`` times in fixed montage order (the model's own- re-judge σ, not its order σ) and summarise per language — the loop's judge arm."""- model_id = model_id or cfg.judge- thinking = thinking or cfg.judge_thinking- if calibrate_fn is None:- from codeverse3d.addons.calibration import calibrate as calibrate_fn- out: dict[str, CalibSummary] = {}- iter_dir = cfg.iter_dir(iteration)- for lang, d in _present(cfg, iteration, languages):- digests = digests_for(d, track=cfg.track)- jobs = [(pid, dg.picked_round) for pid, dg in sorted(digests.items()) if dg.picked_round is not None]-- def one(job: tuple[str, int], *, root: Path = d, lang_name: str = lang.value) -> Any | None:- pid, picked = job- try:- return calibrate_fn([root / "runs" / pid], model_id=model_id, n_samples=n_samples,- out_dir=iter_dir / "judge_calib" / lang_name / pid, geometry_mode=None,- rounds=[picked], thinking=thinking, max_workers=1, fixed_order=True)- except Exception as e: # noqa: BLE001 — one run's re-judge must not cost the table- log.warning("judge-calib %s/%s failed: %s", lang_name, pid, e)- return None-- with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:- tables = [t for t in pool.map(one, jobs) if t is not None]- s = calib_summary(lang.value, tables, thinking=thinking)- if not tables:- s.model_id, s.n_samples = model_id, n_samples- out[lang.value] = s- (iter_dir / f"judge_calib_{lang.value}.md").write_text(- f"# {cfg.name} — iteration {iteration} judge calibration\n\n" + render_calib(s))- write_json_atomic(iter_dir / f"judge_calib_{lang.value}.json", s.model_dump(mode="json"))- return out---# --------------------------------------------------------------------------- the ledger: accept / rollback / status-class LedgerRow(BaseModel):- """One decision about the variant (append-only ``ledger.jsonl``; see bench/data/loop/README.md)."""-- ts: str- iteration: int- languages: list[str]- variant: str- version_from: int- version_to: int- variant_hash: str- battery_sha: str- verdicts: dict[str, str] = Field(default_factory=dict, description="language → keep | revert | inconclusive")- decision: Literal["accept", "rollback"]- cost_usd: float = 0.0- tree_commit: str = ""- tree_dirty: bool = False- note: str = ""---def ledger_path(cfg: LoopConfig, data_dir: Path | None = None) -> Path:- return (data_dir or DATA_DIR) / cfg.name / "ledger.jsonl"---def ledger_rows(path: Path) -> list[LedgerRow]:- return read_jsonl(path, LedgerRow)---def append_ledger(path: Path, row: LedgerRow) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- seal_for_append(path)- with path.open("a") as fh:- fh.write(row.model_dump_json() + "\n")---def battery_sha(iter_dir: Path) -> str:- """sha256[:12] over the iteration's battery files — what the row's verdict was measured on."""- h = hashlib.sha256()- for p in sorted(iter_dir.glob("battery_*.yaml")):- h.update(p.name.encode() + b"\0" + p.read_bytes() + b"\0")- return h.hexdigest()[:12]---def tree_state(tree: Path = HARNESS) -> tuple[str, bool]:- """``(commit, dirty)`` of the harness checkout — a ledger row names the code its verdict ran on."""- try:- head = subprocess.run(["git", "-C", str(tree), "rev-parse", "HEAD"], capture_output=True, text=True,- check=False, timeout=30)- status = subprocess.run(["git", "-C", str(tree), "status", "--porcelain", "--untracked-files=no", "--", "."],- capture_output=True, text=True, check=False, timeout=30)- except (OSError, subprocess.SubprocessError):- return "", False- commit = head.stdout.strip() if head.returncode == 0 else ""- return commit, bool(status.returncode == 0 and status.stdout.strip())---def iteration_cost(cfg: LoopConfig, iteration: int) -> float:- from bench.report import load_results-- total = 0.0- for lang in cfg.languages:- d = cfg.iter_dir(iteration) / lang.value- if (d / "results.jsonl").is_file() or (d / "results.json").is_file():- total += sum(r.cost_usd for r in load_results(d))- return round(total, 4)---def iteration_verdicts(cfg: LoopConfig, iteration: int) -> dict[str, str]:- out: dict[str, str] = {}- for lang in cfg.languages:- p = cfg.iter_dir(iteration) / f"compare_{lang.value}.json"- if p.is_file():- out[lang.value] = str(json.loads(p.read_text()).get("decision", ""))- return out---def _row(cfg: LoopConfig, iteration: int, *, paths: VariantPaths, decision: Literal["accept", "rollback"],- version_from: int, version_to: int, note: str) -> LedgerRow:- commit, dirty = tree_state()- return LedgerRow(ts=datetime.now(UTC).isoformat(), iteration=iteration, languages=[x.value for x in cfg.languages],- variant=cfg.variant, version_from=version_from, version_to=version_to,- variant_hash=paths.ledger_hash(), battery_sha=battery_sha(cfg.iter_dir(iteration)),- verdicts=iteration_verdicts(cfg, iteration), decision=decision,- cost_usd=iteration_cost(cfg, iteration), tree_commit=commit, tree_dirty=dirty, note=note)---def accept(cfg: LoopConfig, iteration: int, *, note: str = "", paths: VariantPaths | None = None,- data_dir: Path | None = None) -> LedgerRow:- """The overlay as it stands becomes version N+1: preflight it (a ``routes.toml`` that does not- type-check or an invalid bundle is refused — a run would have degraded to the base routing- silently), bump ``variant.toml``, snapshot both overlay dirs to ``snapshots/<v>_v<N+1>/``, append- the row."""- if not cfg.iter_dir(iteration).is_dir():- raise LoopError(f"iteration {iteration} does not exist under {cfg.out}")- vp = paths or VariantPaths.default(cfg.variant)- vp.preflight()- version_from = vp.version()- version_to = version_from + 1- vp.set_version(version_to)- vp.snapshot_to(snapshot_dir(cfg, version_to))- row = _row(cfg, iteration, paths=vp, decision="accept", version_from=version_from, version_to=version_to, note=note)- if not row.verdicts:- log.warning("iteration %d has no compare_<lang>.json: accepting without a verdict", iteration)- append_ledger(ledger_path(cfg, data_dir), row)- return row---def rollback(cfg: LoopConfig, iteration: int, *, note: str = "", paths: VariantPaths | None = None,- data_dir: Path | None = None) -> LedgerRow:- """Return the overlay dirs to the last accepted state. An iteration that was itself the latest- ``accept`` is un-accepted (its ``version_from`` snapshot comes back and the version with it);- otherwise the working edits made for the iteration are discarded in favour of the current- version's snapshot."""- vp = paths or VariantPaths.default(cfg.variant)- current = vp.version()- rows = ledger_rows(ledger_path(cfg, data_dir))- accepts = [r for r in rows if r.decision == "accept"]- target = current- if accepts and accepts[-1].iteration == iteration and accepts[-1].version_to == current:- target = accepts[-1].version_from- src = snapshot_dir(cfg, target)- if not src.is_dir():- raise LoopError(f"no snapshot {src} to restore (init writes the current version's; accept writes each new one)")- vp.restore_from(src)- if vp.version() != target: # a snapshot taken before the bump still says the old number: pin it- vp.set_version(target)- row = _row(cfg, iteration, paths=vp, decision="rollback", version_from=current, version_to=target, note=note)- append_ledger(ledger_path(cfg, data_dir), row)- return row---def iterations(cfg: LoopConfig) -> list[dict[str, Any]]:- """What each ``iter_NN`` holds: batteries, child exit codes, result counts, the files written."""- out: list[dict[str, Any]] = []- for d in sorted(cfg.out.glob("iter_*")):- if not d.is_dir():- continue- run = json.loads((d / "run.json").read_text()) if (d / "run.json").is_file() else {}- results: dict[str, int] = {}- for lang in cfg.languages:- jl = d / lang.value / "results.jsonl"- if jl.is_file():- results[lang.value] = len({r.get("id") for r in read_jsonl(jl)})- meta = generation_meta(cfg, int(d.name.split("_")[-1])) or {}- out.append({- "iteration": int(d.name.split("_")[-1]), "rung": meta.get("rung"),- "batteries": sorted(p.name for p in d.glob("battery_*.yaml")),- "exit_codes": {k: v.get("returncode") for k, v in run.get("children", {}).items()},- "results": results,- "diagnosis": (d / "diagnosis.md").is_file(),- "compare": sorted(p.stem.removeprefix("compare_") for p in d.glob("compare_*.json")),- "judge_calib": sorted(p.stem.removeprefix("judge_calib_") for p in d.glob("judge_calib_*.json")),- })- return out---def status_text(cfg: LoopConfig, *, paths: VariantPaths | None = None, data_dir: Path | None = None) -> str:- vp = paths or VariantPaths.default(cfg.variant)- try:- version = f"v{vp.version()} ({vp.ledger_hash()})"- except LoopError as e:- version = f"unknown ({e})"- lines = [f"loop {cfg.name}: variant {cfg.variant} {version}; track {cfg.track.value}; "- f"languages {', '.join(x.value for x in cfg.languages)}; "- + (f"source {', '.join(cfg.source)}; " if cfg.source else "") +- f"generator {cfg.generator}; judge {cfg.judge} @ {cfg.judge_thinking}; parallel {cfg.parallel} per language "- f"(stagger {cfg.stagger_s:g} s), rounds {cfg.rounds}, max-minutes {cfg.max_minutes:g}; out {cfg.out}", "",- "| iter | rung | batteries | exit codes | results | diagnosis | compare | judge-calib |",- "|---|---|---|---|---|---|---|---|"]- for it in iterations(cfg):- lines.append(f"| {it['iteration']} | {it['rung'] or '—'} | {len(it['batteries'])} | "- f"{', '.join(f'{k}={v}' for k, v in it['exit_codes'].items()) or '—'} | "- f"{', '.join(f'{k}={v}' for k, v in it['results'].items()) or '—'} | "- f"{'yes' if it['diagnosis'] else '—'} | {', '.join(it['compare']) or '—'} | "- f"{', '.join(it['judge_calib']) or '—'} |")- rows = ledger_rows(ledger_path(cfg, data_dir))- lines += ["", f"ledger {ledger_path(cfg, data_dir)}: {len(rows)} row(s)", "",- "| ts | iter | decision | version | verdicts | cost | hash | tree | note |", "|---|---|---|---|---|---|---|---|---|"]- for r in rows:- lines.append(f"| {r.ts[:19]} | {r.iteration} | {r.decision} | {r.version_from}→{r.version_to} | "- f"{', '.join(f'{k}={v}' for k, v in r.verdicts.items()) or '—'} | ${r.cost_usd:.2f} | {r.variant_hash} | "- f"{r.tree_commit[:9]}{'-dirty' if r.tree_dirty else ''} | {r.note} |")- return "\n".join(lines)---# --------------------------------------------------------------------------- CLI-def _add_out(sp: argparse.ArgumentParser) -> None:- sp.add_argument("--out", type=Path, required=True, help="the loop directory (holds loop.json)")---def _add_iter(sp: argparse.ArgumentParser) -> None:- sp.add_argument("--iter", dest="iteration", type=int, required=True, help="iteration number (0 = the base)")---def _add_langs(sp: argparse.ArgumentParser) -> None:- sp.add_argument("--languages", default="", help="comma list; default: every language of the loop")---def build_parser() -> argparse.ArgumentParser:- ap = argparse.ArgumentParser(prog="python -m bench.loop", description=__doc__.split("\n\n")[0])- ap.add_argument("--data-dir", type=Path, default=None, help=f"where the ledgers live (default {DATA_DIR})")- sub = ap.add_subparsers(dest="cmd", required=True)-- s = sub.add_parser("init", help="freeze the loop's configuration into <out>/loop.json")- s.add_argument("--name", required=True)- _add_out(s)- s.add_argument("--variant", required=True, help="the prompt/skill variant under test (codeverse3d/prompts/variants/<name>)")- s.add_argument("--track", default=Track.SCENE.value, choices=[t.value for t in Track],- help="the track the loop tunes (decides the languages allowed and where the prompts come from)")- s.add_argument("--languages", default="", help="comma list of the track's languages (default: all of them)")- s.add_argument("--source", default="",- help="comma list of battery files under bench/prompts/ (a bare name or a path relative to eval/) "- "the loop selects from; required for every track but scene")- s.add_argument("--generator", default="agy:gemini-4-argon")- s.add_argument("--judge", default="gemini:gemini-4-argon")- s.add_argument("--judge-thinking", default="medium", choices=("off", "low", "medium", "high"))- s.add_argument("--planner", default="", help="battery-generation model (default: the settings planner)")- s.add_argument("--parallel", type=int, default=15, help="run_bench workers per language")- s.add_argument("--stagger", type=float, default=40.0,- help="seconds between the launches of each child's first wave of workers; the children launch "- "half that apart (0 = everything at once)")- s.add_argument("--rounds", type=int, default=2)- s.add_argument("--max-minutes", type=float, default=90.0)- s.add_argument("--n", type=int, default=15, help="prompts per battery")-- s = sub.add_parser("generate", help="write the iteration's batteries (scene: a mix of cached rungs; "- "other tracks: a tier selection from the source batteries)")- _add_out(s)- _add_iter(s)- s.add_argument("--n", type=int, default=None, help="prompts per battery (default: loop.json)")- s.add_argument("--rung", type=int, default=None, help=f"top rung of the mix, 1..{max(RUNGS)} (default: the previous iteration's, else 1)")-- s = sub.add_parser("run", help="run the batteries: one bench.run_bench child per language")- _add_out(s)- _add_iter(s)- _add_langs(s)- s.add_argument("--resume", action="store_true", help="re-run the cells the weather lost (--redo-status infra_failed)")-- s = sub.add_parser("diagnose", help="diagnosis.{md,json} from the iteration's run records")- _add_out(s)- _add_iter(s)- _add_langs(s)-- s = sub.add_parser("compare", help="pair the iteration with another by prompt id: keep / revert / inconclusive")- _add_out(s)- _add_iter(s)- s.add_argument("--against", type=int, required=True, help="the reference iteration")- _add_langs(s)-- s = sub.add_parser("judge-calib", help="re-judge the picked rounds n times: within / between σ, SNR, correlations")- _add_out(s)- _add_iter(s)- s.add_argument("--model", default="", help="judge model (default: the loop's judge)")- s.add_argument("--thinking", default="", choices=("", "off", "low", "medium", "high"), help="default: the loop's")- s.add_argument("--n", type=int, default=3, help="samples per round")- s.add_argument("--workers", type=int, default=4, help="runs re-judged side by side")- _add_langs(s)-- for name, text in (("accept", "bump the variant version, snapshot the overlay, append the ledger row"),- ("rollback", "restore the last accepted overlay, append the ledger row")):- s = sub.add_parser(name, help=text)- _add_out(s)- _add_iter(s)- s.add_argument("--note", default="")-- s = sub.add_parser("status", help="the ledger and the variant version")- _add_out(s)- return ap---def main(argv: Sequence[str] | None = None) -> int:- ap = build_parser()- ns = ap.parse_args(argv)- logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")- try:- return _dispatch(ns)- except LoopError as e:- print(f"error: {e}", file=sys.stderr)- return 2---def _dispatch(ns: argparse.Namespace) -> int:- if ns.cmd == "init":- track = Track(ns.track)- languages = parse_languages(ns.languages) if ns.languages.strip() else list(TRACK_LANGUAGES[track])- try:- cfg = LoopConfig(name=ns.name, out=ns.out.resolve(), variant=ns.variant, languages=languages, track=track,- source=parse_sources(ns.source), generator=ns.generator, judge=ns.judge,- judge_thinking=ns.judge_thinking, planner=ns.planner, parallel=ns.parallel,- stagger_s=ns.stagger, rounds=ns.rounds, max_minutes=ns.max_minutes, n=ns.n)- except ValueError as e: # the track/languages/source rules: a configuration error, not a traceback- raise LoopError(str(e)) from e- print(f"wrote {init(cfg)}")- return 0- cfg = LoopConfig.load(ns.out)- langs = parse_languages(ns.languages) if getattr(ns, "languages", "") else []- if ns.cmd == "generate":- for lang, path in generate_iteration(cfg, ns.iteration, rung=ns.rung, n=ns.n).items():- print(f"{lang.value}: {path}")- return 0- if ns.cmd == "run":- meta = run_iteration(cfg, ns.iteration, languages=langs, resume=ns.resume)- for name, child in meta["children"].items():- print(f"{name}: exit {child['returncode']} ({child['log']})")- print(f"wall {meta['wall_s']:.0f} s → {cfg.iter_dir(ns.iteration) / 'run.json'}")- return 0 if all(c["returncode"] == 0 for c in meta["children"].values()) else 1- if ns.cmd == "diagnose":- for name, d in diagnose_iteration(cfg, ns.iteration, languages=langs).items():- print(f"{name}: {d.n} runs, picked mean {d.picked.get('mean')}, {len(d.recommendations)} recommendation(s)")- print(f"→ {cfg.iter_dir(ns.iteration) / 'diagnosis.md'}")- return 0- if ns.cmd == "compare":- for name, c in compare_iteration(cfg, ns.iteration, ns.against, languages=langs).items():- print(f"{name}: {c.decision} — {c.reason}")- return 0- if ns.cmd == "judge-calib":- for name, s in judge_calib(cfg, ns.iteration, model_id=ns.model, thinking=ns.thinking, n_samples=ns.n,- languages=langs, workers=ns.workers).items():- print(f"{name}: within-sd {s.within_sd} between-sd {s.between_sd} SNR {s.snr} (${s.cost_usd:.2f})")- return 0- if ns.cmd in ("accept", "rollback"):- fn = accept if ns.cmd == "accept" else rollback- row = fn(cfg, ns.iteration, note=ns.note, data_dir=ns.data_dir)- print(f"{row.decision}: {cfg.variant} v{row.version_from} → v{row.version_to} ({row.variant_hash}); "- f"verdicts {row.verdicts or '—'}; ledger {ledger_path(cfg, ns.data_dir)}")- return 0- if ns.cmd == "status":- print(status_text(cfg, data_dir=ns.data_dir))- return 0- raise LoopError(f"unknown command {ns.cmd!r}") # pragma: no cover — argparse restricts the choices---if __name__ == "__main__":- raise SystemExit(main())diff --git a/eval/bench/paired_compare.py b/eval/bench/paired_compare.pyindex ad57c6bd..1a5f9548 100644--- a/eval/bench/paired_compare.py+++ b/eval/bench/paired_compare.py@@ -264,8 +264,8 @@ def arm_names(a: Path, b: Path) -> tuple[str, str]:def paired_rows(out_a: Path, out_b: Path) -> tuple[dict[tuple[str, str], CellResult], str, str]:"""Two ``bench.run_bench`` directories as the cells of two arms, named apart- (:func:`arm_names`) and deduplicated (``latest``): what ``--against`` and- ``bench.loop compare`` pair by prompt id — ``(cells, name_a, name_b)``."""+ (:func:`arm_names`) and deduplicated (``latest``): what ``--against``+ pairs by prompt id — ``(cells, name_a, name_b)``."""name_a, name_b = arm_names(Path(out_a), Path(out_b))rows = rows_from_bench_run(Path(out_a), name_a) + rows_from_bench_run(Path(out_b), name_b)return latest(rows), name_a, name_bdiff --git a/eval/bench/run_bench.py b/eval/bench/run_bench.pyindex c689e11d..390bbcef 100644--- a/eval/bench/run_bench.py+++ b/eval/bench/run_bench.py@@ -35,7 +35,6 @@ import sysimport tracebackfrom collections.abc import Callable, Sequencefrom concurrent.futures import ThreadPoolExecutor, as_completed-from contextlib import AbstractContextManager, nullcontextfrom datetime import UTC, datetimefrom pathlib import Pathfrom time import sleep@@ -59,7 +58,6 @@ from codeverse3d.contracts.spec import ( # noqa: E402FixedPart,ProjectCheck,ReferenceImage,- RunOptions,Spec,)from codeverse3d.cost import run_ledger # noqa: E402@@ -156,8 +154,6 @@ class BenchOptions(BaseModel):redo_status: list[str] = Field(default_factory=list,description="re-run prompts already recorded with one of these statuses ""(the point of `infra_failed`: retry what the weather lost)")- variant: str = Field(default="", description="the per-model prompt/skill variant every run is created with "- "(RunOptions.variant, D105); '' = resolve from Settings like `3dcodeverse make`")REFS_DIR = Path(__file__).resolve().parent / "refs"@@ -194,56 +190,25 @@ def discover_references(item: BenchPrompt, track: Track, *, battery_dir: Path |def build_spec(battery: Battery, item: BenchPrompt, *, backends: Backends, rounds: int,- max_minutes: float, tag0: str, extra_tags: Sequence[str] = (), variant: str = "",+ max_minutes: float, tag0: str, extra_tags: Sequence[str] = (),) -> Spec:"""Shared Spec core for bench drivers (``run_bench`` / ``compare_backends``).- Drivers resolve their own ``Backends`` and pass their leading tag; ``variant`` is frozen on- ``RunOptions.variant`` the way ``3dcodeverse make --variant`` freezes it (the track activates it)."""+ Drivers resolve their own ``Backends`` and pass their leading tag."""return Spec(id=f"{battery.name}/{item.id}", track=battery.track, language=item.language or battery.language, prompt=item.prompt,constraints=Constraints(must_have=list(item.must_have), dimensions_m=item.dimensions_m),references=discover_references(item, battery.track, battery_dir=battery.source_dir),budget=Budget(max_rounds=rounds, max_minutes=max_minutes),backends=backends, tags=[tag0, battery.name, item.tier, item.category, *extra_tags, *item.tags],- options=RunOptions(variant=variant),fixed_parts=list(item.fixed_parts),checks=list(item.checks),)-def resolve_variant(name: str, generator_id: str) -> str:- """The variant a bench run is created with: ``name`` when stated (``--variant``), else what the- settings resolve for the generator (``prompts.variants.resolve_variant`` — the same rule as- ``3dcodeverse make``), else the base. A tree without the variant layer (pre-D105) resolves to the base- unless a name was stated, which it cannot honour."""- if name:- return name- try:- from codeverse3d.prompts.variants import resolve_variant as _resolve- except ImportError:- return ""- return str(_resolve(get_settings(), generator_id) or "")---def activate_variant(name: str) -> AbstractContextManager[Any]:- """``prompts.variants.activate(name)`` for the block (prompt / skill loads of THIS thread read the- overlay) — a no-op for the base. A stated name on a tree without the layer is an error, never a- silent base run: that would be an A/B comparing a tree against itself."""- if not name:- return nullcontext()- try:- from codeverse3d.prompts.variants import activate- except ImportError as e:- raise RuntimeError(f"--variant {name!r} needs codeverse3d.prompts.variants (D105), which this tree "- f"does not have: {e}") from e- return activate(name)--def spec_for(battery: Battery, item: BenchPrompt, opts: BenchOptions) -> Spec:backends = get_settings().backends(generator=opts.generator, planner=opts.planner, judge=opts.judge)return build_spec(battery, item, backends=backends, rounds=opts.rounds,- max_minutes=opts.max_minutes, tag0="bench",- variant=resolve_variant(opts.variant, backends.generator))+ max_minutes=opts.max_minutes, tag0="bench")def record_minutes(run_dir: Path) -> float:@@ -333,13 +298,8 @@ def run_battery(battery_path: Path | str, out_dir: Path | str, opts: BenchOptions | None = None, *,run_fn: RunFn | None = None, on_result: Callable[[BenchItemResult], None] | None = None,) -> list[BenchItemResult]:- """Run (or resume) a battery; returns every result (previous + new). A stated ``opts.variant``- is active for the whole battery (``activate_variant``) and frozen on every spec, which is what- the worker threads' runs read (``BaseTrack.run`` activates ``spec.options.variant`` — a- ContextVar does not cross into a pool thread by itself)."""- opts = opts or BenchOptions()- with activate_variant(opts.variant):- return _run_battery(battery_path, out_dir, opts, run_fn=run_fn, on_result=on_result)+ """Run (or resume) a battery; returns every result (previous + new)."""+ return _run_battery(battery_path, out_dir, opts or BenchOptions(), run_fn=run_fn, on_result=on_result)def _run_battery(@@ -454,9 +414,6 @@ def main(argv: Sequence[str] | None = None) -> int:help="comma list of recorded statuses to re-run, e.g. infra_failed once the provider recovers")ap.add_argument("--report", action=argparse.BooleanOptionalAction, default=True,help="write report.md + report.html when the battery ends")- ap.add_argument("--variant", default="",- help="per-model prompt/skill variant for every run (codeverse3d/prompts/variants/<name>, D105); "- "default: what the settings resolve for the generator, like `3dcodeverse make`")ns = ap.parse_args(argv)if not ns.battery.is_file():ap.error(f"battery not found: {ns.battery}")@@ -469,12 +426,12 @@ def main(argv: Sequence[str] | None = None) -> int:# one source of truth for the worker count and the stagger: BenchOptions (the measured knee; none)opts = BenchOptions(generator=ns.generator, planner=ns.planner, judge=ns.judge, rounds=ns.rounds,max_minutes=ns.max_minutes, limit=ns.limit, ids=ns.ids, tiers=ns.tiers,- redo_status=[x for x in ns.redo_status.split(",") if x], variant=ns.variant,+ redo_status=[x for x in ns.redo_status.split(",") if x],**({} if ns.parallel is None else {"parallel": ns.parallel}),**({} if ns.stagger is None else {"stagger_s": ns.stagger}))out = ns.out or Path(__file__).resolve().parent / "out" / ns.battery.stemprint(f"battery={ns.battery} out={out} generator={ns.generator or 'default'} judge={ns.judge or 'default'}"- + (f" variant={ns.variant}" if ns.variant else ""), flush=True)+, flush=True)def _on(res: BenchItemResult) -> None:print(f" [{res.status}] {res.id}: baseline={res.score_baseline} picked={res.score_picked} "diff --git a/eval/docs/EVAL.md b/eval/docs/EVAL.mdindex bee6080b..3df7e00a 100644--- a/eval/docs/EVAL.md+++ b/eval/docs/EVAL.md@@ -54,18 +54,6 @@ becomes acceptance items (planner-appended in the loop, fixed-judge checklist incomparisons); `dimensions_m` becomes `Spec.constraints.dimensions_m` and adeterministic contract check.-**Generated batteries (2026-10-14, §10).** The argon loop writes its own scene batteries under-`bench/out/<loop>/iter_NN/battery_<lang>.yaml` (`bench.loop generate`; never checked in): the same-`Battery` schema, 30 prompts per language per iteration, every `must_have` the scenes_v2 composition-contract — named zones, asset types with counts, a luminance band, one effect, one animation, a camera-brief with a no-clip requirement — RENDERED from typed fields the planner model returns-(`bench/_loop_prompts.py`), so the counts always parse. Difficulty is a ladder of five rungs with-objective knobs (rung 1: 3 zones / 6 asset types / ≤ 40 instances / day / no water … rung 5: 6+ zones /-14 types / 400 / night + water + interior + particles + a moving hero + precise scale constraints); a-rung's prompts are generated ONCE and cached (`prompts/rung_R_<lang>.yaml`) with ids-`it{NN}_{lang}_r{R}_{k:02d}` that never change, so iterations pair by id; `--rung R` mixes rungs-1..R evenly (the remainder to the hardest), which keeps half of the pairs when the mix moves up.-## 3. Harness battery runs (`python -m bench.run_bench`)```bash@@ -372,9 +360,6 @@ Notes: the earlier criteria-first schema compressed flash to 0.6–0.7 (std 0.01`addons.calibration --thinking` default to it, the record's sampling snapshot carries it.* **The A/B evaluator** (`eval/bench/_fixed_eval.py`) runs `placement_gate` on a scene cellbefore the judge, so the deterministic caps fire in a compare cell as in the loop.- * Not measured yet: the loop's judge-calibration arm (`bench.loop judge-calib`) is the- within-sd / between-sd / SNR readout for scene under argon@medium; until it runs, the- numbers above are the rubric's, not a battery's.* Never tune rubric text against the battery you report on; bump the rubric version(`*_v2`) instead and re-run.@@ -440,13 +425,6 @@ verdict is `bench/stats.decide`, the one paired rule of every report (owner, 202> `paired_compare` says better / worse / inconclusive and `ab_view` B wins / loses / Inconclusive> by the same rule (without the veto).-**The loop's rule (2026-10-14, `bench.loop compare`, §10)** is the same `decide` on the paired picked-score — keep / revert / inconclusive — plus a *deterministic-gate veto* in place of the A/B rig's-per-prompt regression veto: the floating + sunken + interpenetration ERROR count per run (the-`scene_placement` gate's typed kinds) must not rise by more than one on average over the pairs, or the-iteration is reverted whatever the judge said. The contact standards the owner tightened that day-are measured by the gate, not perceived by the VLM, so the gate gets the last word.-Until 2026-09-24 the A/B rule was a threshold — keep iff mean ≥ +0.02 and no regression; revertiff mean ≤ −0.02 or ≥ 2 regressions — and on `[0.25, 0.01, 0.00, 0.02]` it said keep where`paired_compare` said unsupported and `ab_view` inconclusive. Summaries written before then carry@@ -756,157 +734,6 @@ re-run; **cells dropped as `infra_failed` and `budget_exhausted`, per arm** (§7omitted drop count is an unreadable table); links to `record.json` / `report.html`under `bench/out/`.-## 10. The argon loop (`bench/loop.py`, 2026-10-14)--One iteration = one edit of a per-model prompt/skill **variant** (`codeverse3d/prompts/variants/<v>/`-+ `codeverse3d/skills/variants/<v>/`, D105; `argon` first), measured on ~30 scene prompts per language-run in parallel on the generator under test (`agy:gemini-4-argon`), judged by ONE fixed judge at ONE-thinking level (`gemini:gemini-4-argon` @ medium — the level at which argon's within-sd is 0.012, §6).-`init` freezes every knob in `<out>/loop.json`; nothing else takes a model or a budget flag, so two-iterations never differ in anything but the variant and (when `--rung` moves) the prompt mix.--```bash-cd eval-python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon \- --languages scene_threejs,scene_blender --generator agy:gemini-4-argon \- --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 --rounds 2 --max-minutes 90-python -m bench.loop generate --out bench/out/loop_argon --iter 0 # batteries (§2: rung mix, cached ids)-python -m bench.loop run --out bench/out/loop_argon --iter 0 # 2 children × 15 runs; --resume redoes infra_failed-python -m bench.loop diagnose --out bench/out/loop_argon --iter 0 # diagnosis.md / .json-# … edit the variant overlay (prompts, skills routes) for iteration 1 …-python -m bench.loop generate --out bench/out/loop_argon --iter 1 # same rung → the same ids-python -m bench.loop run --out bench/out/loop_argon --iter 1-python -m bench.loop diagnose --out bench/out/loop_argon --iter 1-python -m bench.loop compare --out bench/out/loop_argon --iter 1 --against 0 # keep / revert / inconclusive-python -m bench.loop judge-calib --out bench/out/loop_argon --iter 1 # the judge arm-python -m bench.loop accept --out bench/out/loop_argon --iter 1 --note "placement recipe" # or rollback-python -m bench.loop status --out bench/out/loop_argon-```--* **generate** renders every battery's `must_have` contract from the planner model's typed fields- (`bench/_loop_prompts.contract_lines`), never from prose. Its camera line changed on 2026-10-15:- it now states ONE fixed eye-level viewpoint (where it stands, what it looks along, its height),- because both scene languages render the authored cameras as stills at t = 0 and t = 1.5 s and the- old "tracks / dollies along …" brief was a must-have no run could satisfy (iteration 0: unverified- in 5 of 60 runs, a `missing_must_acceptance` cap on the whole score). A rung cache written before- that date is migrated in place by the next `generate` (`migrate_camera_lines`: the route the model- wrote becomes where the camera stands; ids untouched, `camera_lines_migrated` stamped in the file),- so iteration 1 vs 0 pairs runs whose briefs differ in that one line.-* **run** is one `python -m bench.run_bench … --variant <v> --no-report` child per language, side- by side, with `C3D_JUDGE__THINKING=<level>`, `C3D_VARIANT=<v>`, `C3D_RENDER__BLENDER_GPU_SLOTS=3`- (30 runs share one GPU) and `PYTHONUNBUFFERED=1`; the driver installs the harness's stop handlers- and forwards SIGTERM to the children, whose own handlers (`run_bench.main`) kill their agent /- Blender / Chrome groups so every run records its stop. `iter_NN/run.json` carries pids, exit codes- and the wall clock. Launches are staggered (`stagger_s`, `init --stagger`, default 40 s;- 2026-10-15): each child's first wave of workers starts `stagger_s` apart (`run_bench --stagger`)- and the two children half a stagger apart, so the languages' waves interleave — agy holds one- session per key machine-wide, there are 30 keys, and 15 + 15 runs plus the harness's own planner /- asset / judge calls share a 64-slot pool; iteration 0 launched all 30 at once and 160 of its 172- `asset.generate_failed` key-pool outages fell in the runs' first ten minutes. A later cell starts- when an earlier one finishes, which is staggered by itself.-* **diagnose** reads the run records (`_records.records`, `load_record`): n by status, baseline /- picked mean / median / sd, per-criterion means, defect vote rates, caps fired, gate ERROR / WARN- counts by TYPED kind (`skills.registry.finding_kind`), library reach (lib modules imported by the- agent's files under `deliverable/src`, `src/lib/` itself excluded), cost by stage, minutes, stop- reasons, skills listed vs read, the 12 most frequent judge (kind, target-word) pairs — and a- RECOMMENDATIONS list from deterministic rules (`bench/_loop_diag.RULES`): floating ERROR rate ≥ 25 %- → the placement recipe + skill boost; < 3 lib modules per scene → the effects catalog presentation;- dark_frame ≥ 20 % → the lighting recipe; budget stops ≥ 30 % → raise `--max-minutes` / cut the zone- prompt; outages ≥ 20 % → `run --resume` first; and so on. A person reads it before editing the- variant; no model does.-* **compare** pairs iteration N with M by prompt id (common ids only; the dropped ids are listed):- paired Δ picked score with its 95 % t-interval, the exact sign test, mean Δ per criterion, Δ gate- ERRORs per kind, Δ cost — and the verdict of §8's loop rule: `stats.decide` plus the placement veto- (floating + sunken + interpenetration ERRORs per run must not rise by > 1 on average).-* **judge-calib** re-judges every run's PICKED round n times in fixed montage order- (`addons.calibration.calibrate(fixed_order=True)` — the model's own re-judge σ, not its order σ):- within-sd (rms of the per-round σ), between-sd (σ of the per-round means), their ratio (SNR),- Pearson / Spearman of gate ERRORs against the score, the defect histogram, cost and latency. The- judge is a measuring instrument; this is its calibration certificate per iteration.-* **accept** first refuses an overlay whose `routes.toml` does not type-check or whose bundles fail- `validate_bundle` (the standards of `3dcodeverse skills validate`), then bumps `variant.toml`'s `version`, snapshots both overlay dirs to- `<out>/snapshots/<v>_v<N>/`, and appends a row to `bench/data/loop/<name>/ledger.jsonl` (format:- `bench/data/loop/README.md`); **rollback** restores the last accepted snapshot (an iteration that- was itself the latest accept is un-accepted, version and all); **status** prints the ledger and the- version. Iteration 0 runs the base prompts under the variant plumbing (the `argon` overlay ships- empty), so every later verdict is against a measured baseline, not a remembered one.--What the loop cannot do: it never edits the variant itself (the recommendations are levers, the edit-is a person's), it never compares across rungs (the pairs are by id, so a moved mix compares only the-ids both iterations ran), and a `keep` over 30 pairs is still one battery's verdict — §8's noise floor-applies, which is why the gate veto and the judge arm sit beside the score.--### 10.1 Other tracks (2026-10-15)--The same loop runs `static_object`, `articulated_object` and `graphics`. `init --track` decides the-languages allowed (`TRACK_LANGUAGES`; `--languages` defaults to all of the track's) and every track-but scene names its prompts with `--source` — battery files under `bench/prompts/` (a bare name, or a-path relative to `eval/`; stored in `loop.json` relative to `eval/`). A scene `loop.json` without-`source` (every one written before this) loads as before, and the scene path is unchanged: the same-generator, rung caches, ids and battery bytes (pinned by `test_the_scene_generate_path_is_byte_identical…`).--```bash-cd eval-python -m bench.loop init --name argon_static --out bench/out/loop_argon_static --variant argon \- --track static_object --languages blender,threejs,cadquery --source compare_v4.yaml \- --judge gemini:gemini-4-argon --judge-thinking medium --parallel 8-python -m bench.loop init --name argon_articulated --out bench/out/loop_argon_articulated --variant argon \- --track articulated_object --languages urdf_blender \- --source articulated_v2.yaml,coupled_v1.yaml,articulated_v1.yaml \- --judge gemini:gemini-4-argon --judge-thinking medium --parallel 8-python -m bench.loop init --name argon_graphics --out bench/out/loop_argon_graphics --variant argon \- --track graphics --languages glsl_shader,opengl_python --source graphics_v2.yaml,graphics_v1.yaml \- --judge gemini:gemini-4-argon --judge-thinking medium --parallel 8-# then generate / run / diagnose / compare / judge-calib / accept / rollback / status exactly as above-```--* **generate** does not call a model: it pools the source batteries (deduped by normalised prompt- text, the first id wins; an id that names two different prompts keeps the first), keeps every id- VERBATIM (an iteration's cell is the recorded battery's cell, `bench/refs/<id>/` included), routes- a prompt that names a `language` to that language's battery only, and selects `n` per language by the rung's tier mix- (`bench/_loop_sources.SOURCE_RUNGS`). A prompt that names no language runs in every language of- the loop on the object tracks (compare_v4 is a `language: blender` battery of prompts that are- blender, three.js and CadQuery prompts alike) but takes its battery's `language` on graphics- (`INHERIT_BATTERY_LANGUAGE`: graphics_v1/v2 mark the raw-OpenGL prompts and default the rest to- glsl_shader — a raymarch brief is not an OpenGL prompt). The order inside a tier is sha256(loop name, prompt id), so- the same rung gives the same ids every iteration. `iter_NN/generate.json` records the rung, the- tier counts per language, the sources, the pool (size, duplicates, id collisions) and the ids;- a pool too small for `n` gives a shorter battery, logged and listed under `short`.-- | rung | tiers, in fill order |- |---|---|- | 1 | medium (hash order), then hard (hash order) |- | 2 | hard (hash order), then the hardest medium (most `must_have` + `dimensions_m` items first) |- | 3+ | hard only (hash order) |-- `easy` prompts are never drawn. At `n` = 15: static (compare_v4: 8 medium / 24 hard) runs 8 + 7 at- rung 1 and 15 hard from rung 2 on; articulated (36 prompts, 12 medium / 20 hard) 12 + 3, then 15- hard; graphics is SHORT — graphics_v2 + graphics_v1 hold 9 medium/hard glsl_shader prompts (5 + 4)- and 5 opengl_python ones (1 + 4), so rungs 1–2 run 9 / 5 and rung 3+ 4 / 4. Use `--n 9`; the- opengl_python arm is a smoke arm (5 pairs cannot carry a paired verdict) until more raw-OpenGL- prompts are written — the other graphics batteries (teaser_v1, refs_v1/v2) add one.-* **diagnose** reads the picked round's typed gate findings on the loop's track (`records(track=…)`):- objects — the connectivity ERROR rate split floating / penetration / stray islands (islands are a- WARN in the gate and counted at WARN), the contract ERROR rate split bbox (part / instance /- overall bbox, orientation) / ground gap / missing parts; articulated adds `joint_sweep` ERRORs and- joint axis / limit ERRORs (`lint/urdf_joint`, `lint/mimic`, `motion_direction/wrong_direction`);- graphics — `gl_frames` black, blown, no motion (`static`, a WARN) and broken (NaN; a render with- no frames has no `gl_frames` report and shows in `unscored_rate`); each gate rate is over the runs- whose picked round RAN that gate (a run whose every build failed is not a clean run);- every track — lint ERRORs, budget stops, outages, unscored, the must-have cap, skills deep-read,- cost, minutes, scores, judge issues. The rules are one table (`_loop_diag.RULES`, each naming its- tracks; the rates in `GATE_METRICS`): e.g. floating ≥ 25 % → "connectivity: contact band", bbox ≥- 25 % → "bbox: dims", joint axis ≥ 20 % → "joints: axis/limits", black / blown ≥ 15 % and no motion- ≥ 20 % on graphics. The markdown names the track; the scene-only library section is left out.-* **compare**'s veto is per track (`_loop_diag.VETOES`): scene — floating + sunken + interpenetration- ERRORs; objects — connectivity + contract ERRORs, articulated adding `joint_sweep` and- `motion_direction/wrong_direction`, each run counted at most 3 (`OBJECT_VETO_CAP`: connectivity- reports one penetration per part pair, and one noisy prompt must not revert an iteration alone);- the same limit (a mean rise > 1 per run reverts). The field stays `placement_rise` on every track.- Graphics has none: its ERRORs are image-level (at most ~2 per run) and the shader rubric caps them.-* **judge-calib** re-judges with each run's own rubric (`addons.calibration` → `rubric_for`); accept,- rollback and status are track-agnostic (status prints the track and the sources).-## Judge experiments log**2026-08-29 — profiles and the detail round.** `RoundPolicy.detail_rounds` is tri-statediff --git a/eval/tests/test_bench.py b/eval/tests/test_bench.pyindex bb14970d..2f6449c4 100644--- a/eval/tests/test_bench.py+++ b/eval/tests/test_bench.py@@ -288,59 +288,15 @@ def test_the_first_wave_is_staggered_and_later_cells_are_not(tmp_path: Path, monassert naps == [(7.0, False)] and (out / "runs" / f"{ids[1]}.attempt1").is_dir()-def test_a_variant_is_frozen_on_every_spec_and_active_for_the_battery(tmp_path: Path, monkeypatch):- """``--variant NAME`` (D105): ``RunOptions.variant`` on each spec — what the track activates in its- worker thread — and ``prompts.variants.activate`` around the battery; a stated name on a tree- without the layer is an error, never a silent base run."""- import sys- import types- from contextlib import contextmanager-+def test_the_launcher_installs_the_stop_handlers(tmp_path: Path, monkeypatch):import bench.run_bench as rb- fake = types.ModuleType("codeverse3d.prompts.variants")- fake.active = ""- fake.seen: list[str] = []-- @contextmanager- def activate(name: str):- fake.active = name- try:- yield- finally:- fake.active = ""-- fake.activate = activate- fake.resolve_variant = lambda settings, generator_id: {"agy:gemini-4-argon": "argon"}.get(generator_id, "")- monkeypatch.setitem(sys.modules, "codeverse3d.prompts.variants", fake)battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"- inner = _fake_run_fn({})-- def run(spec, ws, resume):- fake.seen.append(f"{spec.options.variant}/{fake.active}")- return inner(spec, ws, resume)-- run_battery(battery, tmp_path / "a", BenchOptions(parallel=1, limit=2, variant="argon", generator="g"), run_fn=run)- assert fake.seen == ["argon/argon"] * 2 and fake.active == "", "frozen on the spec, active for the block, released"- spec = json.loads((tmp_path / "a" / "runs" / "furn_easy_stool" / "spec.json").read_text())- assert spec["options"]["variant"] == "argon"- # no --variant: the settings resolve it for the generator, as `3dcodeverse make` does — frozen, not activated- fake.seen.clear()- run_battery(battery, tmp_path / "b", BenchOptions(parallel=1, limit=1, generator="agy:gemini-4-argon"), run_fn=run)- assert fake.seen == ["argon/"]- run_battery(battery, tmp_path / "c", BenchOptions(parallel=1, limit=1, generator="codex:gpt-6.1-sol"), run_fn=run)- assert fake.seen[-1] == "/"- # the launcher hands the flag over and installs the stop handlersseen: dict = {}monkeypatch.setattr(rb, "run_battery", lambda battery, out, opts, *, on_result=None: seen.update(opts=opts) or [])monkeypatch.setattr(rb, "install_stop_handlers", lambda: seen.update(handlers=True))- assert rb.main([str(battery), "--out", str(tmp_path / "d"), "--variant", "argon", "--no-report"]) == 0- assert seen["opts"].variant == "argon" and seen["handlers"] is True- # a tree without the layer: the base resolves silently, a stated name does not- monkeypatch.setitem(sys.modules, "codeverse3d.prompts.variants", None)- assert rb.resolve_variant("", "agy:gemini-4-argon") == ""- with pytest.raises(RuntimeError, match="prompts.variants"):- run_battery(battery, tmp_path / "e", BenchOptions(parallel=1, limit=1, variant="argon"), run_fn=inner)+ assert rb.main([str(battery), "--out", str(tmp_path / "d"), "--no-report"]) == 0+ assert seen["handlers"] is Truedef test_the_report_command_rebuilds_the_report(tmp_path: Path, capsys):diff --git a/eval/tests/test_loop.py b/eval/tests/test_loop.pydeleted file mode 100644index d2d3b399..00000000--- a/eval/tests/test_loop.py+++ /dev/null@@ -1,1089 +0,0 @@-"""``bench/loop.py``: the argon tuning loop (scene, objects, graphics), driven offline with fakes (no model, no child process)."""--from __future__ import annotations--import json-import logging-import sys-import time-from collections.abc import Sequence-from pathlib import Path-from types import SimpleNamespace as NS-from typing import Any--import pytest-import yaml--from bench import loop-from bench._loop_diag import (- PLACEMENT_KINDS,- compare_dirs,- diagnose_dir,- js_lib_modules,- loop_verdict,- py_lib_modules,-)-from bench._loop_prompts import (- CAMERA_PREFIX,- LEGACY_CAMERA_PREFIX,- LUMINANCE_CEILING,- LUMINANCE_FLOOR,- RUNGS,- AssetCount,- GeneratedBattery,- GeneratedPrompt,- camera_line,- check_prompt,- contract_lines,- migrate_camera_lines,- mix_counts,- rung_text,-)-from bench.paired_compare import PairedStats-from bench.run_bench import Battery, BenchItemResult, BenchPrompt-from codeverse3d.addons.calibration import CalibrationRow, CalibrationTable-from codeverse3d.contracts.chat import ChatRequest, ChatResponse-from codeverse3d.contracts.common import Language, Usage-from codeverse3d.prompts.variants import variant_hash-from codeverse3d.spatial.frame_metrics import DARK_MEAN_LUM-from tests.conftest import make_fake_run--THREEJS, BLENDER = Language.SCENE_THREEJS, Language.SCENE_BLENDER-CATEGORIES = ("urban", "rural", "nature", "waterfront", "interior", "industrial", "transport", "fantasy", "historic", "garden")-#: a night band that clears the gate's floor by a margin, whatever the floor is set to-NIGHT_LOW = LUMINANCE_FLOOR + 0.03-#: an overlay bundle `skills.validate_bundle` accepts (measured, verified, a body): what accept lets through-VALID_SKILL = (- "---\nname: c3d-scene-placement\ndescription: Seat every asset on its support. Use when placement fires.\n"- 'license: Apache-2.0\nmetadata:\n evidence: measured\n verified: "2026-10-14"\n---\n\n'- "# c3d-scene-placement\n\nRule one: measure the gap before you move anything.\n")---# --------------------------------------------------------------------------- fixtures-def cfg(tmp_path: Path) -> loop.LoopConfig:- c = loop.LoopConfig(name="t_loop", out=tmp_path / "loop", variant="argon", languages=[THREEJS, BLENDER],- generator="agy:gemini-4-argon", judge="gemini:gemini-4-argon", judge_thinking="medium",- parallel=2, rounds=1, max_minutes=10.0, n=6)- c.save()- return c---def overlay(tmp_path: Path) -> loop.VariantPaths:- """A variant's two overlay directories, the way Lane V lays them out, in a tmp tree."""- prompts = tmp_path / "prompts" / "variants" / "argon"- skills = tmp_path / "skills" / "variants" / "argon"- prompts.mkdir(parents=True)- skills.mkdir(parents=True)- (prompts / "variant.toml").write_text(- '[variant]\nname = "argon"\n# the loop bumps it on accept\nversion = 1\n'- 'generators = ["agy:gemini-4-argon"]\ndescription = "argon on the scene track"\n\n[knobs]\nskills_max = 4\n')- (prompts / "README.md").write_text("# argon\n")- (skills / "routes.toml").write_text("# no rows yet\n")- return loop.VariantPaths(name="argon", prompts_root=prompts, skills_root=skills)---def good_prompt(rung: int, k: int) -> GeneratedPrompt:- """A prompt that satisfies rung ``rung``'s rules (and only just: the counts sit under the cap)."""- r = RUNGS[rung]- count = max(1, r.instances // r.asset_types)- lighting = {1: "day", 2: "dusk", 3: "night", 4: "night", 5: "night"}[rung]- features = {1: [], 2: [], 3: [], 4: ["water"], 5: ["interior", "water", "particles"]}[rung]- return GeneratedPrompt(- title=f"place {rung}-{k}", category=CATEGORIES[k % len(CATEGORIES)],- prompt=f"a place number {k} at rung {rung} with zone 0 and zone 1 and a walk-through",- zones=[f"zone {i}" for i in range(r.zones)],- beyond="the lane runs on downhill past the last zone into orchards that fade into the haze",- asset_types=[AssetCount(name=f"things {i}", count=count, designs=2 if i == 0 else 1) for i in range(r.asset_types)],- lighting=lighting, features=features, mood="warm low sun" if lighting != "night" else "lantern glow",- luminance_low=NIGHT_LOW if lighting == "night" else 0.3, luminance_high=0.35 if lighting == "night" else 0.6,- effect="steam rising from two vents", animation="a wheel turns continuously",- camera="at the lane's near end looking along it at 1.6 m",- hero="the hero wheel" if r.hero else "", hero_motion="rotates once per 8 s" if r.hero else "",- scale_constraints=["the tower is 18 m tall", "the arch spans 6 m"] if r.scale else [],- )---def good_battery(rung: int, n: int) -> GeneratedBattery:- return GeneratedBattery(prompts=[good_prompt(rung, k) for k in range(n)])---class FakePlanner:- """Answers a generation request from a script: ``answers[call index]`` → the JSON text. The rung- is read off the request so one fake serves every rung; ``None`` means "a good battery"."""-- provider, model, id = "gemini", "gemini-4-argon", "gemini:gemini-4-argon"-- def __init__(self, answers: list[GeneratedBattery | None] | None = None):- self.answers = answers or []- self.requests: list[ChatRequest] = []-- def generate(self, request: ChatRequest) -> ChatResponse:- self.requests.append(request)- text = request.messages[0].text- rung = int(text.split("for rung ", 1)[1].split(".", 1)[0])- n = int(text.split("Write ", 1)[1].split(" ", 1)[0])- i = len(self.requests) - 1- battery = self.answers[i] if i < len(self.answers) and self.answers[i] is not None else good_battery(rung, n)- return ChatResponse(text=json.dumps(battery.model_dump(mode="json")),- usage=Usage(backend="gemini", model="gemini-4-argon", input_tokens=10, output_tokens=10))---def _write_rows(out_lang: Path, rows: list[BenchItemResult]) -> None:- out_lang.mkdir(parents=True, exist_ok=True)- (out_lang / "results.jsonl").write_text("".join(r.model_dump_json() + "\n" for r in rows))---def _scene_run(out_lang: Path, pid: str, scores: tuple[float, float], *, placement_errors: int = 0,- lib_imports: tuple[str, ...] = ("noise", "finish"), defects: dict[str, bool] | None = None,- caps: list[str] = ()) -> BenchItemResult:- """A scene run under ``out_lang/runs/<pid>``: make_fake_run's record + a scene_placement gate on the- picked round (round 1, the higher score), a deliverable with lib imports, and its bench row."""- ws, rec = make_fake_run(out_lang / "runs", pid, language=THREEJS, generator="agy:gemini-4-argon", scores=scores)- data = json.loads(ws.record_path.read_text())- picked = data["rounds"][1]- findings = [{"gate": "scene_placement", "severity": "error", "target": f"Zone/Crate_{i}",- "message": f"Crate_{i} floats 0.12 m above Ground", "data": {"kind": "floating", "gap_m": 0.12}}- for i in range(placement_errors)]- findings.append({"gate": "scene_placement", "severity": "warn", "target": "Zone/Lamp", "message": "Lamp sunken 0.11 m",- "data": {"kind": "sunken", "sunk_m": 0.11}})- findings.append({"gate": "scene_placement", "severity": "info", "target": "scene", "message": "summary",- "data": {"kind": "summary"}})- picked["gates"].append({"gate": "scene_placement", "passed": placement_errors == 0, "findings": findings})- picked["judgment"]["raw"] = json.dumps({"defects": defects or {}, "caps": {"caps_applied": [{"rule": c, "cap": 0.6} for c in caps]}})- data["extra"] = {"stop_reason": "max_rounds"}- ws.record_path.write_text(json.dumps(data))- src = ws.root / "deliverable" / "src"- (src / "zones").mkdir(parents=True)- (src / "lib").mkdir()- (src / "zones" / "quay.js").write_text("".join(f"import {{ x{i} }} from '../lib/{m}.js';\n" for i, m in enumerate(lib_imports)))- (src / "scene.js").write_text("import { env } from './env.js';\nimport * as three from 'three';\n")- (src / "lib" / "noise.js").write_text("import { k } from './finish.js';\n") # the library's own import: not the agent's- return BenchItemResult(id=pid, tier="medium", category="urban", score_baseline=scores[0], score_picked=scores[1],- picked_round=1, rounds=2, cost_usd=1.5, minutes=12.0, status="max_rounds",- workspace=str(ws.root), generator="agy:gemini-4-argon", judge="gemini:gemini-4-argon")---# --------------------------------------------------------------------------- init-def test_init_writes_the_config_and_snapshots_the_overlay(cfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path):- (cfg.out / loop.LOOP_JSON).unlink() # the fixture saved it; init refuses to overwrite one- p = loop.init(cfg, paths=overlay)- assert p == cfg.out / "loop.json" and loop.LoopConfig.load(cfg.out).languages == [THREEJS, BLENDER]- snap = cfg.out / "snapshots" / "argon_v1"- assert (snap / "prompts" / "variant.toml").is_file() and (snap / "skills" / "routes.toml").is_file()- snapshot = json.loads((snap / "snapshot.json").read_text())- assert snapshot["version"] == 1 and snapshot["hash"] == overlay.ledger_hash(), "the ledger's number, not a private one"- with pytest.raises(loop.LoopError):- loop.init(cfg, paths=overlay)- with pytest.raises(ValueError): # a scene loop runs scene languages only- loop.LoopConfig(name="x", out=tmp_path, variant="argon", languages=[Language.BLENDER], generator="g", judge="j")- assert loop.parse_languages("scene_threejs, scene_blender") == [THREEJS, BLENDER]- with pytest.raises(loop.LoopError):- loop.parse_languages("scene_threejs,nope")---# --------------------------------------------------------------------------- the rungs-def test_the_rung_ladder_is_the_owners_table_and_the_mix_splits_evenly():- assert [(r.zones, r.asset_types, r.instances) for r in RUNGS.values()] == [- (3, 6, 40), (4, 8, 80), (5, 10, 150), (6, 12, 250), (6, 14, 400)]- assert mix_counts(1, 30) == {1: 30} and mix_counts(2, 30) == {1: 15, 2: 15}- assert mix_counts(4, 30) == {1: 7, 2: 7, 3: 8, 4: 8}, "the remainder goes to the hardest rungs"- assert sum(mix_counts(5, 30).values()) == 30- with pytest.raises(ValueError):- mix_counts(6, 30)- for level in RUNGS:- assert check_prompt(good_prompt(level, 0), RUNGS[level]) == [], level- # rung 1: day and no water; rung 4: a hero; rung 5: scale constraints; everyone: a band the gate accepts- wet = good_prompt(1, 0).model_copy(update={"features": ["water"]})- assert any("forbids 'water'" in p for p in check_prompt(wet, RUNGS[1]))- dark = good_prompt(1, 0).model_copy(update={"luminance_low": 0.05})- assert any("luminance band" in p for p in check_prompt(dark, RUNGS[1]))- assert any("hero" in p for p in check_prompt(good_prompt(3, 0), RUNGS[4]))- assert any("scale" in p for p in check_prompt(good_prompt(4, 0), RUNGS[5]))- few = good_prompt(2, 0).model_copy(update={"zones": ["a", "b"]})- assert any("needs at least 4" in p for p in check_prompt(few, RUNGS[2]))- # `beyond` (2026-10-15): what continues past the detailed area is a required field and a contract line,- # so "nothing past the bounds" fails an acceptance item instead of being the default shape- nowhere = good_prompt(1, 0).model_copy(update={"beyond": " "})- assert any("empty beyond" in p for p in check_prompt(nowhere, RUNGS[1]))- lines = contract_lines(good_prompt(4, 1))- assert lines[0].startswith("6 zones: ") and "at least 20 things 0 using at least 2 distinct designs" in lines- assert lines[1].startswith("beyond: the lane runs on downhill") and "continues past the detailed zones" in lines[1]- # the rung text asks for the field and never dictates a layout (no walk-through order, no eye-level default)- for level in RUNGS:- text = rung_text(RUNGS[level])- assert "beyond:" in text and "walk-through" not in text and "in order" not in text and "eye-level" not in text, level- assert any(ln.startswith("night mood:") and f"mean luminance roughly {NIGHT_LOW:.2f}-0.35" in ln for ln in lines)- assert any(ln.startswith("water:") for ln in lines) and any(ln.startswith("hero: the hero wheel") for ln in lines)- assert any("never intersects any geometry" in ln for ln in lines)---def test_the_camera_line_is_a_still_viewpoint_and_old_lines_migrate_once():- """Both scene languages render the authored cameras as STILLS at t = 0 and t = 1.5 s, so a brief that- asked for a dolly was a must-have no run could satisfy (iteration 0: unverified in 5 of 60 runs, a- `missing_must_acceptance` cap on the whole score). The line now states a fixed viewpoint whose height is- the brief's own (2026-10-15: "eye-level" left the prefix — a tower or balcony viewpoint is not an unverified- must item); a cached line of the old moving form is rewritten around the route the model wrote, once, in- the first fixed form, which stays verbatim because the cached rungs pair iterations."""- assert camera_line(" at the quay's landward end looking along it at 1.6 m ") == (- "camera: a FIXED camera, at the quay's landward end looking along it at 1.6 m; the harness renders "- "still cameras only (nothing dollies or tracks); it never intersects any geometry (no clipping, nothing cut by "- "the near plane)")- assert CAMERA_PREFIX == "camera: a FIXED camera" and LEGACY_CAMERA_PREFIX == "camera: a FIXED eye-level camera"- lines = contract_lines(good_prompt(1, 0))- assert [ln for ln in lines if ln.startswith("camera: ")] == [camera_line("at the lane's near end looking along it at 1.6 m")]- assert "still cameras only (nothing dollies or tracks)" in rung_text(RUNGS[1]) and "path" not in rung_text(RUNGS[1])- old_line = ("camera: tracks forward from the gravel access path to the shaded bottling corner at 1.6 m height; the "- "camera never intersects any geometry (no clipping, nothing cut by the near plane)")- old = BenchPrompt(id="it00_scene_threejs_r1_01", prompt="p", tier="medium",- must_have=["3 zones: a, b, c", old_line, "effect: steam rising from a grate"])- fresh = BenchPrompt(id="it02_scene_threejs_r2_01", prompt="p", tier="medium",- must_have=[camera_line("at the gate looking in at 1.6 m"), "animation: the awning extends"])- assert migrate_camera_lines([old, fresh]) == 1- assert old.must_have == [- "3 zones: a, b, c",- 'camera: a FIXED eye-level camera standing where this route begins and looking along it — "tracks forward from '- 'the gravel access path to the shaded bottling corner at 1.6 m height"; the harness renders still cameras only '- "(nothing dollies or tracks); it never intersects any geometry (no clipping, nothing cut by the near plane)",- "effect: steam rising from a grate"]- assert fresh.must_have == [camera_line("at the gate looking in at 1.6 m"), "animation: the awning extends"]- assert migrate_camera_lines([old, fresh]) == 0, "idempotent: the fixed form is recognised, nothing moves twice"- # a cache in the FIRST fixed form (iteration 1's) is recognised too — never wrapped a second time- legacy = BenchPrompt(id="it01_scene_threejs_r1_02", prompt="p", tier="medium",- must_have=[f"{LEGACY_CAMERA_PREFIX}, at the gate looking in at 1.6 m; the harness renders still cameras only"])- before = list(legacy.must_have)- assert migrate_camera_lines([legacy]) == 0 and legacy.must_have == before---def test_the_luminance_floor_is_the_frame_gates_dark_threshold():- """The floor the batteries' bands must clear IS ``frame_metrics.DARK_MEAN_LUM`` (imported, never a- copy): the day the gate is raised, the loop must not keep generating night prompts whose scenes are- ``dark_frame``-gated by construction — a diagnosis would blame the variant for the battery."""- assert LUMINANCE_FLOOR == DARK_MEAN_LUM and 0.0 < LUMINANCE_FLOOR < LUMINANCE_CEILING < 1.0- assert f"{DARK_MEAN_LUM:.2f}" in rung_text(RUNGS[3]), "the generation prompt states the gate's floor"- under = good_prompt(3, 0).model_copy(update={"luminance_low": DARK_MEAN_LUM - 0.01,- "luminance_high": DARK_MEAN_LUM + 0.2})- assert any("luminance band" in p for p in check_prompt(under, RUNGS[3]))- at = under.model_copy(update={"luminance_low": DARK_MEAN_LUM})- assert check_prompt(at, RUNGS[3]) == [], "AT the threshold is not gated (the gate fires on mean < threshold)"---# --------------------------------------------------------------------------- generate-def test_generate_writes_valid_batteries_with_stable_ids_and_a_rising_mix(cfg: loop.LoopConfig):- fake = FakePlanner()- paths = loop.generate_iteration(cfg, 0, rung=1, chat_model=fake)- assert set(paths) == {THREEJS, BLENDER} and len(fake.requests) == 2, "one generation per language"- b = Battery.load(paths[THREEJS])- assert b.language is THREEJS and b.name == "t_loop_it00_scene_threejs"- assert [p.id for p in b.prompts] == [f"it00_scene_threejs_r1_{k:02d}" for k in range(1, 7)]- assert {p.tier for p in b.prompts} == {"medium"} and all("rung1" in p.tags for p in b.prompts)- assert b.prompts[0].must_have[0] == "3 zones: zone 0, zone 1, zone 2"- assert fake.requests[0].response_schema is not None and fake.requests[0].label == "loop:generate"- assert "rung 1" in fake.requests[0].messages[0].text and "FORBIDDEN: water" in fake.requests[0].messages[0].text- assert (cfg.out / "prompts" / "rung_1_scene_threejs.yaml").is_file()- # iteration 1 at the same rung: the cache answers, the ids pair- loop.generate_iteration(cfg, 1, chat_model=fake)- assert len(fake.requests) == 2- assert [p.id for p in Battery.load(cfg.iter_dir(1) / "battery_scene_threejs.yaml").prompts] == [p.id for p in b.prompts]- assert loop.default_rung(cfg, 2) == 1- # --rung 2 moves half the mix up: rung 1's first three ids stay, rung 2 is generated now (ids say it02)- paths2 = loop.generate_iteration(cfg, 2, rung=2, chat_model=fake)- assert len(fake.requests) == 4- ids = [p.id for p in Battery.load(paths2[THREEJS]).prompts]- assert ids[:3] == [f"it00_scene_threejs_r1_{k:02d}" for k in (1, 2, 3)]- assert ids[3:] == [f"it02_scene_threejs_r2_{k:02d}" for k in (1, 2, 3)]- meta = json.loads((cfg.iter_dir(2) / "generate.json").read_text())- assert meta["rung"] == 2 and meta["mix"] == {"1": 3, "2": 3} and meta["ids"]["scene_threejs"] == ids- assert loop.default_rung(cfg, 3) == 2, "the next iteration keeps the rung unless told otherwise"- with pytest.raises(loop.LoopError):- loop.generate_iteration(cfg, 3, rung=9, chat_model=fake)---def test_generate_migrates_an_old_rung_cache_in_place_and_keeps_its_ids(cfg: loop.LoopConfig, caplog):- """A rung cache written before 2026-10-15 carries the moving-camera line iteration 0 ran with; the- next `generate` rewrites that line in the cache (ids untouched — they pair iterations), says so, and- builds the battery from the fixed form. A cache already in the new form is left alone."""- fake = FakePlanner()- loop.generate_iteration(cfg, 0, rung=1, chat_model=fake)- cache = cfg.out / "prompts" / "rung_1_scene_threejs.yaml"- data = yaml.safe_load(cache.read_text())- old_line = ("camera: dollies along the lane at 1.6 m; the camera never intersects any geometry (no clipping, nothing "- "cut by the near plane)")- for p in data["prompts"]: # age the cache to the form iteration 0 was generated with- p["must_have"] = [old_line if ln.startswith("camera: ") else ln for ln in p["must_have"]]- cache.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))- untouched = (cfg.out / "prompts" / "rung_1_scene_blender.yaml").read_text()- with caplog.at_level(logging.INFO):- paths = loop.generate_iteration(cfg, 1, chat_model=fake)- assert len(fake.requests) == 2, "the cache answered: nothing was regenerated"- after = yaml.safe_load(cache.read_text())- assert [p["id"] for p in after["prompts"]] == [p["id"] for p in data["prompts"]]- assert after["camera_lines_migrated"]["n"] == 6 and after["generated_at"] == data["generated_at"]- migrated = [ln for p in after["prompts"] for ln in p["must_have"] if ln.startswith("camera: ")]- assert len(migrated) == 6 and all(- ln.startswith('camera: a FIXED eye-level camera standing where this route begins and looking along it — '- '"dollies along the lane at 1.6 m"; the harness renders still cameras only') for ln in migrated)- assert "migrated 6 camera line(s)" in caplog.text- assert (cfg.out / "prompts" / "rung_1_scene_blender.yaml").read_text() == untouched, "already in the new form"- b = Battery.load(paths[THREEJS])- assert all(any(ln.startswith("camera: a FIXED eye-level camera") for ln in p.must_have) for p in b.prompts)- stamp = cache.stat().st_mtime_ns- loop.generate_iteration(cfg, 2, chat_model=fake)- assert cache.stat().st_mtime_ns == stamp, "idempotent: a migrated cache is not rewritten again"---def test_generate_reasks_once_with_the_typed_problems_then_refuses(tmp_path: Path):- c = loop.LoopConfig(name="t", out=tmp_path / "l", variant="argon", languages=[THREEJS], generator="g", judge="j", n=4)- c.save()- bad = good_battery(1, 4)- bad.prompts[0].zones = ["only one"]- fake = FakePlanner([bad, None])- loop.generate_iteration(c, 0, rung=1, chat_model=fake)- assert len(fake.requests) == 2 and fake.requests[1].label == "loop:generate-reask"- reask = fake.requests[1].messages- assert reask[1].role == "assistant" and reask[2].role == "user" and "needs at least 3" in reask[2].text- assert len(yaml.safe_load((c.out / "prompts" / "rung_1_scene_threejs.yaml").read_text())["prompts"]) == 4- c2 = loop.LoopConfig(name="t2", out=tmp_path / "l2", variant="argon", languages=[THREEJS], generator="g", judge="j", n=4)- c2.save()- with pytest.raises(loop.LoopError, match="after one re-ask"):- loop.generate_iteration(c2, 0, rung=1, chat_model=FakePlanner([bad, bad]))- assert not (c2.out / "prompts").exists(), "a battery that failed the rung rules is never cached"---# --------------------------------------------------------------------------- run-class FakePopen:- calls: list[dict[str, Any]] = []-- def __init__(self, argv: list[str], **kw: Any):- self.argv, self.kw, self.pid, self.returncode = argv, kw, 4242 + len(FakePopen.calls), 0- FakePopen.calls.append({"argv": argv, **kw})-- def poll(self) -> int:- return self.returncode-- def wait(self, timeout: float | None = None) -> int:- return self.returncode---def test_run_builds_the_child_argv_and_env_and_records_exit_codes(cfg: loop.LoopConfig, monkeypatch):- loop.generate_iteration(cfg, 0, rung=1, chat_model=FakePlanner())- installed: list[bool] = []- monkeypatch.setattr(loop, "install_stop_handlers", lambda: installed.append(True))- naps: list[float] = []- # the module's view of `time`, never the global sleep: pytest-xdist's worker threads sleep too- monkeypatch.setattr(loop, "time", NS(sleep=lambda s: naps.append(s), monotonic=time.monotonic))- FakePopen.calls = []- meta = loop.run_iteration(cfg, 0, popen=FakePopen)- assert installed == [True] and len(FakePopen.calls) == 2, "one child per language, side by side"- assert naps == [cfg.stagger_s / 2] == [20.0], "the second child launches half a stagger after the first"- call = FakePopen.calls[0]- argv = call["argv"]- assert argv[:3] == [sys.executable, "-m", "bench.run_bench"] and argv[3] == str(cfg.iter_dir(0) / "battery_scene_threejs.yaml")- assert argv[argv.index("--out") + 1] == str(cfg.iter_dir(0) / "scene_threejs")- for flag, value in (("--generator", "agy:gemini-4-argon"), ("--judge", "gemini:gemini-4-argon"), ("--parallel", "2"),- ("--stagger", "40.0"), ("--rounds", "1"), ("--max-minutes", "10.0"), ("--variant", "argon")):- assert argv[argv.index(flag) + 1] == value, flag- assert "--no-report" in argv and "--redo-status" not in argv and "--planner" not in argv- env = call["env"]- assert (env["C3D_JUDGE__THINKING"], env["C3D_VARIANT"], env["C3D_RENDER__BLENDER_GPU_SLOTS"], env["PYTHONUNBUFFERED"]) == \- ("medium", "argon", "5", "1")- assert call["cwd"] == str(loop.REPO) and call["start_new_session"] is True- run = json.loads((cfg.iter_dir(0) / "run.json").read_text())- assert run["children"]["scene_threejs"]["pid"] == 4242 and run["children"]["scene_blender"]["returncode"] == 0- assert run["wall_s"] >= 0 and (cfg.iter_dir(0) / "run_scene_threejs.log").read_text().startswith("--- ")- assert meta["children"]["scene_blender"]["argv"][3].endswith("battery_scene_blender.yaml")- # --resume re-runs what the weather lost; one language only runs one child- FakePopen.calls = []- naps.clear()- loop.run_iteration(cfg, 0, languages=[BLENDER], resume=True, popen=FakePopen)- assert len(FakePopen.calls) == 1 and FakePopen.calls[0]["argv"][-2:] == ["--redo-status", "infra_failed"]- assert naps == [], "one child: nothing to interleave with"- with pytest.raises(loop.LoopError, match="generate"):- loop.run_iteration(cfg, 5, popen=FakePopen)- # the stagger is a loop knob: a loop.json from before it loads with the default, and 0 means no flag- data = json.loads((cfg.out / loop.LOOP_JSON).read_text())- del data["stagger_s"]- (cfg.out / loop.LOOP_JSON).write_text(json.dumps(data))- assert loop.LoopConfig.load(cfg.out).stagger_s == 40.0- flat = cfg.model_copy(update={"stagger_s": 0.0})- assert "--stagger" not in loop.child_argv(flat, THREEJS, Path("b.yaml"), Path("o"), resume=False)- with pytest.raises(ValueError):- loop.LoopConfig(name="x", out=cfg.out, variant="argon", languages=[THREEJS], generator="g", judge="j", stagger_s=-1)- base = loop.child_env(loop.LoopConfig(name="b", out=cfg.out, variant="", languages=[THREEJS], generator="g", judge="j"),- base={"C3D_VARIANT": "stale"})- assert "C3D_VARIANT" not in base, "no variant: the launching shell's cannot leak into the base run"---# --------------------------------------------------------------------------- diagnose-def test_lib_import_scanners_read_the_agents_files(tmp_path: Path):- py = tmp_path / "zone.py"- py.write_text("from lib.place import seat\nimport lib.noise\nfrom lib import scatter, motion\nfrom os import path\n"- "import math\nfrom .local import x\n")- assert sorted(set(py_lib_modules(py))) == ["motion", "noise", "place", "scatter"]- js = tmp_path / "zone.js"- js.write_text("import { fbm } from '../lib/noise.js';\nimport { finish } from \"./lib/finish.js\";\n"- "import * as THREE from 'three';\nimport { x } from '../other/lib/x.js';\n")- assert js_lib_modules(js) == ["noise", "finish"]- (tmp_path / "broken.py").write_text("def (:\n")- assert py_lib_modules(tmp_path / "broken.py") == []---def test_diagnose_reads_records_gates_library_use_and_recommends(cfg: loop.LoopConfig):- out_lang = cfg.iter_dir(0) / "scene_threejs"- rows = [- _scene_run(out_lang, "it00_scene_threejs_r1_01", (0.5, 0.7), placement_errors=2,- defects={"floating_asset": True, "flat_ground": False}, caps=["floating_asset"]),- _scene_run(out_lang, "it00_scene_threejs_r1_02", (0.4, 0.6), placement_errors=1, lib_imports=("noise",),- defects={"floating_asset": True}, caps=["floating_asset", "missing_must_acceptance"]),- _scene_run(out_lang, "it00_scene_threejs_r1_03", (0.6, 0.8), lib_imports=("noise", "finish", "sky", "water")),- _scene_run(out_lang, "it00_scene_threejs_r1_04", (0.55, 0.65)),- BenchItemResult(id="it00_scene_threejs_r1_05", tier="medium", status="infra_failed", errors="ModelError: 503 overloaded"),- ]- _write_rows(out_lang, rows)- # a redo archived an older tree beside run 04 (run_bench.archive_attempt): same spec id, sorts- # after the live run — it must never stand in for it- _scene_run(out_lang, "it00_scene_threejs_r1_04.attempt1", (0.1, 0.1), placement_errors=5)- stale = json.loads((out_lang / "runs" / "it00_scene_threejs_r1_04.attempt1" / "record.json").read_text())- stale["spec"]["id"] = "it00_scene_threejs_r1_04"- (out_lang / "runs" / "it00_scene_threejs_r1_04.attempt1" / "record.json").write_text(json.dumps(stale))- d = diagnose_dir("scene_threejs", out_lang)- assert d.n == 5 and d.by_status == {"infra_failed": 1, "max_rounds": 4} and d.n_scored == 4- assert d.picked["mean"] == pytest.approx(0.6875) and d.baseline["mean"] == pytest.approx(0.5125)- assert set(d.criteria_mean) == {"fidelity", "geometry"} and d.criteria_mean["fidelity"] == pytest.approx(0.6875)- assert d.gate_error_runs["scene_placement/floating"] == 2 and d.gate_error_total["scene_placement/floating"] == 3- assert d.gate_warn_total["scene_placement/sunken"] == 4 and "scene_placement/summary" not in d.gate_warn_total- assert d.defect_rates == {"floating_asset": 0.5} and d.caps_fired == {"floating_asset": 2, "missing_must_acceptance": 1}- assert d.lib_module_hist == {"noise": 4, "finish": 3, "sky": 1, "water": 1}, "src/lib's own imports never count"- assert d.lib_modules_mean == pytest.approx((2 + 1 + 4 + 2) / 4)- assert d.metrics["floating_error_rate"] == 0.5 and d.metrics["infra_failed_rate"] == 0.2- assert d.metrics["missing_must_rate"] == 0.25 and d.metrics["budget_stop_rate"] == 0.0- fired = {r.rule for r in d.recommendations}- assert {"floating", "library", "weather", "must"} <= fired and "lighting" not in fired and "budget" not in fired- # minutes come from the record (RunRecord.minutes, THE number), never the row: make_fake_run's- # plan step 24 s active + two 12 s rounds = 0.8 min, whatever the row says- assert d.stop_reasons == {"max_rounds": 4} and d.cost_total == pytest.approx(6.0) and d.minutes_mean == pytest.approx(0.8)- assert d.top_issues[0][0] == "geometry" and d.top_issues[0][1] == "Leg"- # the command writes both files, every language in one diagnosis- res = loop.diagnose_iteration(cfg, 0)- assert set(res) == {"scene_threejs"} # scene_blender never ran: skipped with a warning- md = (cfg.iter_dir(0) / "diagnosis.md").read_text()- assert "RECOMMENDATIONS" in md and "placement recipe" in md and "scene_placement/floating | 2 | 3 | 0" in md- data = json.loads((cfg.iter_dir(0) / "diagnosis.json").read_text())- assert data["scene_threejs"]["n"] == 5 and len(data["scene_threejs"]["runs"]) == 5- with pytest.raises(loop.LoopError):- loop.diagnose_iteration(cfg, 7)---# --------------------------------------------------------------------------- compare-def _stats(deltas: dict[str, float]) -> PairedStats:- return PairedStats(harness_arm="a", oneshot_arm="b", n=len(deltas), deltas=deltas)---def test_the_loop_verdict_is_decide_plus_the_gate_veto():- up = {f"p{i}": d for i, d in enumerate((0.10, 0.11, 0.09, 0.12))}- assert loop_verdict(_stats(up), 0.0)[0] == "keep"- assert loop_verdict(_stats(up), None)[0] == "keep"- assert loop_verdict(_stats({k: -v for k, v in up.items()}), 0.0)[0] == "revert"- assert loop_verdict(_stats({"p0": 0.25, "p1": 0.01, "p2": 0.0, "p3": 0.02}), 0.0)[0] == "inconclusive"- assert loop_verdict(_stats({"p0": 0.3, "p1": 0.3}), 0.0)[0] == "inconclusive", "two pairs decide nothing"- decision, reason = loop_verdict(_stats(up), 1.5)- assert decision == "revert" and reason.startswith("gate veto") and "score said better" in reason- assert loop_verdict(_stats(up), 1.0)[0] == "keep", "a rise AT the limit is not a veto"---def test_compare_pairs_by_id_and_the_placement_veto_overrides_the_score(cfg: loop.LoopConfig):- a, b = cfg.iter_dir(1) / "scene_threejs", cfg.iter_dir(0) / "scene_threejs"- ids = [f"it00_scene_threejs_r1_{k:02d}" for k in range(1, 5)]- _write_rows(b, [_scene_run(b, pid, (0.4, 0.6)) for pid in ids] + [_scene_run(b, "it00_scene_threejs_r1_09", (0.4, 0.6))])- _write_rows(a, [_scene_run(a, pid, (0.4, 0.6 + 0.1 * (i + 1) / (i + 1))) for i, pid in enumerate(ids)])- c = compare_dirs("scene_threejs", a, b)- assert c.paired.n == 4 and c.dropped_ids == ["it00_scene_threejs_r1_09"]- assert c.paired.mean_delta == pytest.approx(0.1) and c.decision == "keep"- assert c.criteria_delta == {"fidelity": pytest.approx(0.1), "geometry": pytest.approx(0.1)}- assert c.placement_rise == 0.0 and c.gate_error_delta == {} and c.cost_delta == 0.0- # the same scores, but the candidate's scenes gain two floating ERRORs each: the gate wins- a2 = cfg.iter_dir(2) / "scene_threejs"- _write_rows(a2, [_scene_run(a2, pid, (0.4, 0.7), placement_errors=2) for pid in ids])- c2 = compare_dirs("scene_threejs", a2, b)- assert c2.placement_rise == 2.0 and c2.decision == "revert" and "gate veto" in c2.reason- assert c2.gate_error_delta == {"scene_placement/floating": 8} and PLACEMENT_KINDS[0] == "scene_placement/floating"- res = loop.compare_iteration(cfg, 2, 0)- assert res["scene_threejs"].decision == "revert"- md = (cfg.iter_dir(2) / "compare_scene_threejs.md").read_text()- assert "**revert**" in md and "| it00_scene_threejs_r1_01 | +0.100 |" in md- assert json.loads((cfg.iter_dir(2) / "compare_scene_threejs.json").read_text())["paired"]["n"] == 4- with pytest.raises(loop.LoopError):- loop.compare_iteration(cfg, 2, 2)---# --------------------------------------------------------------------------- judge-calib-def test_judge_calib_rejudges_each_picked_round_in_fixed_order_and_summarises(cfg: loop.LoopConfig):- out_lang = cfg.iter_dir(0) / "scene_threejs"- _write_rows(out_lang, [_scene_run(out_lang, "p1", (0.5, 0.7), placement_errors=2), _scene_run(out_lang, "p2", (0.6, 0.9))])- seen: list[dict[str, Any]] = []-- def fake_calibrate(run_dirs, **kw):- seen.append({"run_dirs": run_dirs, **kw})- pid = Path(run_dirs[0]).name- mean, std = (0.65, 0.02) if pid == "p1" else (0.88, 0.04)- row = CalibrationRow(run=pid, round=kw["rounds"][0], kind="refine", gate_errors=2 if pid == "p1" else 0,- gate_warnings=1, stored_overall=0.7 if pid == "p1" else 0.9, mean=mean, std=std,- uncapped=mean, defect_penalty=0.0, defects_present=["floating_asset"] if pid == "p1" else [],- caps=["floating_asset"] if pid == "p1" else [], passed=True, n_used=3, cost_usd=0.05,- duration_s=20.0)- return CalibrationTable(model_id=kw["model_id"], n_samples=kw["n_samples"], fixed_order=True, rows=[row])-- res = loop.judge_calib(cfg, 0, calibrate_fn=fake_calibrate, workers=2)- assert len(seen) == 2 and {s["rounds"][0] for s in seen} == {1}, "the picked round only"- assert all(s["fixed_order"] and s["thinking"] == "medium" and s["model_id"] == "gemini:gemini-4-argon"- and s["n_samples"] == 3 and s["geometry_mode"] is None for s in seen)- assert all(str(s["out_dir"]).startswith(str(cfg.iter_dir(0) / "judge_calib" / "scene_threejs")) for s in seen)- s = res["scene_threejs"]- assert s.rounds == 2 and s.within_sd == pytest.approx(((0.02 ** 2 + 0.04 ** 2) / 2) ** 0.5, abs=1e-4)- assert s.between_sd == pytest.approx(0.1626, abs=1e-3) and s.snr == pytest.approx(s.between_sd / s.within_sd, abs=1e-2)- assert s.defects == {"floating_asset": 1} and s.caps == {"floating_asset": 1} and s.cost_usd == pytest.approx(0.1)- assert s.mean_stored == pytest.approx(0.8) and s.pearson_errors_vs_score is None, "two rounds: no correlation"- md = (cfg.iter_dir(0) / "judge_calib_scene_threejs.md").read_text()- assert "within-sd" in md and "gemini:gemini-4-argon" in md- assert json.loads((cfg.iter_dir(0) / "judge_calib_scene_threejs.json").read_text())["thinking"] == "medium"- res2 = loop.judge_calib(cfg, 0, model_id="gemini:other", thinking="high", n_samples=5, calibrate_fn=fake_calibrate)- assert seen[-1]["model_id"] == "gemini:other" and seen[-1]["thinking"] == "high" and res2["scene_threejs"].n_samples == 5---# --------------------------------------------------------------------------- accept / rollback / status-def test_accept_bumps_snapshots_and_rollback_restores(cfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path):- data_dir = tmp_path / "data"- (cfg.out / loop.LOOP_JSON).unlink()- loop.init(cfg, paths=overlay)- it1 = cfg.iter_dir(1)- it1.mkdir(parents=True)- (it1 / "battery_scene_threejs.yaml").write_text("name: x\n")- (it1 / "compare_scene_threejs.json").write_text(json.dumps({"decision": "keep"}))- # the iteration-1 edit of the overlay- (overlay.prompts_root / "scene_threejs").mkdir()- (overlay.prompts_root / "scene_threejs" / "system.md").write_text("# seat everything\n")- (overlay.skills_root / "routes.toml").write_text('[[boost]]\nskill = "c3d-scene-placement"\ndelta = 20\n')- before = overlay.overlay_hash()- row = loop.accept(cfg, 1, note="placement recipe", paths=overlay, data_dir=data_dir)- assert (row.decision, row.version_from, row.version_to, row.note) == ("accept", 1, 2, "placement recipe")- assert row.verdicts == {"scene_threejs": "keep"} and row.languages == ["scene_threejs", "scene_blender"]- assert row.variant_hash == overlay.overlay_hash() != before, "the bump is part of the hash"- assert row.battery_sha and len(row.battery_sha) == 12 and row.cost_usd == 0.0- assert overlay.version() == 2- toml = overlay.toml.read_text()- assert "# the loop bumps it on accept" in toml and "version = 2" in toml and "[knobs]" in toml- snap2 = cfg.out / "snapshots" / "argon_v2"- assert (snap2 / "prompts" / "scene_threejs" / "system.md").is_file() and "delta = 20" in (snap2 / "skills" / "routes.toml").read_text()- assert json.loads((snap2 / "snapshot.json").read_text())["hash"] == row.variant_hash, "one number for the snapshot and the row"- ledger = loop.ledger_path(cfg, data_dir)- assert ledger == data_dir / "t_loop" / "ledger.jsonl" and len(loop.ledger_rows(ledger)) == 1- # iteration 2 edits, then a rollback: the edits go, version 2 stays- (overlay.prompts_root / "scene_threejs" / "system.md").write_text("# a worse idea\n")- (overlay.prompts_root / "scene_threejs" / "extra.md").write_text("x\n")- it2 = cfg.iter_dir(2)- it2.mkdir()- row2 = loop.rollback(cfg, 2, note="worse", paths=overlay, data_dir=data_dir)- assert (row2.decision, row2.version_from, row2.version_to) == ("rollback", 2, 2)- assert (overlay.prompts_root / "scene_threejs" / "system.md").read_text() == "# seat everything\n"- assert not (overlay.prompts_root / "scene_threejs" / "extra.md").exists() and overlay.version() == 2- # rolling back the accepted iteration itself un-accepts it: v1 comes back, the system.md overlay and boost gone- row3 = loop.rollback(cfg, 1, paths=overlay, data_dir=data_dir)- assert (row3.version_from, row3.version_to) == (2, 1) and overlay.version() == 1- assert not (overlay.prompts_root / "scene_threejs").exists() and (overlay.skills_root / "routes.toml").read_text() == "# no rows yet\n"- rows = loop.ledger_rows(ledger)- assert [r.decision for r in rows] == ["accept", "rollback", "rollback"] and rows[0].ts < rows[-1].ts- text = loop.status_text(cfg, paths=overlay, data_dir=data_dir)- assert "variant argon v1" in text and "| 1 | accept | 1→2 |" in text and "scene_threejs=keep" in text- with pytest.raises(loop.LoopError, match="snapshot"):- loop.rollback(loop.LoopConfig(name="other", out=tmp_path / "o", variant="argon", languages=[THREEJS],- generator="g", judge="j"), 1, paths=overlay, data_dir=data_dir)- stray = loop.VariantPaths(name="argon", prompts_root=tmp_path / "not_an_overlay", skills_root=overlay.skills_root)- (tmp_path / "not_an_overlay").mkdir()- with pytest.raises(loop.LoopError, match="refusing"):- stray.restore_from(cfg.out / "snapshots" / "argon_v1")---def test_the_snapshot_hash_is_the_ledger_hash_not_the_loops_own(cfg: loop.LoopConfig, overlay: loop.VariantPaths,- tmp_path: Path, monkeypatch):- """snapshot.json, the ledger row and the iteration's run records must say ONE number — the variant- layer's ``variant_hash`` (README.md left out) — so a snapshot pairs with the runs it was measured on;- the loop's own ``overlay_hash`` (every file) is only the fallback for a tree the layer does not know."""-- class FakeVariants:- """The D105 API, pointed at the tmp overlay: it knows the tree and hashes it its own way."""-- def variant_info(self, name: str) -> Any:- return NS(name=name, version=1)-- def variant_root(self, name: str) -> Path:- return overlay.prompts_root-- def variant_hash(self, name: str) -> str:- return "feedfacecafe"-- monkeypatch.setattr(loop, "_variants_api_or_none", lambda: FakeVariants())- assert overlay.ledger_hash() == "feedfacecafe" != overlay.overlay_hash()- snap = overlay.snapshot_to(tmp_path / "snap")- assert json.loads((snap / "snapshot.json").read_text())["hash"] == "feedfacecafe"- (cfg.out / loop.LOOP_JSON).unlink()- loop.init(cfg, paths=overlay)- assert json.loads((cfg.out / "snapshots" / "argon_v1" / "snapshot.json").read_text())["hash"] == "feedfacecafe"- cfg.iter_dir(1).mkdir()- row = loop.accept(cfg, 1, paths=overlay, data_dir=tmp_path / "data")- assert row.variant_hash == "feedfacecafe"- assert json.loads((cfg.out / "snapshots" / "argon_v2" / "snapshot.json").read_text())["hash"] == row.variant_hash- # a tree the layer does not know (another prompts_root): the fallback, and it is the same number- # in the row and the snapshot- stray = loop.VariantPaths(name="argon", prompts_root=tmp_path / "elsewhere" / "variants" / "argon",- skills_root=overlay.skills_root)- stray.prompts_root.mkdir(parents=True)- (stray.prompts_root / "variant.toml").write_text('[variant]\nname = "argon"\nversion = 1\n')- assert stray.ledger_hash() == stray.overlay_hash() != "feedfacecafe"- assert json.loads((stray.snapshot_to(tmp_path / "stray") / "snapshot.json").read_text())["hash"] == stray.overlay_hash()---def test_the_shipped_overlays_snapshot_hash_is_the_run_records_hash(tmp_path: Path):- """The real ``argon`` overlay, read-only (``snapshot_to`` only copies): the snapshot's number IS- ``prompts.variants.variant_hash`` — what a run record carries — and the loop-private fingerprint- differs from it by the README.md the overlay ships."""- real = loop.VariantPaths.default("argon")- data = json.loads((real.snapshot_to(tmp_path / "real") / "snapshot.json").read_text())- assert data["hash"] == real.ledger_hash() == variant_hash("argon") and len(data["hash"]) == 12- if any(rel.endswith("/README.md") for rel, _ in real.files()):- assert real.overlay_hash() != data["hash"], "README.md is in the tree but never in the record's hash"---def test_init_and_accept_refuse_a_skills_overlay_a_run_would_degrade(cfg: loop.LoopConfig, overlay: loop.VariantPaths,- tmp_path: Path):- """A run never refuses a broken overlay — ``variants_table`` logs a routes.toml that does not- type-check and routes with the BASE table, ``iter_skills`` skips an invalid bundle — so the loop- must, BEFORE a version, a snapshot or a ledger row claims the overlay was measured."""- data_dir = tmp_path / "data"- (cfg.out / loop.LOOP_JSON).unlink()- routes = overlay.skills_root / "routes.toml"- routes.write_text('[[route]]\nrule = "V1"\nskill = "c3d-scene-materials"\npriority = "85"\ntracks = ["scene"]\n')- with pytest.raises(loop.LoopError, match="routes.toml does not type-check.*priority must be an integer"):- loop.init(cfg, paths=overlay)- assert not (cfg.out / loop.LOOP_JSON).exists() and not (cfg.out / "snapshots").exists(), "refused before anything was written"- routes.write_text("# no rows yet\n")- loop.init(cfg, paths=overlay)- cfg.iter_dir(1).mkdir(parents=True)-- def refused(pattern: str) -> None:- with pytest.raises(loop.LoopError, match=pattern):- loop.accept(cfg, 1, paths=overlay, data_dir=data_dir)- assert overlay.version() == 1 and not (cfg.out / "snapshots" / "argon_v2").exists()- assert not loop.ledger_path(cfg, data_dir).exists()-- # a rule id the base table already uses; then an overlay bundle the run would skip: a frontmatter- # naming another bundle, then one that parses but fails the library's standards- routes.write_text('[[route]]\nrule = "R1"\nskill = "c3d-scene-materials"\npriority = 85\ntracks = ["scene"]\n')- refused("already taken")- routes.write_text('[[boost]]\nskill = "c3d-scene-materials"\ndelta = 20\n')- bundle = overlay.skills_root / "c3d-scene-placement"- bundle.mkdir()- (bundle / "SKILL.md").write_text("---\nname: c3d-other\ndescription: x\n---\n\nbody\n")- refused(r"skill bundle c3d-scene-placement .* is invalid .*directory name")- (bundle / "SKILL.md").write_text("---\nname: c3d-scene-placement\ndescription: x\n---\n\nbody\n")- refused("metadata.verified")- # fixed: accept goes through, and the snapshot carries the bundle- (bundle / "SKILL.md").write_text(VALID_SKILL)- row = loop.accept(cfg, 1, paths=overlay, data_dir=data_dir)- assert row.version_to == 2 and (cfg.out / "snapshots" / "argon_v2" / "skills" / "c3d-scene-placement" / "SKILL.md").is_file()- assert overlay.preflight() is None and len(loop.ledger_rows(loop.ledger_path(cfg, data_dir))) == 1---def test_accept_needs_the_iteration_and_a_version_line(cfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path):- with pytest.raises(loop.LoopError, match="does not exist"):- loop.accept(cfg, 3, paths=overlay, data_dir=tmp_path / "d")- overlay.toml.write_text('[variant]\nname = "argon"\n')- with pytest.raises(loop.LoopError):- overlay.version()- overlay.toml.write_text('[variant]\nname = "argon"\nversion = 3\n[knobs]\nversion = 9\n')- overlay.set_version(4)- assert overlay.toml.read_text() == '[variant]\nname = "argon"\nversion = 4\n[knobs]\nversion = 9\n', "only [variant].version moves"---# --------------------------------------------------------------------------- CLI-def test_the_cli_dispatches_and_refuses_without_a_loop(tmp_path: Path, capsys, monkeypatch):- assert loop.main(["status", "--out", str(tmp_path / "none")]) == 2- assert "bench.loop init" in capsys.readouterr().err- out = tmp_path / "l"- monkeypatch.setattr(loop, "_variants_api_or_none", lambda: None)- assert loop.main(["init", "--name", "t", "--out", str(out), "--variant", "argon", "--languages", "scene_threejs",- "--parallel", "3", "--stagger", "5", "--rounds", "1", "--max-minutes", "20", "--n", "4"]) == 0- c = loop.LoopConfig.load(out)- assert (c.parallel, c.stagger_s, c.rounds, c.max_minutes, c.n, c.languages) == (3, 5.0, 1, 20.0, 4, [THREEJS])- assert c.out == out.resolve() and c.judge_thinking == "medium"- assert loop.main(["init", "--name", "t", "--out", str(out), "--variant", "argon"]) == 2, "one loop per --out"- assert loop.main(["status", "--out", str(out)]) == 0- assert "loop t: variant argon" in capsys.readouterr().out---# =========================================================================== the scene path, pinned-#: sha256[:16] of the scene batteries `generate` wrote BEFORE the loop learned the other tracks-#: (main 9a8333e0, FakePlanner, the `cfg` fixture's knobs): iteration 0 at rung 1, iteration 2 at rung 2.-#: The multi-track change must leave the scene path byte-identical — same ids, same caches, same files.-SCENE_GOLDEN = {- "iter_00/battery_scene_blender.yaml": "e86879fc2fee3a52",- "iter_00/battery_scene_threejs.yaml": "bb12ccfa9863484f",- "iter_02/battery_scene_blender.yaml": "311ce859a978527d",- "iter_02/battery_scene_threejs.yaml": "f1c5102f944ff60d",-}---def test_the_scene_generate_path_is_byte_identical_to_before_the_other_tracks(cfg: loop.LoopConfig):- import hashlib-- fake = FakePlanner()- loop.generate_iteration(cfg, 0, rung=1, chat_model=fake)- loop.generate_iteration(cfg, 2, rung=2, chat_model=fake)- got = {rel: hashlib.sha256((cfg.out / rel).read_bytes()).hexdigest()[:16] for rel in SCENE_GOLDEN}- assert got == SCENE_GOLDEN- meta = json.loads((cfg.iter_dir(2) / "generate.json").read_text())- assert sorted(meta) == ["batteries", "generated_at", "ids", "iteration", "languages", "mix", "n", "rung"], \- "the scene generate.json keeps its keys: no track / tiers / sources"- assert sorted(p.name for p in (cfg.out / "prompts").iterdir()) == [- "rung_1_scene_blender.yaml", "rung_1_scene_threejs.yaml", "rung_2_scene_blender.yaml", "rung_2_scene_threejs.yaml"]---# =========================================================================== the other tracks-BLENDER_OBJ, THREEJS_OBJ, CADQUERY = Language.BLENDER, Language.THREEJS, Language.CADQUERY---def _battery_file(path: Path, track: str, language: str, prompts: list[dict[str, Any]]) -> Path:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(yaml.safe_dump({"name": path.stem, "track": track, "language": language, "prompts": prompts}))- return path---def _p(pid: str, tier: str, text: str, *, must: int = 2, **kw: Any) -> dict[str, Any]:- return {"id": pid, "tier": tier, "category": "furniture", "prompt": text,- "must_have": [f"item {i}" for i in range(must)], **kw}---def sources(tmp_path: Path) -> list[Path]:- """Two small static_object batteries: a duplicate by text (b_med_1 = a_med_1, case and spaces- aside), an id collision (b's a_hard_1 is another prompt), one three.js-only prompt, an easy one,- a relative reference, and one medium with more acceptance items than the rest (the hardest)."""- (tmp_path / "src" / "refs").mkdir(parents=True)- (tmp_path / "src" / "refs" / "stool.png").write_bytes(b"png")- a = _battery_file(tmp_path / "src" / "a.yaml", "static_object", "blender", [- _p("a_easy_1", "easy", "a plain cube"),- _p("a_med_1", "medium", "a wooden stool with three legs", references=["refs/stool.png"]),- _p("a_med_2", "medium", "a ceramic teapot"),- _p("a_hard_1", "hard", "a rolltop desk with pigeonholes"),- _p("a_hard_2", "hard", "a penny-farthing bicycle"),- _p("a_hard_3", "hard", "a lattice dome pavilion", language="threejs"),- ])- b = _battery_file(tmp_path / "src" / "b.yaml", "static_object", "blender", [- _p("b_med_1", "medium", " A wooden stool with three LEGS "),- _p("a_hard_1", "hard", "a completely different prompt under a taken id"),- _p("b_hard_1", "hard", "a drill press on a cast base"),- _p("b_med_3", "medium", "a brass desk lamp", must=5),- ])- return [a, b]---def ocfg(tmp_path: Path, sources: list[Path]) -> loop.LoopConfig:- c = loop.LoopConfig(name="t_static", out=tmp_path / "loop_static", variant="argon", track="static_object",- languages=[BLENDER_OBJ, THREEJS_OBJ], source=[str(p) for p in sources],- generator="agy:gemini-4-argon", judge="gemini:gemini-4-argon", parallel=2, rounds=1,- max_minutes=10.0, n=4)- c.save()- return c---def test_init_validates_the_languages_by_track_and_needs_sources_off_the_scene_track(- tmp_path: Path, sources: list[Path], capsys, monkeypatch):- src = [str(p) for p in sources]- ok = loop.LoopConfig(name="s", out=tmp_path, variant="argon", track="static_object", languages=[BLENDER_OBJ],- source=src, generator="g", judge="j")- assert ok.track is loop.Track.STATIC_OBJECT- for bad in ({"track": "static_object", "languages": [BLENDER], "source": src}, # scene_blender: not static- {"track": "static_object", "languages": [BLENDER_OBJ]}, # no source- {"track": "scene", "languages": [THREEJS], "source": src}, # scene generates its own- {"track": "graphics", "languages": [Language.URDF_BLENDER], "source": src}):- with pytest.raises(ValueError):- loop.LoopConfig(name="s", out=tmp_path, variant="argon", generator="g", judge="j", **bad)- # the running scene loop's loop.json (written before `source` and `stagger_s` existed) loads as a scene loop- old = tmp_path / "old_scene"- old.mkdir()- (old / loop.LOOP_JSON).write_text(json.dumps({- "schema_version": 1, "name": "argon_scene", "out": str(old), "variant": "argon",- "languages": ["scene_threejs", "scene_blender"], "generator": "agy:gemini-4-argon",- "judge": "gemini:gemini-4-argon", "judge_thinking": "medium", "planner": "", "parallel": 15, "rounds": 1,- "max_minutes": 90.0, "n": 15, "track": "scene", "created_at": "2026-10-15T09:14:55.651617+00:00"}))- sc = loop.LoopConfig.load(old)- assert sc.track is loop.Track.SCENE and sc.source == [] and sc.languages == [THREEJS, BLENDER]- # --source: a bare name resolves under bench/prompts/ and is stored relative to eval/; a file- # outside eval/ stays absolute; a missing one is refused- assert loop.parse_sources("compare_v4.yaml, bench/prompts/graphics_v1.yaml") == [- "bench/prompts/compare_v4.yaml", "bench/prompts/graphics_v1.yaml"]- assert loop.parse_sources(f"{sources[0]},{sources[0]}") == [str(sources[0].resolve())]- with pytest.raises(loop.LoopError, match="no such battery"):- loop.parse_sources("nope_v9.yaml")- # the CLI: --track decides the default languages; a scene language on an object track is exit 2- monkeypatch.setattr(loop, "_variants_api_or_none", lambda: None)- out = tmp_path / "cli"- assert loop.main(["init", "--name", "s", "--out", str(out), "--variant", "argon", "--track", "static_object",- "--source", ",".join(src)]) == 0- c = loop.LoopConfig.load(out)- assert c.languages == [BLENDER_OBJ, CADQUERY, THREEJS_OBJ] and c.source == [str(p.resolve()) for p in sources]- assert loop.main(["init", "--name", "s", "--out", str(tmp_path / "cli2"), "--variant", "argon",- "--track", "static_object", "--languages", "scene_blender", "--source", src[0]]) == 2- assert loop.main(["init", "--name", "s", "--out", str(tmp_path / "cli3"), "--variant", "argon",- "--track", "articulated_object"]) == 2- assert "--source is required" in capsys.readouterr().err- assert not (tmp_path / "cli2").exists() and not (tmp_path / "cli3").exists()- assert loop.main(["status", "--out", str(out)]) == 0- assert "track static_object" in capsys.readouterr().out---def test_generate_from_sources_dedupes_routes_and_selects_by_rung(ocfg: loop.LoopConfig, sources: list[Path], caplog):- from bench._loop_sources import SOURCE_RUNGS, stable_rank-- def by_hash(ids: list[str]) -> list[str]:- return sorted(ids, key=lambda i: stable_rank(ocfg.name, i))-- paths = loop.generate_iteration(ocfg, 0, rung=1)- blender, threejs = Battery.load(paths[BLENDER_OBJ]), Battery.load(paths[THREEJS_OBJ])- assert (blender.track.value, blender.language, threejs.language) == ("static_object", BLENDER_OBJ, THREEJS_OBJ)- assert blender.name == "t_static_it00_blender"- medium = by_hash(["a_med_1", "a_med_2", "b_med_3"])- # rung 1: every medium first (hash order), then the hash-first hard of what the language may run- assert [p.id for p in blender.prompts] == medium + by_hash(["a_hard_1", "a_hard_2", "b_hard_1"])[:1]- assert [p.id for p in threejs.prompts] == medium + by_hash(["a_hard_1", "a_hard_2", "a_hard_3", "b_hard_1"])[:1]- pooled = {p.id: p for b in (blender, threejs) for p in b.prompts}- assert "b_med_1" not in pooled and "a_easy_1" not in pooled, "the duplicate by text and the easy tier never run"- stool = next(p for p in blender.prompts if p.id == "a_med_1")- assert stool.references == [str((sources[0].parent / "refs" / "stool.png").resolve())], "made absolute"- meta = json.loads((ocfg.iter_dir(0) / "generate.json").read_text())- assert meta["track"] == "static_object" and meta["rung"] == 1 and meta["n"] == 4- assert meta["sources"] == ocfg.source and meta["tiers"] == [["medium", "hash"], ["hard", "hash"]]- assert meta["pool"] == {"size": 8, "duplicates": ["b_med_1"], "id_collisions": ["a_hard_1"]}- assert meta["tier_counts"]["blender"] == {"medium": 3, "hard": 1} and meta["short"] == {}- assert meta["ids"]["blender"] == [p.id for p in blender.prompts]- # the next iteration at the same rung: the same ids (the pairs), and the rung carries over- assert loop.default_rung(ocfg, 1) == 1- loop.generate_iteration(ocfg, 1)- again = Battery.load(ocfg.iter_dir(1) / "battery_blender.yaml")- assert [p.model_dump() for p in again.prompts] == [p.model_dump() for p in blender.prompts], "same ids, same prompts"- # rung 2: hard first, then the HARDEST medium (b_med_3: five acceptance items); three.js has four hard- loop.generate_iteration(ocfg, 2, rung=2)- b2 = [p.id for p in Battery.load(ocfg.iter_dir(2) / "battery_blender.yaml").prompts]- t2 = Battery.load(ocfg.iter_dir(2) / "battery_threejs.yaml").prompts- assert b2 == by_hash(["a_hard_1", "a_hard_2", "b_hard_1"]) + ["b_med_3"]- assert {p.tier for p in t2} == {"hard"} and len(t2) == 4- assert next(p for p in t2 if p.id == "a_hard_3").language is THREEJS_OBJ, "the per-prompt language rides along"- assert next(p for p in t2 if p.id == "a_hard_1").prompt == "a rolltop desk with pigeonholes", "the first id wins"- # rung 3 and above: hard only — blender holds three, n is four: a shorter battery, said out loud- with caplog.at_level(logging.WARNING):- loop.generate_iteration(ocfg, 3, rung=5)- meta3 = json.loads((ocfg.iter_dir(3) / "generate.json").read_text())- assert meta3["short"] == {"blender": {"wanted": 4, "got": 3}} and "the battery runs 3" in caplog.text- assert meta3["tiers"] == [["hard", "hash"]] and SOURCE_RUNGS[3] == SOURCE_RUNGS[max(SOURCE_RUNGS)]- assert [p.id for p in Battery.load(ocfg.iter_dir(3) / "battery_blender.yaml").prompts] == b2[:3]- assert not (ocfg.out / "prompts").exists(), "no planner, no rung cache: the batteries are the cache"- with pytest.raises(loop.LoopError):- loop.generate_iteration(ocfg, 4, rung=9)- # a source battery of another track is refused- wrong = _battery_file(sources[0].parent / "scene.yaml", "scene", "scene_threejs", [_p("s1", "hard", "a quay")])- bad = ocfg.model_copy(update={"source": [*ocfg.source, str(wrong)]})- with pytest.raises(loop.LoopError, match="scene battery"):- loop.generate_iteration(bad, 5, rung=1)---def test_graphics_sources_route_an_unmarked_prompt_to_its_batterys_language(tmp_path: Path):- """graphics_v1/v2: "per-prompt `language: opengl_python` marks the raw-OpenGL prompts (battery- default is glsl_shader)" — an unmarked shader brief never lands in the opengl_python battery."""- glsl = _battery_file(tmp_path / "g.yaml", "graphics", "glsl_shader", [- _p("glsl_rain", "medium", "neon rain on a window"),- _p("glsl_sea", "hard", "a raymarched sea at dusk"),- _p("ogl_cubes", "hard", "instanced spinning cubes", language="opengl_python"),- ])- cfg = loop.LoopConfig(name="t_gfx", out=tmp_path / "loop_gfx", variant="argon", track="graphics",- languages=[Language.GLSL_SHADER, Language.OPENGL_PYTHON], source=[str(glsl)],- generator="g", judge="j", n=4)- paths = loop.generate_iteration(cfg, 0, rung=1)- by_lang = {lang: [p.id for p in Battery.load(path).prompts] for lang, path in paths.items()}- assert sorted(by_lang[Language.GLSL_SHADER]) == ["glsl_rain", "glsl_sea"]- assert by_lang[Language.OPENGL_PYTHON] == ["ogl_cubes"]- assert {p.language for p in Battery.load(paths[Language.GLSL_SHADER]).prompts} == {Language.GLSL_SHADER}---def _object_run(out_lang: Path, pid: str, scores: tuple[float, float], findings: Sequence[tuple[str, str, str]] = (),- *, language: Language = BLENDER_OBJ, ran: Sequence[str] = ("connectivity", "contract")) -> BenchItemResult:- """An object run under ``out_lang/runs/<pid>``: make_fake_run's record + typed gate findings- ``(gate, severity, data.kind)`` on the picked round (round 1), and its bench row. The gates in- ``ran`` report (passed when no finding names them), as a build that produced a mesh does."""- ws, _ = make_fake_run(out_lang / "runs", pid, language=language, generator="agy:gemini-4-argon", scores=scores)- data = json.loads(ws.record_path.read_text())- by_gate: dict[str, list[dict[str, Any]]] = {g: [] for g in ran}- for gate, sev, kind in findings:- by_gate.setdefault(gate, []).append({"gate": gate, "severity": sev, "target": "Leg_1", "message": f"{kind} here",- "data": {"kind": kind}})- data["rounds"][1]["gates"] += [{"gate": g, "passed": not fs, "findings": fs} for g, fs in by_gate.items()]- data["extra"] = {"stop_reason": "max_rounds"}- ws.record_path.write_text(json.dumps(data))- return BenchItemResult(id=pid, tier="hard", category="furniture", score_baseline=scores[0], score_picked=scores[1],- picked_round=1, rounds=2, cost_usd=1.0, minutes=10.0, status="max_rounds",- workspace=str(ws.root), generator="agy:gemini-4-argon", judge="gemini:gemini-4-argon")---def test_diagnose_reads_the_object_gates_by_typed_kind(ocfg: loop.LoopConfig):- out_lang = ocfg.iter_dir(0) / "blender"- _write_rows(out_lang, [- _object_run(out_lang, "o1", (0.5, 0.7), [("connectivity", "error", "floating"), ("connectivity", "error", "floating"),- ("contract", "error", "overall_bbox")]),- _object_run(out_lang, "o2", (0.5, 0.6), [("connectivity", "error", "penetration"),- ("connectivity", "warn", "stray_islands")]),- _object_run(out_lang, "o3", (0.4, 0.5), [("contract", "error", "ground_gap"), ("lint:blender", "error", "api_trap"),- ("contract", "warn", "footprint_offset")]),- _object_run(out_lang, "o4", (0.6, 0.8)),- # every build failed: the fallback round ran lint only — out of the connectivity / contract denominators- _object_run(out_lang, "o5", (0.2, 0.2), ran=()),- ])- # a scene run that strayed into the directory (no row) is another track's: never read- make_fake_run(out_lang / "runs", "stray_scene", language=THREEJS, scores=(0.1, 0.1))- d = diagnose_dir("blender", out_lang, track=loop.Track.STATIC_OBJECT)- assert d.track == "static_object" and d.n == 5 and d.n_scored == 5- assert d.runs[0].gates_run == ["connectivity", "contract", "lint"] and d.runs[4].gates_run == ["lint"]- m = d.metrics- assert (m["conn_floating_error_rate"], m["conn_penetration_error_rate"], m["conn_islands_rate"]) == (0.25, 0.25, 0.25)- assert (m["connectivity_error_rate"], m["contract_error_rate"]) == (0.5, 0.5)- assert (m["contract_bbox_error_rate"], m["contract_ground_error_rate"], m["contract_missing_error_rate"]) == (0.25, 0.25, 0.0)- assert m["lint_error_rate"] == 0.2 and m["budget_stop_rate"] == 0.0 and m["infra_failed_rate"] == 0.0- assert "floating_error_rate" not in m and "lib_modules_mean" not in m and "joint_sweep_error_rate" not in m- assert d.gate_error_total["connectivity/floating"] == 2 and d.gate_warn_total["contract/footprint_offset"] == 1- fired = {r.rule for r in d.recommendations}- assert fired == {"connectivity", "penetration", "islands", "bbox", "ground", "lint"}, fired- # a WARN-only contract kind (footprint_offset, instance_count) never counts as an ERROR rate- assert not any("instance" in r.text for r in d.recommendations)- # the command: the track named in the markdown, no scene-only library section- loop.diagnose_iteration(ocfg, 0)- md = (ocfg.iter_dir(0) / "diagnosis.md").read_text()- assert md.startswith("# t_static — iteration 0 diagnosis (static_object track)") and "track `static_object`" in md- assert "### library" not in md and "connectivity: contact band" in md and "bbox: dims" in md- assert json.loads((ocfg.iter_dir(0) / "diagnosis.json").read_text())["blender"]["track"] == "static_object"---def test_the_articulated_and_graphics_rates_and_rules():- from bench._loop_diag import RunDigest, diagnose_digests-- def run(pid: str, errors: dict[str, int], warns: dict[str, int] | None = None,- ran: Sequence[str] = ("lint", "connectivity", "contract", "joint_sweep", "motion_direction", "gl_frames")) -> RunDigest:- return RunDigest(id=pid, status="max_rounds", score_picked=0.5, picked_round=1, gate_errors=errors,- gate_warns=warns or {}, gates_run=list(ran))-- art = diagnose_digests("urdf_blender", Path("x"), [- run("a1", {"joint_sweep/penetration": 2, "lint/urdf_joint": 1}),- run("a2", {"motion_direction/wrong_direction": 1, "connectivity/floating": 1}),- run("a3", {}), run("a4", {})], track=loop.Track.ARTICULATED_OBJECT)- assert art.metrics["joint_sweep_error_rate"] == 0.25 and art.metrics["joint_axis_error_rate"] == 0.5- assert {"joints", "connectivity"} <= {r.rule for r in art.recommendations} and "sweep" not in {r.rule for r in art.recommendations}- gfx = diagnose_digests("glsl_shader", Path("x"), [- run("g1", {"gl_frames/black": 1}), run("g2", {}, {"gl_frames/static": 1}),- run("g3", {"gl_frames/nan": 1, "lint/syntax": 1}), run("g4", {}),- run("g5", {}, ran=("lint",))], track=loop.Track.GRAPHICS) # a render with no frames: no gl_frames report- assert (gfx.metrics["frame_black_rate"], gfx.metrics["frame_no_motion_rate"], gfx.metrics["frame_broken_rate"]) == (0.25, 0.25, 0.25)- assert gfx.metrics["lint_error_rate"] == 0.2- assert {"black", "no_motion", "broken", "lint"} <= {r.rule for r in gfx.recommendations}- assert "conn_floating_error_rate" not in gfx.metrics and "blown" not in {r.rule for r in gfx.recommendations}---def test_compare_on_an_object_track_vetoes_a_connectivity_contract_rise(ocfg: loop.LoopConfig):- from bench._loop_diag import compare_digests-- ids = ["a_med_1", "a_med_2", "b_med_3", "b_hard_1"]- b = ocfg.iter_dir(0) / "blender"- _write_rows(b, [_object_run(b, pid, (0.4, 0.6)) for pid in ids])- a = ocfg.iter_dir(1) / "blender"- _write_rows(a, [_object_run(a, pid, (0.4, 0.7)) for pid in ids])- c = compare_dirs("blender", a, b, track=loop.Track.STATIC_OBJECT)- assert c.paired.n == 4 and c.decision == "keep" and c.placement_rise == 0.0 and c.track == "static_object"- # the same scores, but every candidate run gains a floating part and a bbox ERROR: the gate wins- a2 = ocfg.iter_dir(2) / "blender"- _write_rows(a2, [_object_run(a2, pid, (0.4, 0.7), [("connectivity", "error", "floating"),- ("contract", "error", "part_bbox")]) for pid in ids])- c2 = compare_dirs("blender", a2, b, track=loop.Track.STATIC_OBJECT)- assert c2.placement_rise == 2.0 and c2.decision == "revert"- assert c2.reason.startswith("gate veto: connectivity+contract ERRORs rose by +2.00 per run")- assert c2.gate_error_delta == {"connectivity/floating": 4, "contract/part_bbox": 4}- res = loop.compare_iteration(ocfg, 2, 0, languages=[BLENDER_OBJ])- md = (ocfg.iter_dir(2) / "compare_blender.md").read_text()- assert res["blender"].decision == "revert" and "connectivity+contract ERRORs Δ +2.00 per run (veto above +1)" in md- # scene placement kinds mean nothing on an object track, and graphics has no veto at all- da = {"p": _digest("p", {"scene_placement/floating": 5})}- db = {"p": _digest("p", {})}- st = _stats({"p": 0.1})- assert compare_digests("blender", "a", "b", st, da, db, track=loop.Track.STATIC_OBJECT).placement_rise == 0.0- g = compare_digests("glsl_shader", "a", "b", st, {"p": _digest("p", {"gl_frames/black": 3})}, db,- track=loop.Track.GRAPHICS)- assert g.placement_rise is None and "gate veto" not in g.reason- # one noisy object (0 → 14 penetrations, one per part pair) counts OBJECT_VETO_CAP, not 14: no veto alone- from bench._loop_diag import OBJECT_VETO_CAP- st15 = _stats({f"p{i}": 0.0 for i in range(15)})- da15 = {f"p{i}": _digest(f"p{i}", {"connectivity/penetration": 14} if i == 0 else {}) for i in range(15)}- db15 = {f"p{i}": _digest(f"p{i}", {}) for i in range(15)}- noisy = compare_digests("blender", "a", "b", st15, da15, db15, track=loop.Track.STATIC_OBJECT)- assert noisy.placement_rise == round(OBJECT_VETO_CAP / 15, 4) and "gate veto" not in noisy.reason- # articulated: the pose sweep and a wrong-way joint are in the veto (the judge caps them too)- art = compare_digests("urdf_blender", "a", "b", st, {"p": _digest("p", {"joint_sweep/penetration": 2,- "motion_direction/wrong_direction": 1})},- db, track=loop.Track.ARTICULATED_OBJECT)- assert art.placement_rise == 3.0 and art.reason.startswith("gate veto: connectivity+contract+joint ERRORs")- assert compare_digests("blender", "a", "b", st, {"p": _digest("p", {"joint_sweep/penetration": 2})}, db,- track=loop.Track.STATIC_OBJECT).placement_rise == 0.0- from bench._loop_diag import render_comparison- assert "no gate veto on the graphics track" in render_comparison(g)---def _digest(pid: str, errors: dict[str, int]) -> Any:- from bench._loop_diag import RunDigest-- return RunDigest(id=pid, status="max_rounds", score_picked=0.5, picked_round=1, gate_errors=errors)---def test_a_static_object_loop_end_to_end(ocfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path, monkeypatch):- """init → generate → run → diagnose → compare → judge-calib → accept → status on static_object,- with fakes for the children (FakePopen), the runs (make_fake_run records) and the re-judge."""- data_dir = tmp_path / "data"- (ocfg.out / loop.LOOP_JSON).unlink()- loop.init(ocfg, paths=overlay)- assert loop.LoopConfig.load(ocfg.out).source == ocfg.source- for it in (0, 1):- loop.generate_iteration(ocfg, it, rung=1 if it == 0 else None)- monkeypatch.setattr(loop, "install_stop_handlers", lambda: None)- monkeypatch.setattr(loop, "time", NS(sleep=lambda s: None, monotonic=time.monotonic))- FakePopen.calls = []- loop.run_iteration(ocfg, 1, popen=FakePopen)- assert [c["argv"][3] for c in FakePopen.calls] == [str(ocfg.iter_dir(1) / f"battery_{x}.yaml") for x in ("blender", "threejs")]- # the children's output, faked: iteration 1 scores higher on every pair with no new gate ERRORs- for it, up in ((0, 0.0), (1, 0.15)):- for lang in (BLENDER_OBJ, THREEJS_OBJ):- ids = json.loads((ocfg.iter_dir(it) / "generate.json").read_text())["ids"][lang.value]- d = ocfg.iter_dir(it) / lang.value- _write_rows(d, [_object_run(d, pid, (0.4, 0.6 + up + 0.01 * k), language=lang) for k, pid in enumerate(ids)])- diag = loop.diagnose_iteration(ocfg, 1)- assert set(diag) == {"blender", "threejs"} and diag["blender"].n == 4 and diag["blender"].track == "static_object"- cmp = loop.compare_iteration(ocfg, 1, 0)- assert {k: v.paired.n for k, v in cmp.items()} == {"blender": 4, "threejs": 4}- assert {v.decision for v in cmp.values()} == {"keep"}-- def fake_calibrate(run_dirs, **kw):- pid = Path(run_dirs[0]).name- row = CalibrationRow(run=pid, round=kw["rounds"][0], kind="refine", gate_errors=0, gate_warnings=0,- stored_overall=0.7, mean=0.7, std=0.01, uncapped=0.7, defect_penalty=0.0, defects_present=[],- caps=[], passed=True, n_used=3, cost_usd=0.01, duration_s=5.0)- return CalibrationTable(model_id=kw["model_id"], n_samples=kw["n_samples"], fixed_order=True, rows=[row])-- calib = loop.judge_calib(ocfg, 1, calibrate_fn=fake_calibrate, workers=1)- assert calib["blender"].rounds == 4, "the object records are read: every picked round re-judged"- row = loop.accept(ocfg, 1, note="contact band", paths=overlay, data_dir=data_dir)- assert row.verdicts == {"blender": "keep", "threejs": "keep"} and row.languages == ["blender", "threejs"]- text = loop.status_text(ocfg, paths=overlay, data_dir=data_dir)- assert "track static_object" in text and "| 1 | 1 | 2 |" in text and "blender=keep" in textdiff --git a/harness/CLAUDE.md b/harness/CLAUDE.mdindex e106cf6c..098a5132 100644--- a/harness/CLAUDE.md+++ b/harness/CLAUDE.md@@ -13,7 +13,7 @@ It does not implement an agent loop: the in-process `api-agent` was deleted2026-08-28 (owner's call — reimplementing what the vendors already ship was neverthis project's job). Plus a data-flywheel record per run.-Read `docs/ARCHITECTURE.md` (design, package map, authoring contracts, what a run+Read `docs/ARCHITECTURE.md` (design, package map, what a runreally does, known limits), `docs/RUNBOOK.md` (how to run / resume / extend), `eval/docs/EVAL.md`(evaluation protocol + judge calibration) and `eval/docs/COMPLEXITY.md` (the objectivecomplexity vector + the score-vs-complexity corpus study) before changing anything.@@ -97,7 +97,6 @@ cd harness# Every track states REQUIREMENTS, never templates (D106 scene, D107 the rest, 2026-10-15): no language ships a cookbook, no inlined# recipes, placeholder skeletons; a prompt / skill keeps only interface, sandbox rules and measured thresholds, each contract.md ONE# executable interface example (tests/prompts/test_snippets_run.py), the craft as short optional practices in the skills (fences ≤ ~12 lines).-3dcodeverse make "..." --variant argon # per-model prompt/skill overlay: prompts/variants/<name>/ + skills/variants/<name>/ (D105; C3D_VARIANT, C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}')3dcodeverse make "neon rain on a window" --track graphics --language glsl_shader3dcodeverse make "..." --image ref.png --candidates 3 --rounds 2 --dim height=0.45 --must "three legs" --no-run3dcodeverse make "..." --no-pick # a run = baseline + --rounds refine rounds (fixed); make then picks a round → deliverable/ unless --no-pick@@ -111,7 +110,6 @@ cd harness3dcodeverse gallery serve [ROOTS...] [--port 8765] [--reload] · 3dcodeverse gallery build --out gallery.html [--embed](cd ../eval && python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-4-argon) # report: python -m bench.report bench/out/<battery>python -m codeverse3d.addons.calibration runs/<slug>... --model gemini:gemini-4-argon --n 3 --out out/-(cd ../eval && python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon --languages scene_threejs,scene_blender --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 && python -m bench.loop generate --iter 0 && python -m bench.loop run --iter 0 && python -m bench.loop diagnose --iter 0) # the argon loop (eval/docs/EVAL.md §10): then compare --iter N --against M · judge-calib --iter N · accept|rollback --iter N · statuspython ../eval/bench/complexity_report.py ../eval/bench/out --recursive # score-vs-complexity + $/complexity point (eval/docs/COMPLEXITY.md)python ../eval/bench/compare_backends.py --prompts ../eval/bench/prompts/compare_v1.yaml --arms harness:agy:gemini-4-argon,oneshot:claude-code --judge gemini:gemini-4-argon --out ../eval/bench/out/compare_v1python -m tests.prompts.manifest [--bless | --dump DIR] # what every model is shown, pinned (RUNBOOK §7): bless only a change a model is MEANT to seediff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.pyindex 79719446..b57e9842 100644--- a/harness/codeverse3d/cli/_common.py+++ b/harness/codeverse3d/cli/_common.py@@ -1,5 +1,4 @@-"""Shared CLI plumbing: Rich formatting, the run mutex, workspace opening / creation and-variant resolution."""+"""Shared CLI plumbing: Rich formatting, the run mutex and workspace opening / creation."""from __future__ import annotations@@ -8,7 +7,6 @@ import mathimport shutilfrom collections.abc import Iteratorfrom contextlib import ExitStack, contextmanager-from dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Annotated, Any@@ -244,60 +242,4 @@ def check_backends(backends: Any) -> None:raise CliError(f"--{role} {value!r}: {e}", code=2) from None-# --------------------------------------------------------------------------- the variant-@dataclass(frozen=True)-class ResolvedVariant:-- name: str- version: int- hash: str- source: str # "--variant" | "settings.variant" | "settings.variants" | "" (base)-- @property- def label(self) -> str:- return f"{self.name} v{self.version} ({self.hash}) via {self.source}" if self.name else "base"---def resolve_variant(settings: Any | None, generator: str, flag: str | None = None) -> ResolvedVariant:- """Resolve the variant: ``flag`` over ``settings.variant`` over ``settings.variants[<generator>]``- over the base. An unknown name is a typed refusal (exit 2)."""- from codeverse3d.prompts import variants as V-- settings = settings or get_settings()- try:- if flag and flag.strip():- name, source = flag.strip(), "--variant"- else:- name = V.resolve_variant(settings, generator)- source = ("settings.variant" if name and settings.variant.strip() == name- else "settings.variants" if name else "")- if not name:- return ResolvedVariant(name="", version=0, hash="", source="")- info = V.variant_info(name)- return ResolvedVariant(name=name, version=info.version, hash=V.variant_hash(name), source=source)- except ValueError as e:- raise CliError(f"bad configuration: {e}", code=2) from e---def record_variant(record: RunRecord) -> str:- block = record.extra.get("variant")- stamped = str(block.get("name") or "") if isinstance(block, dict) else ""- return record.spec.options.variant or stamped---@contextmanager-def replay_variant(record: RunRecord) -> Iterator[str]:- """Activate the variant a stored run used; an unshipped one warns and falls back to base."""- from codeverse3d.prompts.variants import activate, variant_info-- name = record_variant(record)- if name:- try:- variant_info(name)- except ValueError as e:- warn(f"replaying with the base prompts: {e}")- name = ""- with activate(name):- yield name-diff --git a/harness/codeverse3d/cli/flywheel_cmd.py b/harness/codeverse3d/cli/flywheel_cmd.pyindex cbea6aa2..ffa81dc4 100644--- a/harness/codeverse3d/cli/flywheel_cmd.py+++ b/harness/codeverse3d/cli/flywheel_cmd.py@@ -1,4 +1,4 @@-"""``3dcodeverse flywheel export | pairs | caption | index``."""+"""``3dcodeverse flywheel export | pairs | refine | caption``."""from __future__ import annotationsdiff --git a/harness/codeverse3d/cli/inspect_cmd.py b/harness/codeverse3d/cli/inspect_cmd.pyindex 5569ea38..bb4eecda 100644--- a/harness/codeverse3d/cli/inspect_cmd.py+++ b/harness/codeverse3d/cli/inspect_cmd.py@@ -113,8 +113,7 @@ def judge(if rnd is None or rnd.renders is None or not rnd.renders.views:raise C.CliError(f"round {idx} has no renders (rounds/r{idx:02d}.json / record.json)")rubric_name = J.rubric_for(rec, rnd, rubric)- with C.replay_variant(rec):- inp = J.build_judge_input(ws, rec, rnd)+ inp = J.build_judge_input(ws, rec, rnd)missing = [v.path for v in inp.renders.views if not Path(v.path).is_file()]if missing:raise C.CliError(f"round {idx}: {len(missing)} of its {len(inp.renders.views)} judged renders are not on disk "@@ -125,8 +124,8 @@ def judge(except ValueError as e:raise C.CliError(str(e), code=2) from en_images = J.count_prompt_images(inp, rubric_name, judge_obj)- # writes into the run: one writer per run dir; judged under the run's variant- with C.mutating(ws, what=f"3dcodeverse judge {ws.root.name}", action="judge"), C.replay_variant(rec):+ # writes into the run: one writer per run dir+ with C.mutating(ws, what=f"3dcodeverse judge {ws.root.name}", action="judge"):try:with join_post_run(ws):verdict = judge_obj.judge(inp)diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.pyindex 11cfaf21..ea7654f8 100644--- a/harness/codeverse3d/cli/main.py+++ b/harness/codeverse3d/cli/main.py@@ -182,7 +182,7 @@ app = typer.Typer(help="3dcodeverse: LLMs write raw 3D code; the harness builds, judges, refines, records.",pretty_exceptions_enable=False,)-app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / captions.")+app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / refine / captions.")app.add_typer(gallery_app,name="gallery",@@ -244,15 +244,6 @@ def make(planner: Annotated[str | None, typer.Option()] = None,judge: Annotated[str | None, typer.Option()] = None,image: Annotated[list[Path] | None, typer.Option("--image", help="reference image(s)")] = None,- variant: Annotated[- str,- typer.Option(- "--variant",- help="per-model prompt/skill variant (an overlay under codeverse3d/prompts/variants/<name>/ "- "and codeverse3d/skills/variants/<name>/, frozen on the spec); default: C3D_VARIANT, else "- "C3D_VARIANTS[<generator>] by the id as typed and then by its served model, else the base",- ),- ] = "",rounds: Annotated[int | None,typer.Option(@@ -329,8 +320,6 @@ def make(raise _no_best_of_n(track)backends = settings.backends(generator=generator, planner=planner, judge=judge)C.check_backends(backends)- # resolved once here and frozen on the spec- chosen = C.resolve_variant(settings, backends.generator, variant)# validate the whole Spec before touching the filesystem (no orphan run directory)try:spec = Spec(@@ -348,7 +337,7 @@ def make(budget=Budget(**{k: v for k, v in{"max_rounds": rounds, "max_minutes": max_minutes}.items() if v is not None}),backends=backends,- options=RunOptions(candidates=candidates, variant=chosen.name),+ options=RunOptions(candidates=candidates),seed=seed,tags=tag,)@@ -372,7 +361,6 @@ def make(f"({settings.judge.max_px}px/{settings.judge.detail_crops}crop)","rounds": spec.budget.max_rounds,"candidates": candidates,- "variant": chosen.label,},))diff --git a/harness/codeverse3d/cli/skills_cmd.py b/harness/codeverse3d/cli/skills_cmd.pyindex 008f8c31..bf9ef60c 100644--- a/harness/codeverse3d/cli/skills_cmd.py+++ b/harness/codeverse3d/cli/skills_cmd.py@@ -32,25 +32,21 @@ def list_skills(from codeverse3d.skills import iter_skillsfrom codeverse3d.skills.registry import ROUTED_SKILLS, ROUTES- # the base library, then every shipped variant's overlay (rows labelled by variant)- roots = _roots()- found = [(root, s) for root in roots for s in iter_skills(root.path)]- overlay_rows = {root.variant: _overlay_routes(root.variant) for root in roots if root.variant}+ found = list(iter_skills())t = Table(title="3dcodeverse skills")- for col in ("name", "variant", "evidence", "verified", "lines", "~tokens", "refs", "target", "dir",+ for col in ("name", "evidence", "verified", "lines", "~tokens", "refs", "target", "dir",*(["routes"] if routes else [])):t.add_column(col)- for root, s in found:+ for s in found:tg = target_for(s.name)- row = [s.name, root.variant, s.evidence, s.verified, str(s.body_lines), str(s.body_tokens),+ row = [s.name, s.evidence, s.verified, str(s.body_lines), str(s.body_tokens),str(len(s.references)), tg.metric if tg else "[red]none[/]",("" if not tg else tg.direction if tg.measurable else f"{tg.direction} ?")]if routes:- table = (*ROUTES, *overlay_rows.get(root.variant, ()))- row.append(",".join(r.rule for r in table if r.skill == s.name))+ row.append(",".join(r.rule for r in ROUTES if r.skill == s.name))t.add_row(*row)console.print(t)- missing = [n for n in ROUTED_SKILLS if n not in {s.name for root, s in found if not root.variant}]+ missing = [n for n in ROUTED_SKILLS if n not in {s.name for s in found}]if missing:console.print(f"[yellow]{len(missing)} routed skill(s) have no bundle yet:[/] {', '.join(missing)}")@@ -82,82 +78,31 @@ def validate(from codeverse3d.skills.model import SkillError, parse_skillfrom codeverse3d.skills.registry import ROUTED_SKILLS- # every root a run can route from, so a malformed overlay bundle fails here as `<variant>/<bundle>`- roots = _roots()- total = bad = tables_bad = 0- base_names: set[str] = set()- unshipped: list[str] = []- for root in roots:- dirs = bundle_dirs(root.path)- total += len(dirs)- for d in dirs:- issues = validate_bundle(d)- with contextlib.suppress(SkillError):- issues += check_claims(parse_skill(d))- if issues:- bad += 1- console.print(f"[red]FAIL[/] {root.label(d.name)}")- for i in issues:- console.print(f" - {i}")- else:- console.print(f"[green]ok[/] {root.label(d.name)}")- if not root.variant:- base_names = {d.name for d in dirs}- continue- table_bad, orphans = _check_table(root, base_names | {d.name for d in dirs})- tables_bad += table_bad- if orphans:- style = "red" if strict else "yellow"- console.print(f"[{style}]{root.variant}/routes.toml: {len(orphans)} row(s) route a bundle "- f"nobody ships:[/] {', '.join(orphans)}")- unshipped += orphans+ dirs = bundle_dirs()+ bad = 0+ for d in dirs:+ issues = validate_bundle(d)+ with contextlib.suppress(SkillError):+ issues += check_claims(parse_skill(d))+ if issues:+ bad += 1+ console.print(f"[red]FAIL[/] {d.name}")+ for i in issues:+ console.print(f" - {i}")+ else:+ console.print(f"[green]ok[/] {d.name}")prompt_issues = check_prompt_claims()for i in prompt_issues:console.print(f"[red]FAIL[/] prompts/_claims.toml - {i}")- missing = [n for n in ROUTED_SKILLS if n not in base_names]+ missing = [n for n in ROUTED_SKILLS if n not in {d.name for d in dirs}]if missing:style = "red" if strict else "yellow"console.print(f"[{style}]{len(missing)} routed skill(s) have no bundle:[/] {', '.join(missing)}")- console.print(f"\n{total - bad}/{total} bundles valid"- + (f", {tables_bad} routes.toml invalid" if tables_bad else ""))- if bad or tables_bad or prompt_issues or (strict and (missing or unshipped)):+ console.print(f"\n{len(dirs) - bad}/{len(dirs)} bundles valid")+ if bad or prompt_issues or (strict and missing):raise typer.Exit(code=1)-def _roots() -> list:- """Every root the library ships; a ``variant.toml`` that does not parse is reported and exits 1."""- from codeverse3d.skills import shipped_roots-- try:- return shipped_roots()- except ValueError as e:- err_console.print(f"[red]FAIL[/] variants - {e}")- raise typer.Exit(code=1) from e---def _overlay_routes(variant: str) -> tuple:- """A variant's ``[[route]]`` rows for the ``--routes`` column; an invalid table lists as empty."""- from codeverse3d.skills import variants_table-- try:- return variants_table(variant).routes- except ValueError as e:- err_console.print(f"[yellow]{variant}/routes.toml rejected:[/] {e}")- return ()---def _check_table(root, available: set[str]) -> tuple[int, list[str]]:- """One overlay's ``routes.toml``: ``(1 if invalid else 0, rows routing a skill no root ships)``."""- from codeverse3d.skills import variants_table-- try:- table = variants_table(root.variant)- except ValueError as e:- console.print(f"[red]FAIL[/] {root.variant}/routes.toml - {e}")- return 1, []- return 0, [f"{r.rule} -> {r.skill}" for r in table.routes if r.skill not in available]--@skills_app.command("report")def report(runs_dir: Annotated[Path, typer.Argument(help="a runs root, a bench out dir, or one workspace")],diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.pyindex e4079527..f43bbd81 100644--- a/harness/codeverse3d/config.py+++ b/harness/codeverse3d/config.py@@ -78,10 +78,8 @@ class Agents(BaseModel):"Override per id with `codex:<model>@<effort>`.")claude_effort: str = Field(default="xhigh",- description="`--effort` passed to every `claude-code:` session (low|medium|high|xhigh|max; '' in the "- "config file leaves it to the CLI). A harness session reads no user settings (`--setting-sources project`), so the "- "effort is the harness's to state; xhigh is what sessions ran at while they still inherited the "- "owner's ~/.claude/settings.json (until 2026-09-22).")+ description="`--effort` passed to every `claude-code:` session (low|medium|high|xhigh|max; '' leaves it "+ "to the CLI). A harness session reads no user settings, so the effort is stated here.")class Render(BaseModel):@@ -127,10 +125,8 @@ class Limits(BaseModel):max_parallel_builds: int = Field(default=8, ge=1, description="concurrent build subprocesses (>= 1)")agent_max_turns: Count = Field(default=0,- description="hard cap on model turns per agent session (0 = the backend's own default, "- "which is what ships: a 28-turn cap cost $0.02 more and 0.205 of a score point in its "- "own A/B — docs/COST.md §17 — so no profile sets one; name it here or as "- "C3D_AGENT_MAX_TURNS if you want one).",+ description="hard cap on model turns per agent session (0 = the backend's own default; claude-code "+ "then gets AgentJob.max_turns = 60). C3D_AGENT_MAX_TURNS.",)@@ -145,13 +141,9 @@ class Rate(BaseModel):max_in_flight: int = Field(default=96,ge=0, # negative is not "unlimited" (0 is); a negative would poison the slot accounting- description="machine-wide cap on concurrent model calls (0 = off): every process draws "- "from the same N slot files, so the machine never exceeds the largest N any process runs "- "with. Measured knee: a 128-call burst of 12k-token prompts ran 29.6 calls/min at 16 "- "in-flight, 43.9 at 32, 72.9 at 64 and fell back to 47.2 at 128 (docs/COST.md Part III) — with 22 "- "keys; raised 64 → 96 on 2026-10-15 for the 30-key pool after iteration 0 of the argon loop hit the "- "64 cap 172 times at launch while the keys themselves showed no 429 pressure (12 concurrent calls on "- "one key: 0 × 429; re-measure the knee when the loops run two tracks at once).")+ description="machine-wide cap on concurrent model calls (0 = off): every process draws from the same "+ "N slot files. Measured knee with 22 keys: 72.9 calls/min at 64 in flight, 47.2 at 128; 96 serves "+ "the 30-key pool.")hedge: int = Field(default=2, ge=1,description="keys a retry is raced on once a call has met its first 503 (1 = off). Measured "@@ -168,16 +160,14 @@ class Judge(BaseModel):samples: int = Field(default=1, description="default VLM samples per verdict")slices: Literal["on-error", "off"] = Field(default="on-error",- description="conditional cross-section slices (D48, C3D_JUDGE__SLICES): 'on-error' appends ≤2 "- "interior slice images + one provenance-elicitation sentence to an object-track verdict whose "- "connectivity gate carries an ERROR; clean rounds build a byte-identical payload either way. "- "Slice render is local CPU; no profile touches this dial (the channel measured ≤ $0).")+ description="conditional cross-section slices (C3D_JUDGE__SLICES): 'on-error' appends ≤2 interior "+ "slice images + one provenance sentence to an object-track verdict whose connectivity gate carries "+ "an ERROR; clean rounds build a byte-identical payload either way.")thinking: Annotated[Literal["off", "low", "medium", "high"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(default="medium",- description="VLM and pairwise judges' thinking level (C3D_JUDGE__THINKING; models/gemini.THINKING_BUDGET). "- "The default gemini-4-argon thinks only from 'medium' "- "(4096) — measured 2026-10-14 on 19 scene/object rounds: argon@medium within-sd .012 vs .029 at low, "- "same cost, same mean (D105). `3dcodeverse judge --thinking` replays with another level.")+ description="VLM judge thinking level (C3D_JUDGE__THINKING; models/gemini.THINKING_BUDGET). "+ "gemini-4-argon thinks only from 'medium' (4096): within-sd .012 vs .029 at low, same cost. "+ "`3dcodeverse judge --thinking` replays with another level.")class Placement(BaseModel):@@ -255,35 +245,18 @@ class Settings(BaseSettings):model_timeout_s: float = Field(default=1200.0,- description="HTTP read timeout for ONE API model call (per attempt). It is a CEILING: the "- "call ends when the answer does, and gemini.py clips each attempt to the retry budget "- "actually left. 300 s was the binding wall once max_output_tokens went to the model's "- "65 536 ceiling — measured 2026-08-27, output streams at 145 tok/s p50 and 60 tok/s p10, so "- "a 55 800-token plan needs ~930 s and died at the socket, its tokens billed and discarded. "- "Owner's rule 2026-08-27: time may be generous, errors may not.")-- # Per-model prompt/skill variants: overlays under prompts/variants/<name>/ and- # skills/variants/<name>/, chosen by name or exact generator id, never by regex.- variant: str = Field(default="", description="prompt/skill variant for every run of this process "- "(C3D_VARIANT; a name under codeverse3d/prompts/variants/); '' = base")- variants: dict[str, str] = Field(default_factory=dict, description="exact generator id → variant name, "- "e.g. {'agy:gemini-4-argon': 'argon'} (yaml mapping, or env as JSON "- "C3D_VARIANTS='{\"agy:gemini-4-argon\": \"argon\"}'); consulted when "- "`variant` is empty, by the id as typed and then by '<kind>:<served model>'")+ description="HTTP read timeout for ONE API model call (per attempt): a ceiling, generous on purpose "+ "(a 55k-token plan streams for ~930 s at p10; time may be generous, errors may not).")# ------------------------------------------------------------------ switches# tracks/plan_features.py derives the live C3D_* names from these fields.skills: Flag = Field(default=True, description="route, materialise and measure skill bundles ""(D81, on since 2026-09-22); C3D_SKILLS=0 is an A/B's no-skills arm")- skills_max: Count = Field(- default=5, description="bundles attached to one session (skills design §5.2 law 1)")- skills_unverified: Flag = Field(default=True, description="also route the bundles labelled "- "inherited-unverified (with it all 17 route; the cap still holds)")skills_only: str = Field(default="", description="comma list: the router considers ONLY these ""bundles, so an effect A/B can attribute its delta to one; an unknown name "- "routes nothing, which shows up at once as a variant equal to its control")+ "routes nothing")skills_dir: Path | None = Field(default=None, description="another skill library (tests, the live "- "CLI smoke, a private overlay)")+ "CLI smoke)")plan_brief: Flag = Field(default=True, description="expand the engineering brief before planning ""(object tracks)")plan_restart: Flag = Field(default=True, description="re-sample a degenerate plan from the original "diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.pyindex c4ac6786..07e0a459 100644--- a/harness/codeverse3d/contracts/run.py+++ b/harness/codeverse3d/contracts/run.py@@ -229,9 +229,6 @@ class SettingsSnapshot(BaseModel):price_table_version: str = Field(default="", description="content hash of codeverse3d.models.pricing.PRICES")render: dict[str, Any] = Field(default_factory=dict, description="resolved render settings (size, gpu, sheet)")limits: dict[str, Any] = Field(default_factory=dict, description="resolved timeouts / parallelism")- variant: str = Field(default="", description="per-model prompt/skill variant the run used ('' = base; D105)")- variant_version: int = Field(default=0, description="the variant's version from its variant.toml (0 = base)")- variant_hash: str = Field(default="", description="sha256[:12] over the variant overlay's files (name, text), '' = base")class StageCost(BaseModel):diff --git a/harness/codeverse3d/contracts/spec.py b/harness/codeverse3d/contracts/spec.pyindex e8abebcf..b5dfd455 100644--- a/harness/codeverse3d/contracts/spec.py+++ b/harness/codeverse3d/contracts/spec.py@@ -69,9 +69,6 @@ class RunOptions(BaseModel):"""candidates: int | None = Field(default=None, ge=1, description="best-of-N baseline candidates")- variant: str = Field(default="", description="per-model prompt/skill variant this run was created with "- "(codeverse3d/prompts/variants/<name>/, D105); '' = the base prompts and skills; "- "frozen here so a resume and the record name the same overlay")class Spec(BaseModel):diff --git a/harness/codeverse3d/prompts/__init__.py b/harness/codeverse3d/prompts/__init__.pyindex d1e3b663..07ffbdfa 100644--- a/harness/codeverse3d/prompts/__init__.py+++ b/harness/codeverse3d/prompts/__init__.py@@ -1,22 +1,16 @@"""Prompt loader: markdown + jinja2 templates, content-hashed for provenance.-Names resolve through the active variant first (``prompts/variants.py``): an overlay file shadows the-base file, a missing overlay file falls back to the base.+Plain files under ``prompts/``; ``render`` runs a jinja template with strict undefined variables."""from __future__ import annotationsimport hashlib-import loggingfrom functools import lru_cachefrom pathlib import Pathfrom typing import Any-from jinja2 import ChoiceLoader, Environment, FileSystemLoader, StrictUndefined--from codeverse3d.prompts.variants import active_variant, variant_root--log = logging.getLogger(__name__)+from jinja2 import Environment, FileSystemLoader, StrictUndefinedPROMPTS_DIR = Path(__file__).resolve().parent@@ -26,39 +20,17 @@ _FLAGS: dict[str, Any] = {"undefined": StrictUndefined, "trim_blocks": True, "ls_env = Environment(loader=FileSystemLoader(str(PROMPTS_DIR)), **_FLAGS)-@lru_cache(maxsize=16)-def _env_for(variant: str) -> Environment:- """The base environment for ``""``, else overlay-first then base."""- if not variant:- return _env- return Environment(loader=ChoiceLoader([FileSystemLoader(str(variant_root(variant))),- FileSystemLoader(str(PROMPTS_DIR))]), **_FLAGS)---def _resolve(variant: str, rel_path: str) -> Path:- """The file ``rel_path`` reads from under ``variant``: its overlay copy if any, else the base path."""- if variant:- overlay = variant_root(variant) / rel_path- if overlay.is_file():- return overlay- return PROMPTS_DIR / rel_path--@lru_cache(maxsize=512)-def _load(variant: str, rel_path: str) -> str:- p = _resolve(variant, rel_path)+def load_text(rel_path: str) -> str:+ p = PROMPTS_DIR / rel_pathif not p.is_file():raise FileNotFoundError(f"prompt not found: {rel_path}")return p.read_text()-def load_text(rel_path: str) -> str:- return _load(active_variant(), rel_path)--def render(rel_path: str, **ctx: Any) -> str:"""Render a jinja template under prompts/ with ``ctx``; a missing name raises (StrictUndefined)."""- return _env_for(active_variant()).get_template(rel_path).render(**ctx)+ return _env.get_template(rel_path).render(**ctx)def prompt_hash(text: str) -> str:diff --git a/harness/codeverse3d/prompts/variants.py b/harness/codeverse3d/prompts/variants.pydeleted file mode 100644index 126fa5a9..00000000--- a/harness/codeverse3d/prompts/variants.py+++ /dev/null@@ -1,191 +0,0 @@-"""Per-model prompt / skill variants: one overlay directory per name.--``prompts/variants/<name>/<rel>`` shadows ``prompts/<rel>`` and ``skills/variants/<name>/`` shadows-skill bundles. A variant is chosen by ``Settings.variant`` or by ``Settings.variants`` keyed on the-generator id (exact, then ``<kind>:<served model>``); an unknown name raises ``ValueError``. The-active one is a ``ContextVar`` set by :func:`activate` around a run; :func:`variant_hash` records it.-"""--from __future__ import annotations--import hashlib-import logging-import tomllib-from collections.abc import Iterator-from contextlib import contextmanager-from contextvars import ContextVar-from pathlib import Path-from typing import Any--from pydantic import BaseModel, Field--from codeverse3d.config import Settings, get_settings--log = logging.getLogger(__name__)--VARIANTS_DIR: Path = Path(__file__).resolve().parent / "variants"-VARIANT_FILE = "variant.toml"-HASH_EXCLUDED: frozenset[str] = frozenset({"README.md"})--_ACTIVE: ContextVar[str | None] = ContextVar("c3d_variant", default=None)-_WARNED: set[str] = set()---class VariantInfo(BaseModel):-- model_config = {"frozen": True}-- name: str = Field(description="equals the overlay directory name")- version: int = Field(ge=1, description="the loop bumps it on accept (eval/bench/loop.py)")- generators: tuple[str, ...] = Field(default=(), description="informative: the generator ids it was tuned "- "for; selection is Settings.variants / --variant")- description: str = ""---def _plain_name(name: str) -> bool:- return bool(name) and Path(name).name == name and not name.startswith(".")---def variant_root(name: str) -> Path:- if not _plain_name(name):- raise ValueError(f"variant name {name!r} must be a plain directory name")- return VARIANTS_DIR / name---def list_variants() -> dict[str, VariantInfo]:- """Every shipped variant by name (a directory under ``VARIANTS_DIR`` with a ``variant.toml``)."""- if not VARIANTS_DIR.is_dir():- return {}- return {d.name: _parse(d / VARIANT_FILE, d.name)- for d in sorted(VARIANTS_DIR.iterdir()) if d.is_dir() and (d / VARIANT_FILE).is_file()}---def variant_info(name: str) -> VariantInfo:- path = variant_root(name) / VARIANT_FILE if _plain_name(name) else None- if path is None or not path.is_file():- known = ", ".join(list_variants()) or "none"- raise ValueError(f"unknown variant {name!r} (known: {known})")- return _parse(path, name)---def _parse(path: Path, dir_name: str) -> VariantInfo:- try:- data = tomllib.loads(path.read_text(encoding="utf-8"))- except tomllib.TOMLDecodeError as e:- raise ValueError(f"{path}: not valid TOML: {e}") from e- head = data.get("variant")- if not isinstance(head, dict):- raise ValueError(f"{path}: missing the [variant] table")- unknown_tables = sorted(set(data) - {"variant"})- if unknown_tables:- raise ValueError(f"{path}: unknown table(s) {unknown_tables}; variant.toml holds the [variant] table")- unknown = sorted(set(head) - {"name", "version", "generators", "description"})- if unknown:- raise ValueError(f"{path}: unknown [variant] key(s) {unknown}")- name = head.get("name")- if name != dir_name:- raise ValueError(f"{path}: [variant] name {name!r} must equal the directory name {dir_name!r}")- version = head.get("version", 1)- if isinstance(version, bool) or not isinstance(version, int) or version < 1:- raise ValueError(f"{path}: version must be an integer >= 1, got {version!r}")- generators = head.get("generators", [])- if not isinstance(generators, list) or not all(isinstance(g, str) for g in generators):- raise ValueError(f"{path}: generators must be a list of generator ids")- description = head.get("description", "")- if not isinstance(description, str):- raise ValueError(f"{path}: description must be a string")- return VariantInfo(name=name, version=version, generators=tuple(generators), description=description)---def served_id(generator_id: str) -> str:- """``agy:gemini-4-argon-high`` → ``agy:gemini-4-argon``; ``""`` for an id that is not ``<kind>:<model>``."""- from codeverse3d.agents.backends import api_model_effort- from codeverse3d.agents.registry import parse_agent_id-- try:- kind, model = parse_agent_id(generator_id)- except ValueError:- return ""- return f"{kind}:{api_model_effort(model)[0]}"---def resolve_variant(settings: Settings, generator_id: str) -> str:- """The variant name for ``generator_id``: ``settings.variant``, else ``settings.variants`` by id,- else by ``<kind>:<served model>``, else ``""`` (base). An unknown name raises ``ValueError``."""- name = settings.variant.strip()- if not name and settings.variants:- name = settings.variants.get(generator_id, "")- if not name:- served = served_id(generator_id)- if served and served != generator_id:- name = settings.variants.get(served, "")- name = (name or "").strip()- if name:- variant_info(name)- return name---def active_variant() -> str:- current = _ACTIVE.get()- if current is not None:- return current- name = get_settings().variant.strip()- if name and not _plain_name(name):- if name not in _WARNED:- _WARNED.add(name)- log.warning("C3D_VARIANT=%r is not a plain variant name; using the base prompts", name)- return ""- return name---@contextmanager-def activate(name: str) -> Iterator[str]:- """Set the active variant for the block (``""`` = base); an unknown name raises. Nests."""- name = (name or "").strip()- if name:- variant_info(name)- token = _ACTIVE.set(name)- try:- yield name- finally:- _ACTIVE.reset(token)---def _skills_root(name: str) -> Path:- from codeverse3d.skills import variant_dir-- return variant_dir(name)---def variant_hash(name: str) -> str:- """``sha256[:12]`` over the sorted prompt and skills overlay files of ``name``; ``""`` for the base."""- if not name:- return ""- variant_info(name)- h = hashlib.sha256()- for prefix, root in (("prompts", variant_root(name)), ("skills", _skills_root(name))):- if not root.is_dir():- continue- for p in sorted(x for x in root.rglob("*") if x.is_file()):- if p.name in HASH_EXCLUDED or p.name.startswith(".") or "__pycache__" in p.parts:- continue- h.update(f"{prefix}/{p.relative_to(root).as_posix()}\0".encode())- h.update(p.read_bytes())- h.update(b"\0")- return h.hexdigest()[:12]---def variant_block(name: str) -> dict[str, Any]:- """``{"name", "version", "hash"}`` for a record; a variant that vanished keeps its name with version 0."""- if not name:- return {"name": "", "version": 0, "hash": ""}- try:- return {"name": name, "version": variant_info(name).version, "hash": variant_hash(name)}- except (ValueError, OSError) as e:- log.warning("variant %r cannot be read for the record: %s", name, e)- return {"name": name, "version": 0, "hash": ""}---__all__ = ["HASH_EXCLUDED", "VARIANTS_DIR", "VARIANT_FILE", "VariantInfo", "activate", "active_variant",- "list_variants", "resolve_variant", "served_id", "variant_block", "variant_hash", "variant_info",- "variant_root"]diff --git a/harness/codeverse3d/prompts/variants/argon/README.md b/harness/codeverse3d/prompts/variants/argon/README.mddeleted file mode 100644index 40372158..00000000--- a/harness/codeverse3d/prompts/variants/argon/README.md+++ /dev/null@@ -1,26 +0,0 @@-# argon — the prompt overlay for gemini-4-argon on the scene track--This directory is a **variant** (D105, 2026-10-14): an overlay on `codeverse3d/prompts/`.-A file placed here shadows the base file of the same relative path for every run that-activates the variant — `scene_threejs/system.md` here replaces the base system prompt,-`tracks/scene_zone.j2` the zone template — and a file that is not here is read from the base.-A template here may `include` or `extends` a base file (the variant's loader falls through to-the base directory).--The overlay ships **empty**: iteration 0 of the tuning loop (`eval/bench/loop.py`) measures the-base prompts under the variant plumbing, so the first accepted iteration is a measured delta,-not a guess. The loop writes files here, bumps `version` in `variant.toml` on accept and-restores the previous snapshot on rollback.--* `variant.toml` — name (must equal this directory's name), version, the generator ids the- variant was tuned for (informative), an optional `[knobs]` table (`skills_max`,- `skills_only`, applied like a profile: a field the user stated wins).-* The skills half lives in `codeverse3d/skills/variants/argon/` (bundles that shadow base- bundles by name, `routes.toml` with boosts / disabled rules / extra rows).-* `variant_hash("argon")` (`codeverse3d/prompts/variants.py`) covers both halves, this README- excluded; the run record names the variant, its version and that hash.--How a run picks it: `3dcodeverse make --variant argon`, `C3D_VARIANT=argon`, or-`C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}'` (an exact generator id, looked up as typed-and then by `<kind>:<served model>` so the effort suffix does not matter). Never a pattern-over the model id (Law 4).diff --git a/harness/codeverse3d/prompts/variants/argon/variant.toml b/harness/codeverse3d/prompts/variants/argon/variant.tomldeleted file mode 100644index 1d7de7cd..00000000--- a/harness/codeverse3d/prompts/variants/argon/variant.toml+++ /dev/null@@ -1,17 +0,0 @@-# The `argon` variant: gemini-4-argon on the scene track (threejs + blender). D105, 2026-10-14.-#-# This directory mirrors codeverse3d/prompts/: a file placed here (scene_threejs/system.md,-# tracks/scene_zone.j2, ...) shadows the base file of the same relative path for every run that-# activates the variant; a file not placed here is read from the base. The overlay ships EMPTY-# so iteration 0 of eval/bench/loop.py measures the base prompts under the variant plumbing;-# the loop writes files beside this one and bumps `version` on accept.-#-# Selection is explicit, never a regex over the model id: `3dcodeverse make --variant argon`,-# C3D_VARIANT=argon, or C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}' (by the served model, so-# agy:gemini-4-argon-high maps too). `generators` below is informative.--[variant]-name = "argon"-version = 2-generators = ["agy:gemini-4-argon"]-description = "gemini-4-argon on the scene track (threejs + blender)"diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.pyindex 670b9222..aa56d7c6 100644--- a/harness/codeverse3d/record/telemetry.py+++ b/harness/codeverse3d/record/telemetry.py@@ -80,7 +80,6 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:limits = s.limits.model_dump(mode="json")keys = len(s.gemini_api_keys)env = dict(record.environment)- variant, variant_version, variant_hash = _variant_fields(record)return SettingsSnapshot(roles=_role_settings(record),budget=spec.budget.model_dump(mode="json"),@@ -96,24 +95,9 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:price_table_version=price_table_version(),render=render,limits=limits,- variant=variant,- variant_version=variant_version,- variant_hash=variant_hash,)-def _variant_fields(record: RunRecord) -> tuple[str, int, str]:- """``(name, version, hash)`` of the variant the run used; the base is ``("", 0, "")``."""- block = record.extra.get("variant")- block = block if isinstance(block, dict) else {}- name = str(block.get("name") or record.environment.get("variant") or record.spec.options.variant or "")- if not name:- return "", 0, ""- version = block.get("version")- hashed = block.get("hash") or record.prompt_hashes.get("variant", "")- return name, int(version) if isinstance(version, int) and not isinstance(version, bool) else 0, str(hashed or "")--_TOOL_KEYS = frozenset({"python", "platform", "host", "blender", "blender_path", "node", "three","chrome", "puppeteer", "codeverse3d", "harness_git_sha"})diff --git a/harness/codeverse3d/skills/__init__.py b/harness/codeverse3d/skills/__init__.pyindex 5a6f0a7a..89428d34 100644--- a/harness/codeverse3d/skills/__init__.py+++ b/harness/codeverse3d/skills/__init__.py@@ -3,8 +3,6 @@A skill is AGENT-READ material (<=350 lines of requirements and short optional practices for onefailure class) that the harness only materialises, when track / language / kind / plan / theprevious round's gate findings say it applies. The library ships as package data.-``<skills_dir>/variants/<name>/`` overlays it while that variant is active: its bundles shadow-base ones by name, its ``routes.toml`` reshapes the routing table.Public surface: ``select`` (pure routing), ``attach_skills`` (write the routed bundles),``probe_reads`` (which were opened). Controlled by ``C3D_SKILLS`` (default on).@@ -13,14 +11,10 @@ Public surface: ``select`` (pure routing), ``attach_skills`` (write the routed bfrom __future__ import annotationsimport logging-import tomllib-from collections.abc import Iterable, Iterator-from dataclasses import dataclass+from collections.abc import Iteratorfrom pathlib import Path-from typing import TYPE_CHECKING, Anyfrom codeverse3d.config import get_settings-from codeverse3d.prompts.variants import active_variantfrom codeverse3d.skills.model import (SKILL_FILE,Skill,@@ -29,16 +23,8 @@ from codeverse3d.skills.model import (validate_bundle,)-if TYPE_CHECKING:- from codeverse3d.skills.registry import Route-log = logging.getLogger(__name__)-#: per-model overlays: ``<skills_dir>/variants/<name>/``-VARIANTS_SUBDIR = "variants"-#: a variant's routing-table overlay-ROUTES_FILE = "routes.toml"-def skills_dir() -> Path:override = get_settings().skills_dir@@ -47,24 +33,10 @@ def skills_dir() -> Path:return Path(__file__).resolve().parent-def variant_dir(name: str) -> Path:- return skills_dir() / VARIANTS_SUBDIR / name---def library_roots(variant: str | None = None) -> list[Path]:- name = active_variant() if variant is None else variant- roots = [skills_dir()]- if name:- overlay = variant_dir(name)- if overlay.is_dir():- roots.append(overlay)- return roots--def bundle_dirs(root: Path | None = None) -> list[Path]:"""Every directory under the library that looks like a bundle, sorted by name.- ``_claims/``, ``__pycache__/`` and ``variants/`` are invisible; pass an overlay as ``root``.+ ``_claims/`` and ``__pycache__/`` are invisible."""base = Path(root) if root is not None else skills_dir()if not base.is_dir():@@ -85,175 +57,19 @@ def iter_skills(root: Path | None = None, *, strict: bool = False) -> Iterator[Sdef all_skills(root: Path | None = None, *, strict: bool = False) -> dict[str, Skill]:- if root is not None:- return {s.name: s for s in iter_skills(root, strict=strict)}- out: dict[str, Skill] = {}- for r in library_roots():- out.update({s.name: s for s in iter_skills(r, strict=strict)})- return out+ return {s.name: s for s in iter_skills(root, strict=strict)}def load_skill(name: str, root: Path | None = None) -> Skill:- roots = [Path(root)] if root is not None else list(reversed(library_roots()))- for base in roots:- d = base / name- if (d / SKILL_FILE).is_file():- return parse_skill(d)- raise SkillError(f"no skill {name!r} in {' or '.join(str(r) for r in roots)}")---@dataclass(frozen=True)-class ShippedRoot:-- variant: str- path: Path-- def label(self, bundle: str) -> str:- return f"{self.variant}/{bundle}" if self.variant else bundle---def shipped_roots(variants: Iterable[str] | None = None) -> list[ShippedRoot]:- """The base root, then the skills overlay of every shipped variant that has one.-- ``3dcodeverse skills validate`` / ``list`` walk this so a malformed overlay bundle fails validation- instead of silently not routing. ``variants`` defaults to every variant ``list_variants`` knows.- """- from codeverse3d.prompts.variants import list_variants-- names = list(list_variants()) if variants is None else list(variants)- roots = [ShippedRoot("", skills_dir())]- roots += [ShippedRoot(name, variant_dir(name)) for name in names if variant_dir(name).is_dir()]- return roots---# ===================================================================== the variant routing table-@dataclass(frozen=True)-class RouteBoost:-- skill: str- delta: int---@dataclass(frozen=True)-class VariantRoutes:- """A variant's ``routes.toml``: boosts, disabled base rule ids and extra typed rows (appended after the base table)."""-- variant: str = ""- routes: tuple[Route, ...] = ()- boosts: tuple[RouteBoost, ...] = ()- disabled: frozenset[str] = frozenset()-- @property- def boost_map(self) -> dict[str, int]:- out: dict[str, int] = {}- for b in self.boosts:- out[b.skill] = out.get(b.skill, 0) + b.delta- return out-- @property- def empty(self) -> bool:- return not (self.routes or self.boosts or self.disabled)---def variants_table(name: str) -> VariantRoutes:- """The variant's parsed ``routes.toml``, or an empty table when it ships none; raises ``ValueError`` naming the bad row."""- if not name:- return VariantRoutes()- path = variant_dir(name) / ROUTES_FILE- if not path.is_file():- return VariantRoutes(variant=name)- return parse_routes(path, variant=name)---_ROUTE_KEYS = frozenset({"rule", "skill", "priority", "tracks", "languages", "kinds",- "requires_all", "requires_any", "findings", "why"})-_ROUTE_TUPLES = ("tracks", "languages", "kinds", "requires_all", "requires_any", "findings")---def parse_routes(path: Path, *, variant: str = "") -> VariantRoutes:- """Parse one ``routes.toml`` into typed records; every typing error is a ``ValueError`` naming the row."""- from codeverse3d.skills.registry import GATE_FIRED_PRIORITY, ROUTES, Route-- try:- data = tomllib.loads(path.read_text(encoding="utf-8"))- except tomllib.TOMLDecodeError as e:- raise ValueError(f"{path}: not valid TOML: {e}") from e- unknown = sorted(set(data) - {"boost", "disable", "route"})- if unknown:- raise ValueError(f"{path}: unknown table(s) {unknown}; routes.toml holds [[boost]], [[disable]] "- f"and [[route]] rows")- boosts = tuple(RouteBoost(skill=_str(row, "skill", where), delta=_int(row, "delta", where))- for where, row in _rows(data, "boost", path, {"skill", "delta"}))- disabled = frozenset(_str(row, "rule", where) for where, row in _rows(data, "disable", path, {"rule"}))- routes: list[Route] = []- taken = {r.rule for r in ROUTES}- for where, row in _rows(data, "route", path, _ROUTE_KEYS):- findings = _tuple(row, "findings", where)- priority = _int(row, "priority", where)- # a priority >= 90 means "a gate routed this" (Selection.gate_fired): only rows that name findings may sit there- if findings and priority < GATE_FIRED_PRIORITY:- raise ValueError(f"{where}: a gate-fired row (it names findings) needs priority >= "- f"{GATE_FIRED_PRIORITY}, got {priority}")- if not findings and priority >= GATE_FIRED_PRIORITY:- raise ValueError(f"{where}: a standing row (no findings) must stay below "- f"{GATE_FIRED_PRIORITY}, got {priority}")- route = Route(rule=_str(row, "rule", where), skill=_str(row, "skill", where), priority=priority,- tracks=_tuple(row, "tracks", where), languages=_tuple(row, "languages", where),- kinds=_tuple(row, "kinds", where), requires_all=_tuple(row, "requires_all", where),- requires_any=_tuple(row, "requires_any", where), findings=findings,- why=_str(row, "why", where, required=False))- if route.rule in taken:- raise ValueError(f"{where}: rule id {route.rule!r} is already taken — a rule id names ONE "- f"routing decision in every record and ledger row")- taken.add(route.rule)- routes.append(route)- return VariantRoutes(variant=variant, routes=tuple(routes), boosts=boosts, disabled=disabled)---def _rows(data: dict[str, Any], key: str, path: Path, allowed: frozenset[str] | set[str]) -> list[tuple[str, dict[str, Any]]]:- rows = data.get(key, [])- if not isinstance(rows, list):- raise ValueError(f"{path}: [[{key}]] must be an array of tables")- out: list[tuple[str, dict[str, Any]]] = []- for i, row in enumerate(rows):- where = f"{path}: [[{key}]] #{i}"- if not isinstance(row, dict):- raise ValueError(f"{where}: must be a table")- extra = sorted(set(row) - set(allowed))- if extra:- raise ValueError(f"{where}: unknown key(s) {extra} (allowed: {sorted(allowed)})")- out.append((where, row))- return out---def _str(row: dict[str, Any], key: str, where: str, *, required: bool = True) -> str:- value = row.get(key, "")- if not isinstance(value, str):- raise ValueError(f"{where}: {key} must be a string, got {value!r}")- if required and not value.strip():- raise ValueError(f"{where}: {key} is required")- return value.strip()---def _int(row: dict[str, Any], key: str, where: str) -> int:- value = row.get(key)- if isinstance(value, bool) or not isinstance(value, int):- raise ValueError(f"{where}: {key} must be an integer, got {value!r}")- return value---def _tuple(row: dict[str, Any], key: str, where: str) -> tuple[str, ...]:- value = row.get(key, [])- if not isinstance(value, list) or not all(isinstance(v, str) and v.strip() for v in value):- raise ValueError(f"{where}: {key} must be a list of non-empty strings, got {value!r}")- return tuple(v.strip() for v in value)+ base = Path(root) if root is not None else skills_dir()+ if not (base / name / SKILL_FILE).is_file():+ raise SkillError(f"no skill {name!r} in {base}")+ return parse_skill(base / name)from codeverse3d.skills.materialize import attach_skills, materialize_skills # noqa: E402from codeverse3d.skills.registry import plan_signals, select # noqa: E402from codeverse3d.skills.telemetry import probe_reads # noqa: E402-__all__ = ["ROUTES_FILE", "VARIANTS_SUBDIR", "RouteBoost", "ShippedRoot", "Skill", "SkillError",- "VariantRoutes", "all_skills", "attach_skills", "bundle_dirs", "iter_skills", "library_roots",- "load_skill", "materialize_skills", "parse_routes", "plan_signals", "probe_reads", "select",- "shipped_roots", "skills_dir", "validate_bundle", "variant_dir", "variants_table"]+__all__ = ["Skill", "SkillError", "all_skills", "attach_skills", "bundle_dirs", "iter_skills", "load_skill",+ "materialize_skills", "plan_signals", "probe_reads", "select", "skills_dir", "validate_bundle"]diff --git a/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md b/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.mdindex 5b3c9a3d..7b3aa470 100644--- a/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md+++ b/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md@@ -5,7 +5,7 @@ license: Apache-2.0compatibility: CadQuery 2.8 on OCP; one module src/model.py exporting a module-level `result`.metadata:evidence: inherited-unverified- evidence_note: 'Every kernel rule below was probed against the CadQuery 2.8.0 installed in this repo on 2026-08-25 and cross-checked with the cadquery lint, the run_cq wrapper and the language contract. What is NOT available is score evidence. This harness has ZERO graded cadquery bench runs, so nothing here is ranked by measured defect frequency the way the blender and urdf bundles are. Routed by default since 2026-09-22 (C3D_SKILLS_UNVERIFIED defaults on); still unranked until cadquery has 20 graded runs.'+ evidence_note: 'Every kernel rule below was probed against the CadQuery 2.8.0 installed in this repo on 2026-08-25 and cross-checked with the cadquery lint, the run_cq wrapper and the language contract. What is NOT available is score evidence. This harness has ZERO graded cadquery bench runs, so nothing here is ranked by measured defect frequency the way the blender and urdf bundles are. Routed by default since 2026-09-22; still unranked until cadquery has 20 graded runs.'verified: "2026-08-25"target_metric: "build_failure_rate"target_direction: "down"diff --git a/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md b/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.mdindex 992ed0cb..f57dd2b6 100644--- a/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md+++ b/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md@@ -5,7 +5,7 @@ license: Apache-2.0compatibility: "static_object track, language threejs. three r182 ESM in node, exported to GLB by the harness. Imports that resolve: three, three/addons/*, relative files under src/."metadata:evidence: inherited-unverified- evidence_note: "Zero graded threejs bench runs exist (bench/out/*/runs/*, checked 2026-08-25); the only recorded threejs run is runs/e2e_bench_threejs. Every API claim here is verified against codeverse3d/prompts/threejs/contract.md, codeverse3d/languages/threejs/__init__.py, runtime_js/export_glb.mjs and runtime_js/package.json, but the ADVICE has not been A/B'd on our corpus. Routed by default since 2026-09-22 (C3D_SKILLS_UNVERIFIED=0 drops it); upgrade to measured when threejs reaches 20 graded runs."+ evidence_note: "Zero graded threejs bench runs exist (bench/out/*/runs/*, checked 2026-08-25); the only recorded threejs run is runs/e2e_bench_threejs. Every API claim here is verified against codeverse3d/prompts/threejs/contract.md, codeverse3d/languages/threejs/__init__.py, runtime_js/export_glb.mjs and runtime_js/package.json, but the ADVICE has not been A/B'd on our corpus. Routed by default since 2026-09-22; upgrade to measured when threejs reaches 20 graded runs."verified: "2026-10-15"pairs_with: "c3d-part-contact, c3d-bbox-contract"target_metric: "missing_parts"diff --git a/harness/codeverse3d/skills/materialize.py b/harness/codeverse3d/skills/materialize.pyindex cd7073a9..da45f946 100644--- a/harness/codeverse3d/skills/materialize.py+++ b/harness/codeverse3d/skills/materialize.py@@ -17,7 +17,6 @@ from pathlib import Pathfrom typing import Anyfrom codeverse3d.config import get_settings-from codeverse3d.prompts.variants import active_variantfrom codeverse3d.skills.model import Selection, Skill, SkillsMaterializedfrom codeverse3d.skills.prompting import (AGENTS_SKILL_ROOT,@@ -26,7 +25,7 @@ from codeverse3d.skills.prompting import (index_tokens,inline_body,)-from codeverse3d.skills.registry import ROUTES, plan_signals, select+from codeverse3d.skills.registry import plan_signals, selectlog = logging.getLogger(__name__)@@ -139,8 +138,6 @@ def attach_skills(findings: Any = (),single_shot: bool = False,library: dict[str, Skill] | None = None,- max_skills: int | None = None,- allow_unverified: bool | None = None,only: frozenset[str] | None = None,) -> SkillsMaterialized:"""Route → write → return what a session will see. The one entry point tracks call.@@ -158,18 +155,10 @@ def attach_skills(if not library:log.warning("C3D_SKILLS_ONLY=%s matches no bundle in the library; this session attaches nothing",",".join(sorted(picked)))- # the active variant's overlay bundles are already in all_skills(); its routes.toml extends the table- variant = active_variant()- table = _routes_table(variant)sel: list[Selection] = select(- track, language, kind,- signals=plan_signals(plan), findings=findings, library=library,- max_skills=cfg.skills_max if max_skills is None else max_skills,- allow_unverified=cfg.skills_unverified if allow_unverified is None else allow_unverified,- routes=(*ROUTES, *table.routes), boosts=table.boost_map, disabled=table.disabled,- )+ track, language, kind, signals=plan_signals(plan), findings=findings, library=library)out = SkillsMaterialized(listed=[s.name for s in sel], selections=list(sel),- reasons={s.name: s.reason for s in sel}, attached_at=time.time(), variant=variant)+ reasons={s.name: s.reason for s in sel}, attached_at=time.time())if not sel or single_shot:# an empty selection must still sweep, or last round's bundles stay discoverablewith suppress(OSError):@@ -198,16 +187,5 @@ def attach_skills(return out-def _routes_table(variant: str) -> Any:- """The variant's ``routes.toml`` as typed rows; an invalid overlay falls back to the base table."""- from codeverse3d.skills import VariantRoutes, variants_table-- try:- return variants_table(variant)- except (ValueError, OSError) as e:- log.warning("variant %r: routes.toml rejected (%s); this session routes with the base table", variant, e)- return VariantRoutes(variant=variant)--__all__ = ["BODY_FILES", "CONTROL_NAME", "MARK_BEGIN", "MARK_END", "SKILL_ROOTS","attach_skills", "materialize_skills", "write_control", "write_index"]diff --git a/harness/codeverse3d/skills/model.py b/harness/codeverse3d/skills/model.pyindex dc489576..1e0adff9 100644--- a/harness/codeverse3d/skills/model.py+++ b/harness/codeverse3d/skills/model.py@@ -11,7 +11,7 @@ from pydantic import BaseModel, Fieldfrom codeverse3d.cost.guard import text_tokens-#: ``metadata.evidence`` values; the router refuses ``inherited-unverified`` when C3D_SKILLS_UNVERIFIED is 0.+#: ``metadata.evidence`` values; a label only: the router routes every level.EVIDENCE_MEASURED = "measured"EVIDENCE_INHERITED = "inherited-unverified"EVIDENCE_MIXED = "mixed"@@ -82,8 +82,6 @@ class SkillsMaterialized(BaseModel):inlined: str = Field(default="", description="single-shot: the one body inlined, '' otherwise")attached_at: float = Field(default=0.0, description="epoch seconds of the attach: the read probe credits ""only tool calls a CLI session logged after it (telemetry.probe_reads)")- variant: str = Field(default="", description="the prompt/skill variant active at the attach ('' = base; "- "D105) — its overlay bundles and routes.toml shaped `selections`")# ===================================================================== loaderdiff --git a/harness/codeverse3d/skills/registry.py b/harness/codeverse3d/skills/registry.pyindex acbd03ea..1a0d1ba1 100644--- a/harness/codeverse3d/skills/registry.py+++ b/harness/codeverse3d/skills/registry.py@@ -9,12 +9,11 @@ conditions hold, ``priority`` decides who survives the cap, and gate-fired rowsfrom __future__ import annotationsimport logging-from collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom typing import Anyfrom codeverse3d.contracts.artifacts import LintKind-from codeverse3d.skills.model import EVIDENCE_INHERITED, Selection, Skill+from codeverse3d.skills.model import Selection, Skill# --------------------------------------------------------------------------- finding kindsUNTYPED = "untyped"@@ -153,11 +152,9 @@ ROUTES: tuple[Route, ...] = (findings=(LINT_PART_NOT_IMPORTED,),why="a part file was written but never imported, so its geometry does not exist"),Route("R10", "c3d-cadquery-forms", 75, languages=("cadquery",), kinds=BUILD_KINDS,- why="cadquery authoring (evidence: inherited-unverified — unranked by our corpus; routed by default "- "since 2026-09-22, C3D_SKILLS_UNVERIFIED=0 drops it)"),+ why="cadquery authoring (evidence: inherited-unverified — unranked by our corpus)"),Route("R11", "c3d-threejs-forms", 75, tracks=("static_object",), languages=("threejs",), kinds=BUILD_KINDS,- why="three.js object authoring (evidence: inherited-unverified — unranked by our corpus; routed by "- "default since 2026-09-22, C3D_SKILLS_UNVERIFIED=0 drops it)"),+ why="three.js object authoring (evidence: inherited-unverified — unranked by our corpus)"),Route("R12", "c3d-urdf-joints", 80, tracks=("articulated_object",), languages=("urdf_blender",),kinds=("baseline", "refine", "rebuild", "repair"),why="joints, limits and axes: joint_sweep fires on 38% and motion_direction on 35% of urdf runs"),@@ -288,27 +285,6 @@ def _row_applies(row: Route, track: str, language: str, kind: str, signals: dictreturn not (row.requires_any and not any(signals.get(k) for k in row.requires_any))-#: the floor of a gate-fired row: ``Selection.gate_fired`` reads priority >= 90 as "a gate routed this",-#: so a variant boost may not move a row across it-GATE_FIRED_PRIORITY = 90---def effective_priority(row: Route, boosts: Mapping[str, int]) -> int:- """``row.priority`` plus the variant's boost, clamped so standing rows stay below and gate-fired rows at or above the floor."""- delta = int(boosts.get(row.skill, 0))- if not delta:- return row.priority- boosted = row.priority + delta- if row.gate_fired:- return max(GATE_FIRED_PRIORITY, boosted)- if boosted >= GATE_FIRED_PRIORITY:- log.warning("variant boost %+d lifts standing route %s (%s, priority %d) to %d: clamped to %d — a "- "standing row never outranks a gate-fired one", delta, row.rule, row.skill, row.priority,- boosted, GATE_FIRED_PRIORITY - 1)- return GATE_FIRED_PRIORITY - 1- return max(0, boosted)--def select(track: str,language: str,@@ -318,30 +294,22 @@ def select(findings: Any = (),library: dict[str, Skill] | None = None,max_skills: int = 5,- allow_unverified: bool = False,- routes: Sequence[Route] = ROUTES,- boosts: Mapping[str, int] | None = None,- disabled: frozenset[str] = frozenset(),) -> list[Selection]:"""The routed bundles for one session, ranked, capped, each with its reason.- ``findings`` may be ``GateFinding``s, ``GateReport``s or kind strings; ``routes`` / ``boosts`` /- ``disabled`` are a variant's reshaping of the table.+ ``findings`` may be ``GateFinding``s, ``GateReport``s or kind strings."""from codeverse3d.skills import all_skillslib = library if library is not None else all_skills()sig = dict(signals or {})- boost: Mapping[str, int] = boosts or {}kinds = [f for f in findings if isinstance(f, str)] if findings else []if findings and not kinds:kinds = finding_kinds(findings)best: dict[str, Selection] = {}first_seen: dict[str, int] = {}- for order, row in enumerate(routes):- if row.rule in disabled:- continue+ for order, row in enumerate(ROUTES):hit = row.matches_finding(kinds) if row.gate_fired else Noneif row.gate_fired and hit is None:continue@@ -354,12 +322,8 @@ def select(# a table row without a bundle must not crash a runlog.debug("route %s names skill %r, which is not in the library", row.rule, row.skill)continue- if skill.evidence == EVIDENCE_INHERITED and not allow_unverified:- log.debug("skill %s is %s and C3D_SKILLS_UNVERIFIED is off; not routed", skill.name, EVIDENCE_INHERITED)- continue- priority = effective_priority(row, boost)- reason = (f"{row.rule}: {row.why}" + (f" [{hit}]" if hit else "")- + (f" (variant boost {priority - row.priority:+d})" if priority != row.priority else ""))+ priority = row.priority+ reason = f"{row.rule}: {row.why}" + (f" [{hit}]" if hit else "")first_seen.setdefault(row.skill, order)prev = best.get(row.skill)if prev is None:diff --git a/harness/codeverse3d/skills/variants/argon/README.md b/harness/codeverse3d/skills/variants/argon/README.mddeleted file mode 100644index dac552df..00000000--- a/harness/codeverse3d/skills/variants/argon/README.md+++ /dev/null@@ -1,19 +0,0 @@-# argon — the skills overlay for gemini-4-argon on the scene track--The skills half of the `argon` variant (D105, 2026-10-14; the prompts half is-`codeverse3d/prompts/variants/argon/`). Three things may live here:--* **Bundles** — `c3d-<name>/SKILL.md` (+ `references/`), shadowing a base bundle of the same- name or adding a new one. `codeverse3d.skills.all_skills()` is the base library updated by- this directory while the variant is active; a bundle here is validated like a base one.-* **`_claims/<name>.toml`** — a shadowed bundle's pinned numbers; looked up here first, then in- the base `_claims/`.-* **`routes.toml`** — `[[boost]]` rows (a priority delta per skill, clamped so a standing row- never reaches the gate-fired floor of 90 and a fired row never drops under it), `[[disable]]`- rows (base rule ids to skip) and `[[route]]` rows (extra typed routes, appended after the base- table). Parsed with `tomllib` into typed records; a row that does not type-check is logged- and the base table routes.--It ships empty: iteration 0 of `eval/bench/loop.py` measures the base library and table.-The run record's `extra.variant.hash` covers this directory (README excluded) together with-the prompts overlay.diff --git a/harness/codeverse3d/skills/variants/argon/routes.toml b/harness/codeverse3d/skills/variants/argon/routes.tomldeleted file mode 100644index 5904f754..00000000--- a/harness/codeverse3d/skills/variants/argon/routes.toml+++ /dev/null@@ -1,20 +0,0 @@-# The `argon` variant's routing table (D105, 2026-10-14) — EMPTY: iteration 0 of the loop-# measures the base table. Parsed by codeverse3d/skills/__init__.py::parse_routes with tomllib-# into typed rows (no regex); a row that does not type-check is rejected at attach time-# (logged, the base table routes) and refused by the tests. Three row kinds:-#-# [[boost]] # add `delta` to the priority of every route naming `skill`: a standing-# skill = "c3d-scene-materials" # row is clamped below 90, a gate-fired row never drops under 90-# delta = 20-#-# [[disable]] # skip a base rule by id-# rule = "R27"-#-# [[route]] # an extra typed row, appended AFTER the base table (ties keep base order);-# rule = "V1" # a fresh id (never one the base table uses); priority >= 90 only with `findings`-# skill = "c3d-scene-materials"-# priority = 85-# tracks = ["scene"]-# languages = ["scene_blender"]-# kinds = ["env", "zone", "refine"]-# why = "flat albedo is the audit's most-cited surface defect on argon zones"diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.pyindex c74eb010..68f8b1ba 100644--- a/harness/codeverse3d/tracks/common.py+++ b/harness/codeverse3d/tracks/common.py@@ -141,7 +141,6 @@ class RunContext:tool_cards: str = ""prompt_hashes: dict[str, str] = field(default_factory=dict)extra: dict[str, Any] = field(default_factory=dict)- variant: str = ""@propertydef language(self) -> Language:diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.pyindex 805b9d89..2bfc2e22 100644--- a/harness/codeverse3d/tracks/lifecycle.py+++ b/harness/codeverse3d/tracks/lifecycle.py@@ -37,12 +37,6 @@ from codeverse3d.orchestrator import (from codeverse3d.proc import EventLog, fan_out, read_json_or_nonefrom codeverse3d.prompts import load_text, renderfrom codeverse3d.prompts.catalog import language_text-from codeverse3d.prompts.variants import (- activate,- active_variant,- resolve_variant,- variant_block,-)from codeverse3d.record.record import previous_verdictfrom codeverse3d.tracks.candidates import run_best_of_nfrom codeverse3d.tracks.common import RunContext, Services@@ -87,11 +81,7 @@ def plan_stage_inputs(spec: Spec) -> dict[str, Any]:def plan_stage_key(spec: Spec, track: Track) -> dict[str, Any]:- key: dict[str, Any] = {"spec": plan_stage_inputs(spec), "track": track.value}- variant = spec.options.variant or active_variant()- if variant:- key["variant"] = variant- return key+ return {"spec": plan_stage_inputs(spec), "track": track.value}def spec_fingerprint(spec: Spec) -> str:@@ -283,8 +273,7 @@ class BaseTrack:# ------------------------------------------------------------------ public APIdef run(self, spec: Spec, ws: Workspace, *, resume: bool = False, force: bool = False) -> RunRecord:ws.create()- variant = self.variant_for(spec)- with activate(variant), run_ledger(ws.root, run=run_binding().run or ws.root.name):+ with run_ledger(ws.root, run=run_binding().run or ws.root.name):if not ws.spec_path.is_file() or not resume:ws.write_json(ws.spec_path, spec)events = EventLog(ws.events_path)@@ -293,10 +282,7 @@ class BaseTrack:ctx = self.build_context(spec, ws, events, state)runner = StageRunner(ws, events, state, frozen=bool(rounds))events.emit("run.start", track=self.track.value, language=spec.language.value, resume=resume,- agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge,- variant=variant)- if variant:- events.emit("variant.active", **variant_block(variant))+ agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge)stop = RunStatus.FAILEDerror = ""try:@@ -321,12 +307,6 @@ class BaseTrack:raisereturn self.finalise(ctx, rounds, stop, error=error)- # ------------------------------------------------------------------ the variant- @staticmethod- def variant_for(spec: Spec) -> str:- """The variant this run activates: the spec's frozen choice, else the one resolved for its generator."""- return spec.options.variant or resolve_variant(get_settings(), spec.backends.generator)-# ------------------------------------------------------------------ resume reconciliationdef reconcile_resume(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState,*, resume: bool, force: bool) -> list[RoundRecord]:@@ -407,8 +387,7 @@ class BaseTrack:ctx = RunContext(spec=spec, ws=ws, events=events, settings=settings, budget=budget, runtime=runtime,services=self.services, state=state, policy=policy, track=self.track, rubric=rubric,agent_id=spec.backends.generator,- agent=metered_agent(self._agent), model=metered_chat_model(self._model),- variant=active_variant())+ agent=metered_agent(self._agent), model=metered_chat_model(self._model))ctx.contract_text = language_text(spec.language, "contract.md")ctx.tool_cards = self.services.tool_cards(self.track.value, spec.language.value)ctx.record_prompt("contract", ctx.contract_text)@@ -643,8 +622,6 @@ class BaseTrack:extra["finalise_rebuild_failed"] = ctx.extra["finalise_rebuild_failed"]if ctx.extra.get("aborted_rounds"):extra["aborted_rounds"] = ctx.extra["aborted_rounds"]- variant = variant_block(ctx.variant)- extra["variant"] = variantprior_extra, prior_hashes = self._prior_record_fields(ctx.ws)if ctx.extra.get("finalise_rebuild_failed", None) == "":prior_extra.pop("finalise_rebuild_failed", None)@@ -656,15 +633,11 @@ class BaseTrack:extra["aborted_rounds"] = prior_aborted + [a for a in ctx.extra["aborted_rounds"]if a not in prior_aborted]hashes = {**prior_hashes, **dict(ctx.prompt_hashes)}- if ctx.variant and variant["hash"]:- hashes["variant"] = variant["hash"]- elif not ctx.variant:- hashes.pop("variant", None)return RunRecord(spec=ctx.spec, plan=ctx.plan, workspace=str(ctx.ws.root), status=status, rounds=rounds,total_usage=ledger_usage(load_ledger(ctx.ws.root)), steps=list(ctx.state.steps),environment={"python": platform.python_version(), "host": platform.node(), "track": self.track.value,- "language": ctx.language.value, "generator": ctx.agent_id, "variant": ctx.variant},+ "language": ctx.language.value, "generator": ctx.agent_id},prompt_hashes=hashes, started_at=ctx.state.started_at,finished_at=datetime.now(UTC), error=error,extra=extra,diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.pyindex 48fb5f73..5f2d7d78 100644--- a/harness/codeverse3d/tracks/plan_features.py+++ b/harness/codeverse3d/tracks/plan_features.py@@ -5,8 +5,7 @@ from __future__ import annotationsfrom codeverse3d.config import Settings-GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED",- "C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF"})+GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF"})NODE_SIDE_ENV: frozenset[str] = frozenset({"C3D_BROWSER_REUSE", "C3D_PAGE_TTL_MS"})diff --git a/harness/codeverse3d/tracks/skills_hook.py b/harness/codeverse3d/tracks/skills_hook.pyindex 110b8831..ab7dfe44 100644--- a/harness/codeverse3d/tracks/skills_hook.py+++ b/harness/codeverse3d/tracks/skills_hook.py@@ -43,8 +43,7 @@ def attach_for_round(ctx: RunContext, *, index: int, kind: str, findings: Sequenfor sel in got.selections:ctx.record_prompt(f"skill:{sel.name}", sel.skill.body)ctx.events.emit("skills.attached", round=index, kind=kind, skills=got.listed,- index_tokens=got.index_tokens, inlined=got.inlined or None, reasons=got.reasons,- variant=got.variant)+ index_tokens=got.index_tokens, inlined=got.inlined or None, reasons=got.reasons)return got@@ -84,7 +83,7 @@ def record_usage(ctx: RunContext, *, index: int, kind: str) -> SkillsUsage | Nonusage = probe_reads(ctx.ws.root, got)append_usage(ctx.ws.root, usage, round=index, kind=kind, agent=ctx.agent_id,track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),- language=ctx.language.value, variant=got.variant)+ language=ctx.language.value)except Exception as e: # noqa: BLE001 — telemetry never costs a roundlog.warning("skills telemetry failed for round %d: %s", index, e)return Nonediff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.mdindex f242fb4a..b93216bf 100644--- a/harness/docs/INSTALL.md+++ b/harness/docs/INSTALL.md@@ -378,7 +378,6 @@ export C3D_LIMITS__AGENT_TIMEOUT_S=900export C3D_DEFAULT_CANDIDATES=2export C3D_DEFAULT_JUDGE=gemini:gemini-4-argonexport C3D_JUDGE__THINKING=medium-export C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}' # per-model prompt/skill variant by exact generator id; C3D_VARIANT=argon names one for every run```Every knob the harness reads is a `Settings` field (`codeverse3d/config.py`, one description@@ -411,7 +410,7 @@ rows name what is optional or busy.| `python deps` | FAIL | a core import is missing/broken | `pip install -e 'harness[all]'`; a broken native lib (`fcl`) shows up here too — reinstall that wheel (`pip install --force-reinstall python-fcl`) || `python deps` | WARN | only optional-extra modules missing (`shapely` / `yourdfpy` / `mcp` / `moderngl` / `cadquery`) | install the extra the row names, e.g. `pip install -e 'harness[mesh,urdf,mcp,graphics,cad]'` (§4) || `blender` | FAIL | no binary found, or `--version` failed | §6 — install Blender, or `export C3D_BINARIES__BLENDER=/path/to/blender`. If it is found but fails, run it by hand: a `libSM.so.6`/`libICE.so.6` error means you need the `LD_LIBRARY_PATH` wrapper |-| `blender cycles` | WARN | Cycles sees no CUDA device | scene_blender's judged frames render on the CPU (a few times slower) — fine without an NVIDIA GPU; on WSL2 install the vendor WSL GPU driver. The row also names the judged-frame engine / samples / device (`C3D_RENDER__BLENDER_*`) |+| `blender cycles` | WARN | Cycles sees no CUDA device | scene_blender's judged frames render on the CPU (a few times slower) — fine without an NVIDIA GPU; on WSL2 install the vendor WSL GPU driver. The row also names the judged-frame engine / samples / device (`C3D_RENDER__BLENDER_ENGINE` / `_SAMPLES` / `_DEVICE`) || `blender eevee` | WARN / FAIL | the EEVEE smoke frame ran on llvmpipe (software GL), or did not render | only matters with `C3D_RENDER__BLENDER_ENGINE=eevee`: the harness runs EEVEE under the Mesa d3d12 env (`spatial/gl_render.GPU_ENV`); llvmpipe here means that env found no GPU. `--no-gpu` skips the smoke frame || `blender render` | FAIL / SKIP | the render probe could not run Blender (or there is none) | see the `blender` row || `blender gpu slots` | WARN | every machine-wide GPU Blender render slot is held right now | other renders are on the GPU; a render waits `C3D_RENDER__BLENDER_GPU_WAIT_S` for a slot and then renders on the CPU — nothing to fix unless it stays full. `C3D_RENDER__BLENDER_GPU_SLOTS` sizes it |diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex 17de1af9..b6ca1496 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -50,15 +50,10 @@ Useful flags (`3dcodeverse make --help`):* `--max-minutes`, `--dim height=0.45`, `--must`, `--must-not`, `--style`, `--tag`, `--seed` (alabel: it re-keys the plan, nothing else is seeded by it), `--slug`, `--runs-dir`, `--force`,`--no-run` (workspace + spec.json only).-* `--variant NAME` — a per-model prompt/skill overlay (`codeverse3d/prompts/variants/<name>/` +- `codeverse3d/skills/variants/<name>/`), frozen on `spec.options.variant` so `resume` and- `judge` read the same files; default `C3D_VARIANT`, else `C3D_VARIANTS` keyed by the exact- generator id, else the base prompts.-Expected cost/time with gemini-3.8-flash: object tracks ≈ $0.7–0.9 and 12–36 min for baseline +-1 refine; best-of-2 single-shot ≈ $0.25 / 8 min; graphics single-shot ≈ $0.05 / 2 min per judged-round; scenes ≈ $2.3 and 30 min before the first judged round, then ≈ $0.36 / ~7 min per refine-(give scenes `--max-minutes 60`). Actual spend: `3dcodeverse cost <slug>`.+Expected cost with the default `agy:gemini-4-argon` generator (median `total_usage` over the recorded+Oct-Nov runs, mixed round counts): static_object ≈ $2.2, articulated ≈ $4.2, graphics ≈ $4.4, scene ≈+$10.4; give scenes `--max-minutes 60` or more. Actual spend: `3dcodeverse cost <slug>`.## 3. Backends@@ -232,17 +227,6 @@ storm's rows (`--redo-status error,infra_failed,budget`) rather than reading the(`tests/prompts/test_files.py`); a new language or track adds its scenario to `SCENARIOS`.Every new template variable is guarded `{% if name is defined and name %}` for at least onewave: templates are read at render time, so a live worker on old python renders the new file.-* **A per-model variant**: `codeverse3d/prompts/variants/<name>/variant.toml` (`[variant]` name =- the directory name, version, generators, description) beside the prompt- files that shadow the base ones by relative path (a template there may `include` a base- file), and `codeverse3d/skills/variants/<name>/` for bundles that shadow base bundles by name,- their `_claims/`, and `routes.toml` (`[[boost]]` skill + delta, `[[disable]]` rule, `[[route]]`- extra typed rows with fresh ids). Nothing else changes: `prompts.load_text` / `render` /- `catalog.language_text` and `skills.all_skills` resolve through the active variant, the record- carries `extra.variant` {name, version, hash} + `prompt_hashes.variant`. An overlay starts- EMPTY (the shipped `argon` is) so its first iteration measures the base; the manifest gets one- scenario per variant. Selection is explicit — `--variant`, `C3D_VARIANT`, `C3D_VARIANTS` —- never a pattern over the model id.* **New spatial tool**: pydantic args + `@tool("name", Args, "…", tracks=(…), languages=(…),cost_hint=…)` in `spatial/tools.py`; available to tracks, MCP and prompt cards at once. Update`tests/spatial_tools` EXPECTED_TOOLS.diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.mdindex 6b4ffe07..83d760fb 100644--- a/harness/docs/SKILLS.md+++ b/harness/docs/SKILLS.md@@ -14,9 +14,7 @@ format is not ours to bend — and it is why the bundles reach a session only thnative skill loader: claude-code, codex and agy discover them themselves.`C3D_SKILLS` is **on by default**; `C3D_SKILLS=0` is the off switch and an A/B's no-skills arm.-Knobs: `C3D_SKILLS_MAX` (5 bundles a session), `C3D_SKILLS_UNVERIFIED` (the-`inherited-unverified` bundles, on), `C3D_SKILLS_ONLY` (restrict the library before routing),-`C3D_SKILLS_DIR` (another library).+Knobs: `C3D_SKILLS_ONLY` (restrict the library before routing), `C3D_SKILLS_DIR` (another library).## 1. How the library is managed@@ -24,8 +22,7 @@ Knobs: `C3D_SKILLS_MAX` (5 bundles a session), `C3D_SKILLS_UNVERIFIED` (theplain `SKILL.md` directories that know nothing about any backend — `cp -r` one into`~/.claude/skills/` and it works without the harness. `registry.py` picks the set from typedinputs. The one thing that differs between coding agents is the discovery root, in one file,-`skills/prompting.py` (`_BACKEND_ROOTS`; `tests/skills/test_delivery.py` fails if per-backend-knowledge leaks anywhere else):+`skills/prompting.py` (`_BACKEND_ROOTS`):| backend | discovery root | how the CLI shows and activates a bundle ||---|---|---|@@ -51,7 +48,7 @@ the prose came from — not a measured effect.| skill | track | language | evidence | routes ||---|---|---|---|---|| `c3d-part-contact` | object tracks | any | measured | R1, R2 |-| `c3d-bbox-contract` | object + scene | any | measured | R3, R4 |+| `c3d-bbox-contract` | object tracks | any | measured | R3, R4 || `c3d-repeats-and-mirrors` | object tracks | any | measured | R6, R7 || `c3d-blender-forms` | any | blender, urdf_blender | measured | R8, R9 || `c3d-urdf-joints` | articulated_object | urdf_blender | measured | R12, R13 |@@ -89,9 +86,9 @@ turns `(track, language, kind, plan signals, findings)` into a ranked, capped, rFour laws, all tested:1. **Gate findings outrank everything.** A row answering a finding sits at priority ≥ 90,- standing rows at ≤ 80: a repair round spends its budget on what broke — the input no CLI's+ standing rows below 90: a repair round spends its budget on what broke — the input no CLI'sown loader can see, and the reason routing is in code.-2. **The cap is 5** (`C3D_SKILLS_MAX`); it cuts the low-priority tail, never the gate-fired head.+2. **The cap is 5** (`select(max_skills=)`); it cuts the low-priority tail, never the gate-fired head.3. **Quiet kinds attach nothing on their own** — `asset`, `asset_fix`, `reference` are short,narrow sessions. A gate-fired row still reaches them.4. **Unknown input degrades to `[]`, never an exception** — a planner failure must not also take@@ -120,13 +117,11 @@ is `None`, not a number.```3dcodeverse skills report eval/bench/out/<battery> # deep-read rate per skill per backend (--json)-3dcodeverse skills validate [--strict] # bundles, overlays, routes, claims+3dcodeverse skills validate [--strict] # bundles, claims```Target: ≥ 60 % deep-read, counted only over sessions the control says were measurable. A skillunder 20 % over 20 such sessions is merged or deleted — a library that only grows ends as bloat.-`pytest -m live tests/skills/test_live_discovery.py` proves on the real CLIs that a bundle is-found and opened through each discovery root.## 5. How to add a skill@@ -162,5 +157,4 @@ found and opened through each discovery root.Body rules: ≤ 350 lines and ≤ 2,500 tokens; no code fence over 12 lines; never restate a frame,unit or naming rule (`conventions.py` owns those); every corpus percentage carries its battery,its n and its date. `tests/skills/` enforces all of it: the spec's field rules, the body budget,-every `_claims` number against its live constant, every tool / gate kind / rubric criterion /-constant a bundle names still existing, the four routing laws, and the read probe.+every `_claims` number against its live constant, the four routing laws, and the read probe.diff --git a/harness/tests/orchestrator_tracks/test_plan_features.py b/harness/tests/orchestrator_tracks/test_plan_features.pyindex 7b2a1b49..85966a00 100644--- a/harness/tests/orchestrator_tracks/test_plan_features.py+++ b/harness/tests/orchestrator_tracks/test_plan_features.py@@ -17,7 +17,6 @@ def test_every_settings_field_is_a_live_switch_and_anything_else_is_dead():for name in Settings.model_fields[section].annotation.model_fields]live += [*Settings.FLAT, *NODE_SIDE_ENV, *GENERATION_SIDE_ENV]assert dead_env_keys(dict.fromkeys(live, "1")) == []- assert {"C3D_VARIANT", "C3D_VARIANTS"} <= set(live), "the variant switches (D105) are Settings fields"retired = ["C3D_PLAN_FEATURES", "C3D_FEWER_TURNS", "C3D_DETAIL_ROUNDS", "C3D_RATE__STORM_GATE","C3D_RATE__TPM_PER_KEY", "C3D_MYSTERY_KNOB"]assert dead_env_keys({**dict.fromkeys(retired, "1"), "C3D_PLAN_BRIEF": "off"}) == sorted(retired)@@ -33,7 +32,3 @@ def test_pin_plan_refuses_only_live_switches_not_known_to_act_after_planning():"C3D_PLAN_BRIEF is not known to act after planning"]assert pin_plan_blockers({"GEMINI_CLI_HOME": "/x"}) == ["GEMINI_CLI_HOME is not known to act after planning"]- # a variant overlays the planner templates and keys the plan stage (D105): never shared across arms- assert pin_plan_blockers({"C3D_VARIANT": "argon"}) == ["C3D_VARIANT is not known to act after planning"]- assert pin_plan_blockers({"C3D_VARIANTS": '{"agy:gemini-4-argon": "argon"}'}) == [- "C3D_VARIANTS is not known to act after planning"]diff --git a/harness/tests/prompts/manifest.json b/harness/tests/prompts/manifest.jsonindex 11093089..a797e062 100644--- a/harness/tests/prompts/manifest.json+++ b/harness/tests/prompts/manifest.json@@ -18,11 +18,11 @@"job:refine@r01/prompt": {"bytes": 7267, "sha256": "a718673dc59d566a5af561d8543756e0326057613430e6dae0cb13eb23b8234e"},"job:refine@r01/scope": {"bytes": 379, "sha256": "d17ae76997ec9443d52089e32ec81ecac3ba2c93529b227533942e84598113d9"},"job:refine@r01/system": {"bytes": 3271, "sha256": "29f5a9b2e7b9a879be58963ce95ae6fbec7460dae6785d542b214d6b850e21f4"},- "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9819, "sha256": "0a7445d421267800ff75c73621b735d79a7ceb04ab107e640f52c145916b0201"},+ "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9801, "sha256": "ad8b9b44bf755a91f00acbb9fab508db1862302222e8e89a46da3a28bb19385a"},"judge:articulated:runs/run/artifacts/renders/r00/messages": {"bytes": 7266, "sha256": "44869437393997f2107fdf0a59b70d830557064fa5958abfbee786e535323a2c"},"judge:articulated:runs/run/artifacts/renders/r00/sampling": {"bytes": 11992, "sha256": "0450937509be0de6976f74c7d439af0878caa67d4105d01afcec4a211cfbfbd2"},"judge:articulated:runs/run/artifacts/renders/r00/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},- "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10722, "sha256": "67b607398aa3997504db43be1092ecec063fc228f55af02dc66755ee602b993a"},+ "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10704, "sha256": "b64488b3d6bac252c89181cb8954d2cdcc0381d5df0a544fc2d9643ac2360299"},"judge:articulated:runs/run/artifacts/renders/r01/messages": {"bytes": 7591, "sha256": "a2e7394b1d8515b0256e914ceb6b07eaf526a634104ea03829c559e5fd7ebf67"},"judge:articulated:runs/run/artifacts/renders/r01/sampling": {"bytes": 11992, "sha256": "0450937509be0de6976f74c7d439af0878caa67d4105d01afcec4a211cfbfbd2"},"judge:articulated:runs/run/artifacts/renders/r01/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},@@ -51,11 +51,11 @@"chat:planner:planner/messages": {"bytes": 1328, "sha256": "313c87553cf38df423dc9245a8af4cca5a41a844b489e13a5dc08e8c44eabba5"},"chat:planner:planner/sampling": {"bytes": 10001, "sha256": "0ff37a3ae43fdf878dd0911a9954d57e49365ad788c84818ea01d350310ab401"},"chat:planner:planner/system": {"bytes": 20030, "sha256": "45dccfcf72b4c6e46b7ceeaae8af0ebddf6f6e6b5970cda5fe900aa47682bf06"},- "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9539, "sha256": "f0513f5660eed412e9e260200d50ba2cb4d5ea144d252fe7b6a86a4c94b0306d"},+ "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9521, "sha256": "4dc6d5eb8c3c153bf1d79511745835a97ad82ba97326bea5879a2b8fdd73fce1"},"judge:articulated:runs/run/artifacts/renders/r00/messages": {"bytes": 7120, "sha256": "7a0ef8d51456faa2c38867eea6c502fbe1a7aa30d6cd9f23b44701a2d11846bf"},"judge:articulated:runs/run/artifacts/renders/r00/sampling": {"bytes": 11992, "sha256": "0450937509be0de6976f74c7d439af0878caa67d4105d01afcec4a211cfbfbd2"},"judge:articulated:runs/run/artifacts/renders/r00/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},- "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10442, "sha256": "faeb5630c2e4ba0081b5ec45b166279deb1ad38548014ef829110a2c452d8d3d"},+ "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10424, "sha256": "f9543697737dd031f4e4af1a1eb52bd54bc59e88efdec15b3d7d0716d010b7a5"},"judge:articulated:runs/run/artifacts/renders/r01/messages": {"bytes": 7445, "sha256": "2a654e5bb10f8a642367b40c8893a16dce24c4bc4f6941cfbba76ce348ad4f1c"},"judge:articulated:runs/run/artifacts/renders/r01/sampling": {"bytes": 11992, "sha256": "0450937509be0de6976f74c7d439af0878caa67d4105d01afcec4a211cfbfbd2"},"judge:articulated:runs/run/artifacts/renders/r01/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},@@ -81,15 +81,15 @@"job:baseline_c1@r00/prompt": {"bytes": 11347, "sha256": "5aca38cfae577e7e5e5974c2b6cd64e55ec35a1dfab33eaf62eff70652854df5"},"job:baseline_c1@r00/scope": {"bytes": 383, "sha256": "831265b54627f1f6c1bfadebefa4e898d6b543b253bf6be0685b5383bd39fb57"},"job:baseline_c1@r00/system": {"bytes": 3173, "sha256": "c3879a563e2a512b82358d0c3927dcbfe9347725e592035a9b64c5d1b34e6654"},- "judge:shader:runs/run/_cand/c0/artifacts/renders/r00/input": {"bytes": 4013, "sha256": "53102aacf0ecbb26bb489751b12f64205ca575c6ed6005650f9297108f4e2577"},+ "judge:shader:runs/run/_cand/c0/artifacts/renders/r00/input": {"bytes": 3995, "sha256": "dc9ed48e7f91deb16b26c1b205ed86f9f7dfc4231c0339d9bfd27e7859973e85"},"judge:shader:runs/run/_cand/c0/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/_cand/c0/artifacts/renders/r00/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/_cand/c0/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/_cand/c1/artifacts/renders/r00/input": {"bytes": 4013, "sha256": "0cd59e323b50bd972a8187ab1752601a68a09be5b4cad5a8ff31272358edb36a"},+ "judge:shader:runs/run/_cand/c1/artifacts/renders/r00/input": {"bytes": 3995, "sha256": "ab5da86ecd5f0ef59593ee884c1cbc3633427aaded121ac33048c0ca4a6561a7"},"judge:shader:runs/run/_cand/c1/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/_cand/c1/artifacts/renders/r00/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/_cand/c1/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3959, "sha256": "5a6cd939181903bcd28e49d83b7f86b407558242c1e86a91c82bd4fb147dd0ef"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3941, "sha256": "048cac847c6642718479660d31a9493a2116660129a9077f841257225f70886a"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -117,15 +117,15 @@"job:refine@r02/prompt": {"bytes": 4828, "sha256": "f02f3a218edb95d79000fd339cc556045baccd5087231dd293db83195c927fa7"},"job:refine@r02/scope": {"bytes": 375, "sha256": "c4a7fdb0b390ec75d595006e11b9982113e60c49f5a62a978153167053bbcd33"},"job:refine@r02/system": {"bytes": 3173, "sha256": "c3879a563e2a512b82358d0c3927dcbfe9347725e592035a9b64c5d1b34e6654"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3959, "sha256": "4dde2639e506ef0d2636bde47835d14b7f8702f43bdf5f4d7c6072ed65c6637c"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3941, "sha256": "6765238c348c45471ba13aad1cd5314fdddf5f841f2196e942d2d8878abd520f"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5012, "sha256": "2eadea804479eca53e39ff1fb2b505e71188e16cb38241b7e77dce40d5f97032"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 4994, "sha256": "7f2ca50cf2f58bd09a2074eb477315ef4fde382eb805f8bcab725825427e541a"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 4123, "sha256": "a1f0c207406de6f415fdb8516b695aaedf7f06d25598f33932d2ad728f8c881f"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r02/input": {"bytes": 5008, "sha256": "260f183b612bd9ae84a5ad913e2fdd84788d144f9a24a14aba70d410caf861f6"},+ "judge:shader:runs/run/artifacts/renders/r02/input": {"bytes": 4990, "sha256": "ee8ee593b0868f9bc914843e4140e393b915839759ba79d63100fa39df687a1a"},"judge:shader:runs/run/artifacts/renders/r02/messages": {"bytes": 4123, "sha256": "5b81b09f9d6a7e3225549454099d07143f5bb726c3ccff263b4afc7bfe13d88b"},"judge:shader:runs/run/artifacts/renders/r02/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r02/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -156,7 +156,7 @@"job:rebuild@r01/prompt": {"bytes": 11530, "sha256": "55b953a2ecd60c415cec8995694d1dc731bd0d8135bc594a1ba07d68b7f5f09f"},"job:rebuild@r01/scope": {"bytes": 379, "sha256": "471fba995682e47fe12099cb5881743a8aeae71a0243fa3598c72d69a5b31f98"},"job:rebuild@r01/system": {"bytes": 3173, "sha256": "c3879a563e2a512b82358d0c3927dcbfe9347725e592035a9b64c5d1b34e6654"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 3959, "sha256": "df77c1b050ec2b6aacb408eeb09dc6b9ab0bd37e6aadea89a54db3ce9dffede3"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 3941, "sha256": "31966e4dc5f000ac191df212871fc7ba3d5bb758dbea382e41828e3470cf6214"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -179,11 +179,11 @@"chat:planner:planner/messages": {"bytes": 348, "sha256": "f50fc3cdf3a426fc9c9b830b6e68d2cfe9fd9b7125550362b018f9c9b454b25c"},"chat:planner:planner/sampling": {"bytes": 3421, "sha256": "918170272cea656e8c542c54b777c57d1a4567a8cc36a0c1cd825cb81a01b9bb"},"chat:planner:planner/system": {"bytes": 11919, "sha256": "194d0e2a724c4799816033228af15cac568dd51c14ed85bff9c94ae5ba281866"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3976, "sha256": "6047e9f7c3985e1827f3ecc3263d87012c8a3c074b9bc33517e11e12751d2e58"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3958, "sha256": "3866e76ad0c136348c696e9c728048f05642bbab184f65631672aa35c68e6318"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5029, "sha256": "d3e2b3031ba4e6593d3c55af498869db17277952dcf5f320ac415bc04616aca7"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5011, "sha256": "7c2cd0aa5cd17a1dd2097bbcc73ef0c1c2e5dd68ba545bbd094f1568b9254252"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 4123, "sha256": "a1f0c207406de6f415fdb8516b695aaedf7f06d25598f33932d2ad728f8c881f"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -207,11 +207,11 @@"job:refine@r01/prompt": {"bytes": 4809, "sha256": "564c35401c05213d9906d0ecf84ead9e8c8a54ef51cae13eeb59fcb98e1b7275"},"job:refine@r01/scope": {"bytes": 354, "sha256": "81a4042ba077832530b2a9f64d3e1415da1b655b00caf1006ed51ee616a7b17b"},"job:refine@r01/system": {"bytes": 2729, "sha256": "d12d4891ce72156aa561bdfa0ed1fb20c5826412024b0be07b423949528e5df6"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3963, "sha256": "5401be1bc487921af05b2dc05e8dc7c0fb7f2ee373d2741928c54417eee99b6e"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3945, "sha256": "3257514cce63b1bfe81f07f17b98f2c063cb857f3b57f2673748499d04669273"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3731, "sha256": "355b5a5eb7617171897155fe818a3975dea97d127ae8416f1352a67bb6a84a19"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5016, "sha256": "6e97c9effd603ac4a768006e2b4c63ce29506fe163aae8c36087f3f2f62390fc"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 4998, "sha256": "9f7b8ea366993c7286b701da37dd30a159b18ecb80535d97eccaf3da7bd518a8"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 4127, "sha256": "a4c4a41eea8d4af3df6646d2aa757c01a0ab663614361e61e76e84e21f9d5378"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11662, "sha256": "88d8e8ec41fe9fc983cb78208877ac3d1c9148a4f67637ee61b6e23451a9e0dc"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -281,15 +281,15 @@"job:zones_quay_water@r00/prompt": {"bytes": 35057, "sha256": "8e18d1a7baa4f7747fabe9affb187b29ba5a39e9e2d5342ebe5027c9ec20c68c"},"job:zones_quay_water@r00/scope": {"bytes": 364, "sha256": "69a91221629a23e4f5bc8ce393294d5c6a00213156b2d2ded4783159a0f02557"},"job:zones_quay_water@r00/system": {"bytes": 7239, "sha256": "67334373ec84ee3a89a3870646aef6a41f03b9ae15678e06e800bc206e10673d"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "8b1b52e0e3fd832fda14a7913d35cef8d5bda2cb02b8aea5a2935bbc1f7d5714"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3672, "sha256": "81702556fdc47d01d2cccfa4b0421eaacfbf23fdf98427daa2117a53228a78df"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "676859b5172ea33c86195b543b5c80e49dc907598dbdddb57a9734e58df9e8a1"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "b546f93804fc3a29f245076f24cee36e64a1a7a5d45181f05eacc5bf59fc2dc0"},+ "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4672, "sha256": "acb770e39a06a487ab42061ff1914c88f598d937c75081e318edd5c67b9fded9"},"judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "35679341c294b774ac1c228d9a2bc56f4792f8831dd1c216b513e4427e6cb0c1"},"judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4686, "sha256": "5321b87318ce2cbdd7d3b6d6669d3283574a1e3034030803577f386c6e0d2d35"},+ "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4668, "sha256": "300b42e4fbb9cf1ece80cc4d186d9432075f89f0005855c2050e8c7ee74b81ea"},"judge:scene:runs/run/artifacts/renders/r02/messages": {"bytes": 5298, "sha256": "0b15d27d13b64c082c86c2e4cea5d85a7f0b3e9daef93b5cb62f698d06570437"},"judge:scene:runs/run/artifacts/renders/r02/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r02/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -347,7 +347,7 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3707, "sha256": "30b3e2a3c085d3231818fcaa188e1f93732151dd987f311121f2a5320110c27d"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3689, "sha256": "54390a4fb6ee710da77617182f21e2e8033cac13151d9ca4181b71363cc34bca"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "676859b5172ea33c86195b543b5c80e49dc907598dbdddb57a9734e58df9e8a1"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -411,15 +411,15 @@"job:zones_quay_water@r00/prompt": {"bytes": 42361, "sha256": "ba7f066f892074d3b6230f7380a1a3492167ab8c24a045e3ee38f0acab6a420a"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "5e7031f1c8d724681399e545e6adf0af8e6a8da6cae4364c7220a15b41f0744b"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3672, "sha256": "72ae732ea58daccf1d6161a994a9cc3154f968ba9ee78967af117fb25222c020"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "ea728103072ad97014d8af107bb40109b9aef55ab30f817a017e3542b091682a"},+ "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4672, "sha256": "28634c817ed85af90e41fd4cefce4be5df04db7ac259b86c75517a78ccbacc67"},"judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "c9a488e3385bb803ce084eda9a1ad2ed58c338201f1ad6d7f416cf0070f1a9f1"},"judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4686, "sha256": "905a0f9912bb1052573d52017e5f838a18d429827cbcd52be7e6a7f6f40842f0"},+ "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4668, "sha256": "1a5cfd39d1ca345300797f90c137f5d596eaf990a315474de03a2885e0a627cb"},"judge:scene:runs/run/artifacts/renders/r02/messages": {"bytes": 5298, "sha256": "d8e7af12d299bcc4d09f7b68a6cdf3de2816e89d0d785ff88153c9e3aa5ce8cd"},"judge:scene:runs/run/artifacts/renders/r02/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r02/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -485,15 +485,15 @@"job:zones_quay_water@r00/prompt": {"bytes": 42541, "sha256": "986c0f46f90e4f652c336741d6925c1bf7f7b2d83dbe5977ba8a9856dfa4c576"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/input": {"bytes": 3759, "sha256": "d3507d23f5a84d828cef7b6b6f9b2c5df3795a2c300ee7aaeb038af59267fc30"},+ "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/input": {"bytes": 3741, "sha256": "7185b51a841c678f200aa9fc6a1bf6b26cb8be47b3c42962664da3a299e7e90d"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/messages": {"bytes": 3099, "sha256": "eee511c765a105054417cb3fa37bf67c24bcf9022da44dc086385878a61d5f67"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/sampling": {"bytes": 8358, "sha256": "d816200df3d61ed4afb3251779d3981fe0bdf6ef70db86cbba3dd76dcc28edf6"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/system": {"bytes": 8834, "sha256": "8b52aa8a0e80ff6ba98f494c36013745f5dd07a4e1040d72ff7f55aeeb907ba5"},- "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/input": {"bytes": 3779, "sha256": "91ec992fade8a7c1907c0888c2a65715a0ab1ec40ed8d2cd1037a976cf6e82e8"},+ "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/input": {"bytes": 3761, "sha256": "439e3fbc5718c1b3fe3d7e1591d5af19bb2d20a8e513873bfcba50956d64a467"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/messages": {"bytes": 3099, "sha256": "eee511c765a105054417cb3fa37bf67c24bcf9022da44dc086385878a61d5f67"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/sampling": {"bytes": 8358, "sha256": "d816200df3d61ed4afb3251779d3981fe0bdf6ef70db86cbba3dd76dcc28edf6"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/system": {"bytes": 8834, "sha256": "8b52aa8a0e80ff6ba98f494c36013745f5dd07a4e1040d72ff7f55aeeb907ba5"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3697, "sha256": "dab5e24ca050491a18ba9f81e894fb7f1103e9d3a16bf93c708ac7fd6ab54944"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3679, "sha256": "34ce59a8de89ad32fe921283158ef0d995e93ac41051f7fcb2679723843cd382"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4937, "sha256": "407f918497c4e96ed25d4a9c5c968993644c2a43fadfcc1bc6a0c4f7e6a9d99f"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -529,7 +529,7 @@"job:zones_quay_water@r00/prompt": {"bytes": 41688, "sha256": "752f5e1a1ee0e088ac14df293d7d28d56a29c6d8249f3a2a13f1d1e2249964df"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "ebaaf972b6033176defee1013c1eb8b83843caef8172efe2dba99ccfb339a33f"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3672, "sha256": "b40bb6aefe2d2bd6f97b89ad77bdc28a712c78f8d5624089b7debb54c2740499"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -603,62 +603,6 @@"runs/run:zones": "0526c0ee5233"}},- "scene.scene_threejs.agent.variant_argon": {- "payloads": {- "chat:model:asset_bollard:r00/messages": {"bytes": 3327, "sha256": "1a2c11617634f2944f0e66819a64d644a0180612213856e98575191a481f2a5b"},- "chat:model:asset_bollard:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},- "chat:model:asset_bollard:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},- "chat:model:asset_fishing_boat:r00/messages": {"bytes": 3365, "sha256": "583f9c5888c4ff1567e3cbb2d9e3e8701e31169fd30f295d89dae16e046e55cc"},- "chat:model:asset_fishing_boat:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},- "chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},- "chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},- "chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26641, "sha256": "97cc784b73ca9dfb4f46cc62c0db7c73d9cb6085db85b7feba1895d98e0fa6f6"},- "chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},- "chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},- "chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "chat:planner:zone-layout#1/messages": {"bytes": 401, "sha256": "73206223434695497c74e5f8f5bc0a0f1b147a7dc38147645c6cf42b5372484b"},- "chat:planner:zone-layout#1/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},- "chat:planner:zone-layout#1/system": {"bytes": 3391, "sha256": "fa6d28546a947ddc6ab8d0adb8af97a1605873109a47cf7f097f72d9788fd678"},- "chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},- "chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},- "chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "context:runs/run/files": {"bytes": 55626, "sha256": "210ef1318159cf47ac914cf0013d623c34ee57bc7723ca301da1e1a3881b5b86"},- "job:env@r00/prompt": {"bytes": 36302, "sha256": "f12e0b146910ce6a10b44229fb8b080fc72943831b04231f0522f6fdfb3892b2"},- "job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},- "job:env@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "job:refine_quay@r01/prompt": {"bytes": 10042, "sha256": "1eefaead62e4787c4560d4411a977b090d9471c643a56ade7130591f15c57af1"},- "job:refine_quay@r01/scope": {"bytes": 352, "sha256": "95a620093126d95e34400b4879d58c03bb641810cf02cc497835c80890c54a01"},- "job:refine_quay@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "job:refine_water@r01/prompt": {"bytes": 10047, "sha256": "2ffb0fea225d7eb12d212d915509b18ad0db399e348e3591e8bd4645161fca7a"},- "job:refine_water@r01/scope": {"bytes": 354, "sha256": "5c7aa29b996f768b637082248e69fbe65f7ed49d9f5abff27c464da564365b74"},- "job:refine_water@r01/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "job:zones_quay_water@r00/prompt": {"bytes": 42361, "sha256": "ba7f066f892074d3b6230f7380a1a3492167ab8c24a045e3ee38f0acab6a420a"},- "job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},- "job:zones_quay_water@r00/system": {"bytes": 5625, "sha256": "3e4c806c832c2fb4ab9dd3b1d5063c611b07258ce2fa6d9b3f25df5a467734c7"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "5e7031f1c8d724681399e545e6adf0af8e6a8da6cae4364c7220a15b41f0744b"},- "judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},- "judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},- "judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "ea728103072ad97014d8af107bb40109b9aef55ab30f817a017e3542b091682a"},- "judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "c9a488e3385bb803ce084eda9a1ad2ed58c338201f1ad6d7f416cf0070f1a9f1"},- "judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},- "judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "skills:runs/run:baseline@r00/routed": {"bytes": 156, "sha256": "cae5ab46c39f9f4efb7ae3c4758b05d768025f93d525d5e13812b916a583fd30"},- "skills:runs/run:env@r00/routed": {"bytes": 164, "sha256": "eb0e2aca5a76b26e49a2d2c862a9405ef2e3e1130e719cca9a1f23fe1b264402"},- "skills:runs/run:refine@r01/routed": {"bytes": 156, "sha256": "cae5ab46c39f9f4efb7ae3c4758b05d768025f93d525d5e13812b916a583fd30"},- "skills:runs/run:zone@r00/routed": {"bytes": 161, "sha256": "c2efc99419ed923cc9093c675fa27abc39d11613b9d2ac59e2cc5aea67d7d191"}- },- "stage_keys": {- "runs/run:assemble": "eb288074ac5b",- "runs/run:assets": "e3fcf2d29017",- "runs/run:env": "e3fcf2d29017",- "runs/run:layouts": "e3fcf2d29017",- "runs/run:plan": "23a48aef8e1b",- "runs/run:skeleton": "6bd35d0cf375",- "runs/run:zones": "0526c0ee5233"- }- },"scene.scene_threejs.single_shot.fresh": {"payloads": {"chat:model:asset_bollard:r00#0/messages": {"bytes": 3327, "sha256": "1a2c11617634f2944f0e66819a64d644a0180612213856e98575191a481f2a5b"},@@ -697,7 +641,7 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3707, "sha256": "8f701fd0fdbfc05436f36752f885dce6996d23adc4ecca76a446ebfb676fff5f"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3689, "sha256": "c4ead7a71aa9b80215f27957818255c47af9201854ead9274d4ac469ff532769"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14069, "sha256": "9f5073025f0011d617d13bbde6605bf7358111b7700df92c41c23035482f789b"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -736,19 +680,19 @@"job:refine@r01/prompt": {"bytes": 7038, "sha256": "7567826ea7793e5f05f355c236b5984aa89abde8942f86b2a9e8a2e1881096c6"},"job:refine@r01/scope": {"bytes": 426, "sha256": "3a39df2f37665e52ae78549431ea567fa9591605332e152cd7d41d2b58914893"},"job:refine@r01/system": {"bytes": 2865, "sha256": "e8bdde0b2251c9f422c9a02c8c457543798280f5215e740312ffb73f1d0d867f"},- "judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/input": {"bytes": 5480, "sha256": "d0f5d8618797710a5a8672d0e150fe844e47964c684f564870815881b8fccd22"},+ "judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/input": {"bytes": 5462, "sha256": "a21a757770535dd1d068af2978177506fddcb8482fdbb53cd9c251983ed4dc63"},"judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/messages": {"bytes": 4246, "sha256": "029c3c03fe1f78f6f0d8b6b1b6bb4825d2851b55595a3c15c1a03f052b0b9771"},"judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/input": {"bytes": 5480, "sha256": "634a91a0f2eb65344528e8d83e744d8eba81d77d1b8697885a023f546199bef5"},+ "judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/input": {"bytes": 5462, "sha256": "d71335a62809d8613408bbaa6f10096ecae5d92abc5e7f6075580786ca443acb"},"judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/messages": {"bytes": 4246, "sha256": "029c3c03fe1f78f6f0d8b6b1b6bb4825d2851b55595a3c15c1a03f052b0b9771"},"judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9043, "sha256": "dbaaabdbe8a66ecafe6caaf78c9d263dea54caa61f73b1c2a58356ac4eb232e8"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9025, "sha256": "2276889cf2682a61020f6b614f3b91e0ac4ad0bcc584f97a9907e0a6c93ead45"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6699, "sha256": "7df542d34f969f456ab2fcd720b5ccf3a4547b1c57ed59a81df0a84a4d540b9a"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10256, "sha256": "039d3ffebaf48a6e6adb10eeb65db4d8be1c1902af599781104b174ea82108f8"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10238, "sha256": "a8d1e6e95f76b7a3077f9cd96b1a463916c3655999426819cfc94396abec29aa"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7124, "sha256": "a800f572433fa02006cc5a02c883359497949586963a0edeb799e047048d8f2c"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -786,11 +730,11 @@"job:refine@r02/prompt": {"bytes": 7215, "sha256": "7d084dc936a0ca89af24a348321c9a88fd523c8353a034fe3bb37df511bcfe8e"},"job:refine@r02/scope": {"bytes": 350, "sha256": "4e7e7adc88c67e32725d4fbf7d2f95b24d0166d57881f69cf543ab1c6936ea35"},"job:refine@r02/system": {"bytes": 2205, "sha256": "2ca6cc8997115b5940dcef874355b65c82f25ee8000b964fe0ad96dce25ac0e8"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 9448, "sha256": "57f45cc8b04164a946635a087e7a5d925c8da6ba463e595f7f9723a3c8c49b4b"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 9430, "sha256": "c9a5a760b2906d5b2ab1c50e9f348f7c32436f053069b7178db63a4bf63ccf41"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 6808, "sha256": "afe220b9286ff63c1e78b62cf853ead93c525947a873c6eaea80d9094a9d483e"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10657, "sha256": "c43068c990f633b1a5cfe0136b3c6255f37d49b4724aadc45bcafe17f5280b36"},+ "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10639, "sha256": "bc7b2069ffea9329e19a0cb91c07a0b54212928319b2580efc93362c837c8025"},"judge:static_object:runs/run/artifacts/renders/r02/messages": {"bytes": 7233, "sha256": "d6a82300f22e09f4cc9f7d5a09ec89e5c6e9b300eab6b8899fc61648ac406c21"},"judge:static_object:runs/run/artifacts/renders/r02/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r02/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -821,15 +765,15 @@"job:refine@r02/prompt": {"bytes": 7174, "sha256": "3474b8ace6d7212c7430b362f161485f9243cdc6ef3118dc5d342c8720b85de5"},"job:refine@r02/scope": {"bytes": 428, "sha256": "57e2f2633c63ce908a2842199385fe002439dcc7d6f68ffac0261d5be22cb8e1"},"job:refine@r02/system": {"bytes": 3208, "sha256": "e24e99f321231e5587cae7f4fbbbcc50fbd254768f4f4c860c4dfa8f83804810"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9242, "sha256": "24388c1c7e23be39af16276200ef38c874d6bd7a6f5efc2e8af4a639ac9ccaa9"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9224, "sha256": "fdb6ec2554e63b152539af50d322b5778b6285adeb9ee00450d667029bfc1221"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6756, "sha256": "447c252713a4d26c70c0b368c30217605f33543c3a329b6c32bee7099bdb1860"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10455, "sha256": "3b59af59898d972cffb2178b608d9ffba14af4b76f5eb7b96993e3536cb8b29e"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10437, "sha256": "4734189530815ca3a8aeb43c59e474da530a6418e16e3d275cb57e073817eeb6"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7181, "sha256": "0ee41f64bf25c8490c05f3478f11afde83f2d8fc7f4753553d7497f1ef83543a"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10451, "sha256": "e47aeb8f1cb8ad461a97940370c9fdd54d95a077c9a84df047a51167c66a5f64"},+ "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10433, "sha256": "002cf9a4d55774f5573eee573f2d4e2445fd033b5c51ef13b6d68da00684b006"},"judge:static_object:runs/run/artifacts/renders/r02/messages": {"bytes": 7181, "sha256": "61b52dd59cc941e842e0e789faf595cd9ed24187eba10e7cc399e1ca792eb099"},"judge:static_object:runs/run/artifacts/renders/r02/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r02/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -857,11 +801,11 @@"job:refine@r01/prompt": {"bytes": 8861, "sha256": "40ce1992b720f3a98f57dedeab35b70590f3f9a49ef111a544a300896fa39a35"},"job:refine@r01/scope": {"bytes": 644, "sha256": "f5e0c8fc1e3c0527734f358ad11929cedc505d872e61bbbfa4926d2cf5f4a1d0"},"job:refine@r01/system": {"bytes": 3208, "sha256": "e24e99f321231e5587cae7f4fbbbcc50fbd254768f4f4c860c4dfa8f83804810"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 11147, "sha256": "cea087f4cc7335c78c7dbe31cd08285d097c7627cb53151853c3d882639b6f8b"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 11129, "sha256": "9fbe7bb7c1d664a4c563585c2dcb8873356ed0292bc2be3a87f09bd36ce29f16"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 7002, "sha256": "90d9f0c3e869c20608b23834b3a93df8242b1dd3324fdfda3b91de9542337eb0"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11137, "sha256": "3b6a70558e21e796673b65818721913f7720c6ee7e31dd35225cb4ca1bdcf20e"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 12332, "sha256": "6879d4d19d95bb191dba70f85960b7fc5a2b385d850cdbc7b5f57a0f86a2e6e3"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 12314, "sha256": "0e543d60800d9639a63a442b7bd2b64e30c7983e3c04c6edc91a42305edad365"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7429, "sha256": "70fca81684fcce477eadc3e0d5c329b3dcc31dcc527958abf29e484a0d555a7c"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11137, "sha256": "3b6a70558e21e796673b65818721913f7720c6ee7e31dd35225cb4ca1bdcf20e"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -888,11 +832,11 @@"job:refine@r01/prompt": {"bytes": 7012, "sha256": "9db3905eac671203349cd349d93748e1abadf89a9f584948cf3e64f0527abbcd"},"job:refine@r01/scope": {"bytes": 428, "sha256": "186e31cec33c5144bbc9713eb76374ef7608534682433c9a9288191efc417ec4"},"job:refine@r01/system": {"bytes": 3208, "sha256": "e24e99f321231e5587cae7f4fbbbcc50fbd254768f4f4c860c4dfa8f83804810"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9043, "sha256": "e6f38103435ee5364a2bf61e2caedd75d4f4a7cf77c7d03d38d202bd8f73c1fa"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9025, "sha256": "12e05e5120953aafac4881840ec24c8ef68e01581959d2a89dc7af001e480314"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6699, "sha256": "6e3964ce3478de892b3c5dde9eb3154e9a54c2a669315a8e6f4b808c15dd930c"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10256, "sha256": "211aff02135e7034dd64d7c3c0a812acfad49abb4b87b6a441ddbb355d9e9117"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10238, "sha256": "836f3063574dbf9925df7a140546078df064c176376e6734ee54db056a2ed018"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7124, "sha256": "0e3a5d3ed25799eec213d2d7fd92ae5009e4d88d5a818eeaf0aef3de8d47b932"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -921,11 +865,11 @@"chat:planner:planner/messages": {"bytes": 1354, "sha256": "5b1a589e27562a3668649aed4be4857a34804a2acdc140eb8fb3630d970f71a6"},"chat:planner:planner/sampling": {"bytes": 6272, "sha256": "04dbfbbd42d8b93a12571a1908beacc7eb471e6f2c0fc077371aa86e2a99fb40"},"chat:planner:planner/system": {"bytes": 18287, "sha256": "0e78778a5c81b420699c7148ee039722877c818cea9844f793d543fccc8ef97b"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9060, "sha256": "9db5de7f375d60e4e56f9677affd8c4fbe4261f62d0111d1c021f08dcd5690bf"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9042, "sha256": "5b6d5fadc28c4a3641aeb7635af8f3f945b7e13c5e595a982448c760c33ffb44"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6699, "sha256": "6e3964ce3478de892b3c5dde9eb3154e9a54c2a669315a8e6f4b808c15dd930c"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10273, "sha256": "97bda1184c1cd78145113857ec2e8917f6f51bd969f028f9dac064b1ee9dd0bb"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10255, "sha256": "5c0949fdf11eae6956d53afff7238fc4b53e9e14b9da30be7f2bb3e7b329e6a8"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7124, "sha256": "0e3a5d3ed25799eec213d2d7fd92ae5009e4d88d5a818eeaf0aef3de8d47b932"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11371, "sha256": "275368055f7250512e426b330f9720fcfbdad1d1ea1a739102ab9f3521a3fb25"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.pyindex c325e873..de04ad08 100644--- a/harness/tests/prompts/manifest.py+++ b/harness/tests/prompts/manifest.py@@ -401,9 +401,6 @@ SCENARIOS: dict[str, tuple[Track, Language, dict[str, Any], Callable[[Rig], None"scene.scene_threejs.agent.fresh": (SC, Language.SCENE_THREEJS, {"plan": small_scene(), "broken_assets": frozenset({"Bollard"})},_two_runs(1, 2)),"scene.scene_threejs.agent.no_layouts": (SC, Language.SCENE_THREEJS, {"plan": small_scene()}, _switched("C3D_ZONE_LAYOUTS", "off", 0)),- # the argon variant (D105) ships EMPTY overlays: every payload equals the fresh scene's, only the- # plan stage key carries the variant name — iteration 0 of the loop measures exactly this- "scene.scene_threejs.agent.variant_argon": (SC, Language.SCENE_THREEJS, {"plan": small_scene()}, _switched("C3D_VARIANT", "argon", 1)),"scene.scene_threejs.agent.hero": (SC, Language.SCENE_THREEJS, {"scores": (0.6, 0.7)}, lambda r: r.run(rounds=0)),# the zones never build again: repairs and the rebuild own scene.js/env.js, not the zone files"scene.scene_threejs.agent.rebuild": (SC, Language.SCENE_THREEJS, {"plan": small_scene(), "fail": frozenset({"zones_quay_water"})},diff --git a/harness/tests/prompts/test_variants.py b/harness/tests/prompts/test_variants.pydeleted file mode 100644index 8a0121a3..00000000--- a/harness/tests/prompts/test_variants.py+++ /dev/null@@ -1,100 +0,0 @@-"""The variant layer (D105): selection, the prompt overlay, caches, activation, the record."""--from __future__ import annotations--import shutil-from pathlib import Path--import pytest-from jinja2 import TemplateNotFound--from codeverse3d import prompts-from codeverse3d.config import Settings, get_settings-from codeverse3d.contracts.common import Language-from codeverse3d.prompts import variants as V-from codeverse3d.prompts.variants import (- VARIANTS_DIR,- activate,- resolve_variant,- variant_info,-)-from tests.prompts.conftest import PROMPTS_DIR--TV_TOML = ('[variant]\nname = "tv"\nversion = 3\ngenerators = ["agy:gemini-4-argon"]\n'- 'description = "a test variant"\n')--def _clear() -> None:- prompts._load.cache_clear()- prompts._env_for.cache_clear()- get_settings.cache_clear()-[email protected](autouse=True)-def _no_process_variant(monkeypatch):- """No variant from this machine's environment, and no cached overlay from another test."""- monkeypatch.delenv("C3D_VARIANT", raising=False)- monkeypatch.delenv("C3D_VARIANTS", raising=False)- _clear()- yield- _clear()--def overlay(tmp_path: Path, monkeypatch) -> Path:- """A tmp ``VARIANTS_DIR`` holding ``tv``: a system.md that shadows blender's, a template only the- variant ships, and a role template that includes a BASE file (the ChoiceLoader fall-through)."""- root = tmp_path / "variants"- shutil.copytree(VARIANTS_DIR / "argon", root / "argon") # the shipped one stays known beside tv- tv = root / "tv"- for d in ("blender", "tracks", "system"):- (tv / d).mkdir(parents=True)- (tv / "variant.toml").write_text(TV_TOML)- (tv / "README.md").write_text("docs only\n")- (tv / "blender" / "system.md").write_text("# OVERLAY SYSTEM\n")- (tv / "tracks" / "only_in_variant.j2").write_text("overlay {{ x }}\n")- (tv / "system" / "role_repair.j2").write_text("OVERLAY ROLE {{ contract }}\n{% include 'system/singleshot_format.md' %}")- monkeypatch.setattr(V, "VARIANTS_DIR", root)- _clear()- return root--# --------------------------------------------------------------------------- selection-def test_resolution_order_including_the_served_model_lookup(overlay):- """settings.variant > variants[id as typed] > variants['<kind>:<served model>'] > base; plain lookups."""- table = {"agy:gemini-4-argon": "tv", "agy:gemini-4-argon-low": "argon", "claude-code:claude-opus-5": "tv"}- assert resolve_variant(Settings(variant="argon", variants=table), "agy:gemini-4-argon") == "argon"- assert resolve_variant(Settings(variants=table), "agy:gemini-4-argon-low") == "argon", "the id as typed wins"- assert resolve_variant(Settings(variants=table), "agy:gemini-4-argon-high") == "tv", "then the served model"- assert resolve_variant(Settings(variants=table), "agy:gemini-4-argon") == "tv"- assert resolve_variant(Settings(variants=table), "single-shot:gemini:gemini-4-argon") == "", "no served spelling"- assert resolve_variant(Settings(variant=" tv "), "x") == "tv"- assert V.served_id("agy:gemini-4-argon-medium") == "agy:gemini-4-argon" and V.served_id("nocolon") == ""--def test_variant_toml_is_type_checked(overlay):- (overlay / "tv" / "variant.toml").write_text('[variant\nname = "tv"\n')- with pytest.raises(ValueError, match="not valid TOML"):- variant_info("tv")--# --------------------------------------------------------------------------- the prompt overlay-def test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):- base_system = (PROMPTS_DIR / "blender" / "system.md").read_text()- base_contract = (PROMPTS_DIR / "blender" / "contract.md").read_text()- with activate("tv"):- assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\n"- assert prompts.load_text("blender/contract.md") == base_contract, "no overlay copy: the base file"- assert prompts.render("tracks/only_in_variant.j2", x=1) == "overlay 1\n"- rendered = prompts.render("system/role_repair.j2", contract="C")- assert rendered.startswith("OVERLAY ROLE C\n")- assert (PROMPTS_DIR / "system" / "singleshot_format.md").read_text().strip() in rendered, "a base include"- # the catalog resolves through the same loader: callers do not change- from codeverse3d.prompts.catalog import language_text-- assert language_text(Language.BLENDER, "system.md") == "# OVERLAY SYSTEM\n"- assert language_text(Language.BLENDER, "contract.md") == base_contract- with pytest.raises(FileNotFoundError):- prompts.load_text("blender/nowhere.md")- assert prompts.load_text("blender/system.md") == base_system- with pytest.raises(TemplateNotFound):- prompts.render("tracks/only_in_variant.j2", x=1)--# --------------------------------------------------------------------------- provenance--# --------------------------------------------------------------------------- the run-diff --git a/harness/tests/skills/test_telemetry.py b/harness/tests/skills/test_telemetry.pyindex 4bfc7013..85700d3e 100644--- a/harness/tests/skills/test_telemetry.py+++ b/harness/tests/skills/test_telemetry.py@@ -30,8 +30,7 @@ def _plan(n=3):def _attach(ws, library, **kw):return attach_skills(ws, track="static_object", language="blender", kind="baseline",- plan=_plan(), library=library,- max_skills=5, allow_unverified=False, **kw)+ plan=_plan(), library=library, **kw)def _touch_read(path: Path) -> None:"""Simulate a reader on a filesystem whose atime we cannot rely on in a test."""diff --git a/harness/tests/skills/test_variants.py b/harness/tests/skills/test_variants.pydeleted file mode 100644index 4e949476..00000000--- a/harness/tests/skills/test_variants.py+++ /dev/null@@ -1,243 +0,0 @@-"""The skills half of a variant (D105): overlay bundles, the typed routes.toml, boosts, disabled-rules, extra rows, the claims lookup and what attach_skills stamps."""--from __future__ import annotations--import logging-from pathlib import Path-from types import SimpleNamespace as NS--import pytest--from codeverse3d.config import get_settings-from codeverse3d.prompts import variants as V-from codeverse3d.prompts.variants import activate-from codeverse3d.skills import (- all_skills,- bundle_dirs,- library_roots,- load_skill,- parse_routes,- variant_dir,- variants_table,-)-from codeverse3d.skills.registry import (- GATE_FIRED_PRIORITY,- ROUTED_SKILLS,- ROUTES,- effective_priority,- select,-)-from tests.skills.conftest import write_bundle--ROUTES_TOML = """-[[boost]]-skill = "c3d-repeats-and-mirrors"-delta = 20--[[disable]]-rule = "R3"--[[route]]-rule = "V1"-skill = "c3d-new-sheet"-priority = 80-tracks = ["static_object"]-kinds = ["baseline"]-why = "a test row"-"""--def _plan(n: int = 3, instances: int = 1):- return NS(parts=[NS(name=f"P{i}", instances=instances, symmetry="none", children=[]) for i in range(n)], summary="")--def variant(tmp_path: Path, monkeypatch) -> Path:- """A tmp library (every routed bundle, measured) with the overlay ``variants/tv/``: a shadowing- ``c3d-part-contact``, a new ``c3d-new-sheet``, its own ``_claims`` and ``routes.toml``; plus the prompts- half (``variant.toml``) so ``activate("tv")`` is legal."""- lib = tmp_path / "lib"- for name in ROUTED_SKILLS:- write_bundle(lib, name)- overlay = lib / "variants" / "tv"- write_bundle(overlay, "c3d-part-contact", body="OVERLAY RULES: seat every part.")- write_bundle(overlay, "c3d-new-sheet", description="A sheet only the variant ships. Use it when routed.")- (overlay / "_claims").mkdir()- (overlay / "_claims" / "c3d-part-contact.toml").write_text("claim = []\n")- (overlay / "routes.toml").write_text(ROUTES_TOML)- (overlay / "README.md").write_text("docs\n")- (lib / "_claims").mkdir()- (lib / "_claims" / "c3d-bbox-contract.toml").write_text("claim = []\n")- monkeypatch.setenv("C3D_SKILLS_DIR", str(lib))- monkeypatch.delenv("C3D_VARIANT", raising=False)- monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)- monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)- prompts_root = tmp_path / "prompt_variants"- (prompts_root / "tv").mkdir(parents=True)- (prompts_root / "tv" / "variant.toml").write_text('[variant]\nname = "tv"\nversion = 1\n')- monkeypatch.setattr(V, "VARIANTS_DIR", prompts_root)- get_settings.cache_clear()- yield lib- get_settings.cache_clear()--# --------------------------------------------------------------------------- the overlay library-def test_an_overlay_bundle_shadows_the_base_and_a_new_name_is_added(variant):- assert library_roots() == [variant]- assert "OVERLAY" not in all_skills()["c3d-part-contact"].body and "c3d-new-sheet" not in all_skills()- with activate("tv"):- assert library_roots() == [variant, variant_dir("tv")]- lib = all_skills()- assert "OVERLAY RULES: seat every part." in lib["c3d-part-contact"].body- assert lib["c3d-part-contact"].dir == variant_dir("tv") / "c3d-part-contact"- assert lib["c3d-new-sheet"].dir.parent == variant_dir("tv")- assert set(lib) == set(ROUTED_SKILLS) | {"c3d-new-sheet"}- assert "OVERLAY RULES: seat every part." in load_skill("c3d-part-contact").body- assert load_skill("c3d-bbox-contract").dir.parent == variant, "a bundle the overlay lacks: the base"- assert all_skills(variant)["c3d-part-contact"].dir.parent == variant, "an explicit root is that root alone"- assert library_roots("tv") == [variant, variant_dir("tv")] and library_roots("none") == [variant]- assert [d.name for d in bundle_dirs()] == sorted(ROUTED_SKILLS), "variants/ has no SKILL.md: never listed"- assert "OVERLAY" not in load_skill("c3d-part-contact").body--# --------------------------------------------------------------------------- the router-def test_boosts_move_the_ranking_but_never_cross_the_gate_fired_floor(library, caplog):- r3 = next(r for r in ROUTES if r.rule == "R3") # standing, 65- r4 = next(r for r in ROUTES if r.rule == "R4") # gate-fired, 95- assert effective_priority(r3, {}) == 65 and effective_priority(r3, {"c3d-bbox-contract": 10}) == 75- with caplog.at_level(logging.WARNING, logger="codeverse3d.skills.registry"):- assert effective_priority(r3, {"c3d-bbox-contract": 40}) == GATE_FIRED_PRIORITY - 1- assert "clamped" in caplog.text and "R3" in caplog.text- assert effective_priority(r4, {"c3d-bbox-contract": -40}) == GATE_FIRED_PRIORITY- assert effective_priority(r4, {"c3d-bbox-contract": 3}) == 98- assert effective_priority(r3, {"c3d-bbox-contract": -80}) == 0- plan = _plan(instances=2) # R1 part-contact 70, R3 bbox 65, R6 repeats 55, R8 blender-forms 75- from codeverse3d.skills.registry import plan_signals-- base = [s.name for s in select("static_object", "blender", "baseline", signals=plan_signals(plan), library=library)]- assert base == ["c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract", "c3d-repeats-and-mirrors"]- got = select("static_object", "blender", "baseline", signals=plan_signals(plan), library=library,- boosts={"c3d-repeats-and-mirrors": 20})- # 55 + 20 = 75 ties R8's 75, and R6 sits before R8 in the table: the tie keeps the table order- assert [s.name for s in got] == ["c3d-repeats-and-mirrors", "c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract"]- boosted = got[0]- assert boosted.priority == 75 and not boosted.gate_fired and "(variant boost +20)" in boosted.reason- # a boost big enough to reach 90 is clamped: a standing row never reads as gate-fired in telemetry- got = select("static_object", "blender", "baseline", signals=plan_signals(plan), library=library,- boosts={"c3d-repeats-and-mirrors": 60})- assert got[0].name == "c3d-repeats-and-mirrors" and got[0].priority == 89 and not got[0].gate_fired--# --------------------------------------------------------------------------- routes.toml--def _write(lib: Path, text: str) -> Path:- p = lib / "variants" / "tv" / "routes.toml"- p.write_text(text)- return p-[email protected]("text, problem", [- ('[[route]]\nrule = "V1"\nskill = "x"\npriority = "high"\n', r"\[\[route\]\] #0: priority must be an integer"),- ('[[route]]\nrule = "R1"\nskill = "x"\npriority = 70\n', "rule id 'R1' is already taken"),- ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 95\n', "standing row .* must stay below 90"),- ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 50\nfindings = ["lint/*"]\n', "gate-fired row .* needs priority >= 90"),- ('[[boost]]\nskill = "x"\ndelta = 1.5\n', r"\[\[boost\]\] #0: delta must be an integer"),- ('[[boost]\nskill = "x"\n', "not valid TOML"),-])-def test_routes_toml_typing_errors_are_refused(variant, text, problem):- with pytest.raises(ValueError, match=problem):- parse_routes(_write(variant, text))- with pytest.raises(ValueError, match=problem):- variants_table("tv")--# --------------------------------------------------------------------------- the CLIs walk the overlays-BROKEN_SKILL = "---\nname: c3d-bbox-contract\ndescription: the closing fence is missing\n# body\n"--def _cli(*args: str, width: int = 300):- """``3dcodeverse skills ...`` through typer's runner, the CLI console wide enough for one table row per- line: an xdist worker runs under ``COLUMNS=80``, which rich pins on the console when it is built, so- the width is set on the console itself (and restored) rather than through the environment."""- from unittest import mock-- from typer.testing import CliRunner-- from codeverse3d.cli import _common- from codeverse3d.cli.main import app-- with mock.patch.object(_common.console, "_width", width):- return CliRunner().invoke(app, ["skills", *args])--def test_skills_validate_walks_every_shipped_overlay_and_a_broken_overlay_bundle_fails(variant):- """A loop iteration writes bundles into ``skills/variants/<v>/`` and they are routed the moment the- variant is active — so ``skills validate`` must see them, labelled by their variant, and a malformed- one must FAIL here instead of vanishing from a session with a logged warning (the row that named- it then routes nothing)."""- n = len(ROUTED_SKILLS) + 2- r = _cli("validate")- assert r.exit_code == 0, r.output- assert "ok tv/c3d-part-contact" in r.output and "ok tv/c3d-new-sheet" in r.output- assert "ok c3d-part-contact" in r.output and f"{n}/{n} bundles valid" in r.output- bad = variant_dir("tv") / "c3d-bbox-contract"- bad.mkdir()- (bad / "SKILL.md").write_text(BROKEN_SKILL)- r = _cli("validate")- assert r.exit_code == 1- assert "FAIL tv/c3d-bbox-contract" in r.output and "frontmatter" in r.output- assert "ok c3d-bbox-contract" in r.output, "the base bundle it shadows is still fine"- assert f"{n}/{n + 1} bundles valid" in r.output- (bad / "SKILL.md").unlink()- bad.rmdir()- # the overlay's table is checked too: a row that does not type-check is a FAIL named by the variant...- _write(variant, '[[route]]\nrule = "V1"\nskill = "x"\npriority = "high"\n')- r = _cli("validate")- assert r.exit_code == 1 and "FAIL tv/routes.toml" in r.output and "priority must be an integer" in r.output- # ...and a row routing a bundle nobody ships gets the base's yellow line, red under --strict- _write(variant, '[[route]]\nrule = "V1"\nskill = "c3d-nowhere"\npriority = 70\n')- r = _cli("validate")- assert r.exit_code == 0 and "tv/routes.toml" in r.output and "V1 -> c3d-nowhere" in r.output- assert _cli("validate", "--strict").exit_code == 1--# --------------------------------------------------------------------------- attach_skills + the hook-def ws(tmp_path: Path) -> Path:- root = tmp_path / "ws"- root.mkdir()- (root / "AGENTS.md").write_text("# body\n")- return root--def test_attach_skills_routes_through_the_variant_table_and_stamps_the_variant(variant, ws):- from codeverse3d.skills.materialize import attach_skills-- kw = {"track": "static_object", "language": "blender", "kind": "baseline", "plan": _plan(instances=2)}- base = attach_skills(ws, **kw)- assert base.variant == "" and base.listed == ["c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract",- "c3d-repeats-and-mirrors"]- with activate("tv"):- got = attach_skills(ws, **kw)- # V1 at 80 leads; the boosted R6 (55+20) ties R8 at 75 and keeps the base order; R3 is disabled- assert got.variant == "tv"- assert got.listed == ["c3d-new-sheet", "c3d-repeats-and-mirrors", "c3d-blender-forms", "c3d-part-contact"]- assert "(variant boost +20)" in got.reasons["c3d-repeats-and-mirrors"] and got.reasons["c3d-new-sheet"].startswith("V1:")- contact = next(s for s in got.selections if s.name == "c3d-part-contact")- assert "OVERLAY RULES" in contact.skill.body, "the overlay bundle, not the base one"- assert "OVERLAY RULES" in (ws / ".agents" / "skills" / "c3d-part-contact" / "SKILL.md").read_text()- assert (ws / ".claude" / "skills" / "c3d-new-sheet" / "SKILL.md").is_file()--class _Events(list):- def emit(self, name, **kw):- self.append((name, kw))--def test_the_hook_carries_the_variant_into_the_event_and_the_telemetry_row(variant, ws, monkeypatch):- from codeverse3d.proc import read_jsonl_lenient- from codeverse3d.tracks import skills_hook as H-- monkeypatch.setenv("C3D_SKILLS", "on")- hashes: dict[str, str] = {}- ctx = NS(ws=NS(root=ws), spec=NS(track=NS(value="static_object")), language=NS(value="blender"),- agent_id="agy:gemini-4-argon", agent_kind="agy", plan=_plan(instances=2), single_shot=False, extra={},- events=_Events(), prompt_hashes=hashes, record_prompt=lambda name, text: hashes.__setitem__(name, text))- with activate("tv"):- got = H.attach_for_round(ctx, index=0, kind="baseline")- assert got is not None and got.variant == "tv"- usage = H.record_usage(ctx, index=0, kind="baseline")- assert usage is not None- attached = next(kw for name, kw in ctx.events if name == "skills.attached")- assert attached["variant"] == "tv" and attached["skills"] == got.listed- assert "OVERLAY RULES" in hashes["skill:c3d-part-contact"], "the body a session saw is what is hashed"- (row,) = read_jsonl_lenient(ws / "telemetry" / "skills.jsonl")- assert row["variant"] == "tv" and row["agent"] == "agy:gemini-4-argon" and row["listed"] == got.listed