Skip to content

Official Codebase of 3DCodeVerse

Python

eval loop: every track loops, not only the scene (owner: "其他的也都可以用gemini 4 argon看看好好loop一下")

gaoypengee717c55b28e
diff --git a/eval/bench/_loop_diag.py b/eval/bench/_loop_diag.py
index 0695ea87..69c151cf 100644
--- a/eval/bench/_loop_diag.py
+++ b/eval/bench/_loop_diag.py
@@ -6,18 +6,23 @@ picked round's gates / verdict / skills, and the deliverable's source — and th
battery of them:
* :func:`diagnose_dir` — the numbers and a RECOMMENDATIONS list produced by deterministic rules
- (:data:`RULES`): a rate crosses its threshold → one named lever. No model reads the diagnosis;
- a person does, before editing the variant.
+ (: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 —
- the floating + sunken + interpenetration ERROR count per run must not rise by more than
+ 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).
+``"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
@@ -42,10 +47,17 @@ 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 Severity
+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
+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",
@@ -55,6 +67,50 @@ PLACEMENT_KINDS: tuple[str, ...] = ("scene_placement/floating", "scene_placement
#: (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_v2 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['"]""")
@@ -88,11 +144,13 @@ class RunDigest(BaseModel):
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 = ""
- @property
- def placement_errors(self) -> int:
- return sum(self.gate_errors.get(k, 0) for k in PLACEMENT_KINDS)
+ 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:
@@ -176,6 +234,7 @@ def digest_run(run_dir: Path, row: BenchItemResult | None = None) -> RunDigest:
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)
@@ -218,9 +277,9 @@ def _raw(text: str) -> dict[str, Any]:
return raw if isinstance(raw, dict) else {}
-def digests_for(out_lang: Path) -> dict[str, RunDigest]:
+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``)."""
+ each run once — ``_records.records``, the loop's ``track`` only)."""
rows: dict[str, BenchItemResult] = {}
jl = out_lang / "results.jsonl"
if jl.is_file():
@@ -228,7 +287,7 @@ def digests_for(out_lang: Path) -> dict[str, RunDigest]:
out: dict[str, RunDigest] = {}
runs_root = out_lang / "runs"
if runs_root.is_dir():
- for rec_path, data in records(runs_root, track="scene"):
+ 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`
@@ -244,13 +303,15 @@ def digests_for(out_lang: Path) -> dict[str, RunDigest]:
# --------------------------------------------------------------------------- diagnosis
@dataclass(frozen=True)
class Rule:
- """A deterministic lever: when ``metric`` crosses ``threshold`` (``above`` or below), say ``text``."""
+ """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:
@@ -261,18 +322,21 @@ class Rule:
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"),
+ "(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)"),
+ "(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)"),
+ "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),
+ "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)"),
+ "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"),
+ "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,
@@ -282,9 +346,101 @@ RULES: tuple[Rule, ...] = (
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"),
+ "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"),
+ "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,)),
)
@@ -301,6 +457,7 @@ class Diagnosis(BaseModel):
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
@@ -337,9 +494,19 @@ def _rate(hits: int, n: int) -> float | None:
return round(hits / n, 4) if n else None
-def diagnose_digests(language: str, out_dir: Path, digests: Iterable[RunDigest]) -> Diagnosis:
+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), n=len(runs), runs=runs)
+ 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]
@@ -355,7 +522,7 @@ def diagnose_digests(language: str, out_dir: Path, digests: Iterable[RunDigest])
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(set(d.caps))
+ 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()}
@@ -386,16 +553,11 @@ def diagnose_digests(language: str, out_dir: Path, digests: Iterable[RunDigest])
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, n_gated = len(evaluated), len(gated)
+ 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 = {
- "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,
+ **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),
@@ -404,14 +566,29 @@ def diagnose_digests(language: str, out_dir: Path, digests: Iterable[RunDigest])
}
diag.recommendations = [
Recommendation(rule=r.name, metric=r.metric, value=v, threshold=r.threshold, text=r.text)
- for r in RULES if (v := diag.metrics.get(r.metric)) is not None and r.fires(v)
+ 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 diagnose_dir(language: str, out_lang: Path) -> Diagnosis:
- """The diagnosis of one ``bench.run_bench`` output directory."""
- return diagnose_digests(language, out_lang, digests_for(out_lang).values())
+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:
@@ -437,8 +614,9 @@ def render_diagnosis(d: Diagnosis) -> str:
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]
- 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)"]
+ 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
@@ -461,31 +639,37 @@ class Comparison(BaseModel):
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 floating+sunken+interpenetration ERRORs per run")
+ 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) -> tuple[str, str]:
- """``(decision, reason)``: ``stats.decide`` on the paired picked scores, then the gate veto."""
+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 placement_rise is not None and placement_rise > VETO_RISE:
+ if veto is not None and placement_rise is not None and placement_rise > VETO_RISE:
decision = "revert"
- reason = (f"gate veto: floating+sunken+interpenetration ERRORs rose by {placement_rise:+.2f} per run "
+ 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]) -> Comparison:
- cmp = Comparison(language=language, name_a=name_a, name_b=name_b, paired=st,
+ 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]] = {}
@@ -498,33 +682,37 @@ def compare_digests(language: str, name_a: str, name_b: str, st: PairedStats,
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)
- rises.append(a.placement_errors - b.placement_errors)
+ 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)
+ cmp.decision, cmp.reason = loop_verdict(st, cmp.placement_rise, veto)
return cmp
-def compare_dirs(language: str, dir_a: Path, dir_b: Path) -> Comparison:
+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), digests_for(dir_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; "
- f"placement ERRORs Δ {_f(c.placement_rise, '+.2f')} per run (veto above {VETO_RISE:+.0f})", ""]
+ 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", "Δ"))
@@ -600,7 +788,7 @@ def render_calib(s: CalibSummary) -> str:
return "\n".join(lines)
-__all__ = ["PLACEMENT_KINDS", "RULES", "VETO_RISE", "CalibSummary", "Comparison", "Diagnosis", "Recommendation",
- "Rule", "RunDigest", "calib_summary", "compare_digests", "compare_dirs", "diagnose_digests",
+__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_sources.py b/eval/bench/_loop_sources.py
new file mode 100644
index 00000000..cf90d0f1
--- /dev/null
+++ b/eval/bench/_loop_sources.py
@@ -0,0 +1,182 @@
+"""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/loop.py b/eval/bench/loop.py
index bb38fdee..0d18ac4e 100644
--- a/eval/bench/loop.py
+++ b/eval/bench/loop.py
@@ -1,4 +1,4 @@
-"""The argon scene-tuning loop: generate → run → diagnose → compare → judge-calib → accept / rollback.
+"""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 \\
@@ -13,16 +13,26 @@
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 scene prompts per language, run in
+``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)
+ 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)
@@ -56,7 +66,7 @@ from pathlib import Path
from typing import Any, Literal
import yaml
-from pydantic import BaseModel, Field, field_validator
+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/)
@@ -85,6 +95,13 @@ from bench._loop_prompts import ( # noqa: E402
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
@@ -95,6 +112,7 @@ 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
@@ -134,18 +152,28 @@ class LoopConfig(BaseModel):
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 = ""
- @field_validator("languages")
- @classmethod
- def _scene_languages(cls, v: list[Language]) -> list[Language]:
- allowed = TRACK_LANGUAGES[Track.SCENE]
+ @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 scene languages {[a.value for a in allowed]}, got {bad or v}")
+ 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]}")
- return 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}"
@@ -170,6 +198,32 @@ def parse_languages(text: str) -> list[Language]:
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
@@ -356,6 +410,9 @@ def init(cfg: LoopConfig, *, paths: VariantPaths | None = None) -> Path:
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()
@@ -449,13 +506,22 @@ def _bench_prompts(battery: GeneratedBattery, lang: Language, rung: int, *, iter
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: a mix of the cached rungs up to ``rung``
- (:func:`bench._loop_prompts.mix_counts`), validated through ``Battery`` before it is written."""
+ """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)
@@ -473,10 +539,8 @@ def generate_iteration(cfg: LoopConfig, iteration: int, *, rung: int | None = No
description=f"loop {cfg.name} iteration {iteration}: {size} scene prompts, rungs "
+ ", ".join(f"{lvl}×{c}" for lvl, c in counts.items()),
prompts=prompts)
- data = battery.model_dump(mode="json")
- Battery.model_validate(data) # what the file will load as, not what we built
path = iter_dir / f"battery_{lang.value}.yaml"
- path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))
+ _write_battery(path, battery)
out[lang] = path
ids[lang.value] = [p.id for p in prompts]
write_json_atomic(iter_dir / "generate.json", {
@@ -486,6 +550,58 @@ def generate_iteration(cfg: LoopConfig, iteration: int, *, rung: int | None = No
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."""
@@ -604,11 +720,12 @@ def _present(cfg: LoopConfig, iteration: int, languages: Sequence[Language] = ()
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)
+ 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", "",
- f"variant `{cfg.variant}`, generator `{cfg.generator}`, judge `{cfg.judge}` @ {cfg.judge_thinking}", ""]
+ 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
@@ -624,7 +741,7 @@ def compare_iteration(cfg: LoopConfig, iteration: int, against: int, *,
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)
+ 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(
@@ -647,7 +764,7 @@ def judge_calib(cfg: LoopConfig, iteration: int, *, model_id: str = "", thinking
out: dict[str, CalibSummary] = {}
iter_dir = cfg.iter_dir(iteration)
for lang, d in _present(cfg, iteration, languages):
- digests = digests_for(d)
+ 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:
@@ -834,7 +951,9 @@ def status_text(cfg: LoopConfig, *, paths: VariantPaths | None = None, data_dir:
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}; languages {', '.join(x.value for x in cfg.languages)}; "
+ 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 |",
@@ -877,7 +996,12 @@ def build_parser() -> argparse.ArgumentParser:
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("--languages", default="scene_threejs,scene_blender")
+ 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"))
@@ -890,7 +1014,8 @@ def build_parser() -> argparse.ArgumentParser:
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 (a mix of cached rungs)")
+ 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)")
@@ -947,9 +1072,15 @@ def main(argv: Sequence[str] | None = None) -> int:
def _dispatch(ns: argparse.Namespace) -> int:
if ns.cmd == "init":
- cfg = LoopConfig(name=ns.name, out=ns.out.resolve(), variant=ns.variant, languages=parse_languages(ns.languages),
- 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)
+ 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)
diff --git a/eval/docs/EVAL.md b/eval/docs/EVAL.md
index c35440f6..0d250629 100644
--- a/eval/docs/EVAL.md
+++ b/eval/docs/EVAL.md
@@ -834,6 +834,77 @@ is a person's), it never compares across rungs (the pairs are by id, so a moved
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-state
diff --git a/eval/tests/test_loop.py b/eval/tests/test_loop.py
index 25c852f0..d2d3b399 100644
--- a/eval/tests/test_loop.py
+++ b/eval/tests/test_loop.py
@@ -1,4 +1,4 @@
-"""``bench/loop.py``: the argon scene-tuning loop, driven offline with fakes (no model, no child process)."""
+"""``bench/loop.py``: the argon tuning loop (scene, objects, graphics), driven offline with fakes (no model, no child process)."""
from __future__ import annotations
@@ -6,6 +6,7 @@ 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
@@ -718,3 +719,371 @@ def test_the_cli_dispatches_and_refuses_without_a_loop(tmp_path: Path, capsys, m
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 text
diff --git a/harness/codeverse3d/skills/registry.py b/harness/codeverse3d/skills/registry.py
index a9220ae8..ba0f7a2e 100644
--- a/harness/codeverse3d/skills/registry.py
+++ b/harness/codeverse3d/skills/registry.py
@@ -68,6 +68,12 @@ SCENE_PLACEMENT_SEATING: tuple[str, ...] = (
)
+def gate_family(gate: str) -> str:
+ """A gate's name as its findings' kinds carry it: every ``lint:<language>`` gate folds to ``lint``."""
+ gate = gate.strip().lower()
+ return "lint" if gate.startswith("lint") else gate
+
+
def finding_kind(finding: Any) -> str | None:
"""A ``GateFinding`` → ``"<gate>/<data.kind>"``, or ``None`` for census/INFO lines.
@@ -75,8 +81,7 @@ def finding_kind(finding: Any) -> str | None:
and routing a skill off it would attach the penetration sheet to a run with none."""
if str(getattr(finding, "severity", "warn")).lower() == "info":
return None
- gate = str(getattr(finding, "gate", "") or "").strip().lower()
- family = "lint" if gate.startswith("lint") else gate
+ family = gate_family(str(getattr(finding, "gate", "") or ""))
data = getattr(finding, "data", None)
kind = data.get("kind") if isinstance(data, dict) else None
return f"{family}/{kind if isinstance(kind, str) and kind else UNTYPED}"