Skip to content

Official Codebase of 3DCodeVerse

Python

Merge origin/main into ziyao/eval-integrity

ziyaocf3430129c7d
diff --cc .github/workflows/ci.yml
index 1b61e0c2,b90e5666..89324cb4
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@@ -30,13 -33,8 +34,9 @@@ jobs
# Node is not installed on the runner, so the node floor (20.6.0, see
# runtime_js/package.json "engines") is only checked by the version logic in
# tests/core/test_portability.py — the `node`-marked tests are deselected below.
- name: offline tests (py${{ matrix.python-version }})
+ name: offline tests (py3.13 — the one supported version)
runs-on: ubuntu-latest
+ timeout-minutes: 40
- strategy:
- fail-fast: false
- matrix:
- python-version: ["3.10", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
diff --cc .gitignore
index 14b0134d,2bd28ba2..6ffccf31
--- a/.gitignore
+++ b/.gitignore
@@@ -17,5 -17,3 +17,6 @@@ harness/logs
*.log
build/
dist/
+# in-tree virtualenv (docs/INSTALL.md tells users to create one)
+.venv/
++.venv*/
diff --cc harness/bench/_fixed_eval.py
index 843d9ebc,e8767d0e..494153a7
--- a/harness/bench/_fixed_eval.py
+++ b/harness/bench/_fixed_eval.py
@@@ -56,21 -54,26 +56,30 @@@ class FixedEvaluator
self.judge_model = judge_model
self.n_samples = n_samples
self.settings = settings or get_settings()
- self.rubric = rubric
+ self.track = track
- self.language = language
++ self.language = language # the battery's default; cells are built with THEIR spec's language (runtime())
+ # articulated batteries are judged on articulated_v1 (rest views + the pose sheet the
+ # joint sweep renders); the rubric follows the battery's track unless a caller pins one
+ self.rubric = rubric or RUBRIC_BY_TRACK.get(track.value, RUBRIC)
- self._runtime: Any = None
+ self._runtimes: dict[Language, Any] = {}
self._judge: Any = None
- @property
- def runtime(self) -> Any:
- if self._runtime is None:
+ def runtime(self, language: Language | str) -> Any:
+ """The build runtime for THIS cell's language, cached per language.
+
+ This was hardwired to Blender. A three.js cell whose harness run had been judged
+ 0.589 on ``src/object.js`` was then evaluated by the Blender runtime, which raised
+ ``MissingEntryFile: src/model.py does not exist`` — and the cell was recorded
+ ``build_failed`` with a hard **0.0**. Measured 2026-08-26 on
+ ``fancy_v1/tj``; every three.js cell in that battery was heading for the same
+ false zero. Same bug class as b4ea4cc (``entry_of``), one layer further down.
+ """
+ lang = Language(language)
+ if lang not in self._runtimes:
from codeverse.languages import get_runtime
- self._runtime = get_runtime(self.language)
- return self._runtime
+ self._runtimes[lang] = get_runtime(lang)
+ return self._runtimes[lang]
@property
def judge(self) -> Any:
diff --cc harness/bench/compare_backends.py
index d2a93376,dff8e9a3..2bc9c96c
--- a/harness/bench/compare_backends.py
+++ b/harness/bench/compare_backends.py
@@@ -61,10 -64,9 +64,9 @@@ from bench._fixed_eval import RUBRIC, E
from bench._infra import is_budget_exhaustion, is_infra_failure # noqa: E402
from bench._jsonl import seal_for_append # noqa: E402
from bench._oneshot import ( # noqa: E402
-- MODEL_FILE,
OneShotBackend,
OneShotResult,
+ files_for,
get_oneshot_backend,
oneshot_prompt,
repair_prompt,
@@@ -206,13 -206,26 +209,27 @@@ def _generate_oneshot(arm: Arm, spec: S
res.error = ""
if attempt + 1 >= max_attempts:
return
-- build, lint = deps.evaluator.build(eval_ws) # repair arm: error feedback only
++ build, lint = deps.evaluator.build(eval_ws, spec.language) # repair arm: error feedback only
if build.ok and not lint.errors:
return
- prompt = repair_prompt(spec, (eval_ws.root / MODEL_FILE).read_text(), build, lint, attempt + 1)
+ previous = {rel: (eval_ws.root / rel).read_text() for rel in files_for(spec.language) if (eval_ws.root / rel).is_file()}
+ prompt = repair_prompt(spec, previous, build, lint, attempt + 1)
+ def entry_of(spec: Spec) -> str:
+ """The file THIS spec's language delivers its code in.
+
+ ``_oneshot.MODEL_FILE`` is ``src/model.py`` because the one-shot arms are a
+ blender-only comparison (their contract prompt is literally python). The HARNESS arm
+ is not: a glsl run delivers ``src/shader.frag``, three.js ``src/object.js``, a scene
+ ``src/scene.js``, moderngl ``src/program.py``. Gating the harness arm on the one-shot
+ constant made every cell in those four languages ``no_code`` / **0.0** while the run
+ itself came back ``passed`` — a rig failure wearing a capability result's clothes, and
+ invisible in the summary. ``ENTRY_FILE`` is the canonical table; consult it.
+ """
+ return ENTRY_FILE[spec.language]
+
+
def _run_harness(spec: Spec, cell: Path, eval_ws: Workspace, deps: CompareDeps, res: CellResult) -> None:
run_ws = Workspace(cell / "run")
resume = run_ws.exists()
@@@ -227,10 -240,8 +244,10 @@@
res.gen_cost_usd = rec.total_usage.cost_usd
res.tool_calls = rec.total_usage.tool_calls
res.harness_status, res.harness_rounds, res.harness_loop_score = rec.status.value, len(rec.rounds), rec.final_score
+ res.harness_stop_reason = str(rec.extra.get("stop_reason") or "")
+ res.harness_aborted_rounds = len(rec.extra.get("aborted_rounds") or [])
- if not (run_ws.root / MODEL_FILE).is_file():
- res.error = f"harness run produced no {MODEL_FILE} (status {rec.status.value}: {rec.error})"
+ if not (run_ws.root / entry_of(spec)).is_file():
+ res.error = f"harness run produced no {entry_of(spec)} (status {rec.status.value}: {rec.error})"
return
# the whole src/ tree: agents may split helpers into src/parts/*.py (the build wrapper puts src/ on sys.path)
shutil.copytree(run_ws.src, eval_ws.src, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
@@@ -254,14 -265,7 +271,14 @@@ def run_cell(battery: Battery, item: Be
_run_harness(spec, cell, eval_ws, deps, res)
else:
_generate_oneshot(arm, spec, cell, eval_ws, opts, deps, res)
- if (eval_ws.root / entry_of(spec)).is_file():
+ # A one-shot arm whose LAST attempt was lost to the provider has not finished
+ # its protocol: `oneshot+repair` writes attempt 0's file before the repair call,
+ # so when that call dies in a 503 storm the broken pre-repair code was being
+ # evaluated and scored 0 — a hard zero for someone else's downtime, the exact
+ # asymmetry tests/compare_bench/test_infra_failures.py exists to end. Drop the
+ # cell instead (infra_failed); --redo-status re-runs the lost attempt only.
+ truncated = arm.kind != "harness" and res.error_is_infra
- if (eval_ws.root / MODEL_FILE).is_file() and not truncated:
++ if (eval_ws.root / entry_of(spec)).is_file() and not truncated:
outcome = deps.evaluator.evaluate(eval_ws, spec)
eval_ws.write_json(eval_ws.root / "eval.json", outcome)
_fill_from_outcome(res, outcome)
diff --cc harness/codeverse/judges/scoring.py
index bb3a29bf,89bc093a..3a8389bd
--- a/harness/codeverse/judges/scoring.py
+++ b/harness/codeverse/judges/scoring.py
@@@ -118,10 -101,9 +124,11 @@@ def aggregate_samples
overall_uncapped = rubric.weighted_overall(mean_scores)
floors = [
- {"criterion": cid, "score": round(sc, 4), "floor": fl} for cid, sc, fl in rubric.floors_hit(mean_scores)
+ {"criterion": cid, "score": round(sc, 4), "floor": fl}
+ for cid, sc, fl in rubric.floors_hit(mean_scores)
]
+ rep = _representative(samples, overalls)
+ tie_broken: list[str] = []
votes: dict[str, list[bool]] = {}
for s in samples:
for aid, ok in s.acceptance_bools.items():
@@@ -139,11 -117,10 +146,14 @@@
for s in samples:
for did, flag in s.defects.items():
d_votes.setdefault(did, []).append(bool(flag))
- defects = {did: (sum(v) * 2 >= len(v) and bool(v)) for did, v in d_votes.items()}
+ defects: dict[str, bool] = {}
+ for did, v in d_votes.items():
+ defects[did], tied = _vote(v, bool(rep.defects.get(did, False)))
+ if tied:
+ tie_broken.append(did)
+ # a checklist defect that a passed gate measured as absent neither penalises nor caps
+ # (judges/caps.measured_absent); it is still named in the verdict tail
+ defects, overridden = veto_measured_defects(rubric, defects, gates)
penalty = round(sum(rubric.defect(did).penalty for did, on in defects.items() if on), 4)
after_defects = max(0.0, overall_uncapped - penalty)
@@@ -152,8 -137,19 +170,18 @@@
overall = caps.overall
passed = overall >= rubric.pass_threshold and not floors and not must_missing
- rep = _representative(samples, overalls)
summary = rep.summary.strip()
- tail = _verdict_tail(rubric, overall, passed, floors, caps, must_missing, defects=defects, penalty=penalty)
+ tail = _verdict_tail(
+ rubric,
+ overall,
+ passed,
+ floors,
+ caps,
+ must_missing,
+ defects=defects,
+ penalty=penalty,
+ overridden=overridden,
+ )
if tail:
summary = (summary + " " if summary else "") + tail
@@@ -214,8 -228,9 +262,9 @@@ def _verdict_tail
return " | ".join(bits) + "]"
- def degraded_judgment(rubric: Rubric, error: str, *, usage: Usage, judge_backend: str, n_requested: int,
- judge_prompt_hash: str = "") -> Judgment:
+ def degraded_judgment(
- rubric: Rubric, error: str, *, usage: Usage, judge_backend: str, n_requested: int
++ rubric: Rubric, error: str, *, usage: Usage, judge_backend: str, n_requested: int, judge_prompt_hash: str = ""
+ ) -> Judgment:
"""A verdict the orchestrator must treat as a GLITCH (not a score): ``raw.status == 'degraded'``."""
breakdown = {
"status": "degraded",
diff --cc harness/docs/RELEASE_NOTES.md
index 6c2983da,64f9f99f..b3b6a922
--- a/harness/docs/RELEASE_NOTES.md
+++ b/harness/docs/RELEASE_NOTES.md
@@@ -1,32 -1,165 +1,192 @@@
- # Addendum — evaluation integrity, 2026-08-25
+ # Release notes
+
+ Newest first.
+
++## Evaluation integrity — 2026-08-25/26
+
+Four changes that affect what a recorded score MEANS, none of which changes a
+score computed under an odd `n_samples` (branch `ziyao/eval-integrity`, D36–D39):
+
+* `record.environment.harness_git_sha` is populated (it was always `""`: the probe
+ looked for `harness/.git`, which does not exist). `-dirty` marks a modified tree.
+* `judge_prompt_hash` (role prompt + rig rules + wire schema) is stored in every
+ `ScoreBreakdown` and in `record.prompt_hashes["judge"]`.
+* Exact vote ties on defects / acceptance items follow the representative sample
+ instead of a fixed direction; `ScoreBreakdown.tie_broken` names the ids. Under
+ the old rule `economy` (n=2) was strictly harsher than `balanced` (n=1) and
+ `quality` (n=3).
+* CI runs the whole offline suite (was 7 of 24 test directories).
+* `bench/paired_compare.py`: paired Δ, 95 % t-interval, exact sign test, per tier, plus a
+ judge-free table (build rate, gate errors) per arm; `bench/prompts/compare_v4.yaml`
+ (40 static prompts); `--judge-samples` on `compare_backends`.
+* `compare_backends`: storm-degraded harness cells are flagged (D40); arm failures are
+ zeros and provider failures are dropped (D41); the articulated track is supported (D42).
+* Python lints survive unparseable source (D43).
+* Measured with these (2026-08-25/26, gemini-3.7-flash, judge gemini-3.1-pro-preview n=3):
+ static compare_v4, n=40 — harness 0.633 vs one-shot+repair 0.487, Δ +0.146
+ [+0.077, +0.215], sign p < 0.001; vs one-shot 0.232, Δ +0.401. Articulated
+ articulated_v2, n=14 — harness 0.309 vs one-shot+repair 0.316, Δ −0.007 (CI crosses 0);
+ 5/14 harness runs failed at planning.
+
++
+ ## Skills — 2026-08-25
+
+ A routed, spec-conformant skill library whose reads we can measure. Baseline `42a5457` →
+ `HEAD`; six commits from five parallel waves (machinery, four authoring waves) plus this
+ verification pass. Full story and the authoring contract: **`docs/SKILLS.md`**.
+
+ **Ships behind `CV3D_SKILLS`, default OFF.** §A/B below says why, with the numbers.
+
+ ### What landed
+
+ * `codeverse/skills/` — 14 bundles authored to the open Agent Skills spec
+ (agentskills.io), a typed R1–R24 route table, an atime read probe, and numbers pinned to
+ live constants. `3dcv skills list|show|validate|report`, `3dcv doctor --skills`.
+ * Routing is automatic and gate-driven: the previous round's gate findings outrank the
+ standing sheets, which is the input no CLI's own skill loader can see.
+ * `RoundRecord.skills` records what was listed, surfaced and read deep, with the index and
+ body token cost, so the price of the feature is auditable per round rather than asserted.
+
+ ### Native loading, proven live
+
+ `pytest -m live tests/skills/test_live_discovery.py` — gemini-cli 0.53.0, codex 0.149.0,
+ claude-code 2.1.245 and agy 1.1.20 each discover a materialised bundle, open `SKILL.md`,
+ open `references/` and follow what they read. Two things this settled that had only been
+ argued: `Skill` was **absent** from claude-code's `ALLOWED_TOOLS` (it would have denied its
+ own skill tool — fixed, and `3dcv doctor --skills` now checks it), and gemini-cli's
+ `activate_skill` consent does not block us under `--approval-mode yolo`.
+
+ ### Defects the verification tests found
+
+ | # | What | Where |
+ |---|---|---|
+ | V-1 | Three language contracts told the agent to overlap parts by 2–4 mm / "≥ 2 mm" while `connectivity.py` WARNs above `PENETRATION_WARN_M` = 2 mm and its own `fix_hint` says "overlap by ≤ 2 mm". Two worked examples welded at 3–4 mm. | `prompts/{blender,cadquery,threejs}/contract.md` |
+ | V-2 | Four bundles' `verified:` dates were YAML **dates**, not strings; the spec says metadata is string→string. `validate_bundle` now reports it instead of coercing. | 4 × `SKILL.md`, `skills/loader.py` |
+ | V-3 | `cv3d-opengl-pipeline` shipped as `evidence: measured` on 5 graded runs. Now `mixed`. | `cv3d-opengl-pipeline/SKILL.md` |
+ | V-4 | The api-agent index quoted whole 1024-char descriptions: **780 tokens** for a five-skill session against a 300-token budget. It quotes the first clause now (342 worst case). | `skills/prompting.py` |
+ | V-5 | The live discovery smoke had never run and could not: it looked for a binary named after the agent kind, but `gemini-cli` runs `gemini` and `claude-code` runs `claude`. | `tests/skills/test_live_discovery.py` |
+ | V-6 | `cv3d-cadquery-forms` still quoted the contract's old unbounded "≥ 2 mm" weld, and the cadquery worked example welded at 3 mm. | `cv3d-cadquery-forms/SKILL.md`, `prompts/cadquery/contract.md` |
+ | V-7 | A body naming one of our constants was not required to pin it; `cv3d-glsl-craft` quoted `DUPLICATE_DIFF` at 1e-4 with no claim row behind it. | `cv3d-glsl-craft`, `tests/skills/test_freshness.py` |
+ | **V-8** | **The read probe was measuring git, not the agent.** See below. | `skills/telemetry.py`, `skills/materialize.py` |
+ | **V-9** | **An A/B launched from a worktree ran the MAIN tree's harness in both arms**, with no symptom at all. See below. | `bench/ab_plan.py`, `bench/compare_backends.py` |
+
+ ### V-9: the A/B rig was comparing a tree with itself
+
+ `ab_plan.spawn_cell` starts each child as a **file path**, so `sys.path[0]` is `bench/` and
+ the cwd is not on the path. `from codeverse._compat import UTC` sat **above** the script's
+ own `sys.path` bootstrap, so that import resolved through the editable install
+ (`__editable__.3dcodeverse-0.1.0.pth` pins a meta-path finder to `/home/yipeng/3dcodeverse`)
+ — and every cell of every arm ran the **main tree**.
+
+ The failure has no symptom. Both arms run the same foreign code, the switch under test is
+ inert, the cells pass, and the report prints a verdict. It voided the plan-loop wave's first
+ A/A (they found it, named the directory `invalid_attempt1_maintree_import`, and worked
+ around it with `PYTHONPATH` in a launch script) and then voided this wave's first A/B: the
+ variant arm ran a tree with no `codeverse/skills` package at all, materialised nothing,
+ emitted no `skills.attached`, and would have reported "no effect".
+
+ Three fixes, because a launch-script workaround protects whoever remembers it: the
+ bootstrap moves above the first `codeverse` import in both bench scripts that have this
+ shape; `ab_plan` refuses to start when `import codeverse` did not resolve inside its own
+ tree, and says how to fix it; and `tests/compare_bench/test_worktree_import.py` asserts the
+ ordering for every bench script that bootstraps `sys.path`.
+
+ ### V-8: the read probe was measuring git
+
+ The design's headline differentiator was read telemetry: `atime > mtime` on
+ `references/*.md` means the agent read the body, because nothing scans `references/`.
+ **Measured, that is false twice over.**
+
+ 1. `Workspace.changed_files` runs `git add -A -N` then `git diff --numstat` after *every*
+ agent session to compute `files_changed`, and git reads each untracked file to diff it.
+ On a real git workspace that alone flips all four files of every bundle to "read", with
+ no agent involved. Reproduced in `test_git_diff_alone_trips_the_control`.
+ 2. A negative control — one bundle whose description does not match the task, prompt "do
+ not read any files, do not activate any skill" — had codex 0.149.0, claude-code
+ 2.1.245, agy 1.1.20 and gemini-cli 0.53.0 **all** open `SKILL.md` and `references/`.
+ Each touched only the discovery root it owns, which independently confirms the mapping.
+
+ Left alone, this metric would have reported 100% forever and we would have believed it.
+ `materialize_skills` now writes one **never-routed, never-indexed control bundle** beside
+ the real ones. Nothing should open it; when something does, `SkillsUsage.control_read` is
+ set, `probe_trustworthy` is false, and `deep_read_rate` returns `None` rather than a
+ confident number. `3dcv skills report` excludes those sessions and says how many it
+ dropped. The control says when the probe is blind; it does not make it see.
+
+ ### Read rate, on an ordinary build task
+
+ Five routed bundles in the workspace, an ordinary "build a dining chair in bpy" prompt,
+ nothing about skills in it: codex, claude-code and agy each came back with 5 of 5 bundles
+ surfaced and deep, 8,041 body tokens. Those runs predate the control, so treat the rate as
+ an upper bound — but the behavioural evidence under it is not ambiguous: codex's
+ `src/parts/common.py` came back with `WELD_OVERLAP = 0.001` and "1 mm weld overlap with
+ the seat", which is `cv3d-part-contact`'s number, not the prompt corpus's 2–5 mm.
+
+ ### New standing tests
+
+ `tests/skills/` — 712 tests: 650 in the default suite, 58 `slow`, 4 `live`.
+
+ * **Contradiction**, library-wide, on the *pre-scale value* rather than the rendered text —
+ "1 cm" and "0.01" metres are one tolerance in two units, and failing that pair would
+ teach the next author to delete the claim.
+ * **Freshness** — every tool, gate kind, rubric criterion, constant, switch, sibling skill
+ and cookbook section a bundle names must still exist in the shipped source.
+ * **Contract agreement** — a skill and its language contract cannot state different
+ numbers, arbitrated by the gate constant rather than by either document.
+ * **Routing properties** — the real library over 5,376 sessions per track, every corpus
+ finding kind, and 2,000 seeded random walks: determinism, the cap, ordering,
+ explainability, and junk degrading to `[]`.
+ * **Spec compliance** re-derived from the raw bytes, plus the reference validator
+ (`pip install skills-ref` → `agentskills`, now in the `dev` extra): 14/14 valid, and its
+ `read-properties` agrees with our loader field for field.
+ * **Budget** re-measured against the shipped descriptions; **packaging** asserts a built
+ wheel holds all 14 `SKILL.md`, all 14 `references/` and all 9 `_claims`.
+ * **Corpus** recomputes each bundle's claimed evidence from `bench/out`.
+
+ ### The A/B, and why it ships OFF
+
+ `bench/out/ab_skills`, eight `static_objects_v2` prompts (the same eight
+ `bench/out/plan_loop/C0` used for its A/A), `--rounds 1`, paired, fixed judge, arms
+ differing only in `CV3D_SKILLS=on`. A Gemini capacity outage held the pool at 0–4 of 6 keys
+ for most of the window: **1 pair scored, 3+ cells `infra_failed`** (excluded, never scored 0;
+ the run was still going when this was written — re-run with `--redo-status infra_failed`
+ before quoting it as final).
+
+ * mean delta **+0.002** (control 0.937, variant 0.939) · CI not computable at n=1 · sign
+ test 1/0, p = 1.000 · the rig printed `inconclusive`, `separated from noise: NO`.
+ * **The read rate on that cell was 0 of 5, with ground truth.** `api-agent` owns its
+ `read_file`, so this is a log and not a probe: the agent made **52 `read_file` calls
+ across 4 sessions and none of them was a skill**, while calling `read_cookbook` twice.
+ The atime probe said 5 of 5 "deep" and its control simultaneously said `control_read:
+ true` — the probe was blind, exactly as V-8 predicts, and the calibration arm supplied
+ the number it could not. The next variant cell repeated it: five bundles materialised,
+ `read_file` called, zero skill paths.
+
+ So the two arms differed by 356 tokens of index that nobody opened, and +0.002 is what that
+ is worth. **Ship OFF**, for three reasons that do not depend on more pairs: the read rate on
+ the harness's own generator is 0 %; the bar it was given (mean ≥ 0, no prompt regressed past
+ 0.03) is one the A/A of two *identical* arms fails twice over (−0.038, −0.206); and the
+ deterministic gate counts inherit the planner's spread directly (an A/A of them swings
+ +5.67 penetrating pairs, `bench/ab_gate_rates.py`).
+
+ Next, in order: **give `api-agent` a first-class skill affordance** (a `read_skill` tool
+ beside `read_cookbook`, or inline the top body) — with 0 % reads no A/B can measure the
+ library at all; then pin the plan (`docs/EVAL.md` §8.1); then reconcile the prompt corpus on
+ weld overlap; then re-run. The three subscription CLIs read all five bundles unprompted and
+ codex's output carried the skill's number, so this is a delivery problem for one backend,
+ not a verdict on the library.
+
+ ### Known open
+
+ Listed in `docs/SKILLS.md` §9. The one that matters most: **`contract.md` was fixed but the
+ wider prompt corpus still teaches 2–5 mm weld overlap** — `tracks/generate_static.j2`,
+ `assemble_static.j2`, `generate_static_part.j2`, `system/harness_contract.md` and three
+ cookbooks. That is a prompt-corpus change with its own measurement, and it is the most
+ likely reason a contact skill would fail to move the number it targets.
+
---
- # Release notes — stability pass, 2026-08-24
+ ## Stability pass — 2026-08-24
Sign-off for the first release intended to be called **stable**. Five parallel waves hunted
the harness for defects, a sixth verified them, three fixed them, and this pass reconciled,
diff --cc harness/tests/compare_bench/conftest.py
index af13079b,af13079b..e2f02779
--- a/harness/tests/compare_bench/conftest.py
+++ b/harness/tests/compare_bench/conftest.py
@@@ -55,7 -55,7 +55,7 @@@ class FakeEvaluator
self.evaluated: list[str] = []
self.builds = 0
-- def build(self, ws: Workspace) -> tuple[BuildResult, GateReport]:
++ def build(self, ws: Workspace, language: object = None) -> tuple[BuildResult, GateReport]:
self.builds += 1
code = (ws.root / MODEL_FILE).read_text()
lint = GateReport(gate="lint:blender", passed=True)
diff --cc harness/tests/compare_bench/test_articulated_compare.py
index 21ded876,00000000..9a1054a4
mode 100644,000000..100644
--- a/harness/tests/compare_bench/test_articulated_compare.py
+++ b/harness/tests/compare_bench/test_articulated_compare.py
@@@ -1,122 -1,0 +1,122 @@@
+"""compare_backends on an articulated battery: two-file one-shot answers, articulated_v1 fixed judge."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[2]
+if str(REPO) not in sys.path:
+ sys.path.insert(0, str(REPO))
+
+from bench._compare_report import RUBRIC_BY_TRACK # noqa: E402
+from bench._fixed_eval import FixedEvaluator # noqa: E402
+from bench._oneshot import ( # noqa: E402
+ MODEL_FILE,
+ URDF_FILE,
+ extract_files,
+ files_for,
+ minimal_contract,
+ oneshot_prompt,
+ repair_prompt,
+ write_answer_files,
+)
+from bench.run_bench import Battery # noqa: E402
+from codeverse.contracts.artifacts import BuildResult, GateReport # noqa: E402
+from codeverse.contracts.common import Language, Track # noqa: E402
+from codeverse.contracts.spec import Constraints, Spec # noqa: E402
+from codeverse.tracks.generation import MultiFileParseError # noqa: E402
+from codeverse.workspace import Workspace # noqa: E402
+
+PROMPTS = REPO / "bench" / "prompts"
+PY = "import bpy\nprint(1)\n"
+XML = '<?xml version="1.0"?>\n<robot name="x"><link name="base"/></robot>\n'
+ENVELOPE = f"=== FILE: {MODEL_FILE} ===\n{PY}=== END FILE ===\n=== FILE: {URDF_FILE} ===\n{XML}=== END FILE ===\n"
+
+
+def _urdf_spec() -> Spec:
+ return Spec(id="t/lamp", track=Track.ARTICULATED_OBJECT, language=Language.URDF_BLENDER,
+ prompt="an architect lamp with two hinged arms",
+ constraints=Constraints(must_have=["two revolute joints"], dimensions_m={"height": 0.6}))
+
+
+def test_urdf_oneshot_prompt_carries_the_frame_recipe_and_the_two_file_envelope():
+ p = oneshot_prompt(_urdf_spec())
+ assert "hand-written URDF" in p and "architect lamp" in p and "MUST HAVE: two revolute joints" in p
+ for rule in ("rpy=\"0 0 0\"", "pivot_child − frame_parent", "−pivot_link", "meshes/<link>.glb", "lower ≤ 0 ≤ upper"):
+ assert rule in p, rule
+ assert f"=== FILE: {MODEL_FILE} ===" in p and f"=== FILE: {URDF_FILE} ===" in p
+ # no harness help: no worked example, no cookbook, no skeleton
+ assert "pedal" not in p.lower() and "cookbook" not in p.lower() and "PIVOT[" not in p
+ assert minimal_contract(Language.URDF_BLENDER) in p
+ # the static contract is untouched by the language switch
+ assert minimal_contract() == minimal_contract(Language.BLENDER) and URDF_FILE not in minimal_contract()
+
+
+def test_files_for_and_extract_files_two_file_answer():
+ assert files_for(Language.BLENDER) == [MODEL_FILE] and files_for(Language.URDF_BLENDER) == [MODEL_FILE, URDF_FILE]
+ got = extract_files(ENVELOPE, Language.URDF_BLENDER)
+ assert got == {MODEL_FILE: PY, URDF_FILE: XML}
+ # fenced blocks each preceded by their path also parse
+ fenced = f"{MODEL_FILE}\n```python\n{PY}```\n{URDF_FILE}\n```xml\n{XML}```\n"
+ assert extract_files(fenced, Language.URDF_BLENDER) == {MODEL_FILE: PY, URDF_FILE: XML}
+ # the static path is unchanged
+ assert extract_files("```python\nimport bpy\n```", Language.BLENDER) == {MODEL_FILE: "import bpy\n"}
+
+
+ f"```python\n{PY}```", # one block, two expected
+ f"=== FILE: {MODEL_FILE} ===\n{PY}=== END FILE ===\n", # envelope with the URDF missing
+ f"=== FILE: {MODEL_FILE} ===\n{PY}=== END FILE ===\n=== FILE: {URDF_FILE} ===\n\n=== END FILE ===\n", # empty urdf
+])
+def test_a_urdf_answer_without_both_files_is_a_format_failure(text: str):
+ with pytest.raises(MultiFileParseError):
+ extract_files(text, Language.URDF_BLENDER)
+
+
+def test_write_answer_files_writes_both(tmp_path):
+ ws = Workspace(tmp_path / "ws")
+ ws.create()
+ paths = write_answer_files(ws, ENVELOPE, Language.URDF_BLENDER)
+ assert [p.relative_to(ws.root).as_posix() for p in paths] == [MODEL_FILE, URDF_FILE]
+ assert (ws.root / URDF_FILE).read_text() == XML and (ws.root / MODEL_FILE).read_text() == PY
+
+
+def test_urdf_repair_prompt_carries_both_previous_files():
+ build = BuildResult(ok=False, language="urdf_blender", error_type="FKMismatch",
+ error_message="link 'arm' visual origin should be -0.1 0 0.3", error_file=URDF_FILE, error_line=9)
+ p = repair_prompt(_urdf_spec(), {MODEL_FILE: PY, URDF_FILE: XML}, build, GateReport(gate="lint:urdf", passed=True), attempt=1)
+ assert "FKMismatch" in p and "corrected files" in p
+ assert f"PREVIOUS `{MODEL_FILE}`" in p and f"PREVIOUS `{URDF_FILE}`" in p and "```xml" in p
+
+
+def test_fixed_evaluator_follows_the_battery_track():
+ ev = FixedEvaluator("gemini:x", n_samples=3, track=Track.ARTICULATED_OBJECT, language=Language.URDF_BLENDER)
+ assert ev.rubric == "articulated_v1" == RUBRIC_BY_TRACK["articulated_object"]
- assert ev.language is Language.URDF_BLENDER and ev.runtime.language is Language.URDF_BLENDER
++ assert ev.language is Language.URDF_BLENDER and ev.runtime(Language.URDF_BLENDER).language is Language.URDF_BLENDER
+ static = FixedEvaluator("gemini:x")
+ assert static.rubric == "static_object_v1" and static.language is Language.BLENDER
+ pinned = FixedEvaluator("gemini:x", rubric="asset_v1", track=Track.ARTICULATED_OBJECT)
+ assert pinned.rubric == "asset_v1"
+
+
+def test_main_builds_the_evaluator_from_the_battery(monkeypatch, tmp_path):
+ from bench import compare_backends as cb
+
+ seen = {}
+
+ def fake_run_matrix(battery_path, out_dir, arms, opts, deps, on_result=None):
+ seen["track"], seen["language"], seen["rubric"] = deps.evaluator.track, deps.evaluator.language, deps.evaluator.rubric
+ (Path(out_dir)).mkdir(parents=True, exist_ok=True)
+ (Path(out_dir) / "results.jsonl").write_text("")
+
+ monkeypatch.setattr(cb, "run_matrix", fake_run_matrix)
+ monkeypatch.setattr(cb, "_preflight", lambda *a, **k: True)
+ rc = cb.main(["--prompts", str(PROMPTS / "articulated_v2.yaml"), "--arms", "oneshot:gemini:x",
+ "--out", str(tmp_path / "out"), "--no-preflight", "--judge-samples", "3"])
+ assert rc == 0
+ assert seen == {"track": Track.ARTICULATED_OBJECT, "language": Language.URDF_BLENDER, "rubric": "articulated_v1"}
+ b = Battery.load(PROMPTS / "articulated_v2.yaml")
+ assert b.track is Track.ARTICULATED_OBJECT and all(p.must_have for p in b.prompts)
diff --cc harness/tests/judges/test_vlm_judge.py
index 0059bd81,40f0415a..666536f5
--- a/harness/tests/judges/test_vlm_judge.py
+++ b/harness/tests/judges/test_vlm_judge.py
@@@ -189,36 -189,67 +189,101 @@@ def test_judge_payload_size_comes_from_
get_settings.cache_clear()
+# ----------------------------------------------------------------------------- D37 judge protocol hash
+def test_judge_prompt_hash_is_recorded_in_every_verdict(judge_input, cache_dir):
+ from codeverse.judges.prompt_builder import judge_prompt_hash
+
+ j = _judge(FakeChatModel([good_reply(R, IDS, 0.8)]), cache_dir=cache_dir).judge(judge_input)
+ raw = json.loads(j.raw)
+ assert raw["judge_prompt_hash"] == judge_prompt_hash(R) and len(raw["judge_prompt_hash"]) == 12
+ assert raw["rubric_hash"] == R.content_hash() and raw["judge_prompt_hash"] != raw["rubric_hash"]
+ # a degraded verdict carries it too, so a glitch is still attributable to a protocol
+ d = _judge(FakeChatModel([ModelError("down", retryable=False)]), cache_dir=cache_dir).judge(judge_input)
+ assert is_degraded(d) and json.loads(d.raw)["judge_prompt_hash"] == judge_prompt_hash(R)
+ assert _judge(FakeChatModel([]), cache_dir=cache_dir).prompt_hash == judge_prompt_hash(R)
+
+
+def test_judge_prompt_hash_tracks_the_protocol_not_the_run(monkeypatch):
+ from codeverse.judges import prompt_builder as pb
+ from codeverse.judges.output_schema import wire_schema
+ from codeverse.judges.prompt_builder import judge_prompt_hash
+
+ base = judge_prompt_hash(R)
+ assert judge_prompt_hash(R) == base # deterministic
+ # per-run content (acceptance ids) is NOT part of it: the schema is hashed with no ids
+ assert wire_schema(R, ["A1"]) != wire_schema(R, []) and judge_prompt_hash(R) == base
+ # the rubric is part of it (through the rendered rubric block)
+ other = load_rubric("shader_v1")
+ assert judge_prompt_hash(other) != base
+ # an edit to the role prompt or the rig rules changes it — that is the whole point
+ monkeypatch.setattr(pb, "_ROLE", pb._ROLE + "\nScore generously.")
+ edited_role = judge_prompt_hash(R)
+ assert edited_role != base
+ monkeypatch.setattr(pb, "RIG_RULES", {**pb.RIG_RULES, "object": "All views show the same object."})
+ assert judge_prompt_hash(R) not in (base, edited_role)
+
++
+ # -------------------------------------------------------- per-sample retry budget (audit 2026-08-26 §5.1)
+ def _fake_clock(monkeypatch):
+ import time as real_time
+ from types import SimpleNamespace
+
+ import codeverse.judges.vlm_judge as mod
+
+ clock = {"t": 0.0}
+ monkeypatch.setattr(mod, "time", SimpleNamespace(monotonic=lambda: clock["t"], time=real_time.time,
+ sleep=real_time.sleep))
+ return clock
+
+
+ def test_each_sample_has_a_retry_budget_and_hands_what_is_left_to_the_model(judge_input, cache_dir, monkeypatch):
+ """The verdict call is 42 s p50 / 73 s p90 on a normal day, 50 / 103 s under a storm
+ (audit 2026-08-26 §2); two storm-day rounds lost 1 162 s and 927 s to 3 x 300 s timeouts
+ before a second sample answered in 128 s. A sample now has SAMPLE_BUDGET_S = 240 s for all
+ its attempts, and every attempt tells the model how much of it remains."""
+ from codeverse.judges.vlm_judge import SAMPLE_BUDGET_S
+
+ clock = _fake_clock(monkeypatch)
+
+ def slow_503(request):
+ clock["t"] += 100.0
+ return ModelError("503 high demand", retryable=True, status=503)
+
+ model = FakeChatModel([slow_503, slow_503, good_reply(R, IDS, 0.8)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and len(model.requests) == 3
+ assert SAMPLE_BUDGET_S == 240.0
+ assert [r.max_wait_s for r in model.requests] == [240.0, 140.0, 40.0]
+
+
+ def test_a_sample_stops_when_its_budget_is_spent(judge_input, cache_dir, monkeypatch):
+ clock = _fake_clock(monkeypatch)
+
+ def spent(request):
+ clock["t"] += 250.0 # one attempt that retried inside the model for the whole budget
+ return ModelError("503 high demand", retryable=True, status=503)
+
+ model = FakeChatModel(default=spent)
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert is_degraded(j) and len(model.requests) == 1, "max_attempts=3, but the budget is gone"
+ assert "sample budget" in j.summary
+ # the budget is a dial: a caller that can afford more gets the attempts back
+ model = FakeChatModel(default=spent)
+ j = _judge(model, cache_dir=cache_dir, sample_budget_s=600).judge(judge_input)
+ assert len(model.requests) == 3
+ assert [r.max_wait_s for r in model.requests] == [600.0, 350.0, 100.0]
+
+
+ def test_the_last_attempt_still_gets_a_real_try(judge_input, cache_dir, monkeypatch):
+ """A few seconds of budget would be a deadline the model cannot use; the floor is 20 s."""
+ from codeverse.judges.vlm_judge import SAMPLE_MIN_WAIT_S
+
+ clock = _fake_clock(monkeypatch)
+
+ def nearly_spent(request):
+ clock["t"] += 235.0
+ return ModelError("503", retryable=True, status=503)
+
+ model = FakeChatModel([nearly_spent, good_reply(R, IDS, 0.8)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and [r.max_wait_s for r in model.requests] == [240.0, SAMPLE_MIN_WAIT_S]