Skip to content

Official Codebase of 3DCodeVerse

Python

harness v0.2: waves 2-3 + verified fix batches + rename CLI to 3dcodeverse/3dcv

gaoypengde94d856d428
diff --git a/README.md b/README.md
index d6813a99..d2408ec6 100644
--- a/README.md
+++ b/README.md
@@ -3,10 +3,11 @@
The 3dcodeverse project. Top-level layout:
- **`harness/`** — the 3dcodeverse harness (python dist `3dcodeverse`, import
- `codeverse`, CLI `3dcodeverse` / `c3v`): the backend that turns prompts into
- raw 3D code (Blender bpy / CadQuery / Three.js / URDF / GLSL) through a
- plan → generate → gate → render → judge → refine loop, and emits
- data-flywheel records. See `harness/README.md`.
+ `codeverse`, CLI `3dcodeverse` / `3dcv`): the backend that turns prompts into
+ raw 3D code (Blender bpy / CadQuery / Three.js / URDF / GLSL / OpenGL) across
+ four tracks (static objects, articulated objects, scenes, graphics) through a
+ plan → generate → gate → render → judge → refine loop, with text-to-image
+ texturing and data-flywheel records. See `harness/README.md`.
- **`finetune/`** — LLM finetuning recipes (LoRA / full-parameter SFT, execution-
and geometry-feedback DPO via unpatched LLaMA-Factory) and the execution-based
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
index 2a9d79e8..a04721a5 100644
--- a/harness/CLAUDE.md
+++ b/harness/CLAUDE.md
@@ -1,13 +1,18 @@
# 3dcodeverse — standing context
-Backend harness (python package `codeverse`, CLI `c3v`) for LLM-written **raw** 3D
-code: Blender bpy · CadQuery · Three.js · URDF · GLSL, across three tracks
-(`static_object`, `articulated_object`, `scene`), with pluggable backends
-(Gemini/Anthropic/OpenAI APIs + gemini-cli / claude-code / codex / antigravity /
-in-process api-agent) and a data-flywheel record per run.
+Backend harness (python package `codeverse`, CLI `3dcodeverse` / short alias `3dcv`,
+repo path `/home/yipeng/3dcodeverse/harness`) for LLM-written **raw** 3D code:
+Blender bpy · CadQuery · Three.js · URDF · GLSL / OpenGL, across four tracks
+(`static_object`, `articulated_object`, `scene`, `graphics`), with pluggable
+backends (Gemini/Anthropic/OpenAI APIs + gemini-cli / claude-code / codex /
+antigravity / in-process api-agent / single-shot), an optional text-to-image
+texture pass, and a data-flywheel record per run.
-Read `docs/ARCHITECTURE.md` (design + package map + authoring contracts) and
-`docs/INTERFACES.md` (binding cross-package signatures) before changing anything.
+Read `docs/ARCHITECTURE.md` (design, package map, authoring contracts, what a run
+really does, known limits), `docs/INTERFACES.md` (binding cross-package signatures as
+built), `docs/RUNBOOK.md` (how to run / resume / extend), `docs/DECISIONS.md`
+(ADR-style laws + deviations) and `docs/EVAL.md` (evaluation protocol + judge
+calibration) before changing anything.
## Laws (do not break)
1. Generated code is raw language — never an SDK/helper import; the harness owns
@@ -17,32 +22,53 @@ Read `docs/ARCHITECTURE.md` (design + package map + authoring contracts) and
3. Deterministic gates/measurements run by the harness; VLM only for perception.
Score is computed in code from rubric weights; caps/floors are explicit.
4. Typed everything; no regex-on-id control flow; no god files (≤ ~400 lines).
-5. Cheap first: lint → build → gates → 4-view sheet → VLM. Budgets are hard.
+5. Cheap first: lint → build → gates → montaged views → VLM. Budgets are hard.
6. Every round = a git commit of `src/`; every call = a `Usage`; every run = `record.json`.
+7. No wrapper re-centres or grounds the object: export **as authored**, warn in the
+ build, let `check_contract`/`check_connectivity` gate it.
## Environment (this machine)
-- Gemini keys: `~/.config/astra3d/gemini_keys.env` (22 keys) → `get_settings().gemini_api_keys`.
+- Gemini keys: `~/.config/astra3d/gemini_keys.env` (22 keys) → `get_settings().gemini_api_keys`
+ (or `GEMINI_API_KEYS` / `GEMINI_API_KEY` env). Settings: `~/.config/codeverse/config.yaml`
+ or `./codeverse.yaml`, env prefix `CV3D_` (`CV3D_RENDER__GPU=off`, `CV3D_RUNS_DIR=…`,
+ `CV3D_DEFAULT_CANDIDATES=2`).
- Blender 5.0.1 headless: `~/.local/bin/blender-5.0` (always `--factory-startup`; clear scene).
- Node 24 + `runtime_js/node_modules` ([email protected], puppeteer; chrome cached). Headless
Chrome WebGL uses the GPU on WSL2 with `--use-angle=gl-egl` + Mesa d3d12 env (see
- `runtime_js/gpu_launch.cjs`); SwiftShader fallback.
-- CLIs: `gemini` 0.53 (api-key auth + `dynamicModelConfiguration` via system settings file,
- else it silently substitutes models), `codex` 0.147, `claude` 2.1, `agy` 1.1.5 — the last
- three run on local subscriptions: test lightly.
-- Main test model: `gemini-3.7-flash`. Judge default: `gemini-3.7-flash` (n_samples=2) or
- `gemini-3.1-pro-preview` for calibration runs.
+ `runtime_js/gpu_launch.cjs`; `CV3D_RENDER_GPU=on|off|auto`); SwiftShader fallback.
+ Bare ESM `import 'three'` needs `--import runtime_js/lib/resolve_three.mjs`
+ (`spatial.node.run_node(three_hook=True)`) — `NODE_PATH` alone does not work.
+ The `graphics` track renders with moderngl (d3d12 GPU context, llvmpipe fallback).
+- CLIs: `gemini` 0.53 (api-key auth + `dynamicModelConfiguration` + `folderTrust.enabled=false`
+ via the system settings file the harness writes — else it silently substitutes models /
+ drops workspace MCP servers), `codex` 0.147+ (MCP needs
+ `default_tools_approval_mode="approve"`), `claude` 2.1, `agy` 1.1 — the last three run
+ on local subscriptions: test lightly. No Anthropic/OpenAI API keys here.
+- Main test model: `gemini-3.7-flash` (lenient judge; needs the defect checklist for
+ range). Judge default `gemini-3.1-pro-preview` (`Settings.default_judge`; tracks use
+ n_samples=1); flash + `--n 3` is the cheap fallback, pro for calibration/eval.
+- Live runs under `runs/` (`e2e_*`): read-only reference material; never modify.
## Commands
```
-pip install -e /home/yipeng/3dcodeverse/harness # once
-c3v doctor
-c3v make "a mid-century wooden dining chair" --track static_object --language blender
-c3v make "..." --track articulated_object --language urdf_blender
-c3v make "..." --track scene --language scene_threejs --generator gemini-cli:gemini-3.7-flash
-c3v resume <slug> · c3v status <slug> · c3v render <slug> · c3v judge <slug>
-c3v tools list · c3v mcp --workspace runs/<slug>
-c3v flywheel export runs/ dataset/ · c3v bench run bench/prompts/static_objects_v1.yaml
-python -m pytest tests -q -m "not live"
+pip install -e /home/yipeng/3dcodeverse/harness # once (entry points: 3dcodeverse, 3dcv)
+cd /home/yipeng/3dcodeverse/harness
+3dcodeverse doctor [--live] [--no-gpu] [--json]
+3dcodeverse make "a mid-century wooden dining chair" --track static_object --language blender
+3dcodeverse make "..." --track static_object --language threejs --generator gemini-cli:gemini-3.7-flash
+3dcodeverse make "..." --track articulated_object --language urdf_blender
+3dcodeverse make "..." --track scene --language scene_threejs --rounds 2 --max-usd 3
+3dcodeverse make "neon rain on a window" --track graphics --language glsl_shader
+3dcodeverse make "..." --image ref.png --candidates 3 --rounds 2 --dim height=0.45 --must "three legs" --texture --no-run
+3dcv resume <slug> · 3dcv status <slug> · 3dcv render <slug> [--mode wire] · 3dcv judge <slug> [--model ... --n 3]
+3dcv texture pass <slug> [--no-judge] · 3dcv texture scene-pack <slug> · 3dcv texture show <slug>
+3dcv tools list · 3dcv tools measure --workspace runs/<slug> · 3dcv mcp --workspace runs/<slug>
+3dcv flywheel export runs/ dataset/ [--pack --drop-duplicates --captions-dir d/] · 3dcv flywheel pairs runs/ pairs.jsonl
+3dcv flywheel caption <slug> [--out dir] · 3dcv flywheel gallery runs/ gallery.html
+3dcv bench run bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-3.1-pro-preview
+python -m codeverse.judges.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/
+python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:api-agent:gemini:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1
+python -m pytest tests -q -m "not live" # ~860 offline tests; add "and not blender and not node" for pure python
```
## Reference material (ideas only — never copy code)
diff --git a/harness/README.md b/harness/README.md
index d2099f75..ce972654 100644
--- a/harness/README.md
+++ b/harness/README.md
@@ -1,27 +1,48 @@
-# 3dcodeverse
+# 3dcodeverse harness
A backend harness in which LLMs write **raw, executable 3D code** — Blender `bpy`,
-CadQuery, Three.js, URDF, GLSL — and a harness plans, builds, measures, renders,
-judges, refines and records every run as data-flywheel material.
+CadQuery, Three.js, URDF, GLSL / OpenGL — and the harness plans, builds, measures,
+renders, judges, refines, textures and records every run as data-flywheel material.
-* **Tracks:** `static_object` · `articulated_object` · `scene`
-* **Languages:** `blender` · `cadquery` · `threejs` · `urdf_blender` · `scene_threejs`
-* **Backends:** Gemini / Anthropic / OpenAI APIs; gemini-cli, Claude Code, Codex,
- Antigravity CLI; and an in-process `api-agent` tool loop on any API model.
-* **Spatial tools** (also an MCP server for agentic CLIs): build, measure,
- render_views/sheet, isolate, cross_section, check_connectivity, check_contract,
- compare_silhouette, joint_sweep, shader_probe, scene_probe, read_cookbook.
-* **Judging:** rubric VLM judge with code-computed scores, floors and caps from
- deterministic gates; pairwise and reference judges.
-* **Flywheel:** git-versioned `src/` per round, `record.json`, sample export,
- preference/repair pairs, captions.
+* **Tracks:** `static_object` · `articulated_object` · `scene` · `graphics`
+* **Languages:** `blender` · `cadquery` · `threejs` · `urdf_blender` ·
+ `scene_threejs` · `glsl_shader` · `opengl_python`
+* **Backends:** Gemini / Anthropic / OpenAI chat models; coding agents `gemini-cli`,
+ `claude-code`, `codex`, `agy` (Antigravity), the in-process `api-agent` tool loop, and
+ `single-shot` generation on any chat model.
+* **Spatial tools** (direct, MCP server `3dcv` for agentic CLIs, native tools for
+ api-agent): build, measure, render_views/sheet, isolate, cross_section,
+ check_connectivity, check_contract, compare_silhouette, joint_sweep, shader_probe,
+ scene_probe, scene_views, gl_probe, gl_frames, texture_pass, texture_preview,
+ read_cookbook.
+* **Judging:** rubric VLM judge (default `gemini-3.1-pro-preview`) on labelled 2×2
+ montages with binary defect checklists; code-computed scores, floors and caps from
+ deterministic gates; pairwise, ranking and reference judges; best-of-N candidates;
+ a calibration harness (`judges/calibration.py`).
+* **Texturing:** optional text-to-image pass — VLM material plan → seamless tiles →
+ world-metre UVs → `object_textured.glb`, shipped only when a before/after judge
+ gate agrees; scene texture packs for prompts.
+* **Flywheel:** git-versioned `src/` per round, `record.json`, sample export with
+ quality tiers + dedupe (+ parquet, tar locators), preference/repair/trajectory
+ pairs, captions, sqlite index, HTML gallery.
```bash
-pip install -e .
-c3v doctor
-c3v make "a mid-century wooden dining chair" --track static_object --language blender
-c3v make "a kitchen cabinet with one door and a drawer" --track articulated_object --language urdf_blender
-c3v make "a small japanese garden at dusk with a koi pond" --track scene --language scene_threejs
+pip install -e . # entry points: 3dcodeverse, 3dcv
+(cd runtime_js && npm install)
+3dcv doctor
+3dcv make "a mid-century wooden dining chair" --track static_object --language blender
+3dcv make "a kitchen cabinet with one door and a drawer" --track articulated_object --language urdf_blender
+3dcv make "a small japanese garden at dusk with a koi pond" --track scene --language scene_threejs
+3dcv make "neon cyberpunk rain on a window" --track graphics --language glsl_shader
+python -m pytest tests -q -m "not live"
```
-Design: `docs/ARCHITECTURE.md` · Interfaces: `docs/INTERFACES.md` · Working rules: `CLAUDE.md`.
+Observed with `gemini-3.7-flash` end to end: chair (blender) 0.67 → 0.74 in 2 rounds,
+12 min, $0.84; cabinet (URDF) 0.68 → 0.93, 12.5 min, $0.84; park bench (threejs via
+gemini-cli) 0.64 → 0.89, 36 min, $0.68; garden scene 0.56 → 0.60 over 2 refine rounds,
+45 min, $2.90; neon-rain shader (graphics, single-shot) 0.79 first round, 2 min, $0.05;
+best-of-2 stool 0.56 → 0.61, 7.6 min, $0.24.
+
+Docs: `docs/ARCHITECTURE.md` (design + what a run does) · `docs/INTERFACES.md`
+(signatures) · `docs/RUNBOOK.md` (operate / extend) · `docs/DECISIONS.md` (ADRs) ·
+`docs/EVAL.md` (evaluation protocol + judge calibration) · `CLAUDE.md` (working rules).
diff --git a/harness/bench/__init__.py b/harness/bench/__init__.py
index 33ff24fb..eca5483f 100644
--- a/harness/bench/__init__.py
+++ b/harness/bench/__init__.py
@@ -1,4 +1,4 @@
-"""Prompt batteries + bench runner/report (``c3v bench run|report``).
+"""Prompt batteries + bench runner/report (``3dcv bench run|report``).
Methodology: paired runs (same battery, same fixed judge model) across
generators; prompts stratified by tier (easy/medium/hard) and category.
diff --git a/harness/bench/_compare_report.py b/harness/bench/_compare_report.py
new file mode 100644
index 00000000..db6f0f35
--- /dev/null
+++ b/harness/bench/_compare_report.py
@@ -0,0 +1,274 @@
+"""Result rows + report.md / report.html for ``bench/compare_backends.py``.
+
+``CellResult`` is one (prompt, arm) cell; ``PairRow`` one pairwise verdict.
+``build_compare_report(out_dir)`` reads ``results.jsonl`` + ``pairwise.jsonl``
+and writes the arm summary table, the per-prompt score matrix, the pairwise
+arena (win rates) and an HTML gallery of the contact sheets side by side.
+"""
+
+from __future__ import annotations
+
+import html
+import json
+import shutil
+import statistics
+from pathlib import Path
+from typing import TypeVar
+
+from pydantic import BaseModel, Field
+
+T = TypeVar("T", bound=BaseModel)
+
+
+class CellResult(BaseModel):
+ prompt_id: str
+ tier: str = ""
+ arm: str
+ kind: str
+ target: str = ""
+ judge: str = ""
+ status: str = Field(default="", description="scored | build_failed | no_code | judge_error | error")
+ score: float | None = Field(default=None, description="fixed-judge overall (0 when the build failed)")
+ score_std: float = 0.0
+ passed: bool | None = None
+ build_ok: bool = False
+ gate_errors: list[str] = Field(default_factory=list)
+ tris: int | None = None
+ gen_cost_usd: float = Field(default=0.0, description="generation cost (harness: whole run incl. its loop judge)")
+ judge_cost_usd: float = Field(default=0.0, description="fixed-judge cost for this cell")
+ gen_seconds: float = 0.0
+ wall_s: float = 0.0
+ attempts: int = 0
+ tool_calls: int = 0
+ criteria: dict[str, float] = Field(default_factory=dict)
+ harness_status: str = ""
+ harness_rounds: int = 0
+ harness_loop_score: float | None = None
+ sheet: str = ""
+ glb: str = ""
+ workspace: str = ""
+ error: str = ""
+
+
+class PairRow(BaseModel):
+ prompt_id: str
+ arm_a: str
+ arm_b: str
+ winner: str = Field(description="a | b | tie")
+ confidence: float = 0.0
+ reasons: list[str] = Field(default_factory=list)
+ orderings: list[dict] = Field(default_factory=list)
+ cost_usd: float = 0.0
+ judged: bool = Field(default=True, description="False when decided by a missing build (no judge call)")
+ error: str = ""
+
+
+def load_jsonl(path: Path, model: type[T]) -> list[T]:
+ """Latest row wins per natural key (re-appended rows on resume)."""
+ if not path.is_file():
+ return []
+ rows: list[T] = []
+ for line in path.read_text().splitlines():
+ if line.strip():
+ rows.append(model.model_validate_json(line))
+ return rows
+
+
+# ----------------------------------------------------------------------------- aggregates
+class ArmStats(BaseModel):
+ arm: str
+ kind: str
+ n: int
+ mean_score: float | None
+ median_score: float | None
+ pass_rate: float | None
+ build_ok_rate: float
+ mean_gen_usd: float
+ mean_judge_usd: float
+ mean_minutes: float
+ tool_calls: int
+ errors: int
+
+
+class PairStats(BaseModel):
+ arm_a: str
+ arm_b: str
+ n: int
+ wins_a: int
+ wins_b: int
+ ties: int
+ win_rate_a: float | None = Field(description="wins_a / (wins_a + wins_b); ties excluded")
+ mean_confidence: float
+
+
+def _mean(xs: list[float]) -> float | None:
+ return round(statistics.fmean(xs), 4) if xs else None
+
+
+def arm_stats(rows: list[CellResult]) -> list[ArmStats]:
+ by_arm: dict[str, list[CellResult]] = {}
+ for r in rows:
+ by_arm.setdefault(r.arm, []).append(r)
+ out = []
+ for arm, rs in by_arm.items():
+ scores = [r.score for r in rs if r.score is not None]
+ passed = [r.passed for r in rs if r.passed is not None]
+ out.append(ArmStats(
+ arm=arm, kind=rs[0].kind, n=len(rs), mean_score=_mean(scores),
+ median_score=round(statistics.median(scores), 4) if scores else None,
+ pass_rate=round(sum(passed) / len(passed), 4) if passed else None,
+ build_ok_rate=round(sum(r.build_ok for r in rs) / len(rs), 4),
+ mean_gen_usd=round(statistics.fmean(r.gen_cost_usd for r in rs), 4),
+ mean_judge_usd=round(statistics.fmean(r.judge_cost_usd for r in rs), 4),
+ mean_minutes=round(statistics.fmean(r.wall_s for r in rs) / 60, 2),
+ tool_calls=sum(r.tool_calls for r in rs), errors=sum(1 for r in rs if r.status in ("error", "judge_error")),
+ ))
+ return sorted(out, key=lambda s: (s.kind != "harness", -(s.mean_score or -1)))
+
+
+def pair_stats(pairs: list[PairRow]) -> list[PairStats]:
+ groups: dict[tuple[str, str], list[PairRow]] = {}
+ for p in pairs:
+ groups.setdefault((p.arm_a, p.arm_b), []).append(p)
+ out = []
+ for (a, b), ps in groups.items():
+ wa, wb = sum(p.winner == "a" for p in ps), sum(p.winner == "b" for p in ps)
+ out.append(PairStats(arm_a=a, arm_b=b, n=len(ps), wins_a=wa, wins_b=wb, ties=len(ps) - wa - wb,
+ win_rate_a=round(wa / (wa + wb), 4) if wa + wb else None,
+ mean_confidence=round(statistics.fmean(p.confidence for p in ps), 3)))
+ return out
+
+
+# ----------------------------------------------------------------------------- markdown
+def _prompt_order(rows: list[CellResult], meta: dict) -> list[str]:
+ """Battery order, restricted to prompts that have at least one cell."""
+ seen = {r.prompt_id for r in rows}
+ ordered = [p["id"] for p in meta.get("battery", {}).get("prompts", []) if p["id"] in seen]
+ return ordered or sorted(seen)
+
+
+def _arm_order(rows: list[CellResult], meta: dict) -> list[str]:
+ """matrix.json arm order first, then any extra arms found in results (a later
+ partial re-run — e.g. gemini arms only — must not drop earlier arms' columns)."""
+ listed = [a for a in meta.get("arms", []) or []]
+ return listed + sorted({r.arm for r in rows} - set(listed))
+
+
+def _f(v: float | None, spec: str = ".3f") -> str:
+ return "-" if v is None else format(v, spec)
+
+
+def _cell_text(r: CellResult | None) -> str:
+ if r is None:
+ return "·"
+ if r.score is None:
+ return f"? ({r.status})"
+ flag = "" if r.build_ok else " ✗build"
+ return f"{r.score:.2f}{'✓' if r.passed else ''}{flag}"
+
+
+def compare_markdown(out: Path, rows: list[CellResult], pairs: list[PairRow], meta: dict) -> str:
+ opts = meta.get("options", {})
+ arms = _arm_order(rows, meta)
+ prompts = _prompt_order(rows, meta)
+ cells = {(r.prompt_id, r.arm): r for r in rows}
+ md = [f"# harness vs one-shot — {meta.get('battery', {}).get('name', out.name)}", "",
+ f"fixed judge: **{opts.get('judge', '?')}** (rubric static_object_v1, n_samples={opts.get('n_samples', 2)}, "
+ f"acceptance = must_have list) · harness loop judge: {opts.get('loop_judge') or 'settings default'} · "
+ f"harness rounds ≤ {opts.get('rounds', '?')}, ≤ ${opts.get('max_usd', '?')} · cells: {len(rows)}", "",
+ "Every arm's final `src/model.py` is re-built, re-rendered and judged by the same evaluator; a failed "
+ "build scores 0. `$gen` for harness arms is the whole run (planner + generator + its loop judge); for "
+ "one-shot arms it is the single call (subscription CLIs report 0 unless the CLI returns a cost).", "",
+ "## arms", "", "| arm | kind | n | mean | median | pass | build ok | $gen | $judge | min | tool calls | errors |",
+ "|---|---|---|---|---|---|---|---|---|---|---|---|"]
+ for s in arm_stats(rows):
+ md.append(f"| {s.arm} | {s.kind} | {s.n} | {_f(s.mean_score)} | {_f(s.median_score)} | {_f(s.pass_rate, '.0%')} | "
+ f"{s.build_ok_rate:.0%} | {s.mean_gen_usd:.2f} | {s.mean_judge_usd:.3f} | {s.mean_minutes:.1f} | "
+ f"{s.tool_calls} | {s.errors} |")
+ md += ["", "## per prompt (score, ✓ = passed, ✗build = build failed)", "",
+ "| prompt | tier | " + " | ".join(arms) + " |", "|---|---|" + "---|" * len(arms)]
+ for pid in prompts:
+ tier = next((r.tier for r in rows if r.prompt_id == pid), "")
+ md.append(f"| {pid} | {tier} | " + " | ".join(_cell_text(cells.get((pid, a))) for a in arms) + " |")
+ md += ["", "## pairwise arena (PairwiseJudge, both orders; ties = orderings disagree or equal)", "",
+ "| harness arm (A) | one-shot arm (B) | n | A wins | B wins | ties | A win rate | conf |", "|---|---|---|---|---|---|---|---|"]
+ for s in pair_stats(pairs):
+ md.append(f"| {s.arm_a} | {s.arm_b} | {s.n} | {s.wins_a} | {s.wins_b} | {s.ties} | {_f(s.win_rate_a, '.0%')} | {s.mean_confidence:.2f} |")
+ if pairs:
+ md += ["", "### pairwise verdicts", "", "| prompt | A | B | winner | conf | judged | reason |", "|---|---|---|---|---|---|---|"]
+ for p in sorted(pairs, key=lambda p: (p.prompt_id, p.arm_a, p.arm_b)):
+ md.append(f"| {p.prompt_id} | {p.arm_a} | {p.arm_b} | {p.winner} | {p.confidence:.2f} | {'yes' if p.judged else 'no'} | "
+ f"{html.escape((p.reasons[0] if p.reasons else p.error)[:160])} |")
+ hr = [r for r in rows if r.kind == "harness"]
+ if hr:
+ md += ["", "## harness runs (loop judge score vs fixed judge score)", "",
+ "| prompt | arm | run status | rounds | loop score | fixed score | $run | min |", "|---|---|---|---|---|---|---|---|"]
+ md += [f"| {r.prompt_id} | {r.arm} | {r.harness_status} | {r.harness_rounds} | {_f(r.harness_loop_score)} | {_f(r.score)} | "
+ f"{r.gen_cost_usd:.2f} | {r.wall_s / 60:.1f} |" for r in sorted(hr, key=lambda r: (r.prompt_id, r.arm))]
+ total_gen, total_judge, total_pw = sum(r.gen_cost_usd for r in rows), sum(r.judge_cost_usd for r in rows), sum(p.cost_usd for p in pairs)
+ md += ["", f"**Total cost**: generation ${total_gen:.2f} · fixed judge ${total_judge:.2f} · pairwise ${total_pw:.2f} "
+ f"(subscription CLIs report their own cost figure or 0)."]
+ errs = [r for r in rows if r.error]
+ if errs:
+ md += ["", "## errors", ""]
+ md += [f"- `{r.prompt_id}` / `{r.arm}` ({r.status}): {r.error.splitlines()[0][:300]}" for r in errs]
+ return "\n".join(md) + "\n"
+
+
+# ----------------------------------------------------------------------------- html gallery
+_STYLE = ("body{font-family:system-ui,sans-serif;margin:24px;background:#111;color:#eee}table{border-collapse:collapse;margin:12px 0}"
+ "td,th{border:1px solid #444;padding:4px 8px;font-size:13px;vertical-align:top}th{background:#222}"
+ ".g img{width:100%;display:block;border-radius:4px}.g td{min-width:260px;max-width:360px}.ok{color:#8f8}.bad{color:#f88}"
+ "pre{white-space:pre-wrap;font-size:11px;color:#bbb}")
+
+
+def compare_html(out: Path, rows: list[CellResult], pairs: list[PairRow], meta: dict) -> str:
+ assets = out / "report_assets"
+ assets.mkdir(exist_ok=True)
+ arms = _arm_order(rows, meta)
+ prompts = _prompt_order(rows, meta)
+ cells = {(r.prompt_id, r.arm): r for r in rows}
+ head = "<tr><th>arm</th><th>n</th><th>mean</th><th>pass</th><th>build ok</th><th>$gen</th><th>min</th></tr>"
+ summ = "".join(f"<tr><td>{html.escape(s.arm)}</td><td>{s.n}</td><td>{_f(s.mean_score)}</td><td>{_f(s.pass_rate, '.0%')}</td>"
+ f"<td>{s.build_ok_rate:.0%}</td><td>{s.mean_gen_usd:.2f}</td><td>{s.mean_minutes:.1f}</td></tr>" for s in arm_stats(rows))
+ pw = "".join(f"<tr><td>{html.escape(s.arm_a)}</td><td>{html.escape(s.arm_b)}</td><td>{s.wins_a}/{s.wins_b}/{s.ties}</td>"
+ f"<td>{_f(s.win_rate_a, '.0%')}</td></tr>" for s in pair_stats(pairs))
+ grid = ["<table class='g'><tr><th>prompt</th>" + "".join(f"<th>{html.escape(a)}</th>" for a in arms) + "</tr>"]
+ for pid in prompts:
+ tds = []
+ for a in arms:
+ r = cells.get((pid, a))
+ if r is None:
+ tds.append("<td>·</td>")
+ continue
+ img = ""
+ if r.sheet and Path(r.sheet).is_file():
+ dst = assets / f"{pid}__{a.replace(':', '_').replace('+', '_')}{Path(r.sheet).suffix}"
+ shutil.copy2(r.sheet, dst)
+ img = f"<img src='report_assets/{dst.name}' loading='lazy'>"
+ cls = "ok" if r.passed else "bad"
+ tds.append(f"<td>{img}<b class='{cls}'>{_f(r.score, '.2f')}</b> {'pass' if r.passed else r.status} · "
+ f"tris {r.tris or '-'} · ${r.gen_cost_usd:.2f} · {r.wall_s / 60:.1f} min"
+ f"{'<pre>' + html.escape(r.error[:300]) + '</pre>' if r.error else ''}</td>")
+ grid.append(f"<tr><td><b>{html.escape(pid)}</b></td>{''.join(tds)}</tr>")
+ grid.append("</table>")
+ name = meta.get("battery", {}).get("name", out.name)
+ return (f"<!doctype html><meta charset='utf-8'><title>compare {html.escape(name)}</title><style>{_STYLE}</style>"
+ f"<h1>harness vs one-shot — {html.escape(name)}</h1><p>fixed judge {html.escape(str(meta.get('options', {}).get('judge')))}</p>"
+ f"<table>{head}{summ}</table><h2>pairwise (A wins / B wins / ties)</h2><table><tr><th>A (harness)</th><th>B (one-shot)</th>"
+ f"<th>w/l/t</th><th>A win rate</th></tr>{pw}</table><h2>gallery</h2>{''.join(grid)}")
+
+
+def build_compare_report(out_dir: Path | str) -> tuple[str, str]:
+ out = Path(out_dir)
+ rows = list({(r.prompt_id, r.arm): r for r in load_jsonl(out / "results.jsonl", CellResult)}.values())
+ pairs = list({(p.prompt_id, p.arm_a, p.arm_b): p for p in load_jsonl(out / "pairwise.jsonl", PairRow)}.values())
+ meta = json.loads((out / "matrix.json").read_text()) if (out / "matrix.json").is_file() else {}
+ md = compare_markdown(out, rows, pairs, meta)
+ page = compare_html(out, rows, pairs, meta)
+ (out / "report.md").write_text(md)
+ (out / "report.html").write_text(page)
+ return md, page
+
+
+__all__ = ["ArmStats", "CellResult", "PairRow", "PairStats", "arm_stats", "build_compare_report", "load_jsonl", "pair_stats"]
diff --git a/harness/bench/_fixed_eval.py b/harness/bench/_fixed_eval.py
new file mode 100644
index 00000000..b37cdc8e
--- /dev/null
+++ b/harness/bench/_fixed_eval.py
@@ -0,0 +1,106 @@
+"""The fixed evaluator shared by every arm of ``bench/compare_backends.py``.
+
+``FixedEvaluator.evaluate(ws, spec)``: BlenderRuntime lint + build → ``measure_glb``
+→ connectivity gate → 8-view ``render_glb`` → ``VlmJudge(static_object_v1,
+<fixed judge>, n_samples)``. The judge's acceptance checklist is the brief's
+``must_have`` list (``acceptance_from_spec``) so harness and one-shot arms are
+scored against exactly the same checklist — never the harness's plan.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
+from codeverse.contracts.common import Language
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import OBJECT_VIEWS
+from codeverse.workspace import Workspace
+
+RUBRIC = "static_object_v1"
+
+
+def acceptance_from_spec(spec: Spec) -> list[AcceptanceItem]:
+ """The fixed judge's checklist: the brief's must_have items, identical for every arm."""
+ return [AcceptanceItem(id=f"must_{i + 1}", text=m, how="visual", priority="must")
+ for i, m in enumerate(spec.constraints.must_have)]
+
+
+# ----------------------------------------------------------------------------- fixed evaluator
+class EvalOutcome(BaseModel):
+ build: BuildResult
+ lint: GateReport
+ gates: list[GateReport] = Field(default_factory=list)
+ measurement: Measurement | None = None
+ renders: RenderSet | None = None
+ judgment: Judgment | None = None
+ error: str = ""
+
+ @property
+ def gate_errors(self) -> list[str]:
+ return [f"{g.gate}: {f.message}" for g in self.gates for f in g.errors]
+
+
+class FixedEvaluator:
+ """build → measure → connectivity → render → VlmJudge, the same for every arm."""
+
+ def __init__(self, judge_model: str, *, n_samples: int = 2, settings: Settings | None = None, rubric: str = RUBRIC):
+ self.judge_model = judge_model
+ self.n_samples = n_samples
+ self.settings = settings or get_settings()
+ self.rubric = rubric
+ self._runtime: Any = None
+ self._judge: Any = None
+
+ @property
+ def runtime(self) -> Any:
+ if self._runtime is None:
+ from codeverse.languages import get_runtime
+
+ self._runtime = get_runtime(Language.BLENDER)
+ return self._runtime
+
+ @property
+ def judge(self) -> Any:
+ if self._judge is None:
+ from codeverse.judges.vlm_judge import VlmJudge
+
+ self._judge = VlmJudge(rubric=self.rubric, model_id=self.judge_model, n_samples=self.n_samples)
+ return self._judge
+
+ def build(self, ws: Workspace) -> tuple[BuildResult, GateReport]:
+ lint = self.runtime.lint(ws)
+ build = self.runtime.build(ws, timeout_s=self.settings.limits.build_timeout_s)
+ return build, lint
+
+ def evaluate(self, ws: Workspace, spec: Spec) -> EvalOutcome:
+ from codeverse.judges.base import JudgeInput
+ from codeverse.spatial.connectivity import check_connectivity
+ from codeverse.spatial.measure import measure_glb
+ from codeverse.spatial.render import render_glb
+
+ build, lint = self.build(ws)
+ out = EvalOutcome(build=build, lint=lint, gates=[lint])
+ if not build.ok or not build.glb_path:
+ return out
+ try:
+ glb = Path(build.glb_path)
+ out.measurement = measure_glb(glb)
+ out.gates.append(check_connectivity(glb))
+ r = self.settings.render
+ out.renders = render_glb(glb, ws.renders_dir(0), views=list(OBJECT_VIEWS), width=r.width, height=r.height, sheet=True)
+ inp = JudgeInput(spec=spec, renders=out.renders, measurement=out.measurement, gates=out.gates,
+ acceptance=acceptance_from_spec(spec), round_index=0)
+ out.judgment = self.judge.judge(inp)
+ except Exception as e: # noqa: BLE001 — recorded per cell, never kills the matrix
+ out.error = f"{type(e).__name__}: {e}"
+ return out
+
+
+__all__ = ["RUBRIC", "EvalOutcome", "FixedEvaluator", "acceptance_from_spec"]
diff --git a/harness/bench/_oneshot.py b/harness/bench/_oneshot.py
new file mode 100644
index 00000000..162246da
--- /dev/null
+++ b/harness/bench/_oneshot.py
@@ -0,0 +1,329 @@
+"""One-shot generation backends for ``bench/compare_backends.py``.
+
+A one-shot arm gets ONE raw generation with no harness help: the model sees the
+prompt plus the *minimal* blender contract (file, frame, units, naming, no
+export/camera/lights) and must answer with the complete ``src/model.py``. No
+tools, no cookbook, no plan, no repair loop — the harness only builds, renders
+and judges whatever comes back.
+
+Backends (``get_oneshot_backend``):
+
+* ``claude-code`` / ``claude-code:<model>`` — ``claude -p`` with ``--tools ""``
+ and ``--max-turns 1`` (subscription; model default when none given).
+* ``codex`` / ``codex:<model>`` — ``codex exec`` read-only sandbox, JSONL events
+ (subscription; model default when none given).
+* ``gemini:<m>`` / ``anthropic:<m>`` / ``openai:<m>`` — ``codeverse.models``
+ chat model, one ``ChatRequest``.
+
+Every call runs in a scratch directory *outside* the repository so the CLIs
+cannot pick up CLAUDE.md / AGENTS.md context, and with secrets stripped from the
+environment (``hardened_env``-style), keeping only the CLI's own auth variable.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import tempfile
+import time
+from pathlib import Path
+from typing import Any, Protocol
+
+from pydantic import BaseModel, Field
+
+from codeverse.agents.claude_code import parse_claude_json, usage_from_envelope
+from codeverse.agents.cli_common import is_secret_env, tail
+from codeverse.agents.codex import parse_codex_jsonl
+from codeverse.agents.watchdog import run_with_watchdog
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.chat import ChatMessage, ChatRequest
+from codeverse.contracts.common import Usage
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import LANGUAGE_FRAME, frame_doc
+from codeverse.tracks.generation import MultiFileParseError, parse_multifile
+from codeverse.tracks.repair import format_error_report
+from codeverse.workspace import Workspace
+
+MODEL_FILE = "src/model.py"
+DEFAULT_TIMEOUT_S = 900.0
+IDLE_GRACE_S = 600.0
+
+# ----------------------------------------------------------------------------- contract
+#: The minimal contract: frame/units from conventions (never restated), file, naming, no export.
+_CONTRACT_BODY = """You write ONE file, `{model_file}`, in raw Blender Python (bpy, Blender 5.x API).
+The harness runs it headless (`blender -b --factory-startup --python <wrapper> -- --script {model_file}`)
+inside an EMPTIED scene (no default cube / camera / light) and then exports the result itself.
+
+Frame, units and placement: {frame} Build at real-world size.
+
+Naming: one mesh object per part, `obj.name` set to a unique PascalCase part name (e.g. `Seat`,
+`LegFrontLeft`); no auto-suffixed duplicates like `Leg.001`. Link every object to
+`bpy.context.scene.collection`. Every visible mesh gets a material (Principled BSDF base colour /
+roughness / metallic).
+
+Do NOT: create cameras or lights, touch render/world settings, call `bpy.ops.render.*`,
+`bpy.ops.export_*`, `bpy.ops.import_*`, `bpy.ops.wm.*`, read or write files, use the network, or
+import anything other than `bpy`, `bmesh`, `mathutils`, `math`, `random`. Keep the total under
+500k triangles and finish in under 120 s.
+
+The script must build the whole object when executed top-to-bottom (call your `main()` at module
+level). Make sure the code runs without errors in headless Blender — there is no second chance."""
+
+_OUTPUT_RULE = (f"You have NO tools in this session: you cannot write files, run Blender or inspect anything — "
+ f"the code must appear in your reply. Reply with the COMPLETE contents of `{MODEL_FILE}` as ONE "
+ f"```python fenced code block and nothing else (no prose before or after, no partial snippets).")
+
+
+def minimal_contract() -> str:
+ """Frame/units come from ``codeverse.conventions`` (the single source of truth)."""
+ return _CONTRACT_BODY.format(model_file=MODEL_FILE, frame=frame_doc(LANGUAGE_FRAME["blender"]))
+
+
+def oneshot_prompt(spec: Spec) -> str:
+ """The entire input of a one-shot arm: brief + constraints + minimal contract + output rule."""
+ c = spec.constraints
+ lines = [f"Model this object in raw bpy: {spec.prompt.strip()}"]
+ if c.dimensions_m:
+ lines.append("Dimensions (m): " + ", ".join(f"{k}={v:g}" for k, v in c.dimensions_m.items()))
+ if c.style:
+ lines.append(f"Style: {c.style}")
+ lines.extend(f"MUST HAVE: {m}" for m in c.must_have)
+ lines.extend(f"MUST NOT: {m}" for m in c.must_not)
+ return "\n".join(lines) + "\n\n" + minimal_contract() + "\n\n" + _OUTPUT_RULE
+
+
+def repair_prompt(spec: Spec, previous_code: str, build: BuildResult, lint: GateReport, attempt: int) -> str:
+ """Error-feedback retry (``oneshot+repair`` arm only): previous file + the build error report."""
+ report = format_error_report(build, lint)
+ return (oneshot_prompt(spec)
+ + f"\n\nYour previous attempt ({attempt}) did NOT build. Fix the error below (smallest correct change, "
+ f"keep every part) and return the COMPLETE corrected file.\n\nERROR REPORT:\n{report}\n\n"
+ f"PREVIOUS `{MODEL_FILE}`:\n```python\n{previous_code[:40_000]}\n```")
+
+
+# ----------------------------------------------------------------------------- results
+class OneShotResult(BaseModel):
+ ok: bool = Field(description="a non-empty answer came back (parsing happens later)")
+ text: str = ""
+ usage: Usage = Field(default_factory=Usage)
+ tool_calls: int = Field(default=0, description="tool/command calls the CLI reported (should be 0)")
+ notes: str = ""
+ duration_s: float = 0.0
+ transcript_dir: str = ""
+
+
+class OneShotBackend(Protocol):
+ id: str
+
+ def generate(self, prompt: str, *, out_dir: Path, timeout_s: float = DEFAULT_TIMEOUT_S,
+ label: str = "oneshot") -> OneShotResult: ...
+
+
+_TOOL_XML_CONTENT = re.compile(r'<parameter name="content">\n?(?P<body>.*?)</parameter>', re.S)
+
+
+def _strip_hallucinated_tool_xml(text: str) -> str:
+ """A tool-less CLI model sometimes "writes the file" as XML tool-call text; keep the largest file body."""
+ bodies = [m.group("body") for m in _TOOL_XML_CONTENT.finditer(text)]
+ if not bodies:
+ return text
+ body = max(bodies, key=len)
+ return body if "import bpy" in body else text
+
+
+def extract_model_file(text: str) -> str:
+ """The python file from a one-shot answer (tolerant: fenced block / bare code / FILE envelope /
+ hallucinated Write-tool XML)."""
+ files = parse_multifile(_strip_hallucinated_tool_xml(text), expected_files=[MODEL_FILE])
+ code = files.get(MODEL_FILE) or next(iter(files.values()), "")
+ if not code.strip():
+ raise MultiFileParseError("empty model file in the answer")
+ return code if code.endswith("\n") else code + "\n"
+
+
+def write_model_file(ws: Workspace, text: str) -> Path:
+ """Parse the answer and write ``src/model.py`` into the workspace (raises MultiFileParseError)."""
+ code = extract_model_file(text)
+ dest = ws.root / MODEL_FILE
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(code)
+ return dest
+
+
+# ----------------------------------------------------------------------------- common
+def _scratch_cwd(label: str) -> Path:
+ """A fresh directory outside any repo: no CLAUDE.md/AGENTS.md/.git context can leak in."""
+ return Path(tempfile.mkdtemp(prefix=f"cv3d_oneshot_{label}_"))
+
+
+def _clean_env(keep: set[str]) -> dict[str, str]:
+ env = {k: v for k, v in os.environ.items() if k in keep or not is_secret_env(k)}
+ env["CV3D_AGENT_CONTEXT"] = "1"
+ env["PYTHONUNBUFFERED"] = "1"
+ return env
+
+
+def _dump(out_dir: Path, prompt: str, argv: list[str], stdout: str, stderr: str) -> None:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / "prompt.md").write_text(prompt)
+ (out_dir / "argv.json").write_text(json.dumps([a if a != prompt else f"<prompt {len(prompt)} chars>" for a in argv]))
+ (out_dir / "stdout.txt").write_text(stdout)
+ (out_dir / "stderr.txt").write_text(stderr)
+
+
+# ----------------------------------------------------------------------------- claude -p
+class ClaudeOneShot:
+ """``claude -p`` with every tool disabled and a single turn."""
+
+ kind = "claude-code"
+
+ def __init__(self, model: str = "", binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.claude_cli
+ self.id = f"oneshot:{self.kind}" + (f":{model}" if model else "")
+
+ def argv(self, prompt: str) -> list[str]:
+ argv = [self.binary, "-p", prompt, "--output-format", "json", "--tools", "", "--max-turns", "1",
+ "--no-session-persistence", "--strict-mcp-config"]
+ if self.model:
+ argv += ["--model", self.model]
+ return argv
+
+ def generate(self, prompt: str, *, out_dir: Path, timeout_s: float = DEFAULT_TIMEOUT_S, label: str = "oneshot") -> OneShotResult:
+ cwd = _scratch_cwd("claude")
+ argv = self.argv(prompt)
+ proc = run_with_watchdog(argv, cwd=cwd, env=_clean_env({"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"}),
+ soft_timeout_s=timeout_s, idle_grace_s=IDLE_GRACE_S, activity_dirs=[cwd])
+ _dump(out_dir, prompt, argv, proc.stdout, proc.stderr)
+ env = parse_claude_json(proc.stdout)
+ usage = usage_from_envelope(env, self.model or "default") if env else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str((env or {}).get("result") or "")
+ notes = ""
+ ok = bool(text.strip()) and not proc.timed_out
+ if proc.timed_out:
+ notes = f"timeout after {proc.duration_s:.0f}s ({proc.killed_reason})"
+ elif env is None or proc.rc != 0:
+ notes = f"rc={proc.rc}; no result envelope; stderr: {tail(proc.stderr, 800)}"
+ ok = False
+ elif env.get("is_error"):
+ notes = f"claude is_error subtype={env.get('subtype', '')}: {tail(text, 400)}"
+ ok = False
+ (out_dir / "response.md").write_text(text)
+ return OneShotResult(ok=ok, text=text, usage=usage, tool_calls=usage.tool_calls, notes=notes,
+ duration_s=round(proc.duration_s, 2), transcript_dir=str(out_dir))
+
+
+# ----------------------------------------------------------------------------- codex exec
+def codex_default_model() -> str:
+ """The model ``codex`` will use when none is passed (``~/.codex/config.toml``), for labelling/pricing."""
+ try:
+ import tomllib
+
+ cfg = tomllib.loads((Path.home() / ".codex" / "config.toml").read_text())
+ return str(cfg.get("model") or "")
+ except Exception: # noqa: BLE001 — label only
+ return ""
+
+
+class CodexOneShot:
+ """``codex exec`` in a read-only sandbox on an empty scratch dir (no files to read, nothing to run)."""
+
+ kind = "codex"
+
+ def __init__(self, model: str = "", binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.codex_cli
+ self.id = f"oneshot:{self.kind}" + (f":{model}" if model else "")
+
+ def argv(self, cwd: Path, last_msg: Path) -> list[str]:
+ argv = [self.binary, "exec", "--json", "-C", str(cwd), "--sandbox", "read-only", "--skip-git-repo-check",
+ "--ephemeral", "--color", "never", "-o", str(last_msg)]
+ if self.model:
+ argv += ["--model", self.model]
+ argv.append("-") # prompt on stdin
+ return argv
+
+ def generate(self, prompt: str, *, out_dir: Path, timeout_s: float = DEFAULT_TIMEOUT_S, label: str = "oneshot") -> OneShotResult:
+ cwd = _scratch_cwd("codex")
+ out_dir.mkdir(parents=True, exist_ok=True)
+ last_msg = out_dir / "last_message.md"
+ argv = self.argv(cwd, last_msg)
+ proc = run_with_watchdog(argv, cwd=cwd, env=_clean_env({"OPENAI_API_KEY", "CODEX_API_KEY"}), soft_timeout_s=timeout_s,
+ idle_grace_s=IDLE_GRACE_S, stdin=prompt, activity_dirs=[cwd])
+ _dump(out_dir, prompt, argv, proc.stdout, proc.stderr)
+ events = parse_codex_jsonl(proc.stdout)
+ text = last_msg.read_text() if last_msg.is_file() else "\n\n".join(m for m in events.messages if m.strip())
+ usage = events.usage(self.model or codex_default_model() or "default")
+ usage.latency_ms = int(proc.duration_s * 1000)
+ notes = "; ".join(events.errors[:3])
+ ok = bool(text.strip()) and not proc.timed_out
+ if proc.timed_out:
+ notes = f"timeout after {proc.duration_s:.0f}s ({proc.killed_reason})"
+ elif proc.rc != 0 or events.n_events == 0:
+ notes = f"rc={proc.rc}; events={events.n_events}; stderr: {tail(proc.stderr, 800)}"
+ ok = ok and events.n_events > 0
+ (out_dir / "response.md").write_text(text)
+ return OneShotResult(ok=ok, text=text, usage=usage, tool_calls=events.tool_calls, notes=notes,
+ duration_s=round(proc.duration_s, 2), transcript_dir=str(out_dir))
+
+
+# ----------------------------------------------------------------------------- API chat model
+class ApiOneShot:
+ """One ``ChatRequest`` through ``codeverse.models`` (``gemini:*`` / ``anthropic:*`` / ``openai:*``)."""
+
+ kind = "api"
+
+ def __init__(self, model_id: str, *, chat_model: Any | None = None, temperature: float = 0.5,
+ thinking: str = "medium", max_output_tokens: int = 32000):
+ self.model_id = model_id
+ self.id = f"oneshot:{model_id}"
+ self._model = chat_model
+ self.temperature = temperature
+ self.thinking = thinking
+ self.max_output_tokens = max_output_tokens
+
+ @property
+ def model(self) -> Any:
+ if self._model is None:
+ from codeverse.models import get_chat_model
+
+ self._model = get_chat_model(self.model_id)
+ return self._model
+
+ def generate(self, prompt: str, *, out_dir: Path, timeout_s: float = DEFAULT_TIMEOUT_S, label: str = "oneshot") -> OneShotResult:
+ t0 = time.time()
+ req = ChatRequest(messages=[ChatMessage.user(prompt)], system="You are an expert Blender (bpy) modeller writing raw code.",
+ temperature=self.temperature, thinking=self.thinking, # type: ignore[arg-type]
+ max_output_tokens=self.max_output_tokens, label=label)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / "prompt.md").write_text(prompt)
+ try:
+ resp = self.model.generate(req)
+ except Exception as e: # noqa: BLE001 — a model outage is a recorded failure, not a crash
+ return OneShotResult(ok=False, notes=f"{type(e).__name__}: {e}", duration_s=round(time.time() - t0, 2),
+ transcript_dir=str(out_dir))
+ text = resp.text or ""
+ (out_dir / "response.md").write_text(text)
+ return OneShotResult(ok=bool(text.strip()), text=text, usage=resp.usage, duration_s=round(time.time() - t0, 2),
+ transcript_dir=str(out_dir))
+
+
+# ----------------------------------------------------------------------------- registry
+def get_oneshot_backend(target: str) -> OneShotBackend:
+ """``claude-code[:model]`` · ``codex[:model]`` · ``<provider>:<model>`` (API)."""
+ kind, _, model = target.partition(":")
+ if kind == "claude-code":
+ return ClaudeOneShot(model)
+ if kind == "codex":
+ return CodexOneShot(model)
+ if kind in ("gemini", "anthropic", "openai") and model:
+ return ApiOneShot(target)
+ raise ValueError(f"unknown one-shot target {target!r}; expected claude-code[:m], codex[:m] or <gemini|anthropic|openai>:<model>")
+
+
+__all__ = ["ApiOneShot", "ClaudeOneShot", "CodexOneShot", "MODEL_FILE", "OneShotBackend", "OneShotResult",
+ "extract_model_file", "get_oneshot_backend", "minimal_contract", "oneshot_prompt", "repair_prompt",
+ "write_model_file"]
diff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.py
new file mode 100644
index 00000000..87c7c12a
--- /dev/null
+++ b/harness/bench/compare_backends.py
@@ -0,0 +1,399 @@
+"""Harness vs raw one-shot generation under ONE fixed judge (methodology bench).
+
+ python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \\
+ --arms harness:api-agent:gemini:gemini-3.7-flash,harness:gemini-cli:gemini-3.7-flash,\\
+oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash \\
+ --judge gemini:gemini-3.1-pro-preview --out <dir> [--parallel 3] [--limit N]
+
+Arms
+* ``harness:<generator-id>`` — the full static_object track (plan → generate →
+ build/repair → gates → render → judge → refine, rounds ≤ 3, ≤ $2.5). Its
+ in-loop judge is ``--loop-judge`` (default: the settings default, flash); the
+ loop's own score is NOT the reported score.
+* ``oneshot:<x>`` — ONE raw generation (prompt + minimal contract, no tools, no
+ cookbook, no plan, no repair). ``x`` ∈ ``claude-code[:m]`` · ``codex[:m]`` ·
+ ``gemini|anthropic|openai:<m>``.
+* ``oneshot+repair:<x>`` — same, plus ≤ ``--repair-attempts`` error-feedback
+ retries on build failure (clearly labelled; never judge feedback).
+
+Every arm ends with a ``src/model.py`` that is copied into a fresh eval workspace
+and scored by the SAME fixed evaluator: BlenderRuntime lint+build → measure →
+connectivity gate → 8-view ``render_glb`` → ``VlmJudge(static_object_v1, judge,
+n_samples=2)`` whose acceptance checklist is the battery's ``must_have`` list.
+A failed build (or unparseable answer) scores 0 with the error recorded. Then a
+pairwise arena (``PairwiseJudge``, same judge model, both orders) runs every
+harness arm against every one-shot arm per prompt.
+
+Layout of ``--out``: ``matrix.json`` · ``results.jsonl`` (cells; resume source) ·
+``pairwise.jsonl`` · ``cells/<prompt>/<arm>/{run,gen,eval}`` · ``report.md`` ·
+``report.html`` (+ ``report_assets/``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import sys
+import time
+import traceback
+from collections.abc import Callable, Sequence
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+REPO = Path(__file__).resolve().parents[1]
+if str(REPO) not in sys.path: # `python bench/compare_backends.py` from anywhere
+ sys.path.insert(0, str(REPO))
+
+from bench._compare_report import ( # noqa: E402
+ CellResult,
+ PairRow,
+ build_compare_report,
+ load_jsonl,
+)
+from bench._fixed_eval import RUBRIC, EvalOutcome, FixedEvaluator # noqa: E402
+from bench._oneshot import ( # noqa: E402
+ MODEL_FILE,
+ OneShotBackend,
+ OneShotResult,
+ get_oneshot_backend,
+ oneshot_prompt,
+ repair_prompt,
+ write_model_file,
+)
+from bench.run_bench import Battery, BenchPrompt # noqa: E402
+from codeverse.config import get_settings # noqa: E402
+from codeverse.contracts.artifacts import RenderSet # noqa: E402
+from codeverse.contracts.common import Backends, Budget # noqa: E402
+from codeverse.contracts.run import RunRecord # 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
+
+ArmKind = Literal["harness", "oneshot", "oneshot+repair"]
+
+
+# ----------------------------------------------------------------------------- arms / options
+class Arm(BaseModel):
+ raw: str
+ kind: ArmKind
+ target: str = Field(description="generator id (harness) or one-shot target")
+
+ @property
+ def slug(self) -> str:
+ return self.raw.replace("+", "_plus_").replace(":", "_").replace("/", "_")
+
+
+def parse_arm(text: str) -> Arm:
+ kind, sep, target = text.strip().partition(":")
+ if not sep or not target or kind not in ("harness", "oneshot", "oneshot+repair"):
+ raise ValueError(f"bad arm {text!r}: expected harness:<generator-id> | oneshot:<target> | oneshot+repair:<target>")
+ if kind != "harness":
+ get_oneshot_backend(target) # validates the target early
+ return Arm(raw=text.strip(), kind=kind, target=target) # type: ignore[arg-type]
+
+
+def parse_arms(text: str) -> list[Arm]:
+ arms = [parse_arm(t) for t in text.split(",") if t.strip()]
+ if not arms:
+ raise ValueError("no arms given")
+ if len({a.raw for a in arms}) != len(arms):
+ raise ValueError("duplicate arms")
+ return arms
+
+
+class CompareOptions(BaseModel):
+ judge: str = "gemini:gemini-3.1-pro-preview"
+ loop_judge: str | None = Field(default=None, description="harness in-loop judge (None → settings default)")
+ planner: str | None = None
+ rounds: int = 3
+ max_usd: float = 2.5
+ max_minutes: float = 45.0
+ parallel: int = 3
+ limit: int | None = None
+ ids: list[str] = Field(default_factory=list)
+ resume: bool = True
+ gen_timeout_s: float = 900.0
+ repair_attempts: int = 2
+ n_samples: int = 2
+ pairwise: bool = True
+ redo_status: list[str] = Field(default_factory=list, description="re-run cells whose status is one of these")
+
+
+def spec_for(battery: Battery, item: BenchPrompt, arm: Arm, opts: CompareOptions) -> Spec:
+ generator = arm.target if arm.kind == "harness" else f"single-shot:{arm.target}"
+ backends = Backends(generator=generator, judge=opts.loop_judge or get_settings().default_judge,
+ planner=opts.planner or get_settings().default_planner)
+ return Spec(id=f"{battery.name}/{item.id}", track=battery.track, language=battery.language, prompt=item.prompt,
+ constraints=Constraints(must_have=list(item.must_have), dimensions_m=item.dimensions_m),
+ budget=Budget(max_rounds=opts.rounds, max_usd=opts.max_usd, max_minutes=opts.max_minutes),
+ backends=backends, tags=["compare", battery.name, item.tier, item.category, arm.kind, *item.tags])
+
+
+# ----------------------------------------------------------------------------- deps (fakeable seams)
+RunTrackFn = Callable[[Spec, Workspace, bool], RunRecord]
+
+
+class CompareDeps:
+ """Everything that touches a model / Blender / Chrome; tests swap these for fakes."""
+
+ def __init__(self, evaluator: FixedEvaluator | Any, *, run_track: RunTrackFn | None = None,
+ oneshot_backend: Callable[[str], OneShotBackend] | None = None,
+ pairwise_judge: Callable[[str], Any] | None = None):
+ self.evaluator = evaluator
+ self.run_track = run_track or _default_run_track
+ self.oneshot_backend = oneshot_backend or get_oneshot_backend
+ self.pairwise_judge = pairwise_judge or _default_pairwise
+
+
+def _default_run_track(spec: Spec, ws: Workspace, resume: bool) -> RunRecord:
+ from codeverse.tracks import get_track
+
+ return get_track(spec.track).run(spec, ws, resume=resume)
+
+
+def _default_pairwise(model_id: str) -> Any:
+ from codeverse.judges.pairwise import PairwiseJudge
+
+ return PairwiseJudge(model_id)
+
+
+# ----------------------------------------------------------------------------- one cell
+def _fresh_ws(path: Path) -> Workspace:
+ if path.exists():
+ shutil.rmtree(path)
+ return Workspace(path).create()
+
+
+def _generate_oneshot(arm: Arm, spec: Spec, cell: Path, eval_ws: Workspace, opts: CompareOptions,
+ deps: CompareDeps, res: CellResult) -> None:
+ backend = deps.oneshot_backend(arm.target)
+ prompt = oneshot_prompt(spec)
+ max_attempts = 1 + (opts.repair_attempts if arm.kind == "oneshot+repair" else 0)
+ for attempt in range(max_attempts):
+ gen_dir = cell / "gen" / f"attempt{attempt}"
+ cached = gen_dir / "result.json"
+ if opts.resume and cached.is_file(): # a redo re-uses the recorded answer: no second subscription call
+ gen = OneShotResult.model_validate_json(cached.read_text())
+ else:
+ gen = backend.generate(prompt, out_dir=gen_dir, timeout_s=opts.gen_timeout_s, label=f"oneshot_{spec.id.split('/')[-1]}")
+ if gen.ok: # failures (timeouts, 5xx) are not cached so a redo regenerates
+ gen_dir.mkdir(parents=True, exist_ok=True)
+ cached.write_text(gen.model_dump_json(indent=1))
+ res.attempts = attempt + 1
+ res.gen_cost_usd += gen.usage.cost_usd
+ res.tool_calls += gen.tool_calls
+ res.gen_seconds += gen.duration_s
+ if not gen.ok:
+ res.error = gen.notes or "empty answer"
+ return
+ try:
+ write_model_file(eval_ws, gen.text)
+ except MultiFileParseError as e:
+ res.error = f"unparseable answer: {e}"
+ return
+ res.error = ""
+ if attempt + 1 >= max_attempts:
+ return
+ build, lint = deps.evaluator.build(eval_ws) # 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)
+
+
+def _run_harness(spec: Spec, cell: Path, eval_ws: Workspace, deps: CompareDeps, res: CellResult) -> None:
+ run_ws = Workspace(cell / "run")
+ resume = run_ws.exists()
+ if not resume:
+ run_ws.create()
+ run_ws.write_json(run_ws.spec_path, spec)
+ rec = deps.run_track(spec, run_ws, resume)
+ 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
+ if not (run_ws.root / MODEL_FILE).is_file():
+ res.error = f"harness run produced no {MODEL_FILE} (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"))
+
+
+def run_cell(battery: Battery, item: BenchPrompt, arm: Arm, out: Path, opts: CompareOptions, deps: CompareDeps) -> CellResult:
+ cell = out / "cells" / item.id / arm.slug
+ cell.mkdir(parents=True, exist_ok=True)
+ spec = spec_for(battery, item, arm, opts)
+ res = CellResult(prompt_id=item.id, tier=item.tier, arm=arm.raw, kind=arm.kind, target=arm.target,
+ judge=opts.judge, workspace=str(cell))
+ t0 = time.time()
+ eval_ws = _fresh_ws(cell / "eval")
+ eval_ws.write_json(eval_ws.spec_path, spec)
+ try:
+ if arm.kind == "harness":
+ _run_harness(spec, cell, eval_ws, deps, res)
+ else:
+ _generate_oneshot(arm, spec, cell, eval_ws, opts, deps, res)
+ if (eval_ws.root / MODEL_FILE).is_file():
+ outcome = deps.evaluator.evaluate(eval_ws, spec)
+ eval_ws.write_json(eval_ws.root / "eval.json", outcome)
+ _fill_from_outcome(res, outcome)
+ else:
+ res.status, res.score, res.passed, res.build_ok = "no_code", 0.0, False, False
+ except Exception as e: # noqa: BLE001 — one cell must never kill the matrix
+ res.status = "error"
+ res.error = (res.error + "; " if res.error else "") + f"{type(e).__name__}: {e}\n{traceback.format_exc()[-1200:]}"
+ res.wall_s = round(time.time() - t0, 1)
+ eval_ws.write_json(cell / "cell.json", res)
+ return res
+
+
+def _fill_from_outcome(res: CellResult, o: EvalOutcome) -> None:
+ res.build_ok = o.build.ok
+ res.gate_errors = o.gate_errors
+ res.tris = o.measurement.tri_count if o.measurement else None
+ res.sheet = (o.renders.contact_sheet or "") if o.renders else ""
+ res.glb = o.build.glb_path or ""
+ if not o.build.ok:
+ res.status, res.score, res.passed = "build_failed", 0.0, False
+ res.error = (res.error + "; " if res.error else "") + f"{o.build.error_type}: {o.build.error_message[:400]}"
+ return
+ j = o.judgment
+ if j is None or j.n_samples == 0:
+ res.status, res.score, res.passed = "judge_error", None, None
+ res.error = (res.error + "; " if res.error else "") + (o.error or (j.summary if j else "no judgment"))[:400]
+ return
+ res.judge_cost_usd = j.usage.cost_usd
+ res.score, res.passed, res.score_std, res.status = j.overall, j.passed, j.score_std, "scored"
+ res.criteria = {k: round(v, 3) for k, v in j.scores.items()}
+
+
+# ----------------------------------------------------------------------------- pairwise arena
+def _renders_of(out: Path, r: CellResult) -> RenderSet | None:
+ p = Path(r.workspace) / "eval" / "eval.json"
+ if not p.is_file():
+ return None
+ o = EvalOutcome.model_validate(json.loads(p.read_text()))
+ return o.renders if o.renders and o.renders.views else None
+
+
+def run_pairwise(battery: Battery, cells: dict[tuple[str, str], CellResult], arms: Sequence[Arm], out: Path,
+ opts: CompareOptions, deps: CompareDeps) -> list[PairRow]:
+ path = out / "pairwise.jsonl"
+ done = {(p.prompt_id, p.arm_a, p.arm_b): p for p in load_jsonl(path, PairRow)} if opts.resume else {}
+ harness = [a for a in arms if a.kind == "harness"]
+ oneshot = [a for a in arms if a.kind != "harness"]
+ judge = None
+ with path.open("a") as fh:
+ for item in battery.prompts:
+ for ha in harness:
+ for oa in oneshot:
+ key = (item.id, ha.raw, oa.raw)
+ ca, cb = cells.get((item.id, ha.raw)), cells.get((item.id, oa.raw))
+ if key in done or ca is None or cb is None:
+ continue
+ spec = spec_for(battery, item, ha, opts)
+ ra, rb = _renders_of(out, ca), _renders_of(out, cb)
+ if ra is None or rb is None:
+ winner = "tie" if ra is None and rb is None else ("a" if rb is None else "b")
+ row = PairRow(prompt_id=item.id, arm_a=ha.raw, arm_b=oa.raw, winner=winner, confidence=1.0,
+ reasons=["decided without the judge: a side has no renders (build failed)"], judged=False)
+ else:
+ judge = judge or deps.pairwise_judge(opts.judge)
+ pr = judge.compare(spec, ra, rb, rubric=RUBRIC)
+ row = PairRow(prompt_id=item.id, arm_a=ha.raw, arm_b=oa.raw, winner=pr.winner, confidence=pr.confidence,
+ reasons=list(pr.reasons), orderings=list(pr.orderings), cost_usd=pr.usage.cost_usd,
+ error=pr.error, judged=True)
+ done[key] = row
+ fh.write(row.model_dump_json() + "\n")
+ fh.flush()
+ return list(done.values())
+
+
+# ----------------------------------------------------------------------------- matrix
+def _drop_pairs(path: Path, key: tuple[str, str]) -> None:
+ """Forget pairwise rows touching a cell that is about to be re-run."""
+ rows = [p for p in load_jsonl(path, PairRow) if not (p.prompt_id == key[0] and key[1] in (p.arm_a, p.arm_b))]
+ if path.is_file():
+ path.write_text("".join(p.model_dump_json() + "\n" for p in rows))
+
+
+def _select(battery: Battery, opts: CompareOptions) -> list[BenchPrompt]:
+ items = [p for p in battery.prompts if not opts.ids or p.id in set(opts.ids)]
+ return items[: opts.limit] if opts.limit is not None else items
+
+
+def run_matrix(battery_path: Path | str, out_dir: Path | str, arms: Sequence[Arm], opts: CompareOptions,
+ deps: CompareDeps, *, on_result: Callable[[CellResult], None] | None = None) -> list[CellResult]:
+ battery = Battery.load(battery_path)
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "matrix.json").write_text(json.dumps({"battery": battery.model_dump(mode="json"), "arms": [a.raw for a in arms],
+ "options": opts.model_dump(mode="json"),
+ "started_at": datetime.now(UTC).isoformat()}, indent=2))
+ results = out / "results.jsonl"
+ done = {(r.prompt_id, r.arm): r for r in load_jsonl(results, CellResult)} if opts.resume else {}
+ for key in [k for k, r in done.items() if r.status in set(opts.redo_status)]:
+ _drop_pairs(out / "pairwise.jsonl", key)
+ del done[key]
+ todo = [(p, a) for a in sorted(arms, key=lambda a: a.kind == "harness") # cheap one-shots first
+ for p in _select(battery, opts) if (p.id, a.raw) not in done]
+ with ThreadPoolExecutor(max_workers=max(1, opts.parallel)) as pool, results.open("a") as fh:
+ futs = {pool.submit(run_cell, battery, p, a, out, opts, deps): (p, a) for p, a in todo}
+ for fut in as_completed(futs):
+ r = fut.result()
+ done[(r.prompt_id, r.arm)] = r
+ fh.write(r.model_dump_json() + "\n")
+ fh.flush()
+ if on_result:
+ on_result(r)
+ if opts.pairwise:
+ run_pairwise(battery, done, arms, out, opts, deps)
+ build_compare_report(out)
+ return list(done.values())
+
+
+# ----------------------------------------------------------------------------- CLI
+def main(argv: Sequence[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("--prompts", required=True)
+ ap.add_argument("--arms", required=True, help="comma-separated arm ids")
+ ap.add_argument("--judge", default="gemini:gemini-3.1-pro-preview", help="FIXED judge model id")
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--parallel", type=int, default=3)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--ids", default="", help="comma-separated prompt ids")
+ ap.add_argument("--rounds", type=int, default=3)
+ ap.add_argument("--max-usd", type=float, default=2.5)
+ ap.add_argument("--loop-judge", default=None, help="harness in-loop judge (default: settings default)")
+ ap.add_argument("--repair-attempts", type=int, default=2)
+ ap.add_argument("--gen-timeout", type=float, default=900.0)
+ ap.add_argument("--no-pairwise", action="store_true")
+ ap.add_argument("--redo-status", default="", help="comma list of statuses to re-run (error,no_code,build_failed,judge_error); "
+ "recorded one-shot answers are re-used, not re-generated")
+ ap.add_argument("--no-resume", action="store_true")
+ ap.add_argument("--report-only", action="store_true", help="only rebuild report.md/html from results")
+ ns = ap.parse_args(argv)
+ if ns.report_only:
+ build_compare_report(Path(ns.out))
+ return 0
+ opts = CompareOptions(judge=ns.judge, loop_judge=ns.loop_judge, rounds=ns.rounds, max_usd=ns.max_usd, parallel=ns.parallel,
+ limit=ns.limit, ids=[i for i in ns.ids.split(",") if i], resume=not ns.no_resume,
+ gen_timeout_s=ns.gen_timeout, repair_attempts=ns.repair_attempts, pairwise=not ns.no_pairwise,
+ redo_status=[x for x in ns.redo_status.split(",") if x])
+ arms = parse_arms(ns.arms)
+ deps = CompareDeps(FixedEvaluator(opts.judge, n_samples=opts.n_samples))
+
+ def _log(r: CellResult) -> None:
+ print(f"[{datetime.now().strftime('%H:%M:%S')}] {r.prompt_id:28s} {r.arm:44s} score={r.score} build_ok={r.build_ok} "
+ f"${r.gen_cost_usd:.2f} {r.wall_s / 60:.1f}min {r.status} {r.error[:80]!r}", flush=True)
+
+ run_matrix(ns.prompts, ns.out, arms, opts, deps, on_result=_log)
+ print(f"report: {Path(ns.out) / 'report.md'}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/harness/bench/prompts/compare_v1.yaml b/harness/bench/prompts/compare_v1.yaml
new file mode 100644
index 00000000..c1d97913
--- /dev/null
+++ b/harness/bench/prompts/compare_v1.yaml
@@ -0,0 +1,50 @@
+name: compare_v1
+track: static_object
+language: blender
+description: >
+ 8 static-object prompts (blender / bpy) used to compare the harness loop against
+ raw one-shot generation by strong models under ONE fixed judge. Tiers: 2 easy,
+ 3 medium, 3 hard. must_have items become the fixed judge's acceptance checklist
+ for EVERY arm (no plan-derived items, so harness and one-shot are judged alike).
+prompts:
+ - id: cmp_easy_stool
+ tier: easy
+ category: furniture
+ prompt: a simple three-legged round wooden stool, 45 cm tall
+ must_have: [round seat, three splayed legs of equal length, legs touch the ground]
+ dimensions_m: {height: 0.45}
+ - id: cmp_easy_desk_lamp
+ tier: easy
+ category: lighting
+ prompt: a desk lamp with a heavy round base, a single angled arm and a conical metal shade
+ must_have: [round base on the ground, one straight arm leaning forward, conical shade at the top of the arm, shade opens downward]
+ - id: cmp_med_dining_chair
+ tier: medium
+ category: furniture
+ prompt: a wooden dining chair with a gently curved backrest, a flat seat and four tapered legs
+ must_have: [four tapered legs touching the ground, flat seat slab, backrest visibly curved in plan view, back legs continue up into the backrest posts]
+ - id: cmp_med_wheelbarrow
+ tier: medium
+ category: garden
+ prompt: a garden wheelbarrow with a sheet-metal tray, one front wheel, two straight handles and two rear legs
+ must_have: [open tray with sloped front, single front wheel with a hub, two parallel handles at the back, two rear legs reaching the ground]
+ - id: cmp_med_espresso_machine
+ tier: medium
+ category: appliances
+ prompt: a home espresso machine with a boxy body, a portafilter group head at the front, a steam wand on the right side and a drip tray
+ must_have: [boxy body, group head with a portafilter handle at the front, steam wand on the right side, drip tray at the bottom front, cup warmer top surface]
+ - id: cmp_hard_bicycle
+ tier: hard
+ category: vehicles
+ prompt: a vintage bicycle with a diamond frame, two spoked wheels, handlebars, saddle, pedals with a chainring and a rear rack
+ must_have: [two equal wheels with spokes, diamond frame tubes connecting the wheels, saddle above the rear wheel, handlebars above the front wheel, chainring and pedals between the wheels, rear luggage rack]
+ - id: cmp_hard_acoustic_guitar
+ tier: hard
+ category: instruments
+ prompt: an acoustic guitar standing upright on a small floor stand, with a waisted body, a round sound hole, a fretted neck with a headstock and six tuning pegs
+ must_have: [waisted hourglass body, round sound hole, neck with frets, headstock with six tuning pegs, bridge on the body, stand holding the guitar upright on the ground]
+ - id: cmp_hard_sailboat
+ tier: hard
+ category: vehicles
+ prompt: a small wooden sailboat on a display cradle, with a hull, a keel, one mast with a boom and a triangular mainsail, a rudder and a tiller
+ must_have: [hull with a pointed bow, keel under the hull, single mast with a boom, triangular mainsail, rudder and tiller at the stern, cradle keeping the boat upright on the ground]
diff --git a/harness/bench/report.py b/harness/bench/report.py
index b4cd5599..bd0fb3f7 100644
--- a/harness/bench/report.py
+++ b/harness/bench/report.py
@@ -2,14 +2,14 @@
``build_report(out_dir)`` reads ``results.jsonl`` (or results.json), aggregates
mean/median/pass-rate/cost per tier and category, writes ``report.md`` and
-``report.html`` (contact sheets copied into ``report_assets/``).
+``report.html`` — the same self-contained gallery as ``3dcv flywheel gallery``
+(``codeverse.flywheel.gallery``) with the stats tables above the cards.
"""
from __future__ import annotations
import html
import json
-import shutil
import statistics
from pathlib import Path
from typing import Any
@@ -17,6 +17,9 @@ from typing import Any
from pydantic import BaseModel, Field
from bench.run_bench import BenchItemResult
+from codeverse.flywheel.gallery import GalleryItem, item_from_run, render_gallery
+from codeverse.flywheel.record import RecordError, load_record
+from codeverse.workspace import Workspace
TIER_ORDER = {"easy": 0, "medium": 1, "hard": 2}
@@ -101,21 +104,27 @@ def _md_table(title: str, stats: list[GroupStats]) -> str:
return "\n".join(lines) + "\n"
-def _sheet_for(r: BenchItemResult) -> Path | None:
- ws = Path(r.workspace) if r.workspace else None
- if ws is None or not (ws / "record.json").is_file():
- return None
- try:
- rec = json.loads((ws / "record.json").read_text())
- except ValueError:
- return None
- best = rec.get("best_round")
- for rnd in rec.get("rounds", []):
- if rnd.get("index") == best and rnd.get("renders") and rnd["renders"].get("contact_sheet"):
- p = Path(rnd["renders"]["contact_sheet"])
- p = p if p.is_absolute() else ws / p
- return p if p.is_file() else None
- return None
+def _item_for(r: BenchItemResult) -> GalleryItem:
+ """Gallery card for one bench result: the run record when the workspace has one,
+ else a card built from the result row alone (errors, never-started runs)."""
+ ws_path = Path(r.workspace) if r.workspace else None
+ if ws_path is not None and (ws_path / "record.json").is_file():
+ try:
+ item = item_from_run(Workspace(ws_path), load_record(ws_path))
+ except RecordError:
+ item = None
+ if item is not None:
+ item.key = r.id
+ item.group = f"{r.tier} · {r.category}" if r.category else r.tier
+ item.minutes = r.minutes or item.minutes
+ item.error = item.error or r.errors
+ return item
+ return GalleryItem(
+ key=r.id, title=r.id, group=f"{r.tier} · {r.category}" if r.category else r.tier,
+ generator=r.generator, judge=r.judge, score=r.score_final, baseline_score=r.score_baseline,
+ passed=r.passed, rounds=r.rounds, cost_usd=r.cost_usd, minutes=r.minutes, status=r.status,
+ error=r.errors, links={"workspace": r.workspace} if r.workspace else {},
+ )
def build_report(out_dir: Path | str, *, title: str | None = None) -> BenchReport:
@@ -144,41 +153,23 @@ def build_report(out_dir: Path | str, *, title: str | None = None) -> BenchRepor
return rep
+def _html_table(stats: list[GroupStats]) -> str:
+ rows = "".join(
+ f"<tr><td>{html.escape(s.group)}</td><td>{s.n}</td><td>{_fmt(s.baseline_mean)}</td><td>{_fmt(s.final_mean)}</td>"
+ f"<td>{_fmt(s.delta_mean, '+.3f')}</td><td>{_fmt(s.pass_rate, '.0%')}</td><td>{s.cost_mean:.2f}</td>"
+ f"<td>{s.minutes_mean:.1f}</td><td>{s.errors}</td></tr>"
+ for s in stats
+ )
+ return ("<table><tr><th>group</th><th>n</th><th>baseline</th><th>final</th><th>Δ</th><th>pass</th><th>$/run</th>"
+ f"<th>min/run</th><th>errors</th></tr>{rows}</table>")
+
+
def _html_gallery(out: Path, name: str, results: list[BenchItemResult], rep: BenchReport) -> str:
- assets = out / "report_assets"
- assets.mkdir(exist_ok=True)
- cards = []
- for r in results:
- sheet = _sheet_for(r)
- img = ""
- if sheet is not None:
- dst = assets / f"{r.id}{sheet.suffix}"
- shutil.copy2(sheet, dst)
- img = f'<img src="report_assets/{dst.name}" loading="lazy">'
- badge = "pass" if r.passed else ("fail" if r.passed is False else "na")
- cards.append(
- f'<div class="card {badge}">{img}<div class="meta"><b>{html.escape(r.id)}</b> · {html.escape(r.tier)} · '
- f'{html.escape(r.category)}<br>baseline {_fmt(r.score_baseline)} → final {_fmt(r.score_final)} · '
- f'rounds {r.rounds} · ${r.cost_usd:.2f} · {r.minutes:.1f} min · {html.escape(r.status)}'
- f'{"<br><span class=err>" + html.escape(r.errors[:200]) + "</span>" if r.errors else ""}</div></div>'
- )
-
- def _rows(stats: list[GroupStats]) -> str:
- return "".join(
- f"<tr><td>{html.escape(s.group)}</td><td>{s.n}</td><td>{_fmt(s.baseline_mean)}</td><td>{_fmt(s.final_mean)}</td>"
- f"<td>{_fmt(s.delta_mean, '+.3f')}</td><td>{_fmt(s.pass_rate, '.0%')}</td><td>{s.cost_mean:.2f}</td></tr>"
- for s in stats
- )
-
- table = ("<table><tr><th>group</th><th>n</th><th>baseline</th><th>final</th><th>Δ</th><th>pass</th><th>$/run</th></tr>"
- + _rows([rep.overall] if rep.overall else []) + _rows(rep.by_tier) + "</table>")
- style = ("body{font-family:system-ui,sans-serif;margin:24px;background:#111;color:#eee}"
- ".grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(380px,1fr));gap:14px}"
- ".card{background:#1c1c1c;border-radius:8px;overflow:hidden;border:2px solid #333}.card.pass{border-color:#2e7d32}"
- ".card.fail{border-color:#8a1c1c}.card img{width:100%;display:block}.meta{padding:8px;font-size:13px}"
- ".err{color:#f88}table{border-collapse:collapse;margin:12px 0}td,th{border:1px solid #444;padding:4px 10px}")
- return (f"<!doctype html><meta charset='utf-8'><title>bench {html.escape(name)}</title><style>{style}</style>"
- f"<h1>bench — {html.escape(name)}</h1>{table}<div class='grid'>{''.join(cards)}</div>")
+ style = "<style>table{border-collapse:collapse;margin:8px 0 12px}td,th{border:1px solid #444;padding:3px 10px;font-size:13px}</style>"
+ tables = (style + "<h3>overall + by tier</h3>" + _html_table(([rep.overall] if rep.overall else []) + rep.by_tier)
+ + "<h3>by category</h3>" + _html_table(rep.by_category))
+ items = [_item_for(r) for r in results]
+ return render_gallery(items, f"bench — {name}", extra_html=tables)
def report_dict(rep: BenchReport) -> dict[str, Any]:
diff --git a/harness/codeverse/__init__.py b/harness/codeverse/__init__.py
index bba02f94..f93458a6 100644
--- a/harness/codeverse/__init__.py
+++ b/harness/codeverse/__init__.py
@@ -23,7 +23,7 @@ Package map (each sub-package has its own docstring):
- ``tracks`` static_object / articulated_object / scene pipelines.
- ``orchestrator`` stage runner, round loop, fan-out, budget, events.
- ``flywheel`` run records → dataset samples / preference pairs.
-- ``cli`` ``c3v`` command line.
+- ``cli`` ``3dcv`` command line.
"""
__version__ = "0.1.0"
diff --git a/harness/codeverse/agents/api_agent.py b/harness/codeverse/agents/api_agent.py
index ddd6119a..ea8e8717 100644
--- a/harness/codeverse/agents/api_agent.py
+++ b/harness/codeverse/agents/api_agent.py
@@ -1,6 +1,6 @@
"""``api-agent:<provider>:<model>`` — in-process agentic loop on any ChatModel.
-Tools: sandboxed file tools (+ ``run_shell``) and every spatial registry tool
+Tools: workspace-confined file tools (+ policy-filtered ``run_shell``) and every spatial registry tool
(``build``, ``measure``, ``render_views`` ...) as native function calls. The
loop runs until the model stops calling tools or ``job.max_turns``; it writes a
per-turn transcript JSONL, accumulates ``Usage``, compacts old tool results
diff --git a/harness/codeverse/agents/api_tools.py b/harness/codeverse/agents/api_tools.py
index 4a64758f..a628894b 100644
--- a/harness/codeverse/agents/api_tools.py
+++ b/harness/codeverse/agents/api_tools.py
@@ -1,9 +1,13 @@
-"""Tool set for the in-process ``api-agent``: sandboxed file tools + shell + spatial registry.
-
-Every tool returns a :class:`ToolOutcome` (text, images, is_error). Paths are
-resolved inside the workspace; writes are restricted to ``write_roots``.
-``run_shell`` accepts only an allow-listed interpreter/command with no shell
-operators, runs under the watchdog and never inherits host secrets.
+"""Tool set for the in-process ``api-agent``: workspace-confined file tools + shell + spatial registry.
+
+Every tool returns a :class:`ToolOutcome` (text, images, is_error) and never
+raises. Paths are resolved inside the workspace; writes are restricted to
+``write_roots``. ``run_shell`` is a *policy filter*, not an OS sandbox: only an
+allow-listed program, no shell operators, no inline-code flags (``python -c``,
+``node -e`` …, ``-m`` only for a few stdlib modules), every path-like argument
+must resolve inside the workspace, and the child runs under the watchdog with a
+minimal environment (no host secrets). Trust model = cooperative agent — the
+harness executes the agent's own source files anyway (same as the CLI backends).
"""
from __future__ import annotations
@@ -26,6 +30,14 @@ SHELL_OUT_CAP = 6_000
SHELL_TIMEOUT_S = 180.0
SHELL_ALLOW = ("node", "python", "python3", "ls", "cat", "head", "tail", "wc", "grep", "find", "stat")
_SHELL_OPERATORS = {"|", "&&", "||", ";", ">", ">>", "<", "2>", "&"}
+#: python/node short options that run inline code / a REPL (``-c CODE``, ``-e CODE``, ``-p``, ``-i``)
+#: or load code by path we cannot vet (``-r``); combined forms (``-Bc``, ``-pe``) are caught per letter.
+_INLINE_SHORT = {"python": set("cim"), "python3": set("cim"), "node": set("epir")}
+_INLINE_LONG = ("--eval", "--print", "--interactive", "--input-type", "--require", "--import", "--loader",
+ "--experimental-loader", "--experimental-default-type")
+#: ``python -m <module>`` is allowed only for these stdlib modules (syntax / JSON checks)
+PY_MODULE_ALLOW = ("py_compile", "compileall", "json.tool", "ast", "tokenize")
+_FIND_DENY = ("-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprintf", "-fls", "-fprint0")
_SKIP_GLOB_DIRS = (".git", "node_modules", "__pycache__", "trajectories")
@@ -73,7 +85,8 @@ class FileTools:
specs.append(ToolSpec(
name="run_shell",
description=f"Run ONE command in the workspace root (no pipes/redirects/network). Allowed programs: {', '.join(SHELL_ALLOW)}. "
- "Use it to syntax-check (`node --check src/x.js`, `python -m py_compile src/model.py`) or inspect files.",
+ "Use it to syntax-check (`node --check src/x.js`, `python -m py_compile src/model.py`) or inspect files. "
+ "Inline code (`python -c`, `node -e`) and paths outside the workspace are rejected.",
parameters=_schema({"cmd": {"type": "string", "description": "the command line, e.g. 'node --check src/object.js'"},
"timeout_s": {"type": "integer", "default": 60}}, ["cmd"]),
))
@@ -94,7 +107,9 @@ class FileTools:
return ToolOutcome(f"{name}: bad arguments: {e}", is_error=True)
except PathDenied as e:
return ToolOutcome(f"{name}: {e}", is_error=True)
- except OSError as e:
+ except (OSError, ValueError) as e: # ValueError covers UnicodeDecodeError / bad numbers
+ return ToolOutcome(f"{name}: {type(e).__name__}: {e}", is_error=True)
+ except Exception as e: # noqa: BLE001 — tools never raise into the agent loop
return ToolOutcome(f"{name}: {type(e).__name__}: {e}", is_error=True)
# ------------------------------------------------------------------ paths
@@ -136,7 +151,11 @@ class FileTools:
p = self._resolve(path, write=True)
if not p.is_file():
return ToolOutcome(f"no such file: {path} (use write_file to create it)", is_error=True)
- text = p.read_text()
+ try:
+ text = p.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ return ToolOutcome(f"{path} is not UTF-8 text; edit_file only works on text files (use write_file to replace it)",
+ is_error=True)
n = text.count(old)
if not old:
return ToolOutcome("`old` must be non-empty; read the file and quote the exact text to replace", is_error=True)
@@ -165,24 +184,65 @@ class FileTools:
break
return ToolOutcome("\n".join(out) if out else f"no files match {glob!r}")
- def run_shell(self, cmd: str, timeout_s: int = 60) -> ToolOutcome:
+ # ------------------------------------------------------------------ shell policy
+ def _arg_escapes(self, a: str) -> bool:
+ """True when ``a`` (a path-like argument) resolves outside the workspace or into .git."""
+ root = self.ws.root.resolve()
+ cand = Path(os.path.realpath(os.path.join(root, os.path.expanduser(a))))
+ if cand != root and root not in cand.parents:
+ return True
+ return cand != root and ".git" in cand.relative_to(root).parts
+
+ def _shell_policy_error(self, argv: list[str]) -> str | None:
+ """Why ``argv`` is refused (None = allowed). See the module docstring."""
+ if not argv or os.path.basename(argv[0]) not in SHELL_ALLOW:
+ return f"program {argv[0] if argv else ''!r} not allowed; use one of {SHELL_ALLOW}"
+ prog = os.path.basename(argv[0])
+ inline = _INLINE_SHORT.get(prog, set())
+ rest = argv[1:]
+ for i, a in enumerate(rest):
+ if a == "-" or (prog == "find" and a in _FIND_DENY):
+ return f"{a!r} is not allowed (stdin scripts / find actions are disabled)"
+ if a.startswith("--"):
+ opt, _, val = a.partition("=")
+ if opt in _INLINE_LONG:
+ return f"{opt} is not allowed: inline code / custom loaders are disabled; put code in a file under src/"
+ if val and self._arg_escapes(val):
+ return f"paths outside the workspace are not allowed: {val}"
+ continue
+ if a.startswith("-") and len(a) > 1:
+ letters = a[1:]
+ if prog.startswith("python") and "m" in letters:
+ pre, _, module = letters.partition("m") # -Bm mod / -mmod; -cm is `-c "m"`
+ if set(pre) & inline:
+ return f"{a} is not allowed: inline code / REPL flags are disabled; put code in a file under src/"
+ module = module or (rest[i + 1] if i + 1 < len(rest) else "")
+ if module not in PY_MODULE_ALLOW:
+ return f"python -m {module!r} is not allowed; allowed modules: {PY_MODULE_ALLOW}"
+ continue
+ if set(letters) & inline:
+ return f"{a} is not allowed: inline code / REPL flags are disabled; put code in a file under src/"
+ continue
+ if self._arg_escapes(a):
+ return f"paths outside the workspace are not allowed: {a}"
+ return None
+
+ def run_shell(self, cmd: str, timeout_s: int | float | str = 60) -> ToolOutcome:
try:
argv = shlex.split(cmd)
except ValueError as e:
return ToolOutcome(f"cannot parse command: {e}", is_error=True)
if any(tok in _SHELL_OPERATORS for tok in argv): # no shell is involved; this is just a clear message
return ToolOutcome("shell operators (| && ; > <) are not allowed; run ONE plain command", is_error=True)
- if not argv or os.path.basename(argv[0]) not in SHELL_ALLOW:
- return ToolOutcome(f"program {argv[0] if argv else ''!r} not allowed; use one of {SHELL_ALLOW}", is_error=True)
- for a in argv[1:]:
- if a.startswith("/") and not a.startswith(str(self.ws.root)):
- return ToolOutcome(f"absolute paths outside the workspace are not allowed: {a}", is_error=True)
+ why = self._shell_policy_error(argv)
+ if why:
+ return ToolOutcome(why, is_error=True)
env = {
"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.ws.root), "LANG": "C.UTF-8",
"NODE_PATH": str(get_settings().runtime_js_dir() / "node_modules"), "PYTHONDONTWRITEBYTECODE": "1",
"NO_PROXY": "*", "no_proxy": "*",
}
- t = float(max(5, min(int(timeout_s), int(SHELL_TIMEOUT_S))))
+ t = float(max(5, min(_as_int(timeout_s, 60), int(SHELL_TIMEOUT_S))))
proc = run_with_watchdog(argv, cwd=self.ws.root, env=env, soft_timeout_s=t, idle_grace_s=5, hard_timeout_s=t + 5,
activity_dirs=[], poll_s=0.2)
body = f"$ {cmd}\nrc={proc.rc}" + (" (killed: timeout)" if proc.timed_out else "")
@@ -193,6 +253,14 @@ class FileTools:
return ToolOutcome(body, is_error=proc.rc != 0)
+def _as_int(value: Any, default: int) -> int:
+ """Lenient int coercion for model-supplied numbers ('60', 60.5, 'soon' → default)."""
+ try:
+ return int(float(value))
+ except (TypeError, ValueError):
+ return default
+
+
def _cap(text: str, n: int = SHELL_OUT_CAP) -> str:
if len(text) <= n:
return text
@@ -227,4 +295,4 @@ class SpatialTools:
return ToolOutcome(text, images=images, is_error=not obs.ok, numbers=obs.numbers)
-__all__ = ["FileTools", "SpatialTools", "ToolOutcome", "PathDenied", "SHELL_ALLOW"]
+__all__ = ["FileTools", "SpatialTools", "ToolOutcome", "PathDenied", "SHELL_ALLOW", "PY_MODULE_ALLOW"]
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
index bb7eb1cb..acfcbee4 100644
--- a/harness/codeverse/agents/cli_common.py
+++ b/harness/codeverse/agents/cli_common.py
@@ -1,8 +1,10 @@
"""Shared plumbing for subprocess-based CodingAgent backends.
* :func:`hardened_env` — child environment without unrelated secrets.
-* :func:`begin_session` / :func:`finish_session` — trajectory dir, git
- snapshot before/after, ``files_changed`` from git, ``result.json``.
+* :func:`begin_session` / :func:`finish_session` — trajectory dir (a retry of
+ the same label+round gets ``<label>.a2_rNN`` instead of overwriting attempt 1),
+ git snapshot before/after, ``files_changed`` from git *attributed to this
+ session* (see :func:`attribute_changes`), ``result.json``.
* :func:`deliver_prompt` — argv prompt or "read the prompt file" stub.
* :func:`estimate_cost_safe` — lazy bridge to ``codeverse.models.pricing``.
* :func:`is_transient_failure` — 429 / 503 / empty-response detection.
@@ -15,13 +17,14 @@ import logging
import os
import re
import sys
+import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from codeverse.agents.transcript import Trajectory
-from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.agent import AgentJob, AgentResult, FileChange
from codeverse.contracts.common import Usage
from codeverse.workspace import Workspace
@@ -50,7 +53,7 @@ def hardened_env(ws: Workspace, job: AgentJob, *, keep: set[str] | None = None)
"""
keep = keep or set()
env = {k: v for k, v in os.environ.items() if k in keep or not is_secret_env(k)}
- env["C3V_AGENT_CONTEXT"] = "1"
+ env["CV3D_AGENT_CONTEXT"] = "1"
env["GIT_CEILING_DIRECTORIES"] = str(ws.root.parent)
env["PYTHONUNBUFFERED"] = "1"
env.update(job.env)
@@ -70,11 +73,11 @@ def default_mcp_command(ws: Workspace, *, language: str = "", track: str = "", r
def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:
- """The c3v MCP command for this job: ``.mcp.json`` (materialised) > ``job.extra['mcp_command']`` > default."""
+ """The 3dcv MCP command for this job: ``.mcp.json`` (materialised) > ``job.extra['mcp_command']`` > default."""
mcp = ws.root / ".mcp.json"
if mcp.is_file():
try:
- srv = (json.loads(mcp.read_text()).get("mcpServers") or {}).get("c3v")
+ srv = (json.loads(mcp.read_text()).get("mcpServers") or {}).get("3dcv")
except json.JSONDecodeError:
srv = None
if srv and srv.get("command"):
@@ -86,6 +89,78 @@ def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:
# --------------------------------------------------------------------------- session
+#: paths the harness owns; never attributed to an agent session even when git sees them change
+HARNESS_OWNED_DIRS = ("artifacts", "trajectories", "stages", "rounds", "_cand", "_assets", ".3dcv", ".gemini", ".claude", ".git")
+HARNESS_OWNED_FILES = frozenset({"events.jsonl", "run_state.json", "record.json", "AGENTS.md", "GEMINI.md", "CLAUDE.md",
+ ".mcp.json", ".geminiignore", ".aiexclude", ".gitignore"})
+
+
+@dataclass
+class _LiveSession:
+ """Registry entry: lets concurrent sessions in ONE workspace (scene fan-out) attribute files."""
+
+ label: str
+ hints: frozenset[str]
+ t_start: float
+ t_end: float | None = None
+
+
+_LIVE: dict[str, list[_LiveSession]] = {}
+_LIVE_LOCK = threading.Lock()
+
+
+def _register(ws: Workspace, label: str, hints: frozenset[str]) -> _LiveSession:
+ entry = _LiveSession(label=label, hints=hints, t_start=time.monotonic())
+ with _LIVE_LOCK:
+ _LIVE.setdefault(str(ws.root), []).append(entry)
+ return entry
+
+
+def _sibling_hints(ws: Workspace, me: _LiveSession) -> frozenset[str]:
+ """Files claimed (``extra['files_hint']``) by OTHER sessions that overlapped ``me`` in time."""
+ me.t_end = time.monotonic()
+ with _LIVE_LOCK:
+ entries = _LIVE.get(str(ws.root), [])
+ claimed: set[str] = set()
+ for e in entries:
+ if e is me:
+ continue
+ overlaps = e.t_start <= me.t_end and (e.t_end is None or e.t_end >= me.t_start)
+ if overlaps:
+ claimed |= e.hints
+ oldest_active = min((e.t_start for e in entries if e.t_end is None), default=me.t_end)
+ entries[:] = [e for e in entries if e.t_end is None or e.t_end >= oldest_active]
+ return frozenset(claimed - me.hints)
+
+
+def _hinted(path: str, hints: frozenset[str]) -> bool:
+ return any(path == h or path.startswith(h.rstrip("/") + "/") for h in hints)
+
+
+def attribute_changes(
+ files: list[FileChange],
+ *,
+ write_roots: list[str],
+ own_hints: frozenset[str] = frozenset(),
+ sibling_hints: frozenset[str] = frozenset(),
+) -> list[FileChange]:
+ """The subset of a whole-worktree git diff that belongs to ONE session: inside its
+ ``write_roots``, not harness-owned, and not a file another concurrent session
+ declared as its target (``job.extra['files_hint']``) unless this session declared it too."""
+ roots = tuple(r.strip("/") for r in write_roots if r.strip("/"))
+ out: list[FileChange] = []
+ for f in files:
+ parts = Path(f.path).parts
+ if not parts or parts[0] in HARNESS_OWNED_DIRS or f.path in HARNESS_OWNED_FILES:
+ continue
+ if roots and not any(f.path == r or f.path.startswith(r + "/") for r in roots):
+ continue
+ if sibling_hints and _hinted(f.path, sibling_hints) and not _hinted(f.path, own_hints):
+ continue
+ out.append(f)
+ return out
+
+
@dataclass
class Session:
"""State for one CLI agent run (created by :func:`begin_session`)."""
@@ -99,6 +174,19 @@ class Session:
head_before: str
t0: float = field(default_factory=time.monotonic)
notes: list[str] = field(default_factory=list)
+ attempt: int = 1
+ files_hint: frozenset[str] = frozenset()
+ live: _LiveSession | None = None
+
+
+def _session_label(ws: Workspace, label: str, round_index: int) -> tuple[str, int]:
+ """``label`` for attempt 1; ``<label>.a<n>`` when ``trajectories/<label>_rNN`` already
+ holds a finished attempt (result.json) — a silent-bail retry must not overwrite it."""
+ n, cand = 1, label
+ while (ws.trajectory_dir(cand, round_index) / "result.json").exists():
+ n += 1
+ cand = f"{label}.a{n}"
+ return cand, n
def begin_session(job: AgentJob, kind: str) -> Session:
@@ -108,13 +196,15 @@ def begin_session(job: AgentJob, kind: str) -> Session:
raise FileNotFoundError(f"workspace does not exist: {ws.root}")
if not (ws.root / ".git").exists():
ws.create()
- label = job.label or kind
round_index = int(job.extra.get("round", 0) or 0)
+ label, attempt = _session_label(ws, job.label or kind, round_index)
traj = Trajectory(ws.trajectory_dir(label, round_index))
traj.write_prompt(job.prompt, job.system_append)
+ hints = frozenset(str(h) for h in (job.extra.get("files_hint") or []) if str(h).strip())
+ live = _register(ws, label, hints)
head_before = ws.commit(f"pre:{label}")
return Session(ws=ws, job=job, kind=kind, label=label, round_index=round_index,
- traj=traj, head_before=head_before)
+ traj=traj, head_before=head_before, attempt=attempt, files_hint=hints, live=live)
def finish_session(
@@ -128,16 +218,19 @@ def finish_session(
errors: list[str] | None = None,
**extra: Any,
) -> AgentResult:
- """Commit the agent's work, compute ``files_changed`` via git, write result.json."""
+ """Commit the agent's work, compute ``files_changed`` via git (attributed to this
+ session — see :func:`attribute_changes`), write result.json."""
s.ws.commit(f"agent:{s.label}")
- files = s.ws.changed_files(s.head_before)
+ siblings = _sibling_hints(s.ws, s.live) if s.live is not None else frozenset()
+ files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots,
+ own_hints=s.files_hint, sibling_hints=siblings)
res = AgentResult(
ok=ok, exit_reason=exit_reason, text=text, files_changed=files,
transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),
usage=usage, duration_s=round(time.monotonic() - s.t0, 3), tool_calls=tool_calls,
errors=list(errors or []),
)
- s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index,
+ s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index, attempt=s.attempt, job_label=s.job.label,
head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)
return res
diff --git a/harness/codeverse/agents/codex.py b/harness/codeverse/agents/codex.py
index 48b42291..c5996e39 100644
--- a/harness/codeverse/agents/codex.py
+++ b/harness/codeverse/agents/codex.py
@@ -1,7 +1,7 @@
"""``codex:<model>`` — headless OpenAI Codex CLI session on a workspace.
argv: ``codex exec --json -C <ws> --sandbox workspace-write --skip-git-repo-check
-[--model <model>] [-c mcp_servers.c3v.command=... -c mcp_servers.c3v.args=[...]] <prompt>``
+[--model <model>] [-c mcp_servers.3dcv.command=... -c mcp_servers.3dcv.args=[...]] <prompt>``
(prompt on stdin when long). stdout is JSONL:
* ``{"type":"thread.started","thread_id":...}`` / ``turn.started``
diff --git a/harness/codeverse/agents/gemini_cli.py b/harness/codeverse/agents/gemini_cli.py
index 02f216b4..a133453d 100644
--- a/harness/codeverse/agents/gemini_cli.py
+++ b/harness/codeverse/agents/gemini_cli.py
@@ -6,10 +6,15 @@ argv: ``gemini -p <prompt> -m <model> --approval-mode yolo --skip-trust --output
``GEMINI_CLI_SYSTEM_SETTINGS_PATH`` forcing api-key auth + dynamic model
configuration (otherwise an unknown model is *silently* substituted), Node
heap cap, no self-relaunch.
-* JSON envelope ``{session_id, response, stats:{models:{<m>:{tokens:{input,
- candidates, cached, thoughts}}}, tools:{totalCalls}}}`` → Usage (+ cost via
- pricing). Requested model absent from ``stats.models`` → ``model_substituted``.
-* one retry (rotated key) on transient failures (429 / 503 / empty response).
+* JSON envelope ``{session_id, response, stats:{models:{<m>:{tokens:{prompt,
+ input, candidates, cached, thoughts}}}, tools:{totalCalls}}}`` → Usage (+ cost
+ via pricing). ``tokens.prompt`` is the TOTAL prompt size and ``tokens.input``
+ the UNCACHED part (``prompt - cached``); ``Usage.input_tokens`` follows the
+ pricing convention (total prompt, cached re-priced). Each served model is
+ priced at its own rate. Requested model absent from ``stats.models`` →
+ ``model_substituted``.
+* one retry (rotated key when the pool has one, else the same key) on transient
+ failures (429 / 503 / empty response); a throttled/empty pool never raises.
"""
from __future__ import annotations
@@ -37,16 +42,26 @@ from codeverse.config import get_settings
from codeverse.contracts.agent import AgentJob, AgentResult
from codeverse.contracts.common import Usage
+try:
+ from codeverse.models.keypool import KeyPoolExhausted
+except ImportError: # pragma: no cover - models package is always present in a full install
+
+ class KeyPoolExhausted(RuntimeError): # type: ignore[no-redef]
+ """Stand-in so the retry path can catch the pool's exhaustion uniformly."""
+
+
log = logging.getLogger(__name__)
SYSTEM_SETTINGS = {
# folderTrust must be OFF: with it on, gemini-cli silently disables the workspace
- # .gemini/settings.json mcpServers (even with --skip-trust) → no c3v tools.
+ # .gemini/settings.json mcpServers (even with --skip-trust) → no 3dcv tools.
"security": {"auth": {"selectedType": "gemini-api-key"}, "folderTrust": {"enabled": False}},
"experimental": {"dynamicModelConfiguration": True},
"general": {"topicUpdateNarration": False},
}
IDLE_GRACE_S = 300.0
+#: how long a retry waits for a *different* healthy key before reusing the same one
+RETRY_KEY_WAIT_S = 10.0
class _LocalKeyRotor:
@@ -55,7 +70,7 @@ class _LocalKeyRotor:
def __init__(self, keys: list[str]):
self._keys, self._i = list(keys), 0
- def acquire(self, *, exclude: set[str] | None = None) -> str:
+ def acquire(self, *, exclude: set[str] | None = None, timeout_s: float | None = None) -> str:
for _ in range(len(self._keys)):
k = self._keys[self._i % len(self._keys)]
self._i += 1
@@ -115,20 +130,48 @@ def parse_gemini_json(stdout: str) -> dict[str, Any] | None:
return None
+def _model_usage(tok: dict[str, Any], name: str) -> Usage:
+ """One served model's counters in pricing semantics (``input_tokens`` = total prompt)."""
+ cached = int(tok.get("cached") or 0)
+ prompt = tok.get("prompt")
+ # gemini-cli: tokens.prompt = promptTokenCount (total), tokens.input = prompt - cached
+ total = int(prompt) if prompt is not None else int(tok.get("input") or 0) + cached
+ return Usage(backend="gemini-cli", model=name, input_tokens=total, cached_tokens=cached,
+ output_tokens=int(tok.get("candidates") or 0), thoughts_tokens=int(tok.get("thoughts") or 0))
+
+
def usage_from_stats(stats: dict[str, Any], model: str) -> Usage:
- """Sum tokens across every served model (normally just ``model``)."""
+ """Sum tokens across every served model (normally just ``model``); cost is the
+ sum of each served model priced at its own rate (unknown → requested model's)."""
u = Usage(backend="gemini-cli", model=model)
- for _name, m in (stats.get("models") or {}).items():
- tok = (m or {}).get("tokens") or {}
- u.input_tokens += int(tok.get("input") or tok.get("prompt") or 0)
- u.output_tokens += int(tok.get("candidates") or 0)
- u.cached_tokens += int(tok.get("cached") or 0)
- u.thoughts_tokens += int(tok.get("thoughts") or 0)
+ cost = 0.0
+ for name, m in (stats.get("models") or {}).items():
+ part = _model_usage((m or {}).get("tokens") or {}, str(name))
+ c = estimate_cost_safe("gemini", str(name), part)
+ if c == 0.0 and name != model and (part.input_tokens or part.output_tokens):
+ c = estimate_cost_safe("gemini", model, part) # utility model missing from the price table
+ cost += c
+ u.input_tokens += part.input_tokens
+ u.output_tokens += part.output_tokens
+ u.cached_tokens += part.cached_tokens
+ u.thoughts_tokens += part.thoughts_tokens
u.tool_calls = int(((stats.get("tools") or {}).get("totalCalls")) or 0)
- u.cost_usd = estimate_cost_safe("gemini", model, u)
+ u.cost_usd = cost
return u
+def _retry_key(pool: Any, used: set[str]) -> str | None:
+ """Key for a retry: a different healthy key if one frees up within
+ ``RETRY_KEY_WAIT_S``, else the same key again (single-key pools, 5xx), else
+ ``None`` when every key is throttled (429 cooldown) — the caller then stops."""
+ for exclude in (used, None):
+ try:
+ return pool.acquire(exclude=exclude or None, timeout_s=RETRY_KEY_WAIT_S)
+ except KeyPoolExhausted:
+ continue
+ return None
+
+
class GeminiCliAgent:
kind = "gemini-cli"
@@ -170,12 +213,15 @@ class GeminiCliAgent:
return failed(s, "error", why)
prompt = deliver_prompt(s, _compose_prompt(job))
pool = _key_pool(get_settings().gemini_api_keys)
+ try:
+ key = pool.acquire()
+ except KeyPoolExhausted as e: # every key throttled for the whole wait budget
+ return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")
attempts = 0
used: set[str] = set()
usage_total = Usage(backend=self.kind, model=self.model)
while True:
attempts += 1
- key = pool.acquire(exclude=used or None)
used.add(key)
proc = self._invoke(s, prompt, key, attempt=attempts)
outcome = self._interpret(s, proc)
@@ -183,7 +229,13 @@ class GeminiCliAgent:
pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))
if outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:
break
- s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with rotated key")
+ next_key = _retry_key(pool, used)
+ if next_key is None:
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); no usable key for a retry")
+ break
+ key = next_key
+ how = "rotated key" if key not in used else "same key (no alternative available)"
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with {how}")
s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])
usage_total.cost_usd = round(usage_total.cost_usd, 6)
return finish_session(
diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.py
index 6b308920..23a50be3 100644
--- a/harness/codeverse/agents/materialize.py
+++ b/harness/codeverse/agents/materialize.py
@@ -2,13 +2,18 @@
One shared body is written to ``AGENTS.md`` (codex / generic), ``GEMINI.md``
(gemini-cli) and ``CLAUDE.md`` (claude-code): task-agnostic rules, how to call
-the ``c3v`` spatial tools, where the cookbook is, and the language contract.
+the ``3dcv`` spatial tools, where the cookbook is, and the language contract.
MCP wiring:
-* gemini-cli → ``ws/.gemini/settings.json`` (merged) ``mcpServers.c3v``
+* gemini-cli → ``ws/.gemini/settings.json`` (merged) ``mcpServers.3dcv``
* claude-code → ``ws/.mcp.json``
* codex → ``-c`` overrides returned in :class:`Materialized.codex_overrides`
* agy (Antigravity) → no per-workspace MCP; the body documents the CLI fallback.
+
+Ignore files: ``.geminiignore`` / ``.aiexclude`` hide only noise (:data:`IGNORE_LINES`);
+``.gemini/settings.json`` gets ``context.fileFiltering.respectGitIgnore=false`` because the
+workspace ``.gitignore`` hides ``artifacts/`` + ``trajectories/`` from git and gemini-cli
+would otherwise refuse to read the build census / the long-prompt file there.
"""
from __future__ import annotations
@@ -22,10 +27,23 @@ from pydantic import BaseModel, Field
from codeverse.prompts import PROMPTS_DIR
from codeverse.workspace import Workspace
-C3V_DIR = ".c3v" # harness-owned read-only docs inside the workspace
-MCP_SERVER_NAME = "c3v"
+CV3D_DIR = ".3dcv" # harness-owned read-only docs inside the workspace
+MCP_SERVER_NAME = "3dcv"
MCP_TOOL_TIMEOUT_MS = 600_000
-IGNORE_LINES = ("artifacts/", "trajectories/", ".git/", "node_modules/", "__pycache__/", ".gemini/tmp/")
+#: ``.geminiignore`` / ``.aiexclude`` — gemini-cli's read_file/glob REFUSE ignored paths, so the
+#: agent-facing artefacts must stay readable: ``artifacts/*.json`` (the build tool advertises
+#: ``census.json`` etc.), ``artifacts/tool_renders/`` and ``trajectories/<label>_rNN/task_prompt.md``
+#: (the long-prompt fallback). Only noise / harness-private output is hidden.
+IGNORE_LINES = (
+ "artifacts/renders/", "artifacts/judge/",
+ "trajectories/*/stdout*", "trajectories/*/stderr*", "trajectories/*/transcript.jsonl",
+ "stages/", "rounds/", "_cand/", "_assets/",
+ ".git/", "node_modules/", "__pycache__/", ".gemini/tmp/",
+)
+#: gemini-cli also honours the workspace ``.gitignore`` (``artifacts/``, ``trajectories/``, ``.3dcv/``
+#: are git-ignored run state) unless told otherwise — the per-workspace settings turn that off so
+#: ``IGNORE_LINES`` is the single source of truth for what the agent may read.
+GEMINI_CONTEXT_SETTINGS = {"fileFiltering": {"respectGitIgnore": False, "respectGeminiIgnore": True}}
class Materialized(BaseModel):
@@ -54,7 +72,7 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str])
cards = tool_cards() or "(the tool registry is empty in this environment)"
if agent_kind == "claude-code":
- how = "Tools are exposed by the MCP server `c3v`; their names appear as `mcp__c3v__<name>` (e.g. `mcp__c3v__build`)."
+ how = "Tools are exposed by the MCP server `3dcv`; their names appear as `mcp__c3v__<name>` (e.g. `mcp__c3v__build`)."
elif agent_kind == "agy":
how = (
"This session has no MCP server. Call a tool from the shell instead:\n"
@@ -71,7 +89,7 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str])
else:
how = f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}` (command: `{' '.join(mcp_command)}`); call them by name."
return (
- "## Spatial tools (c3v)\n\n"
+ "## Spatial tools (3dcv)\n\n"
f"{how}\n\n"
"Workflow: edit → `build` → read the errors/numbers → fix → `build` again. Use `render_views` / "
"`render_sheet` to LOOK at what you made before declaring it finished; use `measure` / "
@@ -82,11 +100,11 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str])
def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools: bool, mcp_command: list[str]) -> str:
return (
- "# c3v workspace — rules for the coding agent\n\n"
+ "# 3dcv workspace — rules for the coding agent\n\n"
"You are working inside a harness-managed workspace. Read this whole file before acting.\n\n"
"## Hard rules\n\n"
"1. You may create or edit files ONLY under `src/` and `public/`. Never modify `artifacts/`, "
- "`trajectories/`, `.git/`, `.gemini/`, `.c3v/`, or this file — they are harness-owned.\n"
+ "`trajectories/`, `.git/`, `.gemini/`, `.3dcv/`, or this file — they are harness-owned.\n"
"2. Write RAW code in the language named by the contract below. Never import from `codeverse` or "
"any helper SDK; do not install packages; do not use the network; do not write "
"camera / render / export / file-output code unless the contract explicitly asks for it — "
@@ -135,13 +153,19 @@ def _toml_str_list(items: list[str]) -> str:
return "[" + ", ".join(json.dumps(x) for x in items) + "]"
+#: codex ≥ 0.14x asks for per-tool approval before running an MCP tool; ``codex exec`` has
+#: nobody to answer, so without this every 3dcv call is auto-cancelled ("requires approval").
+CODEX_MCP_APPROVAL_MODE = "approve"
+
+
def codex_mcp_overrides(mcp_command: list[str]) -> list[str]:
- """``-c`` pairs that register the c3v MCP server for one ``codex exec`` call."""
+ """``-c`` pairs that register the 3dcv MCP server for one ``codex exec`` call."""
return [
"-c", f"mcp_servers.{MCP_SERVER_NAME}.command={json.dumps(mcp_command[0])}",
"-c", f"mcp_servers.{MCP_SERVER_NAME}.args={_toml_str_list(mcp_command[1:])}",
"-c", f"mcp_servers.{MCP_SERVER_NAME}.tool_timeout_sec={MCP_TOOL_TIMEOUT_MS // 1000}",
"-c", f"mcp_servers.{MCP_SERVER_NAME}.startup_timeout_sec=60",
+ "-c", f"mcp_servers.{MCP_SERVER_NAME}.default_tools_approval_mode={json.dumps(CODEX_MCP_APPROVAL_MODE)}",
]
@@ -169,16 +193,16 @@ def materialize_workspace(
if spatial_tools and not mcp_command:
raise ValueError("spatial_tools=True requires a non-empty mcp_command")
- # cookbook: copy into the harness-owned .c3v/ dir so every CLI can read it in-workspace
+ # cookbook: copy into the harness-owned .3dcv/ dir so every CLI can read it in-workspace
src = _resolve_cookbook(ws, cookbook_rel)
if src is not None:
- dest = ws.root / C3V_DIR / "cookbook.md"
+ dest = ws.root / CV3D_DIR / "cookbook.md"
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dest)
out.cookbook_path = str(dest)
cookbook_note = (
f"The cookbook for this language — copyable, verified snippets and skeletons — is at "
- f"`{C3V_DIR}/cookbook.md` (relative to the workspace root). Read the relevant sections "
+ f"`{CV3D_DIR}/cookbook.md` (relative to the workspace root). Read the relevant sections "
"before writing code and copy its patterns exactly."
+ (" You may also call the `read_cookbook` tool." if spatial_tools else "")
)
@@ -193,6 +217,7 @@ def materialize_workspace(
gemini_settings = ws.root / ".gemini" / "settings.json"
claude_mcp = ws.root / ".mcp.json"
+ _merge_json(gemini_settings, {"context": dict(GEMINI_CONTEXT_SETTINGS)})
if spatial_tools:
server = {"command": mcp_command[0], "args": list(mcp_command[1:]), "timeout": MCP_TOOL_TIMEOUT_MS}
_merge_json(gemini_settings, {"mcpServers": {MCP_SERVER_NAME: server}})
diff --git a/harness/codeverse/agents/transcript.py b/harness/codeverse/agents/transcript.py
index f3783d68..bcd8383e 100644
--- a/harness/codeverse/agents/transcript.py
+++ b/harness/codeverse/agents/transcript.py
@@ -1,7 +1,7 @@
"""Trajectory folder helper: prompt.md, transcript.jsonl, stdout/stderr, result.json.
Every CodingAgent backend writes its session here
-(``ws.trajectory_dir(label, round)``) so the flywheel and ``c3v status`` can
+(``ws.trajectory_dir(label, round)``) so the flywheel and ``3dcv status`` can
read one uniform layout regardless of backend.
"""
diff --git a/harness/codeverse/cli/__init__.py b/harness/codeverse/cli/__init__.py
index 844b2c43..f5813417 100644
--- a/harness/codeverse/cli/__init__.py
+++ b/harness/codeverse/cli/__init__.py
@@ -1 +1 @@
-"""``c3v`` command line."""
+"""``3dcv`` command line."""
diff --git a/harness/codeverse/cli/_common.py b/harness/codeverse/cli/_common.py
index ef5b9dd1..8ad59d64 100644
--- a/harness/codeverse/cli/_common.py
+++ b/harness/codeverse/cli/_common.py
@@ -37,7 +37,7 @@ def lazy(module: str, attr: str | None = None) -> Any:
except ImportError as e:
raise CliError(
f"{module} is not available ({e}). This command needs that sub-package; "
- f"run `c3v doctor` to see what is installed.", code=2
+ f"run `3dcv doctor` to see what is installed.", code=2
) from e
if attr is None:
return mod
diff --git a/harness/codeverse/cli/_fmt.py b/harness/codeverse/cli/_fmt.py
index 19b4cf04..18ed1557 100644
--- a/harness/codeverse/cli/_fmt.py
+++ b/harness/codeverse/cli/_fmt.py
@@ -36,14 +36,15 @@ def fmt_usd(v: float) -> str:
def rounds_table(record: RunRecord) -> Table:
- t = Table(title="rounds", show_lines=False)
+ t = Table(title="rounds (* = best)", show_lines=False)
for col in ("#", "kind", "build", "gate err", "score", "passed", "cost", "secs", "commit"):
t.add_column(col, justify="right" if col in ("#", "gate err", "score", "cost", "secs") else "left")
for r in record.rounds:
build = "-" if r.build is None else ("ok" if r.build.ok else "[red]FAIL[/red]")
j = r.judgment
passed = "-" if j is None else ("[green]yes[/green]" if j.passed else "no")
- t.add_row(str(r.index), r.kind, build, str(sum(len(g.errors) for g in r.gates)), fmt_score(r.score),
+ best = "*" if record.best_round is not None and r.index == record.best_round else ""
+ t.add_row(f"{r.index}{best}", r.kind, build, str(sum(len(g.errors) for g in r.gates)), fmt_score(r.score),
passed, fmt_usd(r.usage.cost_usd), f"{r.duration_s:.0f}", r.commit[:8])
return t
@@ -96,7 +97,7 @@ def print_observation(obs: Any, *, as_json: bool) -> None:
def doctor_table(rows: list[tuple[str, str, str]]) -> Table:
"""rows: (check, status OK|WARN|FAIL, detail)."""
- t = Table(title="c3v doctor")
+ t = Table(title="3dcv doctor")
t.add_column("check", style="bold")
t.add_column("status")
t.add_column("detail")
diff --git a/harness/codeverse/cli/_judge.py b/harness/codeverse/cli/_judge.py
new file mode 100644
index 00000000..88015952
--- /dev/null
+++ b/harness/codeverse/cli/_judge.py
@@ -0,0 +1,186 @@
+"""``3dcv judge`` implementation: re-judge a round with the SAME inputs the
+in-run judge saw.
+
+The round's renders / measurement / gates come from ``rounds/rNN.json``
+(fallback: the round inside record.json), the acceptance checklist and plan
+digest from ``plan.json``, ``previous`` is the preceding round's (non-degraded)
+verdict, the track-specific ``extra_context`` is rebuilt from the stored gates
+/ frame metrics, and the clay geometry views rendered for the in-run judge
+(``renders/rNN/clay/``) are reattached when present. The judge class matches
+the in-run choice: ``ReferenceJudge`` when the rubric has measured criteria or
+the spec carries reference images, ``VlmJudge`` otherwise.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from codeverse.cli import _common as C
+from codeverse.contracts.artifacts import GateReport, RenderSet, RenderView
+from codeverse.contracts.common import Track
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.run import RoundRecord, RunRecord
+from codeverse.workspace import Workspace
+
+#: rubric per track when the round has no stored judgment (mirrors the tracks)
+TRACK_RUBRIC: dict[Track, str] = {
+ Track.STATIC_OBJECT: "static_object_v1",
+ Track.ARTICULATED_OBJECT: "articulated_v1",
+ Track.SCENE: "scene_v1",
+ Track.GRAPHICS: "shader_v1",
+}
+
+
+def load_round(ws: Workspace, rec: RunRecord, index: int) -> RoundRecord | None:
+ """rounds/rNN.json (written by the round loop) beats the copy in record.json."""
+ p = ws.root / "rounds" / f"r{index:02d}.json"
+ if p.is_file():
+ try:
+ return RoundRecord.model_validate_json(p.read_text())
+ except Exception: # noqa: BLE001 — fall through to the record copy
+ pass
+ return next((r for r in rec.rounds if r.index == index), None)
+
+
+def rubric_for(rec: RunRecord, rnd: RoundRecord, override: str | None) -> str:
+ """--rubric > the rubric the round was judged with > the track default."""
+ if override:
+ return override
+ if rnd.judgment is not None and rnd.judgment.rubric:
+ return rnd.judgment.rubric
+ return TRACK_RUBRIC.get(rec.spec.track, "static_object_v1")
+
+
+def plan_summary_for(ws: Workspace) -> str:
+ """Track-agnostic plan digest from plan.json (same fields the tracks summarise)."""
+ if not ws.plan_path.is_file():
+ return ""
+ try:
+ data = json.loads(ws.plan_path.read_text())
+ except ValueError:
+ return ""
+ plan_digest = C.lazy("codeverse.judges.calibration", "plan_digest")
+ return plan_digest(data)
+
+
+def previous_judgment(ws: Workspace, rec: RunRecord, index: int) -> Any:
+ """The preceding round's verdict (skipping degraded ones), like the round loop."""
+ from codeverse.flywheel.record import effective_judgment
+
+ for i in range(index - 1, -1, -1):
+ rnd = load_round(ws, rec, i)
+ if rnd is None:
+ continue
+ j = effective_judgment(rnd)
+ if j is not None:
+ return j
+ return None
+
+
+def _gate(rnd: RoundRecord, name: str) -> GateReport | None:
+ return next((g for g in rnd.gates if g.gate == name), None)
+
+
+def extra_context_for(ws: Workspace, rec: RunRecord, rnd: RoundRecord) -> str:
+ """Rebuild the track pipeline's ``judge_context`` from the stored artifacts."""
+ track = rec.spec.track
+ if track is Track.GRAPHICS:
+ frame_stats_text = C.lazy("codeverse.tracks.graphics_steps", "frame_stats_text")
+ renderer = ""
+ if rnd.build is not None and isinstance(rnd.build.census, dict):
+ renderer = str(rnd.build.census.get("renderer", ""))
+ return f"FRAME METRICS (harness-measured, renderer {renderer or 'moderngl'}):\n{frame_stats_text(ws)}"
+ if track is Track.ARTICULATED_OBJECT:
+ lines = ["Articulation sheet: the pose_* views show the object at rest, each joint at its lower and upper limit."]
+ sweep = _gate(rnd, "joint_sweep")
+ if sweep is not None:
+ errs = [f"- {f.target or 'joint'}: {f.message}" for f in sweep.errors]
+ lines.append(f"Joint sweep: {'no penetrations' if not errs else str(len(errs)) + ' problems'}")
+ lines.extend(errs[:10])
+ motion = _gate(rnd, "motion_direction")
+ if motion is not None:
+ wrong = [f"- {f.target}: {f.message}" for f in motion.errors]
+ lines.append("Motion direction (harness FK check): "
+ + ("all planned directions realised" if not wrong else f"{len(wrong)} WRONG"))
+ lines.extend(wrong[:6])
+ return "\n".join(lines)
+ if track is Track.SCENE and rec.plan is not None:
+ plan = rec.plan
+ lines = [f"Environment plan: {getattr(plan, 'environment', '')}",
+ "Animation plan: " + "; ".join(getattr(plan, "animation", []) or [])]
+ cameras = getattr(plan, "cameras", []) or []
+ if cameras:
+ lines.append("Cameras: " + "; ".join(f"{c.name} ({c.purpose})" for c in cameras))
+ return "\n".join(lines)
+ return ""
+
+
+def clay_geometry_views(ws: Workspace, index: int) -> RenderSet | None:
+ """The clay views the in-run judge saw (``renders/rNN/clay/``), when present."""
+ d = ws.renders_dir(index) / "clay"
+ if not d.is_dir():
+ return None
+ views = [RenderView(name=p.stem.removeprefix("view_"), path=str(p), mode="clay")
+ for p in sorted(d.glob("view_*.png"))]
+ return RenderSet(views=views, renderer="stored") if views else None
+
+
+def resolve_paths(ws: Workspace, rs: RenderSet | None) -> RenderSet | None:
+ """Round records may store workspace-relative render paths; make them absolute."""
+ if rs is None:
+ return None
+ fixed = []
+ for v in rs.views:
+ p = Path(v.path)
+ fixed.append(v if p.is_absolute() else v.model_copy(update={"path": str(ws.root / p)}))
+ sheet = rs.contact_sheet
+ if sheet and not Path(sheet).is_absolute():
+ sheet = str(ws.root / sheet)
+ return rs.model_copy(update={"views": fixed, "contact_sheet": sheet})
+
+
+def build_judge_input(ws: Workspace, rec: RunRecord, rnd: RoundRecord) -> Any:
+ JudgeInput = C.lazy("codeverse.judges.base", "JudgeInput")
+ acceptance: list[AcceptanceItem] = list(getattr(rec.plan, "acceptance", []) or [])
+ if not acceptance and ws.plan_path.is_file():
+ try:
+ raw = json.loads(ws.plan_path.read_text()).get("acceptance") or []
+ acceptance = [AcceptanceItem.model_validate(a) for a in raw]
+ except (ValueError, TypeError):
+ acceptance = []
+ return JudgeInput(
+ spec=rec.spec, renders=resolve_paths(ws, rnd.renders), measurement=rnd.measurement, gates=rnd.gates,
+ acceptance=acceptance, plan_summary=plan_summary_for(ws), round_index=rnd.index,
+ previous=previous_judgment(ws, rec, rnd.index), extra_context=extra_context_for(ws, rec, rnd),
+ geometry_views=clay_geometry_views(ws, rnd.index),
+ )
+
+
+def make_judge(rec: RunRecord, rubric_name: str, model_id: str, n: int) -> Any:
+ """ReferenceJudge for measured rubrics / reference specs, VlmJudge otherwise."""
+ load_rubric = C.lazy("codeverse.judges.rubrics", "load_rubric")
+ try:
+ rubric = load_rubric(rubric_name)
+ except Exception as e: # unknown rubric name / bad yaml
+ raise C.CliError(f"cannot load rubric {rubric_name!r}: {e}") from e
+ measured = bool(rubric.measured_criteria())
+ if measured or rec.spec.references:
+ ReferenceJudge = C.lazy("codeverse.judges.reference", "ReferenceJudge")
+ return ReferenceJudge(model_id=model_id, n_samples=n, rubric=rubric_name)
+ VlmJudge = C.lazy("codeverse.judges.vlm_judge", "VlmJudge")
+ return VlmJudge(rubric=rubric_name, model_id=model_id, n_samples=n)
+
+
+def count_prompt_images(inp: Any, rubric_name: str) -> int | None:
+ """Number of image parts a single judge sample will send (None on failure)."""
+ try:
+ load_rubric = C.lazy("codeverse.judges.rubrics", "load_rubric")
+ build_judge_messages = C.lazy("codeverse.judges.prompt_builder", "build_judge_messages")
+ from codeverse.contracts.chat import ImagePart
+
+ _, messages = build_judge_messages(inp, load_rubric(rubric_name))
+ return sum(1 for m in messages for p in m.parts if isinstance(p, ImagePart))
+ except Exception: # noqa: BLE001 — informational only
+ return None
diff --git a/harness/codeverse/cli/bench_cmd.py b/harness/codeverse/cli/bench_cmd.py
index f0dd240f..255ddb7f 100644
--- a/harness/codeverse/cli/bench_cmd.py
+++ b/harness/codeverse/cli/bench_cmd.py
@@ -1,4 +1,4 @@
-"""``c3v bench run <battery.yaml> | report <dir>``."""
+"""``3dcv bench run <battery.yaml> | report <dir>``."""
from __future__ import annotations
diff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
index 0713d856..179eef41 100644
--- a/harness/codeverse/cli/doctor.py
+++ b/harness/codeverse/cli/doctor.py
@@ -1,4 +1,4 @@
-"""``c3v doctor`` — environment checks (deps, Blender, node/three/chrome, keys, CLIs, MCP)."""
+"""``3dcv doctor`` — environment checks (deps, Blender, node/three/chrome, keys, CLIs, MCP)."""
from __future__ import annotations
@@ -17,7 +17,7 @@ from codeverse.config import get_settings
doctor_app = typer.Typer(invoke_without_command=True)
Row = tuple[str, str, str]
-_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "PIL", "pyarrow",
+_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "fcl", "PIL", "pyarrow",
"scipy", "shapely", "networkx", "manifold3d", "playwright", "google.genai", "anthropic", "openai",
"yourdfpy", "mcp")
_CLI_TIMEOUT = 25
@@ -57,7 +57,7 @@ def check_blender() -> list[Row]:
s = get_settings()
b = s.resolve_blender()
if not b:
- return [("blender", "FAIL", "no binary (set C3V_BINARIES__BLENDER or put blender-5.0 on PATH)")]
+ return [("blender", "FAIL", "no binary (set CV3D_BINARIES__BLENDER or put blender-5.0 on PATH)")]
okk, v = _ver([b, "--version"], timeout=60)
return [("blender", "OK" if okk else "FAIL", f"{v} @ {b}")]
diff --git a/harness/codeverse/cli/flywheel_cmd.py b/harness/codeverse/cli/flywheel_cmd.py
index f0c415f7..27732a34 100644
--- a/harness/codeverse/cli/flywheel_cmd.py
+++ b/harness/codeverse/cli/flywheel_cmd.py
@@ -1,4 +1,4 @@
-"""``c3v flywheel export | pairs | caption | index | dedupe``."""
+"""``3dcv flywheel export | pairs | caption | index | dedupe | gallery``."""
from __future__ import annotations
@@ -22,15 +22,22 @@ def export_cmd(
pack: Annotated[bool, typer.Option("--pack", help="also pack samples-NNN.tar + byte-range locators")] = False,
tar_prefix: Annotated[str, typer.Option("--tar-prefix", help="repo-root-relative prefix for the tar column")] = "",
include_unbuilt: Annotated[bool, typer.Option("--include-unbuilt", help="also export runs whose best round never built")] = False,
+ captions_dir: Annotated[Path | None, typer.Option("--captions-dir", help="side-car captions written by `caption --out`")] = None,
+ drop_duplicates: Annotated[bool, typer.Option("--drop-duplicates", help="leave exact duplicates (code fingerprint + prompt) out of the index")] = False,
) -> None:
"""Export runs → sample folders + metadata.parquet (+ optional plain tars)."""
from codeverse.flywheel.export import export_samples
- rep = export_samples(runs_dir, out_dir, min_score=min_score, only_passed=only_passed, include_unbuilt=include_unbuilt)
+ rep = export_samples(runs_dir, out_dir, min_score=min_score, only_passed=only_passed, include_unbuilt=include_unbuilt,
+ captions_dir=captions_dir, drop_duplicates=drop_duplicates)
+ tiers = " ".join(f"{t}:{rep.tiers.get(t, 0)}" for t in "ABCD")
console.print(kv_table("export", {"runs": rep.n_runs, "exported": rep.n_exported, "indexed": rep.n_indexed,
+ "duplicates": rep.n_duplicates, "tiers": tiers,
"skipped": len(rep.skipped), "parquet": rep.parquet}))
for d, why in list(rep.skipped.items())[:20]:
warn(f"skip {Path(d).name}: {why}")
+ for g in rep.duplicates[:20]:
+ warn(f"duplicate of {g.canonical}: {', '.join(g.duplicates)}")
if pack:
from codeverse.flywheel.pack import pack_samples, verify_locators
@@ -44,11 +51,12 @@ def pairs_cmd(
runs_dir: Annotated[Path, typer.Argument()],
out_jsonl: Annotated[Path, typer.Argument()],
min_delta: Annotated[float, typer.Option("--min-delta")] = 0.05,
+ trajectories: Annotated[bool, typer.Option("--trajectories/--no-trajectories", help="also mine in-session repair pairs from agent transcripts")] = True,
) -> None:
- """Preference / repair / cross-backend pairs → JSONL."""
+ """Preference / repair (round + in-session) / cross-backend pairs → JSONL."""
from codeverse.flywheel.pairs import build_pairs
- n = build_pairs(runs_dir, out_jsonl, min_delta=min_delta)
+ n = build_pairs(runs_dir, out_jsonl, min_delta=min_delta, trajectories=trajectories)
ok(f"{n} pairs → {out_jsonl}")
@@ -59,9 +67,11 @@ def caption_cmd(
all_runs: Annotated[bool, typer.Option("--all", help="caption every un-captioned run under target")] = False,
force: Annotated[bool, typer.Option("--force", help="re-caption even if captions exist")] = False,
runs_dir: Annotated[Path | None, typer.Option("--runs-dir")] = None,
+ out: Annotated[Path | None, typer.Option("--out", help="write side-car <out>/<slug>.json instead of touching the run (read-only runs)")] = None,
) -> None:
"""Caption run(s): {detailed, instruction, factory} via a chat model."""
from codeverse.flywheel.captions import CaptionError, caption_sample
+ from codeverse.flywheel.export import load_captions
from codeverse.flywheel.record import iter_runs, load_record
if all_runs:
@@ -71,11 +81,11 @@ def caption_cmd(
targets = [(ws, load_record(ws))]
done = skipped = failed = 0
for ws, rec in targets:
- if not force and (rec.extra.get("captions") or {}).get("detailed"):
+ if not force and load_captions(ws, rec, out).get("detailed"):
skipped += 1
continue
try:
- caps = caption_sample(ws, rec, model)
+ caps = caption_sample(ws, rec, model, out_dir=out)
except CaptionError as e:
failed += 1
warn(str(e))
@@ -144,3 +154,17 @@ def dedupe_cmd(
console.print(f"{len(items)} samples, {len(groups)} duplicate groups")
for g in groups:
console.print(" " + " == ".join(g))
+
+
+@flywheel_app.command("gallery")
+def gallery_cmd(
+ runs_dir: Annotated[Path, typer.Argument(help="runs root")],
+ out_html: Annotated[Path, typer.Argument(help="output .html (self-contained)")],
+ title: Annotated[str | None, typer.Option("--title")] = None,
+ thumb_px: Annotated[int, typer.Option("--thumb-px", min=128, help="thumbnail long edge")] = 640,
+) -> None:
+ """One self-contained HTML page: best sheet, score, cost, prompt, links per run."""
+ from codeverse.flywheel.gallery import write_gallery
+
+ path, n = write_gallery(runs_dir, out_html, title=title, thumb_px=thumb_px)
+ ok(f"gallery of {n} runs → {path} ({path.stat().st_size // 1024} KB)")
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
index bbebf2c3..3f140778 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -1,4 +1,4 @@
-"""``c3v`` — the 3dcodeverse command line.
+"""``3dcv`` — the 3dcodeverse command line.
Thin by design: every command builds typed inputs and calls into the harness
packages lazily (``cli/_common.lazy``), so the CLI imports and prints help
@@ -21,16 +21,18 @@ from codeverse.cli._fmt import console, err_console, kv_table, ok, print_record_
from codeverse.cli.bench_cmd import bench_app
from codeverse.cli.doctor import doctor_app
from codeverse.cli.flywheel_cmd import flywheel_app
+from codeverse.cli.texture_cmd import texture_app
from codeverse.cli.tools_cmd import tools
from codeverse.contracts.common import Backends, Budget, Language, Track
from codeverse.contracts.spec import Constraints, ReferenceImage, Spec
-app = typer.Typer(name="c3v", help="3dcodeverse: LLMs write raw 3D code; the harness builds, judges, refines, records.",
+app = typer.Typer(name="3dcv", help="3dcodeverse: LLMs write raw 3D code; the harness builds, judges, refines, records.",
pretty_exceptions_enable=False)
app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / captions / index.")
app.add_typer(bench_app, name="bench", help="Prompt batteries: run + report.")
app.add_typer(doctor_app, name="doctor", help="Environment checks.")
-app.command("tools", help="List spatial tools or run one: `c3v tools list` | `c3v tools <name> --json '{...}' --workspace ws`.")(tools)
+app.add_typer(texture_app, name="texture", help="Text-to-image texturing: object pass / scene pack.")
+app.command("tools", help="List spatial tools or run one: `3dcv tools list` | `3dcv tools <name> --json '{...}' --workspace ws`.")(tools)
RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
@@ -38,7 +40,7 @@ RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (
@app.callback(invoke_without_command=True)
def _root(ctx: typer.Context, version: Annotated[bool, typer.Option("--version", is_eager=True)] = False) -> None:
if version:
- console.print(f"c3v {__version__}")
+ console.print(f"3dcv {__version__}")
raise typer.Exit()
if ctx.invoked_subcommand is None:
console.print(ctx.get_help())
@@ -59,6 +61,7 @@ def make(
rounds: Annotated[int, typer.Option("--rounds", min=0)] = 4,
max_usd: Annotated[float, typer.Option("--max-usd")] = 5.0,
max_minutes: Annotated[float, typer.Option("--max-minutes")] = 60.0,
+ candidates: Annotated[int | None, typer.Option("--candidates", min=1, help="best-of-N baseline: N parallel candidates, keep the best (default: settings.default_candidates or 1)")] = None,
slug: Annotated[str | None, typer.Option("--slug")] = None,
runs_dir: RunsDirOpt = None,
dim: Annotated[list[str] | None, typer.Option("--dim", help="width=1.2 (meters); repeatable")] = None,
@@ -66,12 +69,15 @@ def make(
must_not: Annotated[list[str] | None, typer.Option("--must-not")] = None,
style: Annotated[str, typer.Option("--style")] = "",
tag: Annotated[list[str] | None, typer.Option("--tag")] = None,
+ texture: Annotated[bool, typer.Option("--texture", help="run the text-to-image texture pass after the rounds (adds the 'texture' tag the track hook reads)")] = False,
seed: Annotated[int, typer.Option("--seed")] = 0,
force: Annotated[bool, typer.Option("--force", help="overwrite an existing run dir")] = False,
no_run: Annotated[bool, typer.Option("--no-run", help="only create the workspace + spec.json")] = False,
) -> None:
"""Create a run (workspace + spec.json) and execute the track pipeline."""
image, dim, must, must_not, tag = image or [], dim or [], must or [], must_not or [], tag or []
+ if texture and "texture" not in tag:
+ tag = [*tag, "texture"]
for p in image:
if not p.is_file():
raise C.CliError(f"reference image not found: {p}")
@@ -93,19 +99,21 @@ def make(
ws.write_json(ws.spec_path, spec)
ws.commit("spec")
console.print(kv_table("run", {"slug": run_slug, "workspace": ws.root, "track": track.value,
- "language": language.value, "generator": backends.generator}))
+ "language": language.value, "generator": backends.generator,
+ "candidates": candidates or "default"}))
if no_run:
- ok(f"spec written: {ws.spec_path} (not run; `c3v resume {run_slug}` to start)")
+ ok(f"spec written: {ws.spec_path} (not run; `3dcv resume {run_slug}` to start)")
return
- _run_track(spec, ws, resume=False)
+ _run_track(spec, ws, resume=False, candidates=candidates)
-def _run_track(spec: Spec, ws, *, resume: bool) -> None:
+def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None) -> None:
get_track = C.lazy("codeverse.tracks", "get_track")
+ options = {"n_candidates": candidates} if candidates else {}
try:
- record = get_track(spec.track).run(spec, ws, resume=resume)
+ record = get_track(spec.track, **options).run(spec, ws, resume=resume)
except KeyboardInterrupt:
- raise C.CliError(f"interrupted; resume with `c3v resume {ws.root.name}`", code=130) from None
+ raise C.CliError(f"interrupted; resume with `3dcv resume {ws.root.name}`", code=130) from None
except Exception as e: # the track failed outside its own error handling
err_console.print_exception(max_frames=8)
raise C.CliError(f"run failed: {type(e).__name__}: {e} (workspace {ws.root}; see events.jsonl)") from e
@@ -115,10 +123,14 @@ def _run_track(spec: Spec, ws, *, resume: bool) -> None:
@app.command()
-def resume(slug: str, runs_dir: RunsDirOpt = None) -> None:
+def resume(
+ slug: str,
+ runs_dir: RunsDirOpt = None,
+ candidates: Annotated[int | None, typer.Option("--candidates", min=1, help="best-of-N baseline width (only matters before round 0 ran)")] = None,
+) -> None:
"""Resume an interrupted / partial run (or start a `--no-run` one)."""
ws = C.open_workspace(slug, runs_dir)
- _run_track(C.load_spec(ws), ws, resume=True)
+ _run_track(C.load_spec(ws), ws, resume=True, candidates=candidates)
# --------------------------------------------------------------------------- status
@@ -139,16 +151,56 @@ def status(slug: str, runs_dir: RunsDirOpt = None, events: Annotated[int, typer.
except ValueError:
rows["run_state"] = "(unreadable)"
console.print(kv_table("status", rows))
+ record = None
try:
- print_record_summary(load_record(ws), ws.root)
+ record = load_record(ws)
+ print_record_summary(record, ws.root)
except RecordError as e:
warn(f"no record yet ({e})")
+ _print_candidates(ws)
+ if record is not None and record.extra.get("texturing"):
+ t = record.extra["texturing"]
+ console.print(kv_table("texturing", {
+ "shipped": t.get("shipped"), "delta": t.get("delta"), "reason": t.get("reason", ""),
+ "textures": t.get("n_textures", len(t.get("textures", {}) or {})),
+ "glb": t.get("glb_textured", "") or "-"}))
evs = EventLog(ws.events_path).read()
if evs:
console.print(f"[dim]last {min(events, len(evs))} of {len(evs)} events:[/dim]")
for ev in evs[-events:]:
- extra = {k: v for k, v in ev.items() if k not in ("t", "kind")}
- console.print(f" {ev.get('kind')} {json.dumps(extra, default=str)[:160]}")
+ extra = {k: v for k, v in ev.items() if k not in ("t", "event")}
+ console.print(f" {_event_time(ev)} {ev.get('event', '?'):<14} {json.dumps(extra, default=str)[:160]}")
+
+
+def _print_candidates(ws) -> None:
+ """Best-of-N candidate table + pairwise verdict (rounds/candidates.json), when present."""
+ p = ws.root / "rounds" / "candidates.json"
+ if not p.is_file():
+ return
+ try:
+ data = json.loads(p.read_text())
+ except ValueError:
+ return
+ cands = data.get("candidates") or []
+ rows: dict[str, str] = {"n": str(data.get("n", len(cands)))}
+ for c in cands:
+ mark = " *" if c.get("index") == data.get("selected") else ""
+ score = c.get("score")
+ rows[f"{c.get('label', c.get('index'))}{mark}"] = (
+ f"score {score if score is None else round(score, 3)} build_ok={c.get('build_ok')}")
+ pw = data.get("pairwise")
+ if pw:
+ rows["pairwise"] = f"{pw.get('a')} vs {pw.get('b')} → {pw.get('winner')} (confidence {pw.get('confidence')})"
+ console.print(kv_table("candidates (best-of-N, * = selected)", rows))
+
+
+def _event_time(ev: dict) -> str:
+ from datetime import UTC, datetime
+
+ try:
+ return datetime.fromtimestamp(float(ev["t"]), UTC).strftime("%H:%M:%S")
+ except (KeyError, TypeError, ValueError, OSError):
+ return "--:--:--"
# --------------------------------------------------------------------------- render / judge
@@ -165,6 +217,9 @@ def render(
spec = C.load_spec(ws)
idx = round_index if round_index is not None else _latest_round(ws)
out_dir = out or ws.renders_dir(idx) / ("cli" if mode == "shaded" else f"cli_{mode}")
+ if spec.track is Track.GRAPHICS:
+ _render_graphics(ws, spec, out_dir)
+ return
if spec.track is Track.SCENE:
render_scene = C.lazy("codeverse.spatial.render", "render_scene")
rs = render_scene(ws, out_dir, cameras=None)
@@ -182,36 +237,70 @@ def render(
def judge(
slug: str,
round_index: Annotated[int | None, typer.Option("--round")] = None,
- rubric: Annotated[str | None, typer.Option("--rubric")] = None,
+ rubric: Annotated[str | None, typer.Option("--rubric", help="default: the rubric the round was judged with")] = None,
model: Annotated[str | None, typer.Option("--model", help="judge chat model id")] = None,
n: Annotated[int, typer.Option("--n", min=1)] = 1,
runs_dir: RunsDirOpt = None,
) -> None:
- """Re-judge a round's renders (writes artifacts/judge/rNN_cli.json)."""
+ """Re-judge a round with the SAME inputs as the in-run judge (renders + measurement +
+ gates + acceptance + plan digest + previous verdict + stored clay views); writes
+ artifacts/judge/rNN_cli.json."""
+ from codeverse.cli import _judge as J
from codeverse.flywheel.record import load_record
ws = C.open_workspace(slug, runs_dir)
rec = load_record(ws)
idx = round_index if round_index is not None else (rec.best_round if rec.best_round is not None else _latest_round(ws))
- rnd = next((r for r in rec.rounds if r.index == idx), None)
- if rnd is None or rnd.renders is None:
- raise C.CliError(f"round {idx} has no renders in record.json")
- JudgeInput = C.lazy("codeverse.judges.base", "JudgeInput")
- VlmJudge = C.lazy("codeverse.judges.vlm_judge", "VlmJudge")
- rubric_name = rubric or {Track.STATIC_OBJECT: "static_object_v1", Track.ARTICULATED_OBJECT: "articulated_v1",
- Track.SCENE: "scene_v1"}[rec.spec.track]
- acceptance = list(getattr(rec.plan, "acceptance", []) or [])
- inp = JudgeInput(spec=rec.spec, renders=rnd.renders, measurement=rnd.measurement, gates=rnd.gates,
- acceptance=acceptance, round_index=idx)
- verdict = VlmJudge(rubric=rubric_name, model_id=model or rec.spec.backends.judge, n_samples=n).judge(inp)
+ rnd = J.load_round(ws, rec, idx)
+ if rnd is None or rnd.renders is None or not rnd.renders.views:
+ raise C.CliError(f"round {idx} has no renders (rounds/r{idx:02d}.json / record.json)")
+ rubric_name = J.rubric_for(rec, rnd, rubric)
+ inp = J.build_judge_input(ws, rec, rnd)
+ judge_obj = J.make_judge(rec, rubric_name, model or rec.spec.backends.judge, n)
+ n_images = J.count_prompt_images(inp, rubric_name)
+ try:
+ verdict = judge_obj.judge(inp)
+ except ValueError as e: # e.g. a measured rubric fed to a judge that computes nothing
+ raise C.CliError(f"judge failed: {e}") from e
+ except Exception as e:
+ ReferenceJudgeError = C.lazy("codeverse.judges.reference", "ReferenceJudgeError")
+ if isinstance(e, ReferenceJudgeError):
+ raise C.CliError(f"judge failed: {e}") from e
+ raise
ws.write_json(ws.judge_path(idx, "_cli"), verdict)
- console.print(kv_table("judgment", {"rubric": verdict.rubric, "overall": f"{verdict.overall:.3f}",
- "passed": verdict.passed, "std": verdict.score_std, "summary": verdict.summary,
+ console.print(kv_table("judgment", {"rubric": verdict.rubric, "round": idx, "overall": f"{verdict.overall:.3f}",
+ "passed": verdict.passed, "std": verdict.score_std,
+ "prompt images": n_images if n_images is not None else "?",
+ "stored score": f"{rnd.judgment.overall:.3f}" if rnd.judgment else "-",
+ "summary": verdict.summary,
"cost": f"${verdict.usage.cost_usd:.4f}"}))
for it in verdict.improvement_plan:
console.print(f" [{it.priority}] {it.target}: {it.instruction}")
+def _render_graphics(ws, spec: Spec, out_dir: Path) -> None:
+ """Graphics runs have no GLB: regenerate the judged frames + sheet via the runtime."""
+ import shutil
+
+ get_runtime = C.lazy("codeverse.languages", "get_runtime")
+ br = get_runtime(spec.language).build(ws)
+ if not br.ok:
+ raise C.CliError(f"graphics build failed: {br.error_type}: {br.error_message}")
+ out_dir.mkdir(parents=True, exist_ok=True)
+ frames_dir = Path(br.extra_paths.get("frames") or (ws.artifacts / "frames"))
+ n = 0
+ for p in sorted(frames_dir.glob("*.png")) if frames_dir.is_dir() else []:
+ shutil.copy2(p, out_dir / p.name)
+ n += 1
+ sheet = br.extra_paths.get("sheet") or ""
+ if sheet and Path(sheet).is_file():
+ shutil.copy2(sheet, out_dir / "sheet.png")
+ sheet = str(out_dir / "sheet.png")
+ renderer = br.census.get("renderer", "moderngl") if isinstance(br.census, dict) else "moderngl"
+ console.print(kv_table("renders", {"views": n, "sheet": sheet or "-", "dir": out_dir,
+ "renderer": renderer, "ms": br.duration_ms}))
+
+
def _latest_round(ws) -> int:
rdir = ws.artifacts / "renders"
idxs = sorted(int(p.name[1:]) for p in rdir.glob("r[0-9][0-9]") if p.is_dir()) if rdir.is_dir() else []
diff --git a/harness/codeverse/cli/texture_cmd.py b/harness/codeverse/cli/texture_cmd.py
new file mode 100644
index 00000000..69267eb1
--- /dev/null
+++ b/harness/codeverse/cli/texture_cmd.py
@@ -0,0 +1,107 @@
+"""``3dcv texture`` — text-to-image texturing commands.
+
+ 3dcv texture pass <slug> [--no-judge] [--model gemini:gemini-3.7-flash] [--image-model gemini-3.1-flash-image]
+ 3dcv texture scene-pack <slug> [--n 8] [--model ...]
+ 3dcv texture show <slug>
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from codeverse.cli import _common as C
+from codeverse.cli._fmt import console, kv_table, warn
+from codeverse.contracts.common import Track
+
+texture_app = typer.Typer(name="texture", help="Text-to-image texturing: object pass + scene texture pack.",
+ no_args_is_help=True)
+
+RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
+
+
+def _image_model(name: str | None):
+ GeminiImageModel = C.lazy("codeverse.models.gemini_image", "GeminiImageModel")
+ return GeminiImageModel(name) if name else GeminiImageModel()
+
+
+@texture_app.command("pass")
+def pass_(
+ slug: str,
+ judge: Annotated[bool, typer.Option("--judge/--no-judge", help="before/after VLM ship gate")] = True,
+ model: Annotated[str | None, typer.Option("--model", help="material-plan chat model id (default: spec planner)")] = None,
+ judge_model: Annotated[str | None, typer.Option("--judge-model", help="judge chat model id (default: spec judge)")] = None,
+ image_model: Annotated[str | None, typer.Option("--image-model", help="gemini image model (default gemini-3.1-flash-image)")] = None,
+ size: Annotated[int, typer.Option("--size", min=256, max=2048)] = 1024,
+ runs_dir: RunsDirOpt = None,
+) -> None:
+ """Texture the run's artifacts/object.glb → artifacts/object_textured.glb (+ textures/)."""
+ ws = C.open_workspace(slug, runs_dir)
+ spec = C.load_spec(ws)
+ if spec.track not in (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT):
+ raise C.CliError(f"texture pass is for object tracks; {spec.track.value} runs use `3dcv texture scene-pack`")
+ load_plan = C.lazy("codeverse.spatial.tool_common", "load_plan")
+ plan = load_plan(ws.plan_path)
+ texture_pass = C.lazy("codeverse.texturing.run", "texture_pass")
+ rep = texture_pass(ws, spec, plan, model_id=model or spec.backends.planner, image_model=_image_model(image_model),
+ judge=judge, judge_model_id=judge_model, size=size)
+ _print_report(rep)
+
+
+@texture_app.command("show")
+def show(slug: str, runs_dir: RunsDirOpt = None) -> None:
+ """Print the last texturing report of a run."""
+ ws = C.open_workspace(slug, runs_dir)
+ load_report = C.lazy("codeverse.texturing.run", "load_report")
+ try:
+ rep = load_report(ws)
+ except FileNotFoundError as e:
+ raise C.CliError(str(e)) from e
+ _print_report(rep)
+
+
+def _print_report(rep) -> None:
+ plan_table = C.lazy("codeverse.texturing.plan", "plan_table")
+ console.print(plan_table(rep.plan))
+ rows = {tid: f"{Path(a.path).name} seam={a.seam_score:.3f} (raw {a.seam_score_raw:.3f}) cached={a.cached}"
+ + (f" ERROR {a.error}" if a.error else "") for tid, a in rep.textures.textures.items()}
+ console.print(kv_table("textures", rows or {"-": "none"}))
+ s = rep.summary()
+ if rep.gate is not None and rep.gate.overall_before is not None:
+ s.update({"before": f"{rep.gate.overall_before:.3f}", "after": f"{rep.gate.overall_after:.3f}",
+ "materials": f"{rep.gate.materials_before:.3f} → {rep.gate.materials_after:.3f}"})
+ console.print(kv_table("texture pass", s))
+ for n in rep.notes:
+ warn(n)
+
+
+@texture_app.command("scene-pack")
+def scene_pack(
+ slug: str,
+ n: Annotated[int, typer.Option("--n", min=1, max=16, help="max textures")] = 10,
+ model: Annotated[str | None, typer.Option("--model", help="pack-plan chat model id (default: spec planner; '' = heuristic)")] = None,
+ image_model: Annotated[str | None, typer.Option("--image-model")] = None,
+ size: Annotated[int, typer.Option("--size", min=256, max=2048)] = 1024,
+ out: Annotated[Path | None, typer.Option("--out", help="output dir (default <ws>/public/textures)")] = None,
+ runs_dir: RunsDirOpt = None,
+) -> None:
+ """Generate the scene's tileable texture pack into public/textures/ (+ manifest.json)."""
+ ws = C.open_workspace(slug, runs_dir)
+ spec = C.load_spec(ws)
+ load_plan = C.lazy("codeverse.spatial.tool_common", "load_plan")
+ plan = load_plan(ws.plan_path)
+ ScenePlan = C.lazy("codeverse.contracts.plan", "ScenePlan")
+ if not isinstance(plan, ScenePlan):
+ raise C.CliError("scene-pack needs a scene run (plan.json with zones)")
+ scene_texture_pack = C.lazy("codeverse.texturing.scene_pack", "scene_texture_pack")
+ texture_pack_prompt = C.lazy("codeverse.texturing.scene_pack", "texture_pack_prompt")
+ model_id = spec.backends.planner if model is None else model
+ pack = scene_texture_pack(plan, out or ws.public / "textures", _image_model(image_model), model_id, size=size, n_max=n)
+ rows = {name: f"{e.file or 'FAILED'} tile={e.tile_size_m:.2f}m {e.material_family}/{e.role} seam={e.seam_score:.3f}"
+ + (f" {e.error}" if e.error else "") for name, e in pack.entries.items()}
+ console.print(kv_table("scene texture pack", rows))
+ console.print(kv_table("summary", {"dir": pack.out_dir, "manifest": pack.manifest_path, "source": pack.source,
+ "cost": f"${pack.usage.cost_usd:.4f}", "n": len(pack.manifest())}))
+ console.print(texture_pack_prompt(pack.manifest()))
diff --git a/harness/codeverse/cli/tools_cmd.py b/harness/codeverse/cli/tools_cmd.py
index 0f2dd801..437e3351 100644
--- a/harness/codeverse/cli/tools_cmd.py
+++ b/harness/codeverse/cli/tools_cmd.py
@@ -1,7 +1,7 @@
-"""``c3v tools`` — list registry tools or run one (prints an Observation).
+"""``3dcv tools`` — list registry tools or run one (prints an Observation).
This is also the fallback path for agentic CLIs without MCP support: the
-prompt tells them to shell out to ``c3v tools <name> --json '{...}' --workspace .``.
+prompt tells them to shell out to ``3dcv tools <name> --json '{...}' --workspace .``.
"""
from __future__ import annotations
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
index 14b8f6fb..57baa80c 100644
--- a/harness/codeverse/config.py
+++ b/harness/codeverse/config.py
@@ -1,7 +1,7 @@
"""Harness settings: keys, binaries, directories, defaults.
Resolution order (later wins): built-in defaults < ``~/.config/codeverse/config.yaml``
-< ``./codeverse.yaml`` < environment variables (``C3V_*``). Secrets are never
+< ``./codeverse.yaml`` < environment variables (``CV3D_*``). Secrets are never
written to run records.
Gemini keys: ``GEMINI_API_KEYS`` (csv) or ``GEMINI_API_KEY`` or the owner's
@@ -54,7 +54,7 @@ class Limits(BaseModel):
class Settings(BaseSettings):
- model_config = SettingsConfigDict(env_prefix="C3V_", env_nested_delimiter="__", extra="ignore")
+ model_config = SettingsConfigDict(env_prefix="CV3D_", env_nested_delimiter="__", extra="ignore")
runs_dir: Path = Field(default=Path("runs"))
cache_dir: Path = Field(default=Path.home() / ".cache" / "codeverse")
@@ -69,7 +69,10 @@ class Settings(BaseSettings):
default_planner: str = "gemini:gemini-3.7-flash"
default_generator: str = "api-agent:gemini:gemini-3.7-flash"
- default_judge: str = "gemini:gemini-3.7-flash"
+ # The judge drives the refine loop: the pro tier has ~3x lower sample noise than flash
+ # (calibration 2026-08-23: std 0.03 vs 0.08-0.12) for ~$0.07 per verdict.
+ default_judge: str = "gemini:gemini-3.1-pro-preview"
+ default_candidates: int = Field(default=1, description="best-of-N baseline candidates (tracks read it)")
# ------------------------------------------------------------------ helpers
def resolve_blender(self) -> str:
diff --git a/harness/codeverse/contracts/__init__.py b/harness/codeverse/contracts/__init__.py
index fd6f9146..01cb2c65 100644
--- a/harness/codeverse/contracts/__init__.py
+++ b/harness/codeverse/contracts/__init__.py
@@ -41,7 +41,9 @@ from codeverse.contracts.plan import (
BBox,
CameraPlan,
EffectPlan,
+ GraphicsPlan,
JointPlan,
+ PassPlan,
PartPlan,
Plan,
ScenePlan,
diff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.py
index ea41a46f..82a3ecd2 100644
--- a/harness/codeverse/contracts/agent.py
+++ b/harness/codeverse/contracts/agent.py
@@ -25,7 +25,7 @@ class AgentJob(BaseModel):
timeout_s: int = 1800
max_turns: int = 60
allow_network: bool = False
- spatial_tools: bool = Field(default=True, description="expose the c3v MCP spatial tools to the agent")
+ spatial_tools: bool = Field(default=True, description="expose the 3dcv MCP spatial tools to the agent")
write_roots: list[str] = Field(default_factory=lambda: ["src", "public"], description="dirs the agent may edit")
env: dict[str, str] = Field(default_factory=dict)
extra: dict[str, Any] = Field(default_factory=dict)
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
index 33dc1e24..e1a280c2 100644
--- a/harness/codeverse/contracts/common.py
+++ b/harness/codeverse/contracts/common.py
@@ -16,6 +16,7 @@ class Track(StrEnum):
STATIC_OBJECT = "static_object"
ARTICULATED_OBJECT = "articulated_object"
SCENE = "scene"
+ GRAPHICS = "graphics" # shader / OpenGL effects (2D/2.5D/3D procedural graphics)
class Language(StrEnum):
@@ -26,6 +27,8 @@ class Language(StrEnum):
THREEJS = "threejs" # procedural three.js (ESM) → GLB via GLTFExporter
URDF_BLENDER = "urdf_blender" # bpy link meshes + hand-written URDF
SCENE_THREEJS = "scene_threejs" # multi-file three.js scene (+GLSL, +GLB assets)
+ GLSL_SHADER = "glsl_shader" # Shadertoy-style fragment shader (GLSL 330/ES 3.0), rendered by moderngl
+ OPENGL_PYTHON = "opengl_python" # raw OpenGL via moderngl + GLSL (multi-pass, geometry, FBOs)
#: languages allowed per track
@@ -33,6 +36,7 @@ TRACK_LANGUAGES: dict[Track, tuple[Language, ...]] = {
Track.STATIC_OBJECT: (Language.BLENDER, Language.CADQUERY, Language.THREEJS),
Track.ARTICULATED_OBJECT: (Language.URDF_BLENDER,),
Track.SCENE: (Language.SCENE_THREEJS,),
+ Track.GRAPHICS: (Language.GLSL_SHADER, Language.OPENGL_PYTHON),
}
@@ -84,5 +88,5 @@ class Backends(BaseModel):
planner: str = "gemini:gemini-3.7-flash"
generator: str = "api-agent:gemini:gemini-3.7-flash"
- judge: str = "gemini:gemini-3.7-flash"
+ judge: str = "gemini:gemini-3.1-pro-preview"
captioner: str = "gemini:gemini-3.7-flash"
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.py
index 67a888b5..db80f371 100644
--- a/harness/codeverse/contracts/plan.py
+++ b/harness/codeverse/contracts/plan.py
@@ -201,4 +201,25 @@ class ScenePlan(BaseModel):
return self
-Plan = StaticPlan | ArticulatedPlan | ScenePlan
+class PassPlan(BaseModel):
+ name: str = Field(description="PascalCase pass name, e.g. Clouds, Bloom")
+ kind: Literal["fullscreen", "geometry", "postprocess", "feedback"] = "fullscreen"
+ description: str = Field(description="what this pass draws / computes, concrete")
+
+
+class GraphicsPlan(BaseModel):
+ """Plan for the graphics track (GLSL shader / raw OpenGL program)."""
+
+ title: str
+ summary: str
+ style: str = Field(description="visual style: palette, mood, references in words")
+ resolution: tuple[int, int] = (1280, 720)
+ duration_s: float = Field(default=8.0, description="loop length for judging / video")
+ passes: list[PassPlan] = Field(min_length=1)
+ uniforms: list[str] = Field(default_factory=list, description="uniform names the program exposes (u_time, u_resolution, ...)")
+ motion: str = Field(default="", description="what animates over time and how")
+ key_visuals: list[str] = Field(default_factory=list, description="3-8 visible elements a viewer must recognise")
+ acceptance: list[AcceptanceItem] = Field(default_factory=list)
+
+
+Plan = StaticPlan | ArticulatedPlan | ScenePlan | GraphicsPlan
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
index 6ac1ba19..0e58ef36 100644
--- a/harness/codeverse/contracts/run.py
+++ b/harness/codeverse/contracts/run.py
@@ -11,7 +11,7 @@ from pydantic import BaseModel, Field
from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
from codeverse.contracts.common import Usage
from codeverse.contracts.judgment import Judgment
-from codeverse.contracts.plan import ArticulatedPlan, ScenePlan, StaticPlan
+from codeverse.contracts.plan import ArticulatedPlan, GraphicsPlan, ScenePlan, StaticPlan
from codeverse.contracts.spec import Spec
@@ -48,7 +48,7 @@ class RoundRecord(BaseModel):
class RunRecord(BaseModel):
spec: Spec
- plan: StaticPlan | ArticulatedPlan | ScenePlan | None = None
+ plan: StaticPlan | ArticulatedPlan | ScenePlan | GraphicsPlan | None = None
workspace: str
status: RunStatus = RunStatus.PLANNING
rounds: list[RoundRecord] = Field(default_factory=list)
diff --git a/harness/codeverse/flywheel/__init__.py b/harness/codeverse/flywheel/__init__.py
index bc1e6a82..33b5eb5e 100644
--- a/harness/codeverse/flywheel/__init__.py
+++ b/harness/codeverse/flywheel/__init__.py
@@ -8,5 +8,8 @@ Public API (see docs/INTERFACES.md):
* ``pairs`` ``build_pairs(runs_dir, out_jsonl, min_delta=..)`` → n
* ``captions`` ``caption_sample(ws, record, model_id)`` → ``Captions``
* ``dedupe`` ``code_fingerprint`` · ``mesh_fingerprint`` · ``near_duplicates``
+* ``quality`` ``quality_tier`` (A/B/C/D) · ``prompt_hash`` · exact (code, prompt) duplicate groups
+* ``trajectories`` in-session repair pairs mined from api-agent transcripts
+* ``gallery`` ``write_gallery(runs_dir, out_html)`` · ``render_gallery(items, title)`` (shared with bench/report.py)
* ``index`` ``build_index(runs_dir, out_sqlite)`` + query helpers
"""
diff --git a/harness/codeverse/flywheel/_git.py b/harness/codeverse/flywheel/_git.py
index c5178996..39ab28e7 100644
--- a/harness/codeverse/flywheel/_git.py
+++ b/harness/codeverse/flywheel/_git.py
@@ -38,6 +38,19 @@ def _run(ws: Workspace, *args: str) -> subprocess.CompletedProcess[bytes]:
return proc
+def commit_by_subject(ws: Workspace, subject: str) -> str | None:
+ """SHA of the newest commit whose subject line equals ``subject`` (None = no match)."""
+ try:
+ out = _run(ws, "log", "--format=%H%x00%s").stdout
+ except GitReadError:
+ return None
+ for line in out.decode("utf-8", errors="replace").splitlines():
+ sha, _, subj = line.partition("\0")
+ if subj.strip() == subject:
+ return sha
+ return None
+
+
def commit_exists(ws: Workspace, commit: str) -> bool:
if not commit:
return False
diff --git a/harness/codeverse/flywheel/captions.py b/harness/codeverse/flywheel/captions.py
index 2c6c9c53..940d228d 100644
--- a/harness/codeverse/flywheel/captions.py
+++ b/harness/codeverse/flywheel/captions.py
@@ -8,7 +8,9 @@
Rules enforced in code: strict JSON schema, no API/class names, no brand names,
each field non-empty. Captions are stored in ``record.extra["captions"]`` (with
-provenance) and ``<ws>/captions.json``; ``record.json`` is rewritten.
+provenance) and ``<ws>/captions.json``; ``record.json`` is rewritten — or, with
+``out_dir`` (read-only runs), written as a side-car ``<out_dir>/<slug>.json`` that
+``export_samples(captions_dir=...)`` picks up.
"""
from __future__ import annotations
@@ -30,6 +32,8 @@ from codeverse.workspace import Workspace
MAX_CODE_CHARS = 12_000
N_VIEWS = 2
+#: view-name fragments that show motion (articulated track) — shown to the captioner first
+MOTION_VIEW_HINTS = ("articulation", "pose_")
#: how the instruction must name the target (generic, no API names)
LANGUAGE_PHRASE: dict[Language, str] = {
@@ -38,13 +42,19 @@ LANGUAGE_PHRASE: dict[Language, str] = {
Language.THREEJS: "a Three.js module",
Language.URDF_BLENDER: "a URDF model with Blender-Python-built link meshes",
Language.SCENE_THREEJS: "a Three.js scene",
+ Language.GLSL_SHADER: "a GLSL fragment shader",
+ Language.OPENGL_PYTHON: "an OpenGL Python program",
}
-#: leaked API / platform tokens that must not appear in any caption
+#: leaked API / platform tokens that must not appear in any caption. NOTE:
+#: ``THREE.`` (the API namespace) is checked case-sensitively below — the
+#: platform name "Three.js" is REQUIRED in threejs instructions and must not trip it.
_FORBIDDEN = re.compile(
- r"\b(bpy|bmesh|mathutils|cq\.|cadquery\.|THREE\.|GLTFLoader|ShaderMaterial|MeshStandardMaterial|"
- r"Workplane|Shadertoy|Sketchfab|Gemini|Claude|OpenAI|GPT|Antigravity)\b",
+ r"\b(bpy|bmesh|mathutils|cq\.|cadquery\.|GLTFLoader|ShaderMaterial|MeshStandardMaterial|"
+ r"Workplane|moderngl|Shadertoy|Sketchfab|Gemini|Claude|OpenAI|GPT|Antigravity)\b",
re.IGNORECASE,
)
+#: all-caps ``THREE.<Symbol>`` namespace usage (case-sensitive; "Three.js" / "THREE.js" stay legal)
+_FORBIDDEN_THREE_NS = re.compile(r"\bTHREE\.(?!js\b)")
class Captions(BaseModel):
@@ -103,7 +113,9 @@ def _round_images(ws: Workspace, record: RunRecord) -> tuple[list[ImagePart], li
used.append(str(p))
_add(rnd.renders.contact_sheet, "contact sheet (all views, labelled)")
- for v in rnd.renders.views[:N_VIEWS]:
+ views = list(rnd.renders.views)
+ motion = [v for v in views if any(h in v.name for h in MOTION_VIEW_HINTS)]
+ for v in (motion + [v for v in views if v not in motion])[:N_VIEWS]:
_add(v.path, f"view: {v.name}")
return images, used
@@ -118,7 +130,8 @@ def _code_excerpt(ws: Workspace, record: RunRecord) -> str:
def _user_prompt(record: RunRecord, code: str) -> str:
- kind = {Track.STATIC_OBJECT: "static object", Track.ARTICULATED_OBJECT: "articulated object", Track.SCENE: "scene"}[record.spec.track]
+ kind = {Track.STATIC_OBJECT: "static object", Track.ARTICULATED_OBJECT: "articulated object",
+ Track.SCENE: "scene", Track.GRAPHICS: "animated procedural graphics (judged from sampled frames)"}[record.spec.track]
return (
f"Asset kind: {kind}.\nOriginal user request: {record.spec.prompt}\n\n"
f"Source code (raw, may be truncated):\n{code}\n\nReturn the JSON now."
@@ -129,18 +142,25 @@ def validate_captions(caps: Captions, language: Language) -> list[str]:
"""Rule violations (empty list = ok)."""
problems = []
for field in ("detailed", "instruction", "factory"):
- m = _FORBIDDEN.search(getattr(caps, field))
+ m = _FORBIDDEN.search(getattr(caps, field)) or _FORBIDDEN_THREE_NS.search(getattr(caps, field))
if m:
problems.append(f"{field}: must not mention '{m.group(0)}' (API/platform name)")
phrase_words = {Language.BLENDER: "blender", Language.CADQUERY: "cadquery", Language.THREEJS: "three.js",
- Language.URDF_BLENDER: "urdf", Language.SCENE_THREEJS: "three.js"}[language]
+ Language.URDF_BLENDER: "urdf", Language.SCENE_THREEJS: "three.js",
+ Language.GLSL_SHADER: "glsl", Language.OPENGL_PYTHON: "opengl"}[language]
if phrase_words not in caps.instruction.lower():
problems.append(f"instruction: must name the target language ({LANGUAGE_PHRASE[language]})")
return problems
-def caption_sample(ws: Workspace, record: RunRecord, model_id: str, *, model: object | None = None) -> Captions:
- """Caption the best round of ``record``; stores into record.extra + captions.json."""
+def caption_sample(
+ ws: Workspace, record: RunRecord, model_id: str, *, model: object | None = None, out_dir: Path | str | None = None
+) -> Captions:
+ """Caption the best round of ``record``.
+
+ Default: store into ``record.extra["captions"]`` + ``<ws>/captions.json`` and
+ rewrite ``record.json``. With ``out_dir`` the workspace is left untouched and
+ ``<out_dir>/<slug>.json`` (captions + provenance) is written instead."""
if model is None:
from codeverse.models import get_chat_model
@@ -174,14 +194,28 @@ def caption_sample(ws: Workspace, record: RunRecord, model_id: str, *, model: ob
if caps is None or problems:
raise CaptionError(f"{ws.root}: captions rejected after retry: {problems}")
rnd = best_round_record(record)
- prov = CaptionProvenance(captioner=model_id, round_index=rnd.index if rnd else None, images_used=used,
- code_chars=len(code), prompt_hash=prompt_hash(system), cost_usd=cost)
- record.extra["captions"] = {**caps.model_dump(), "provenance": prov.model_dump(mode="json")}
- ws.write_json(ws.root / "captions.json", caps.model_dump())
+ prov = CaptionProvenance(captioner=model_id, round_index=rnd.index if rnd else None,
+ images_used=[_rel(ws, u) for u in used], code_chars=len(code),
+ prompt_hash=prompt_hash(system), cost_usd=cost)
+ payload = {**caps.model_dump(), "provenance": prov.model_dump(mode="json")}
+ record.extra["captions"] = payload
+ if out_dir is not None:
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / f"{ws.root.name}.json").write_text(json.dumps(payload, indent=2, ensure_ascii=False))
+ return caps
+ ws.write_json(ws.root / "captions.json", payload)
ws.write_json(ws.record_path, record)
return caps
+def _rel(ws: Workspace, path: str) -> str:
+ try:
+ return Path(path).relative_to(ws.root).as_posix()
+ except ValueError:
+ return path
+
+
def _parse_json(text: str) -> dict:
s = text.strip()
if s.startswith("```"):
diff --git a/harness/codeverse/flywheel/export.py b/harness/codeverse/flywheel/export.py
index c739ed9f..24c07c0d 100644
--- a/harness/codeverse/flywheel/export.py
+++ b/harness/codeverse/flywheel/export.py
@@ -7,9 +7,16 @@ consistent):
* ``<out>/metadata.parquet`` — STORAGE_RULES §4 columns (``id, key, name,
captions{detailed,instruction,factory}, meta_json, code, tar, byte_start,
- byte_len, n_files``) plus a few queryable extras (``track, language, score,
- passed, generator``). ``tar``/``byte_*`` are filled by ``pack.py``.
+ byte_len, n_files``) plus queryable extras (``track, language, score, passed,
+ generator, quality_tier, gate_errors, cost_usd, rounds, status,
+ code_fingerprint, prompt_hash, duplicate_of, has_captions``). ``tar``/``byte_*``
+ are filled by ``pack.py``; ``duplicate_of`` by the (code fingerprint, prompt)
+ dedupe pass (``""`` = canonical row).
* ``<out>/metadata.jsonl`` — same rows, one JSON object per line.
+* ``<out>/duplicates.json`` — the duplicate groups found by the last export.
+
+Captions come from ``record.extra["captions"]``, else ``<ws>/captions.json``,
+else ``<captions_dir>/<slug>.json`` (side-car written by ``3dcv flywheel caption --out``).
"""
from __future__ import annotations
@@ -22,8 +29,10 @@ from typing import Any
from pydantic import BaseModel, Field
+from codeverse.contracts.common import Language
from codeverse.contracts.run import RunRecord
from codeverse.flywheel import sample as S
+from codeverse.flywheel.quality import DuplicateGroup, mark_duplicates
from codeverse.flywheel.record import iter_runs
from codeverse.workspace import Workspace
@@ -31,6 +40,7 @@ log = logging.getLogger(__name__)
PARQUET_NAME = "metadata.parquet"
JSONL_NAME = "metadata.jsonl"
+DUPLICATES_NAME = "duplicates.json"
CAPTION_KEYS = ("detailed", "instruction", "factory")
@@ -38,18 +48,42 @@ class ExportReport(BaseModel):
n_runs: int = 0
n_exported: int = 0
n_indexed: int = 0
+ n_duplicates: int = Field(default=0, description="rows marked duplicate_of (dropped when drop_duplicates)")
skipped: dict[str, str] = Field(default_factory=dict, description="run dir → reason")
exported: list[str] = Field(default_factory=list, description="sample dirs (relative to out_dir)")
+ duplicates: list[DuplicateGroup] = Field(default_factory=list)
+ tiers: dict[str, int] = Field(default_factory=dict, description="quality tier → count (indexed rows)")
parquet: str = ""
jsonl: str = ""
-def _captions_of(record: RunRecord) -> dict[str, str]:
+def load_captions(ws: Workspace, record: RunRecord, captions_dir: Path | None = None) -> dict[str, Any]:
+ """Full captions dict (text fields + provenance) from record.extra, ``<ws>/captions.json``
+ or ``<captions_dir>/<slug>.json``; ``{}`` when the run is not captioned."""
caps = record.extra.get("captions") or {}
+ if caps.get("detailed"):
+ return dict(caps)
+ candidates = [ws.root / "captions.json"]
+ if captions_dir is not None:
+ candidates.append(Path(captions_dir) / f"{ws.root.name}.json")
+ for p in candidates:
+ if p.is_file():
+ try:
+ data = json.loads(p.read_text())
+ except ValueError:
+ continue
+ if isinstance(data, dict) and data.get("detailed"):
+ return data
+ return {}
+
+
+def _caption_texts(caps: dict[str, Any]) -> dict[str, str]:
return {k: str(caps.get(k, "") or "") for k in CAPTION_KEYS} if caps.get("detailed") else {}
-def export_one(ws: Workspace, record: RunRecord, out_dir: Path, *, overwrite: bool = True) -> Path:
+def export_one(
+ ws: Workspace, record: RunRecord, out_dir: Path, *, overwrite: bool = True, captions_dir: Path | None = None
+) -> Path:
"""Write the sample folder for one run; returns the sample dir."""
key = S.sample_key(ws)
dest = out_dir / S.sample_rel_dir(record, key)
@@ -66,11 +100,14 @@ def export_one(ws: Workspace, record: RunRecord, out_dir: Path, *, overwrite: bo
if entry not in written:
raise S.SampleError(f"entry file {S.ENTRY_BY_LANGUAGE[record.spec.language]} missing at {code_source}")
renders = S.copy_renders(ws, rnd, dest)
- captions = _captions_of(record)
- (dest / "captions.json").write_text(json.dumps(captions, indent=2, ensure_ascii=False))
- all_files = sorted(written + renders + ["captions.json", "meta.json"])
+ meshes = S.copy_link_meshes(ws, dest) if record.spec.language is Language.URDF_BLENDER else []
+ textured = S.copy_textured(ws, record, dest)
+ captions = load_captions(ws, record, captions_dir)
+ (dest / "captions.json").write_text(json.dumps(_caption_texts(captions), indent=2, ensure_ascii=False))
+ all_files = sorted(written + renders + meshes + textured + ["captions.json", "meta.json"])
meta = S.build_meta(
- ws, record, key=key, entry=entry, files=all_files, renders=renders, rnd=rnd, code_source=code_source
+ ws, record, key=key, entry=entry, files=all_files, renders=renders, rnd=rnd, code_source=code_source,
+ code=files, captions=captions,
)
tmp = dest / "meta.json.tmp"
tmp.write_text(meta.model_dump_json(indent=2))
@@ -87,6 +124,8 @@ def export_samples(
best_round: bool = True,
overwrite: bool = True,
include_unbuilt: bool = False,
+ captions_dir: Path | str | None = None,
+ drop_duplicates: bool = False,
) -> ExportReport:
"""Export every eligible run under ``runs_dir`` into ``out_dir`` and rebuild the index.
@@ -94,7 +133,9 @@ def export_samples(
API stability); the best round is chosen by ``record.best_round`` or the
highest judged score. Runs whose best round never built are skipped unless
``include_unbuilt`` (failed runs are still useful for repair pairs, not as
- dataset samples).
+ dataset samples). Exact duplicates (same code fingerprint + prompt) are
+ marked in the index (``duplicate_of``) and, with ``drop_duplicates``, left
+ out of it (their folders stay on disk).
"""
if not best_round:
raise ValueError("export_samples: only best_round=True is supported")
@@ -108,21 +149,23 @@ def export_samples(
for ws, rec in iter_runs(runs_dir, on_error=_bad):
rep.n_runs += 1
rnd = S.best_round_record(rec)
- score = rnd.score if rnd is not None else None
+ j = S.effective_judgment(rnd) if rnd is not None else None
+ score = j.overall if j is not None else None
if rnd is None:
rep.skipped[str(ws.root)] = "no rounds"
continue
if not include_unbuilt and not (rnd.build is not None and rnd.build.ok):
rep.skipped[str(ws.root)] = "best round did not build"
continue
- if only_passed and not (rnd is not None and rnd.judgment is not None and rnd.judgment.passed):
+ if only_passed and not (j is not None and j.passed):
rep.skipped[str(ws.root)] = "not passed"
continue
if min_score is not None and (score is None or score < min_score):
rep.skipped[str(ws.root)] = f"score {score} < min_score {min_score}"
continue
try:
- dest = export_one(ws, rec, out, overwrite=overwrite)
+ dest = export_one(ws, rec, out, overwrite=overwrite,
+ captions_dir=Path(captions_dir) if captions_dir else None)
except S.SampleError as e:
rep.skipped[str(ws.root)] = str(e)
continue
@@ -132,7 +175,14 @@ def export_samples(
rep.n_exported += 1
rep.exported.append(str(dest.relative_to(out)))
rows = collect_rows(out)
+ rep.duplicates = mark_duplicates(rows)
+ rep.n_duplicates = sum(len(g.duplicates) for g in rep.duplicates)
+ (out / DUPLICATES_NAME).write_text(json.dumps([g.model_dump() for g in rep.duplicates], indent=2))
+ if drop_duplicates:
+ rows = [r for r in rows if not r["duplicate_of"]]
rep.n_indexed = len(rows)
+ for r in rows:
+ rep.tiers[r["quality_tier"]] = rep.tiers.get(r["quality_tier"], 0) + 1
rep.parquet = str(write_parquet(rows, out / PARQUET_NAME))
rep.jsonl = str(write_jsonl(rows, out / JSONL_NAME))
return rep
@@ -164,6 +214,15 @@ def row_for_sample(sample_dir: Path) -> dict[str, Any]:
"score": meta.get("score"),
"passed": meta.get("passed"),
"generator": meta.get("generator", ""),
+ "quality_tier": str(meta.get("quality_tier") or "D"),
+ "gate_errors": int(meta.get("gate_errors") or 0),
+ "cost_usd": float(meta.get("cost_usd") or 0.0),
+ "rounds": int(meta.get("rounds") or 0),
+ "status": str(meta.get("status") or ""),
+ "code_fingerprint": str(meta.get("code_fingerprint") or ""),
+ "prompt_hash": str(meta.get("prompt_hash") or ""),
+ "duplicate_of": "",
+ "has_captions": bool(caps.get("detailed")),
}
@@ -197,6 +256,15 @@ def parquet_schema() -> Any:
("score", pa.float64()),
("passed", pa.bool_()),
("generator", pa.string()),
+ ("quality_tier", pa.string()),
+ ("gate_errors", pa.int32()),
+ ("cost_usd", pa.float64()),
+ ("rounds", pa.int32()),
+ ("status", pa.string()),
+ ("code_fingerprint", pa.string()),
+ ("prompt_hash", pa.string()),
+ ("duplicate_of", pa.string()),
+ ("has_captions", pa.bool_()),
]
)
diff --git a/harness/codeverse/flywheel/gallery.py b/harness/codeverse/flywheel/gallery.py
new file mode 100644
index 00000000..dd9fe355
--- /dev/null
+++ b/harness/codeverse/flywheel/gallery.py
@@ -0,0 +1,222 @@
+"""Self-contained HTML gallery of runs: one card per run with the best round's
+contact sheet (embedded thumbnail), score / cost / rounds / tier, prompt,
+track · language · backend and ``file://`` links to the artifacts.
+
+``render_gallery(items, title)`` is the shared renderer: ``3dcv flywheel gallery``
+feeds it run records (``gallery_items``), ``bench/report.py`` feeds it bench
+results. No external assets — images are base64 JPEG thumbnails, the filter /
+sort controls are a few lines of inline JS.
+"""
+
+from __future__ import annotations
+
+import base64
+import html
+import io
+import statistics
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel.quality import quality_tier
+from codeverse.flywheel.record import effective_judgment, iter_runs
+from codeverse.flywheel.sample import best_round_record, gate_error_summary
+from codeverse.workspace import Workspace
+
+THUMB_PX = 640
+JPEG_QUALITY = 78
+
+
+class GalleryItem(BaseModel):
+ key: str
+ title: str = ""
+ prompt: str = ""
+ track: str = ""
+ language: str = ""
+ generator: str = ""
+ judge: str = ""
+ score: float | None = None
+ baseline_score: float | None = None
+ passed: bool | None = None
+ quality_tier: str = "D"
+ gate_errors: int = 0
+ cost_usd: float = 0.0
+ rounds: int = 0
+ best_round: int | None = None
+ minutes: float | None = None
+ status: str = ""
+ error: str = ""
+ group: str = Field(default="", description="bench tier / category label shown on the card")
+ caption: str = Field(default="", description="instruction caption when available")
+ sheet: str | None = Field(default=None, description="contact sheet path (best round)")
+ links: dict[str, str] = Field(default_factory=dict, description="label → absolute path")
+
+
+def item_from_run(ws: Workspace, rec: RunRecord) -> GalleryItem:
+ rnd = best_round_record(rec)
+ j = effective_judgment(rnd) if rnd is not None else None # degraded → unjudged
+ gates = gate_error_summary(rnd)
+ n_err = sum(gates.values())
+ sheet = None
+ if rnd is not None and rnd.renders is not None and rnd.renders.contact_sheet:
+ p = Path(rnd.renders.contact_sheet)
+ p = p if p.is_absolute() else ws.root / p
+ sheet = str(p) if p.is_file() else None
+ links = {"workspace": str(ws.root), "record.json": str(ws.record_path)}
+ if sheet:
+ links["sheet"] = sheet
+ for name in ("object.glb", "robot.urdf", "object.stl"):
+ if (ws.artifacts / name).is_file():
+ links[name] = str(ws.artifacts / name)
+ if (ws.root / "src").is_dir():
+ links["src/"] = str(ws.root / "src")
+ minutes = ((rec.finished_at - rec.started_at).total_seconds() / 60.0) if rec.finished_at else None
+ caps = rec.extra.get("captions") or {}
+ return GalleryItem(
+ key=ws.root.name,
+ title=(getattr(rec.plan, "object_name", "") or getattr(rec.plan, "title", "") or "") if rec.plan else "",
+ prompt=rec.spec.prompt, track=rec.spec.track.value, language=rec.spec.language.value,
+ generator=rec.spec.backends.generator, judge=rec.spec.backends.judge,
+ score=j.overall if j else rec.final_score, baseline_score=rec.baseline_score,
+ passed=j.passed if j else None,
+ quality_tier=quality_tier(passed=j.passed if j else None, gate_errors=n_err, score=j.overall if j else None),
+ gate_errors=n_err, cost_usd=rec.total_usage.cost_usd, rounds=len(rec.rounds), best_round=rec.best_round,
+ minutes=round(minutes, 1) if minutes is not None else None, status=rec.status.value, error=rec.error,
+ caption=str(caps.get("instruction", "") or ""), sheet=sheet, links=links,
+ )
+
+
+def gallery_items(runs_dir: Path | str) -> list[GalleryItem]:
+ items: list[GalleryItem] = []
+ for ws, rec in iter_runs(runs_dir, on_error=lambda d, e: items.append(
+ GalleryItem(key=d.name, status="invalid", error=str(e), links={"workspace": str(d)}))):
+ items.append(item_from_run(ws, rec))
+ return items
+
+
+# --------------------------------------------------------------------------- rendering
+def thumbnail_data_uri(path: Path | str, *, max_px: int = THUMB_PX) -> str:
+ """Downscaled JPEG as a ``data:`` URI (``""`` when the image cannot be read)."""
+ try:
+ from PIL import Image
+
+ with Image.open(path) as im:
+ im = im.convert("RGB")
+ im.thumbnail((max_px, max_px))
+ buf = io.BytesIO()
+ im.save(buf, format="JPEG", quality=JPEG_QUALITY, optimize=True)
+ except Exception: # missing PIL, unreadable file, …
+ return ""
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
+
+
+def _fmt(v: float | None, spec: str = ".3f") -> str:
+ return "-" if v is None else format(v, spec)
+
+
+def _file_href(path: str) -> str:
+ p = Path(path)
+ return p.as_uri() if p.is_absolute() else html.escape(path)
+
+
+def _card(it: GalleryItem, *, thumb_px: int) -> str:
+ img = thumbnail_data_uri(it.sheet, max_px=thumb_px) if it.sheet else ""
+ pic = f'<a href="{_file_href(it.sheet)}"><img src="{img}" alt="contact sheet" loading="lazy"></a>' if img else \
+ '<div class="noimg">no render</div>'
+ badge = "pass" if it.passed else ("fail" if it.passed is False else "na")
+ links = " · ".join(f'<a href="{_file_href(p)}">{html.escape(n)}</a>' for n, p in it.links.items())
+ head = html.escape(it.title or it.key)
+ grp = f' · <span class="grp">{html.escape(it.group)}</span>' if it.group else ""
+ err = f'<div class="err">{html.escape(it.error[:300])}</div>' if it.error else ""
+ cap = f'<div class="cap">{html.escape(it.caption)}</div>' if it.caption else ""
+ mins = f" · {it.minutes:.1f} min" if it.minutes is not None else ""
+ return (
+ f'<div class="card {badge}" data-track="{html.escape(it.track)}" data-tier="{it.quality_tier}" '
+ f'data-score="{it.score if it.score is not None else -1}" data-cost="{it.cost_usd}" data-key="{html.escape(it.key)}">'
+ f'{pic}<div class="meta">'
+ f'<div class="row1"><b>{head}</b> <span class="tier t{it.quality_tier}">{it.quality_tier}</span>'
+ f'<span class="score">{_fmt(it.score)}</span></div>'
+ f'<div class="prompt">{html.escape(it.prompt)}</div>{cap}'
+ f'<div class="kv">{html.escape(it.track)} · {html.escape(it.language)} · {html.escape(it.generator)}{grp}</div>'
+ f'<div class="kv">baseline {_fmt(it.baseline_score)} → best {_fmt(it.score)} (r{it.best_round if it.best_round is not None else "-"}) · '
+ f'rounds {it.rounds} · gate err {it.gate_errors} · ${it.cost_usd:.2f}{mins} · {html.escape(it.status)}</div>'
+ f'{err}<div class="links">{links}</div></div></div>'
+ )
+
+
+def _summary(items: list[GalleryItem]) -> str:
+ scored = [i.score for i in items if i.score is not None]
+ judged = [i.passed for i in items if i.passed is not None]
+ tiers = {t: sum(1 for i in items if i.quality_tier == t) for t in "ABCD"}
+ parts = [
+ f"{len(items)} runs",
+ f"pass {sum(judged)}/{len(judged)}" if judged else "pass -",
+ f"mean score {statistics.fmean(scored):.3f}" if scored else "mean score -",
+ f"total ${sum(i.cost_usd for i in items):.2f}",
+ "tiers " + " ".join(f"{t}:{n}" for t, n in tiers.items()),
+ ]
+ return " · ".join(html.escape(p) for p in parts)
+
+
+_STYLE = """
+body{font-family:system-ui,sans-serif;margin:20px;background:#111;color:#eee}
+h1{font-size:20px;margin:0 0 6px}.sum{color:#bbb;margin-bottom:10px}
+.ctl{margin:8px 0 14px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;font-size:13px}
+.ctl select,.ctl input{background:#222;color:#eee;border:1px solid #444;padding:3px 6px;border-radius:4px}
+.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(380px,1fr));gap:14px}
+.card{background:#1c1c1c;border-radius:8px;overflow:hidden;border:2px solid #333;display:flex;flex-direction:column}
+.card.pass{border-color:#2e7d32}.card.fail{border-color:#8a1c1c}.card img{width:100%;max-height:420px;object-fit:contain;display:block;background:#fff}
+.noimg{height:160px;display:flex;align-items:center;justify-content:center;color:#777}
+.meta{padding:8px 10px;font-size:13px;line-height:1.4}.row1{display:flex;gap:8px;align-items:center}
+.score{margin-left:auto;font-weight:600;font-size:15px}.tier{padding:0 6px;border-radius:4px;font-weight:700;font-size:12px}
+.tA{background:#2e7d32}.tB{background:#558b2f}.tC{background:#b07a00}.tD{background:#8a1c1c}
+.prompt{color:#ddd;margin:4px 0}.cap{color:#9bd;font-style:italic;margin:2px 0 4px}.kv{color:#aaa}.grp{color:#cba}
+.err{color:#f88;white-space:pre-wrap;margin-top:4px}.links{margin-top:6px}.links a{color:#8cf;margin-right:4px}
+.hidden{display:none}
+"""
+
+_SCRIPT = """
+function apply(){const t=document.getElementById('ftrack').value,q=document.getElementById('ftier').value,
+s=document.getElementById('sort').value,g=document.getElementById('grid'),cards=[...g.children];
+cards.forEach(c=>{const ok=(t===''||c.dataset.track===t)&&(q===''||c.dataset.tier===q);c.classList.toggle('hidden',!ok);});
+const key={score:c=>-parseFloat(c.dataset.score),cost:c=>-parseFloat(c.dataset.cost),key:c=>c.dataset.key,
+tier:c=>c.dataset.tier+(1-parseFloat(c.dataset.score))}[s];
+cards.sort((a,b)=>{const x=key(a),y=key(b);return x<y?-1:x>y?1:0}).forEach(c=>g.appendChild(c));}
+document.querySelectorAll('#ftrack,#ftier,#sort').forEach(e=>e.addEventListener('change',apply));
+"""
+
+
+def render_gallery(items: list[GalleryItem], title: str, *, thumb_px: int = THUMB_PX, extra_html: str = "") -> str:
+ """Complete HTML document (images embedded) for ``items``. ``extra_html`` is
+ inserted above the grid (bench report tables, for example)."""
+ tracks = sorted({i.track for i in items if i.track})
+ opts = "".join(f'<option value="{html.escape(t)}">{html.escape(t)}</option>' for t in tracks)
+ cards = "".join(_card(it, thumb_px=thumb_px) for it in items)
+ return (
+ f"<!doctype html><html><head><meta charset='utf-8'><title>{html.escape(title)}</title>"
+ f"<style>{_STYLE}</style></head><body><h1>{html.escape(title)}</h1>"
+ f"<div class='sum'>{_summary(items)}</div>{extra_html}"
+ f"<div class='ctl'>track <select id='ftrack'><option value=''>all</option>{opts}</select>"
+ f"tier <select id='ftier'><option value=''>all</option>"
+ + "".join(f"<option>{t}</option>" for t in "ABCD")
+ + "</select>sort <select id='sort'><option value='score'>score</option><option value='tier'>tier</option>"
+ f"<option value='cost'>cost</option><option value='key'>name</option></select></div>"
+ f"<div class='grid' id='grid'>{cards}</div><script>{_SCRIPT}</script></body></html>"
+ )
+
+
+def write_gallery(runs_dir: Path | str, out_html: Path | str, *, title: str | None = None,
+ thumb_px: int = THUMB_PX) -> tuple[Path, int]:
+ """Render every run under ``runs_dir`` into ``out_html``; returns (path, n_items)."""
+ items = gallery_items(runs_dir)
+ items.sort(key=lambda i: (-(i.score if i.score is not None else -1.0), i.key))
+ out = Path(out_html)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(render_gallery(items, title or f"3dcv gallery — {Path(runs_dir).name}", thumb_px=thumb_px))
+ return out, len(items)
+
+
+def gallery_dict(items: list[GalleryItem]) -> list[dict[str, Any]]:
+ return [i.model_dump(mode="json") for i in items]
diff --git a/harness/codeverse/flywheel/index.py b/harness/codeverse/flywheel/index.py
index a2df76e6..5e1c3f57 100644
--- a/harness/codeverse/flywheel/index.py
+++ b/harness/codeverse/flywheel/index.py
@@ -11,8 +11,8 @@ from pathlib import Path
from typing import Any
from codeverse.contracts.run import RoundRecord, RunRecord
-from codeverse.flywheel.pairs import prompt_hash
-from codeverse.flywheel.record import iter_runs
+from codeverse.flywheel.quality import prompt_hash, quality_tier
+from codeverse.flywheel.record import effective_judgment, iter_runs
from codeverse.workspace import Workspace
_SCHEMA = """
@@ -21,7 +21,8 @@ CREATE TABLE runs (
generator TEXT, planner TEXT, judge TEXT, status TEXT,
baseline_score REAL, final_score REAL, best_round INTEGER, n_rounds INTEGER, passed INTEGER,
cost_usd REAL, input_tokens INTEGER, output_tokens INTEGER,
- started_at TEXT, finished_at TEXT, duration_s REAL, error TEXT, has_captions INTEGER
+ started_at TEXT, finished_at TEXT, duration_s REAL, error TEXT, has_captions INTEGER,
+ gate_errors INTEGER, quality_tier TEXT, best_commit TEXT
);
CREATE TABLE rounds (
slug TEXT, round_index INTEGER, kind TEXT, commit_sha TEXT, agent_backend TEXT,
@@ -30,7 +31,7 @@ CREATE TABLE rounds (
PRIMARY KEY (slug, round_index)
);
CREATE TABLE usage (
- slug TEXT, round_index INTEGER, role TEXT, backend TEXT, model TEXT,
+ slug TEXT, round_index INTEGER, role TEXT, backend TEXT, model TEXT, -- role: round (agent+judge) | judge
input_tokens INTEGER, output_tokens INTEGER, cached_tokens INTEGER, thoughts_tokens INTEGER,
tool_calls INTEGER, cost_usd REAL, latency_ms INTEGER
);
@@ -42,8 +43,12 @@ CREATE INDEX idx_rounds_slug ON rounds(slug);
def _run_row(ws: Workspace, rec: RunRecord) -> tuple:
best = next((r for r in rec.rounds if r.index == rec.best_round), None)
- passed = None if best is None or best.judgment is None else int(best.judgment.passed)
+ best_j = effective_judgment(best) if best is not None else None # degraded → unjudged
+ passed = None if best_j is None else int(best_j.passed)
dur = (rec.finished_at - rec.started_at).total_seconds() if rec.finished_at else None
+ n_err = sum(len(g.errors) for g in best.gates) if best is not None else 0
+ score = best_j.overall if best_j is not None else None
+ tier = quality_tier(passed=None if passed is None else bool(passed), gate_errors=n_err, score=score)
return (
ws.root.name, str(ws.root), rec.spec.track.value, rec.spec.language.value, rec.spec.prompt,
prompt_hash(rec.spec.prompt), rec.spec.backends.generator, rec.spec.backends.planner,
@@ -52,20 +57,24 @@ def _run_row(ws: Workspace, rec: RunRecord) -> tuple:
rec.total_usage.output_tokens, rec.started_at.isoformat(),
rec.finished_at.isoformat() if rec.finished_at else None, dur, rec.error,
int(bool((rec.extra.get("captions") or {}).get("detailed"))),
+ n_err, tier, best.commit if best is not None else "",
)
def _round_row(slug: str, r: RoundRecord) -> tuple:
+ j = effective_judgment(r) # degraded → unscored
return (
slug, r.index, r.kind, r.commit, r.agent_backend,
- None if r.build is None else int(r.build.ok), sum(len(g.errors) for g in r.gates), r.score,
- None if r.judgment is None else int(r.judgment.passed), 0 if r.judgment is None else len(r.judgment.issues),
+ None if r.build is None else int(r.build.ok), sum(len(g.errors) for g in r.gates),
+ j.overall if j is not None else None,
+ None if j is None else int(j.passed), 0 if j is None else len(j.issues),
r.usage.cost_usd, r.duration_s, r.started_at.isoformat(),
)
def _usage_rows(slug: str, r: RoundRecord) -> list[tuple]:
- rows = [(slug, r.index, "agent", r.usage.backend, r.usage.model, r.usage.input_tokens, r.usage.output_tokens,
+ """``round`` = the round's total (agent session + its judge call); ``judge`` = the judge part of it."""
+ rows = [(slug, r.index, "round", r.usage.backend, r.usage.model, r.usage.input_tokens, r.usage.output_tokens,
r.usage.cached_tokens, r.usage.thoughts_tokens, r.usage.tool_calls, r.usage.cost_usd, r.usage.latency_ms)]
if r.judgment is not None:
u = r.judgment.usage
@@ -87,7 +96,7 @@ def build_index(runs_dir: Path | str, out_sqlite: Path | str) -> int:
con.executescript(_SCHEMA)
for ws, rec in iter_runs(runs_dir):
slug = ws.root.name
- con.execute(f"INSERT INTO runs VALUES ({','.join('?' * 23)})", _run_row(ws, rec))
+ con.execute(f"INSERT INTO runs VALUES ({','.join('?' * 26)})", _run_row(ws, rec))
con.executemany(f"INSERT INTO rounds VALUES ({','.join('?' * 13)})", [_round_row(slug, r) for r in rec.rounds])
con.executemany(f"INSERT INTO usage VALUES ({','.join('?' * 12)})",
[row for r in rec.rounds for row in _usage_rows(slug, r)])
@@ -121,14 +130,15 @@ def summary(db: Path | str) -> list[dict[str, Any]]:
"SELECT track, language, generator, COUNT(*) AS n, AVG(passed) AS pass_rate, "
"AVG(baseline_score) AS baseline_mean, AVG(final_score) AS final_mean, "
"AVG(final_score - baseline_score) AS delta_mean, SUM(cost_usd) AS cost_usd, "
- "AVG(n_rounds) AS rounds_mean FROM runs GROUP BY track, language, generator ORDER BY track, language",
+ "AVG(n_rounds) AS rounds_mean, SUM(quality_tier = 'A') AS n_tier_a, SUM(quality_tier = 'B') AS n_tier_b "
+ "FROM runs GROUP BY track, language, generator ORDER BY track, language",
)
def top_runs(db: Path | str, n: int = 20, *, track: str | None = None) -> list[dict[str, Any]]:
where = "WHERE track = ?" if track else ""
params: tuple = (track, n) if track else (n,)
- return query(db, f"SELECT slug, track, language, generator, final_score, passed, cost_usd, n_rounds "
+ return query(db, f"SELECT slug, track, language, generator, final_score, passed, quality_tier, cost_usd, n_rounds "
f"FROM runs {where} ORDER BY final_score DESC LIMIT ?", params)
diff --git a/harness/codeverse/flywheel/pack.py b/harness/codeverse/flywheel/pack.py
index 6ba0ff32..ac6fc851 100644
--- a/harness/codeverse/flywheel/pack.py
+++ b/harness/codeverse/flywheel/pack.py
@@ -22,6 +22,7 @@ from codeverse.flywheel.export import (
write_jsonl,
write_parquet,
)
+from codeverse.flywheel.quality import mark_duplicates
MAX_TAR_BYTES = int(2.5 * 1024**3)
@@ -50,6 +51,7 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
rows = collect_rows(out)
if not rows:
raise PackError(f"no samples under {out}")
+ mark_duplicates(rows)
rep = PackReport()
tar_idx = 0
tar: tarfile.TarFile | None = None
@@ -60,7 +62,7 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
if tar is not None:
tar.close()
tar_path = out / f"samples-{tar_idx:03d}.tar"
- tar = tarfile.open(tar_path, mode="w", format=tarfile.PAX_FORMAT)
+ tar = tarfile.open(tar_path, mode="w", format=tarfile.PAX_FORMAT) # noqa: SIM115 - closed in _open_new/after loop
rep.tars.append(tar_path.name)
tar_idx += 1
@@ -101,7 +103,8 @@ def verify_locators(out_dir: Path | str) -> int:
with tpath.open("rb") as fh:
fh.seek(row["byte_start"])
blob = fh.read(row["byte_len"])
- members = tarfile.open(fileobj=io.BytesIO(blob), mode="r:").getmembers()
+ with tarfile.open(fileobj=io.BytesIO(blob), mode="r:") as sub:
+ members = sub.getmembers()
files = [m for m in members if m.isfile()]
if len(files) != row["n_files"]:
raise PackError(f"row {row['id']}: {len(files)} files in range, expected {row['n_files']}")
diff --git a/harness/codeverse/flywheel/pairs.py b/harness/codeverse/flywheel/pairs.py
index f2c47218..cd86f4de 100644
--- a/harness/codeverse/flywheel/pairs.py
+++ b/harness/codeverse/flywheel/pairs.py
@@ -8,15 +8,25 @@ Output is JSONL, one object per pair. All kinds share::
* ``preference`` rounds i < j of one run with judge Δ ≥ ``min_delta``; reason =
the judge's improvement plan of round i (what the builder was told to fix).
-* ``repair`` a failed build (round k-1) → the ``repair`` round k that builds;
- ``error`` carries the structured build failure.
+ Degraded (judge-outage) verdicts are treated as *no score*, never as a 0.0.
+* ``repair`` a failed build (round k) → the next round that builds, matched
+ structurally (no track ever emits a ``kind='repair'`` round — lifecycle labels
+ the fixing round ``refine``); ``error`` carries the structured build failure.
+ ``source: "round"``.
+* ``repair`` (``source: "in_round"``) — a round whose build failed right after
+ generation and was fixed by ``build_with_repair`` inside the same round
+ (``notes`` say "repair attempts: N (fixed)"): the ``rNN <kind>: generated``
+ commit is the rejected state, the round's final commit the chosen one; the
+ error message comes from the round's failing ``build.done`` events.
+* ``repair`` (``source: "trajectory"``) — the same shape mined from an agent
+ session's transcript: last failing ``build`` → next successful ``build``
+ (see ``trajectories.py``); ``error`` is the build tool's message.
* ``cross_backend`` the same (prompt, track, language) run under ≥ 2 generators;
best vs each other candidate with Δ ≥ ``min_delta``.
"""
from __future__ import annotations
-import hashlib
import json
from collections import defaultdict
from pathlib import Path
@@ -24,14 +34,15 @@ from typing import Any
from codeverse.contracts.run import RoundRecord, RunRecord
from codeverse.flywheel import _git
-from codeverse.flywheel.record import iter_runs
+from codeverse.flywheel.quality import prompt_hash
+from codeverse.flywheel.record import effective_judgment, iter_runs
+from codeverse.flywheel.trajectories import mine_run
from codeverse.workspace import Workspace
-MAX_INLINE_CODE = 200_000
-
+__all__ = ["build_pairs", "preference_pairs", "repair_pairs", "in_round_repair_pairs",
+ "trajectory_repair_pairs", "cross_backend_pairs", "prompt_hash"]
-def prompt_hash(prompt: str) -> str:
- return hashlib.sha256(prompt.strip().encode()).hexdigest()[:16]
+MAX_INLINE_CODE = 200_000
def _side(ws: Workspace, rnd: RoundRecord, *, cache: dict[str, dict[str, Any]]) -> dict[str, Any]:
@@ -45,12 +56,13 @@ def _side(ws: Workspace, rnd: RoundRecord, *, cache: dict[str, dict[str, Any]])
text, skipped = _git.decode_text_files(raw, max_total=MAX_INLINE_CODE)
cache[key] = {"files": text, "truncated_files": skipped}
c = cache[key]
+ j = effective_judgment(rnd)
return {
"round": rnd.index,
"kind": rnd.kind,
"commit": rnd.commit,
- "score": rnd.score,
- "passed": None if rnd.judgment is None else rnd.judgment.passed,
+ "score": j.overall if j else None,
+ "passed": j.passed if j else None,
"build_ok": None if rnd.build is None else rnd.build.ok,
"files": c["files"],
"truncated_files": c["truncated_files"],
@@ -72,11 +84,13 @@ def _base(ws: Workspace, rec: RunRecord, kind: str) -> dict[str, Any]:
def preference_pairs(ws: Workspace, rec: RunRecord, *, min_delta: float) -> list[dict[str, Any]]:
cache: dict[str, dict[str, Any]] = {}
- judged = [r for r in rec.rounds if r.judgment is not None and r.commit]
+ # degraded (judge-outage) verdicts are glitches, not 0.0 scores — leave those rounds out
+ judged = [r for r in rec.rounds if effective_judgment(r) is not None and r.commit]
out = []
for a_i, lo in enumerate(judged):
for hi in judged[a_i + 1 :]:
- delta = hi.judgment.overall - lo.judgment.overall # type: ignore[union-attr]
+ lo_j, hi_j = effective_judgment(lo), effective_judgment(hi)
+ delta = hi_j.overall - lo_j.overall # type: ignore[union-attr]
if delta < min_delta or lo.commit == hi.commit:
continue
pair = _base(ws, rec, "preference")
@@ -84,8 +98,8 @@ def preference_pairs(ws: Workspace, rec: RunRecord, *, min_delta: float) -> list
chosen=_side(ws, hi, cache=cache),
rejected=_side(ws, lo, cache=cache),
delta=round(delta, 4),
- reason=[it.instruction for it in lo.judgment.improvement_plan], # type: ignore[union-attr]
- issues=[i.model_dump(mode="json") for i in lo.judgment.issues], # type: ignore[union-attr]
+ reason=[it.instruction for it in lo_j.improvement_plan], # type: ignore[union-attr]
+ issues=[i.model_dump(mode="json") for i in lo_j.issues], # type: ignore[union-attr]
)
out.append(pair)
return out
@@ -107,23 +121,108 @@ def _error_of(rnd: RoundRecord) -> dict[str, Any]:
def repair_pairs(ws: Workspace, rec: RunRecord) -> list[dict[str, Any]]:
- """(broken round, error) → (repair round that builds)."""
+ """(broken round, error) → (the next round that builds).
+
+ Matched structurally: the tracks never emit a ``kind='repair'`` round
+ (lifecycle labels every post-baseline round ``refine``), so any round whose
+ build succeeds directly repairs the nearest earlier failed build."""
cache: dict[str, dict[str, Any]] = {}
out = []
rounds = rec.rounds
- for k, rnd in enumerate(rounds):
- if not rnd.kind.startswith("repair") or rnd.build is None or not rnd.build.ok:
+ for k, broken in enumerate(rounds):
+ if broken.build is None or broken.build.ok or not broken.commit:
continue
- broken = next((r for r in reversed(rounds[:k]) if r.build is not None and not r.build.ok), None)
- if broken is None or not broken.commit or not rnd.commit or broken.commit == rnd.commit:
+ fixed = next((r for r in rounds[k + 1 :] if r.build is not None and r.build.ok and r.commit), None)
+ if fixed is None or broken.commit == fixed.commit:
continue
pair = _base(ws, rec, "repair")
pair.update(
- chosen=_side(ws, rnd, cache=cache),
+ source="round",
+ chosen=_side(ws, fixed, cache=cache),
rejected=_side(ws, broken, cache=cache),
delta=None,
error=_error_of(broken),
- reason=list(rnd.instructions),
+ reason=list(fixed.instructions),
+ )
+ out.append(pair)
+ return out
+
+
+def _round_build_errors(ws: Workspace, index: int) -> list[str]:
+ """Failing ``build.done`` error messages of one round, from events.jsonl."""
+ p = ws.events_path
+ if not p.is_file():
+ return []
+ out: list[str] = []
+ for line in p.read_text(errors="replace").splitlines():
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ if ev.get("event") == "build.done" and ev.get("round") == index and ev.get("ok") is False:
+ msg = str(ev.get("error") or "").strip()
+ if msg:
+ out.append(msg)
+ return out
+
+
+def in_round_repair_pairs(ws: Workspace, rec: RunRecord) -> list[dict[str, Any]]:
+ """Builds fixed by ``build_with_repair`` *inside* a round.
+
+ ``tracks/steps.py`` commits ``rNN <kind>: generated`` right before the
+ build+repair loop and notes "repair attempts: N (fixed)" when the loop
+ repaired a failing build; the generated tree is the rejected state."""
+ cache: dict[str, dict[str, Any]] = {}
+ out = []
+ for rnd in rec.rounds:
+ if rnd.build is None or not rnd.build.ok or not rnd.commit:
+ continue
+ if "repair attempts:" not in rnd.notes or "(fixed)" not in rnd.notes:
+ continue
+ generated = _git.commit_by_subject(ws, f"r{rnd.index:02d} {rnd.kind}: generated")
+ if not generated or generated == rnd.commit or not _git.commit_exists(ws, generated):
+ continue
+ try:
+ raw = _git.read_tree_at(ws, generated)
+ except _git.GitReadError:
+ continue
+ rej_files, rej_skipped = _git.decode_text_files(raw, max_total=MAX_INLINE_CODE)
+ chosen = _side(ws, rnd, cache=cache)
+ if rej_files == chosen["files"]:
+ continue # the repair changed nothing under the code roots
+ errors = _round_build_errors(ws, rnd.index)
+ pair = _base(ws, rec, "repair")
+ pair.update(
+ source="in_round",
+ chosen=chosen,
+ rejected={"round": rnd.index, "kind": rnd.kind, "commit": generated, "score": None, "passed": None,
+ "build_ok": False, "files": rej_files, "truncated_files": rej_skipped},
+ delta=None,
+ error={"type": "", "message": errors[-1] if errors else "", "file": "", "line": None,
+ "stderr_tail": "", "stdout_tail": "", "gate_errors": [], "messages": errors},
+ reason=[f"in-round build repair ({rnd.notes})"],
+ )
+ out.append(pair)
+ return out
+
+
+def trajectory_repair_pairs(ws: Workspace, rec: RunRecord) -> list[dict[str, Any]]:
+ """In-session repairs (failing build → fixing build) mined from api-agent transcripts."""
+ out = []
+ for tr in mine_run(ws):
+ pair = _base(ws, rec, "repair")
+ pair.update(
+ source="trajectory",
+ trajectory=tr.trajectory,
+ chosen={"round": tr.round_index, "kind": tr.stage, "commit": "", "turn": tr.fixed_turn, "score": None,
+ "passed": None, "build_ok": True, "files": tr.chosen, "truncated_files": []},
+ rejected={"round": tr.round_index, "kind": tr.stage, "commit": "", "turn": tr.broken_turn, "score": None,
+ "passed": None, "build_ok": False, "files": tr.rejected, "truncated_files": []},
+ delta=None,
+ error={"type": "", "message": tr.error, "file": "", "line": None, "stderr_tail": "", "stdout_tail": "",
+ "gate_errors": []},
+ reason=[f"in-session fix of a failing build ({tr.n_failures} failing build(s) folded)"],
+ changed_files=tr.changed_files,
)
out.append(pair)
return out
@@ -138,17 +237,17 @@ def cross_backend_pairs(groups: dict[tuple[str, str, str], list[tuple[Workspace,
cands = []
for ws, rec in runs:
best = next((r for r in rec.rounds if r.index == rec.best_round), None)
- if best is None or best.judgment is None:
+ if best is None or effective_judgment(best) is None: # unjudged or degraded verdict
continue
cands.append((ws, rec, best))
if len(cands) < 2:
continue
- cands.sort(key=lambda c: c[2].judgment.overall, reverse=True) # type: ignore[union-attr]
+ cands.sort(key=lambda c: effective_judgment(c[2]).overall, reverse=True) # type: ignore[union-attr]
w_ws, w_rec, w_rnd = cands[0]
w_side = _side(w_ws, w_rnd, cache={})
w_side["generator"] = w_rec.spec.backends.generator
for ws, rec, rnd in cands[1:]:
- delta = w_rnd.judgment.overall - rnd.judgment.overall # type: ignore[union-attr]
+ delta = effective_judgment(w_rnd).overall - effective_judgment(rnd).overall # type: ignore[union-attr]
if rec.spec.backends.generator == w_rec.spec.backends.generator or delta < min_delta:
continue
pair = _base(w_ws, w_rec, "cross_backend")
@@ -159,14 +258,18 @@ def cross_backend_pairs(groups: dict[tuple[str, str, str], list[tuple[Workspace,
chosen=w_side, rejected=l_side, delta=round(delta, 4),
reason=f"best-of across generators: {w_rec.spec.backends.generator} > {rec.spec.backends.generator}",
candidates=[{"run": c[0].root.name, "generator": c[1].spec.backends.generator,
- "score": c[2].judgment.overall} for c in cands], # type: ignore[union-attr]
+ "score": effective_judgment(c[2]).overall} for c in cands], # type: ignore[union-attr]
)
out.append(pair)
return out
-def build_pairs(runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float = 0.05) -> int:
- """Write all pair kinds for the runs under ``runs_dir``; returns the number written."""
+def build_pairs(
+ runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float = 0.05, trajectories: bool = True
+) -> int:
+ """Write all pair kinds for the runs under ``runs_dir``; returns the number written.
+
+ ``trajectories`` adds in-session repair pairs mined from agent transcripts."""
out = Path(out_jsonl)
out.parent.mkdir(parents=True, exist_ok=True)
groups: dict[tuple[str, str, str], list[tuple[Workspace, RunRecord]]] = defaultdict(list)
@@ -175,7 +278,10 @@ def build_pairs(runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float
with tmp.open("w") as fh:
for ws, rec in iter_runs(runs_dir):
groups[(prompt_hash(rec.spec.prompt), rec.spec.track.value, rec.spec.language.value)].append((ws, rec))
- for pair in preference_pairs(ws, rec, min_delta=min_delta) + repair_pairs(ws, rec):
+ pairs = preference_pairs(ws, rec, min_delta=min_delta) + repair_pairs(ws, rec) + in_round_repair_pairs(ws, rec)
+ if trajectories:
+ pairs += trajectory_repair_pairs(ws, rec)
+ for pair in pairs:
fh.write(json.dumps(pair, ensure_ascii=False) + "\n")
n += 1
for pair in cross_backend_pairs(groups, min_delta=min_delta):
diff --git a/harness/codeverse/flywheel/quality.py b/harness/codeverse/flywheel/quality.py
new file mode 100644
index 00000000..d7fe8f4c
--- /dev/null
+++ b/harness/codeverse/flywheel/quality.py
@@ -0,0 +1,93 @@
+"""Dataset hygiene: quality tiers + exact-duplicate detection by (code fingerprint, prompt).
+
+* ``quality_tier(passed, gate_errors, score)`` → ``A | B | C | D``::
+
+ A judged passed AND the best round has zero gate errors
+ B judged passed (some gate errors remain)
+ C not passed but best score ≥ 0.6
+ D everything else (unjudged, failed, low score)
+
+* ``find_duplicates(rows)`` groups index rows with identical
+ ``(code_fingerprint, prompt_hash)``; the canonical row of a group is the
+ best (tier, score, fewest gate errors, captioned, then key order) and every other row gets
+ ``duplicate_of = canonical id``.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from collections import defaultdict
+from collections.abc import Iterable
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+QualityTier = Literal["A", "B", "C", "D"]
+TIER_ORDER: dict[str, int] = {"A": 0, "B": 1, "C": 2, "D": 3}
+TIER_C_MIN_SCORE = 0.6
+
+
+def prompt_hash(prompt: str) -> str:
+ """Stable 16-hex id of a (stripped) user prompt — shared by samples, pairs and the index."""
+ return hashlib.sha256(prompt.strip().encode()).hexdigest()[:16]
+
+
+def quality_tier(*, passed: bool | None, gate_errors: int, score: float | None) -> QualityTier:
+ """Tier rule (see module docstring). ``passed`` None = never judged."""
+ if passed:
+ return "A" if gate_errors == 0 else "B"
+ if score is not None and score >= TIER_C_MIN_SCORE:
+ return "C"
+ return "D"
+
+
+class DuplicateGroup(BaseModel):
+ code_fingerprint: str
+ prompt_hash: str
+ canonical: str = Field(description="sample id kept")
+ duplicates: list[str] = Field(default_factory=list, description="sample ids marked duplicate_of=canonical")
+
+
+def _rank(row: dict[str, Any]) -> tuple:
+ """Lower is better: tier, -score, gate errors, un-captioned, key (stable)."""
+ score = row.get("score")
+ return (
+ TIER_ORDER.get(str(row.get("quality_tier") or "D"), 9),
+ -(score if isinstance(score, (int, float)) else -1.0),
+ int(row.get("gate_errors") or 0),
+ 0 if row.get("has_captions") else 1,
+ str(row.get("key") or row.get("id") or ""),
+ )
+
+
+def find_duplicates(rows: Iterable[dict[str, Any]]) -> list[DuplicateGroup]:
+ """Group rows by exact (code_fingerprint, prompt_hash); only groups with ≥ 2 rows are returned.
+
+ Rows without a fingerprint are never grouped. The rows are not modified;
+ use ``mark_duplicates`` to stamp ``duplicate_of``.
+ """
+ buckets: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
+ for r in rows:
+ fp = str(r.get("code_fingerprint") or "")
+ if not fp:
+ continue
+ buckets[(fp, str(r.get("prompt_hash") or ""))].append(r)
+ groups = []
+ for (fp, ph), members in sorted(buckets.items()):
+ if len(members) < 2:
+ continue
+ members = sorted(members, key=_rank)
+ groups.append(DuplicateGroup(code_fingerprint=fp, prompt_hash=ph, canonical=str(members[0]["id"]),
+ duplicates=[str(m["id"]) for m in members[1:]]))
+ return groups
+
+
+def mark_duplicates(rows: list[dict[str, Any]]) -> list[DuplicateGroup]:
+ """Set ``row["duplicate_of"]`` ("" for canonical rows) in place; returns the groups."""
+ for r in rows:
+ r["duplicate_of"] = ""
+ groups = find_duplicates(rows)
+ dup_of = {d: g.canonical for g in groups for d in g.duplicates}
+ for r in rows:
+ r["duplicate_of"] = dup_of.get(str(r.get("id")), "")
+ return groups
diff --git a/harness/codeverse/flywheel/record.py b/harness/codeverse/flywheel/record.py
index cc741740..49543b1f 100644
--- a/harness/codeverse/flywheel/record.py
+++ b/harness/codeverse/flywheel/record.py
@@ -87,18 +87,35 @@ def environment_versions() -> dict[str, str]:
# --------------------------------------------------------------------------- derived fields
+def effective_judgment(r: RoundRecord):
+ """The round's judgment, or ``None`` when it is a degraded (judge-outage)
+ verdict — the flywheel must treat those as 'no score', never as a 0.0."""
+ j = r.judgment
+ if j is None:
+ return None
+ from codeverse.judges.scoring import is_degraded
+
+ return None if is_degraded(j) else j
+
+
+def effective_score(r: RoundRecord) -> float | None:
+ """``r.score`` with degraded judgments filtered out (None = unscored)."""
+ j = effective_judgment(r)
+ return j.overall if j is not None else None
+
+
def best_round_index(record: RunRecord) -> int | None:
"""The round to export: ``record.best_round`` when valid, else the highest
judged score (ties → fewer gate errors), else the last round with a
- successful build, else the last round."""
+ successful build, else the last round. Degraded judgments count as unjudged."""
by_index = {r.index: r for r in record.rounds}
if record.best_round is not None and record.best_round in by_index:
return record.best_round
if not record.rounds:
return None
- judged = [r for r in record.rounds if r.judgment is not None]
+ judged = [r for r in record.rounds if effective_judgment(r) is not None]
if judged:
- best = max(judged, key=lambda r: (r.judgment.overall, -_n_gate_errors(r), r.index)) # type: ignore[union-attr]
+ best = max(judged, key=lambda r: (effective_score(r), -_n_gate_errors(r), r.index)) # type: ignore[arg-type]
return best.index
built = [r for r in record.rounds if r.build is not None and r.build.ok]
if built:
@@ -111,7 +128,10 @@ def _n_gate_errors(r: RoundRecord) -> int:
def round_summary(r: RoundRecord) -> dict[str, Any]:
- """Compact per-round digest (for record.extra, dashboards and the CLI)."""
+ """Compact per-round digest (for record.extra, dashboards and the CLI).
+
+ A degraded judgment shows up as score/passed None + ``judge_degraded``."""
+ j = effective_judgment(r)
return {
"index": r.index,
"kind": r.kind,
@@ -119,20 +139,20 @@ def round_summary(r: RoundRecord) -> dict[str, Any]:
"agent_backend": r.agent_backend,
"build_ok": None if r.build is None else r.build.ok,
"gate_errors": _n_gate_errors(r),
- "score": r.score,
- "passed": None if r.judgment is None else r.judgment.passed,
- "issues": 0 if r.judgment is None else len(r.judgment.issues),
+ "score": j.overall if j else None,
+ "passed": j.passed if j else None,
+ "issues": len(j.issues) if j else 0,
+ "judge_degraded": r.judgment is not None and j is None,
"cost_usd": round(r.usage.cost_usd, 6),
"duration_s": round(r.duration_s, 1),
}
def _sum_usage(rounds: list[RoundRecord]) -> Usage:
+ """Round usage already includes the round's judge call (tracks/steps.py) — do not add it twice."""
total = Usage()
for r in rounds:
total = total + r.usage
- if r.judgment is not None:
- total = total + r.judgment.usage
return total
@@ -140,12 +160,12 @@ def fill_derived(record: RunRecord) -> RunRecord:
"""Fill best/baseline/final/total_usage/finished_at/environment when absent."""
if record.best_round is None:
record.best_round = best_round_index(record)
- scored = [r for r in record.rounds if r.score is not None]
+ scored = [r for r in record.rounds if effective_score(r) is not None]
if record.baseline_score is None and scored:
- record.baseline_score = scored[0].score
+ record.baseline_score = effective_score(scored[0])
if record.final_score is None and record.best_round is not None:
best = next((r for r in record.rounds if r.index == record.best_round), None)
- record.final_score = best.score if best else None
+ record.final_score = effective_score(best) if best else None
if record.total_usage.cost_usd == 0 and record.total_usage.input_tokens == 0 and record.rounds:
record.total_usage = _sum_usage(record.rounds)
if record.finished_at is None:
diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/flywheel/sample.py
index 022f665d..a1707401 100644
--- a/harness/codeverse/flywheel/sample.py
+++ b/harness/codeverse/flywheel/sample.py
@@ -9,6 +9,7 @@ Sample folder (STORAGE_RULES §3/§8 compatible)::
meta.json SampleMeta (typed, below)
captions.json {detailed, instruction, factory} or {} when not captioned
renders/ view_*.png, sheet.png, turntable.mp4, object.glb (< 20 MB)
+ meshes/<link>.glb (urdf_blender) per-link meshes referenced by robot.urdf
"""
from __future__ import annotations
@@ -24,7 +25,9 @@ from codeverse import __version__
from codeverse.contracts.common import Language, Track
from codeverse.contracts.run import RoundRecord, RunRecord
from codeverse.flywheel import _git
-from codeverse.flywheel.record import best_round_index
+from codeverse.flywheel.dedupe import code_fingerprint
+from codeverse.flywheel.quality import QualityTier, prompt_hash, quality_tier
+from codeverse.flywheel.record import best_round_index, effective_judgment, round_summary
from codeverse.workspace import Workspace
#: entry file inside src/ per language
@@ -34,6 +37,8 @@ ENTRY_BY_LANGUAGE: dict[Language, str] = {
Language.URDF_BLENDER: "src/model.py",
Language.THREEJS: "src/object.js",
Language.SCENE_THREEJS: "src/scene.js",
+ Language.GLSL_SHADER: "src/shader.frag",
+ Language.OPENGL_PYTHON: "src/program.py",
}
#: top-level copy of the entry (``code.<ext>``)
CODE_FILE_BY_LANGUAGE: dict[Language, str] = {
@@ -42,6 +47,8 @@ CODE_FILE_BY_LANGUAGE: dict[Language, str] = {
Language.URDF_BLENDER: "code.py",
Language.THREEJS: "code.js",
Language.SCENE_THREEJS: "code.js",
+ Language.GLSL_SHADER: "code.frag",
+ Language.OPENGL_PYTHON: "code.py",
}
LANGUAGE_LABEL: dict[Language, str] = {
Language.BLENDER: "Blender Python",
@@ -49,11 +56,14 @@ LANGUAGE_LABEL: dict[Language, str] = {
Language.URDF_BLENDER: "URDF + Blender Python",
Language.THREEJS: "Three.js (ESM)",
Language.SCENE_THREEJS: "Three.js scene (multi-file ESM + GLSL)",
+ Language.GLSL_SHADER: "GLSL fragment shader",
+ Language.OPENGL_PYTHON: "OpenGL (moderngl Python + GLSL)",
}
TYPE_LABEL: dict[Track, str] = {
Track.STATIC_OBJECT: "3D Objects",
Track.ARTICULATED_OBJECT: "Articulated Objects",
Track.SCENE: "3D Scenes",
+ Track.GRAPHICS: "Procedural Graphics",
}
MAX_GLB_BYTES = 20 * 1024 * 1024
SOURCE_NAME = "3dcodeverse"
@@ -64,6 +74,16 @@ class SampleError(RuntimeError):
"""The run cannot be turned into a sample (no code, no commit, ...)."""
+class AcceptanceEntry(BaseModel):
+ """One plan acceptance item joined with the judge's verdict for the exported round."""
+
+ id: str
+ text: str = ""
+ how: str = ""
+ priority: str = ""
+ passed: bool | None = None
+
+
class SampleMeta(BaseModel):
"""``meta.json`` — everything a consumer needs without opening record.json."""
@@ -94,10 +114,18 @@ class SampleMeta(BaseModel):
passed: bool | None = None
baseline_score: float | None = None
acceptance_results: dict[str, bool] = Field(default_factory=dict)
+ acceptance: list[AcceptanceEntry] = Field(default_factory=list, description="plan checklist + verdicts")
+ gate_errors: int = Field(default=0, description="error findings across all gates of the exported round")
+ gate_summary: dict[str, int] = Field(default_factory=dict, description="gate name → error count")
+ quality_tier: QualityTier = "D"
rounds: int = 0
best_round: int | None = None
+ rounds_summary: list[dict[str, Any]] = Field(default_factory=list, description="compact per-round digest")
+ stop_reason: str = ""
code_commit: str = ""
code_source: str = Field(default="commit", description="commit | working_tree")
+ code_fingerprint: str = Field(default="", description="sha256 of the normalised src/** tree")
+ prompt_hash: str = ""
status: str = ""
cost_usd: float = 0.0
usage: dict[str, Any] = Field(default_factory=dict)
@@ -169,11 +197,18 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
out.append(f"renders/{name}")
if rnd is not None and rnd.renders is not None:
+ names = [v.name for v in rnd.renders.views]
+ by_stem = len(set(names)) != len(names) # scene views repeat a camera name per time → use file stems
for v in rnd.renders.views:
src = _resolve(ws, v.path)
- if src is not None:
- suffix = src.suffix or ".png"
- _cp(src, f"view_{v.name}{suffix}")
+ if src is None:
+ continue
+ name = f"view_{src.stem if by_stem else v.name}{src.suffix or '.png'}"
+ i = 2
+ while f"renders/{name}" in out:
+ name = f"view_{src.stem}_{i}{src.suffix or '.png'}"
+ i += 1
+ _cp(src, name)
sheet = _resolve(ws, rnd.renders.contact_sheet)
if sheet is not None:
_cp(sheet, f"sheet{sheet.suffix or '.png'}")
@@ -183,17 +218,77 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
glb = ws.artifacts / "object.glb"
if glb.is_file() and glb.stat().st_size < MAX_GLB_BYTES:
_cp(glb, "object.glb")
+ gif = ws.artifacts / "preview.gif" # graphics runs: animated loop preview
+ if gif.is_file() and gif.stat().st_size < MAX_GLB_BYTES:
+ _cp(gif, "preview.gif")
+ return out
+
+
+def copy_textured(ws: Workspace, record: RunRecord, dest: Path) -> list[str]:
+ """When the texture pass shipped (``record.extra['texturing'].shipped``):
+ copy the generated ``textures/*.png`` and ``object_textured.glb`` into the sample."""
+ tex = record.extra.get("texturing") or {}
+ if not tex.get("shipped"):
+ return []
+ out: list[str] = []
+ tex_dir = ws.root / str(tex.get("textures_dir") or "artifacts/textures")
+ if tex_dir.is_dir():
+ for p in sorted(tex_dir.glob("*.png")):
+ (dest / "textures").mkdir(parents=True, exist_ok=True)
+ shutil.copy2(p, dest / "textures" / p.name)
+ out.append(f"textures/{p.name}")
+ glb = _resolve(ws, str(tex.get("glb_textured") or "")) or (
+ ws.artifacts / "object_textured.glb" if (ws.artifacts / "object_textured.glb").is_file() else None)
+ if glb is not None and glb.stat().st_size < MAX_GLB_BYTES:
+ (dest / "renders").mkdir(parents=True, exist_ok=True)
+ shutil.copy2(glb, dest / "renders" / "object_textured.glb")
+ out.append("renders/object_textured.glb")
return out
+def copy_link_meshes(ws: Workspace, dest: Path) -> list[str]:
+ """(urdf_blender) copy ``artifacts/meshes/*.glb`` so the sample's robot.urdf resolves."""
+ src = ws.artifacts / "meshes"
+ if not src.is_dir():
+ return []
+ out: list[str] = []
+ total = 0
+ for p in sorted(src.glob("*.glb")):
+ total += p.stat().st_size
+ if total > MAX_GLB_BYTES:
+ break
+ (dest / "meshes").mkdir(parents=True, exist_ok=True)
+ shutil.copy2(p, dest / "meshes" / p.name)
+ out.append(f"meshes/{p.name}")
+ return out
+
+
+def acceptance_entries(record: RunRecord, rnd: RoundRecord | None) -> list[AcceptanceEntry]:
+ """Plan checklist items joined with the round's judge verdicts (ids only when no plan)."""
+ j = effective_judgment(rnd) if rnd is not None else None
+ verdicts = dict(j.acceptance_results) if j is not None else {}
+ items = list(getattr(record.plan, "acceptance", []) or []) if record.plan is not None else []
+ out = [AcceptanceEntry(id=a.id, text=a.text, how=a.how, priority=a.priority, passed=verdicts.get(a.id)) for a in items]
+ known = {a.id for a in items}
+ out += [AcceptanceEntry(id=k, passed=v) for k, v in verdicts.items() if k not in known]
+ return out
+
+
+def gate_error_summary(rnd: RoundRecord | None) -> dict[str, int]:
+ return {g.gate: len(g.errors) for g in rnd.gates} if rnd is not None else {}
+
+
def build_meta(
ws: Workspace, record: RunRecord, *, key: str, entry: str, files: list[str], renders: list[str],
- rnd: RoundRecord | None, code_source: str,
+ rnd: RoundRecord | None, code_source: str, code: dict[str, bytes] | None = None,
+ captions: dict[str, Any] | None = None,
) -> SampleMeta:
spec = record.spec
- j = rnd.judgment if rnd is not None else None
- caps = record.extra.get("captions") or {}
+ j = effective_judgment(rnd) if rnd is not None else None # degraded verdicts count as unjudged
+ caps = captions if captions is not None else (record.extra.get("captions") or {})
code_files = [f for f in files if f.startswith("src/")]
+ gates = gate_error_summary(rnd)
+ n_gate_errors = sum(gates.values())
name = ""
if record.plan is not None:
name = getattr(record.plan, "object_name", "") or getattr(record.plan, "title", "")
@@ -222,10 +317,18 @@ def build_meta(
passed=j.passed if j else None,
baseline_score=record.baseline_score,
acceptance_results=dict(j.acceptance_results) if j else {},
+ acceptance=acceptance_entries(record, rnd),
+ gate_errors=n_gate_errors,
+ gate_summary=gates,
+ quality_tier=quality_tier(passed=j.passed if j else None, gate_errors=n_gate_errors, score=j.overall if j else None),
rounds=len(record.rounds),
best_round=rnd.index if rnd is not None else None,
+ rounds_summary=[round_summary(r) for r in record.rounds],
+ stop_reason=str(record.extra.get("stop_reason", "") or ""),
code_commit=rnd.commit if rnd is not None else "",
code_source=code_source,
+ code_fingerprint=code_fingerprint(code) if code else "",
+ prompt_hash=prompt_hash(spec.prompt),
status=record.status.value,
cost_usd=round(record.total_usage.cost_usd, 6),
usage=record.total_usage.model_dump(mode="json"),
diff --git a/harness/codeverse/flywheel/trajectories.py b/harness/codeverse/flywheel/trajectories.py
new file mode 100644
index 00000000..0fb39b8f
--- /dev/null
+++ b/harness/codeverse/flywheel/trajectories.py
@@ -0,0 +1,212 @@
+"""Mine repair pairs from agent trajectories (``trajectories/<stage>_rNN/transcript.jsonl``).
+
+Round-level repair pairs (``pairs.repair_pairs``) need a round whose build
+failed. Most build failures are fixed *inside* one agent session instead —
+the ``api-agent`` transcript records every ``write_file`` / ``edit_file`` /
+``build`` tool call, so the file state can be replayed::
+
+ write_file ... → build FAIL (error) → edit/write ... → build OK
+ ^ rejected snapshot ^ chosen snapshot
+
+Only the ``api-agent`` transcript format (``assistant`` turns with
+``tool_calls`` + ``tool_result`` turns) is structured enough; CLI backends
+(gemini-cli / codex / claude-code) log raw stdout lines and yield no pairs.
+
+The base file state is the ``pre:<label>`` git commit taken by the harness
+right before the session (nearest one not after the first transcript event);
+``read_file`` results are not used (they may be truncated).
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.flywheel import _git
+from codeverse.workspace import Workspace
+
+BUILD_TOOLS = frozenset({"build", "run_build"})
+MAX_PAIR_CODE = 200_000
+
+
+class TrajectoryRepair(BaseModel):
+ """One in-session repair: the last failing snapshot before a successful build."""
+
+ trajectory: str = Field(description="trajectory dir name, e.g. refine_r00")
+ stage: str
+ round_index: int | None
+ broken_turn: int
+ fixed_turn: int
+ error: str
+ rejected: dict[str, str] = Field(description="path → code at the failing build")
+ chosen: dict[str, str] = Field(description="path → code at the next successful build")
+ changed_files: list[str]
+ n_failures: int = Field(description="consecutive failing builds folded into this pair")
+
+
+def parse_trajectory_name(name: str) -> tuple[str, int | None]:
+ """``refine_r00`` → ``("refine", 0)``; ``zone_koi_pond_r01`` → ``("zone_koi_pond", 1)``."""
+ stem, _, tail = name.rpartition("_r")
+ if stem and tail.isdigit():
+ return stem, int(tail)
+ return name, None
+
+
+def _base_commit(ws: Workspace, label: str, not_after: float | None) -> str | None:
+ """Latest ``pre:<label>`` commit at or before ``not_after`` (epoch seconds)."""
+ try:
+ proc = subprocess.run(
+ ["git", "log", "--format=%H %ct %s"], cwd=ws.root, capture_output=True, text=True, check=False, timeout=30
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if proc.returncode != 0:
+ return None
+ for line in proc.stdout.splitlines(): # newest first
+ sha, _, rest = line.partition(" ")
+ ts, _, subject = rest.partition(" ")
+ if subject.strip() != f"pre:{label}":
+ continue
+ if not_after is None or float(ts) <= not_after + 1.0:
+ return sha
+ return None
+
+
+def _tracked(path: str) -> bool:
+ parts = Path(path).parts
+ return bool(parts) and parts[0] in _git.CODE_ROOTS
+
+
+def _normalise_path(ws: Workspace, raw: str) -> str:
+ p = Path(raw)
+ if p.is_absolute():
+ try:
+ p = p.relative_to(ws.root)
+ except ValueError:
+ return raw
+ return p.as_posix()
+
+
+class _Replay:
+ """Applies write/edit tool calls to an in-memory tree; tracks whether it is exact."""
+
+ def __init__(self, base: dict[str, str]):
+ self.files = dict(base)
+ self.exact = True # False once an edit touched a file we never saw in full
+ self.changed: set[str] = set()
+
+ def write(self, path: str, content: str) -> None:
+ self.files[path] = content
+ self.changed.add(path)
+
+ def edit(self, path: str, old: str, new: str, all_: bool) -> None:
+ if path not in self.files:
+ self.exact = False
+ return
+ text = self.files[path]
+ if not old or old not in text:
+ self.exact = False
+ return
+ self.files[path] = text.replace(old, new) if all_ else text.replace(old, new, 1)
+ self.changed.add(path)
+
+
+def read_events(transcript: Path) -> list[dict[str, Any]]:
+ out = []
+ for line in transcript.read_text(errors="replace").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ out.append(json.loads(line))
+ except ValueError:
+ continue
+ return out
+
+
+def mine_trajectory(ws: Workspace, traj_dir: Path) -> list[TrajectoryRepair]:
+ """Repair pairs from one trajectory folder (empty for non api-agent transcripts)."""
+ transcript = traj_dir / "transcript.jsonl"
+ if not transcript.is_file():
+ return []
+ events = read_events(transcript)
+ calls: dict[str, dict[str, Any]] = {}
+ for ev in events:
+ if ev.get("kind") == "assistant":
+ for c in ev.get("tool_calls") or []:
+ if isinstance(c, dict) and c.get("id"):
+ calls[str(c["id"])] = c
+ if not calls:
+ return []
+ stage, rnd = parse_trajectory_name(traj_dir.name)
+ t0 = next((float(ev["t"]) for ev in events if "t" in ev), None)
+ base_sha = _base_commit(ws, stage, t0)
+ base: dict[str, str] = {}
+ if base_sha:
+ try:
+ base, _ = _git.decode_text_files(_git.read_tree_at(ws, base_sha))
+ except _git.GitReadError:
+ base = {}
+ rp = _Replay(base)
+ broken: tuple[int, dict[str, str], str, set[str]] | None = None # turn, snapshot, error, changed-before
+ n_fail = 0
+ out: list[TrajectoryRepair] = []
+ for ev in events:
+ if ev.get("kind") != "tool_result":
+ continue
+ call = calls.get(str(ev.get("call_id")))
+ if call is None:
+ continue
+ name, args = str(call.get("name")), dict(call.get("arguments") or {})
+ ok = bool(ev.get("ok"))
+ turn = int(ev.get("turn", -1))
+ if name == "write_file" and ok:
+ path = _normalise_path(ws, str(args.get("path", "")))
+ if _tracked(path):
+ rp.write(path, str(args.get("content", "")))
+ elif name == "edit_file" and ok:
+ path = _normalise_path(ws, str(args.get("path", "")))
+ if _tracked(path):
+ rp.edit(path, str(args.get("old", "")), str(args.get("new", "")), bool(args.get("all", False)))
+ elif name in BUILD_TOOLS:
+ if not ok:
+ n_fail += 1
+ broken = (turn, dict(rp.files), str(ev.get("content", ""))[:4000], set(rp.changed))
+ continue
+ if broken is not None and rp.exact:
+ b_turn, b_files, b_err, _ = broken
+ changed = sorted(p for p in set(b_files) | set(rp.files) if b_files.get(p) != rp.files.get(p))
+ if changed:
+ out.append(TrajectoryRepair(
+ trajectory=traj_dir.name, stage=stage, round_index=rnd, broken_turn=b_turn,
+ fixed_turn=turn, error=b_err, rejected=_limit(b_files), chosen=_limit(rp.files),
+ changed_files=changed, n_failures=n_fail,
+ ))
+ broken, n_fail = None, 0
+ return out
+
+
+def _limit(files: dict[str, str], max_total: int = MAX_PAIR_CODE) -> dict[str, str]:
+ out: dict[str, str] = {}
+ total = 0
+ for p in sorted(files):
+ if total + len(files[p]) > max_total:
+ break
+ out[p] = files[p]
+ total += len(files[p])
+ return out
+
+
+def mine_run(ws: Workspace) -> list[TrajectoryRepair]:
+ """All in-session repair pairs of one run (every ``trajectories/*`` folder)."""
+ root = ws.root / "trajectories"
+ if not root.is_dir():
+ return []
+ out: list[TrajectoryRepair] = []
+ for d in sorted(p for p in root.iterdir() if p.is_dir()):
+ out.extend(mine_trajectory(ws, d))
+ return out
diff --git a/harness/codeverse/judges/base.py b/harness/codeverse/judges/base.py
index 955e0eb5..6d4edbd4 100644
--- a/harness/codeverse/judges/base.py
+++ b/harness/codeverse/judges/base.py
@@ -22,6 +22,9 @@ class JudgeInput(BaseModel):
round_index: int = 0
previous: Judgment | None = Field(default=None, description="last verdict (for delta framing)")
extra_context: str = ""
+ geometry_views: RenderSet | None = Field(
+ default=None, description="clay/normals renders for the geometry-only montage (holes, intersections)"
+ )
class Judge(Protocol):
diff --git a/harness/codeverse/judges/calibration.py b/harness/codeverse/judges/calibration.py
new file mode 100644
index 00000000..f1f03c35
--- /dev/null
+++ b/harness/codeverse/judges/calibration.py
@@ -0,0 +1,333 @@
+"""Judge calibration smoke: re-judge finished runs and ask "does the judge separate good from bad?"
+
+``calibrate(run_dirs)`` reads each run's ``rounds/rNN.json`` (read-only), rebuilds
+the ``JudgeInput`` (spec, renders, measurement, gates, plan digest, acceptance),
+re-judges every round with ``n_samples`` (montage order shuffled per sample) and
+tabulates, per round: gate error count, the stored overall, the new mean/std,
+per-criterion std, defects and caps. Across rounds it reports the Pearson and
+Spearman correlation between gate error counts and the new scores (expected
+negative), and between stored and new overalls. Optionally renders a clay /
+normals geometry set for the run's best round (``artifacts/object.glb``) so the
+geometry montage is exercised. Output goes to ``out_dir`` (never into the run).
+
+CLI: ``python -m codeverse.judges.calibration runs/a runs/b --model gemini:gemini-3.7-flash --n 3 --out scratch/``
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+import statistics
+import time
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import RenderSet
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.run import RoundRecord
+from codeverse.contracts.spec import Spec
+from codeverse.judges.base import JudgeInput
+from codeverse.judges.scoring import is_degraded
+from codeverse.judges.vlm_judge import VlmJudge
+
+log = logging.getLogger(__name__)
+
+TRACK_RUBRIC = {"static_object": "static_object_v1", "articulated_object": "articulated_v1", "scene": "scene_v1"}
+GEOMETRY_VIEW_NAMES = ("front_right_34", "back_left_34", "top", "low_front_left")
+
+
+# --------------------------------------------------------------------------- data
+class RoundCase(BaseModel):
+ """One judgeable round reconstructed from a run directory."""
+
+ run: str
+ round_index: int
+ kind: str
+ rubric: str
+ inp: JudgeInput
+ gate_errors: int
+ gate_warnings: int
+ stored: Judgment | None = None
+ is_best: bool = False
+ glb: str | None = None
+
+
+class CalibrationRow(BaseModel):
+ run: str
+ round: int
+ kind: str
+ gate_errors: int
+ gate_warnings: int
+ stored_overall: float | None = None
+ stored_backend: str = ""
+ mean: float
+ std: float
+ uncapped: float
+ defect_penalty: float
+ per_criterion_mean: dict[str, float] = Field(default_factory=dict)
+ per_criterion_std: dict[str, float] = Field(default_factory=dict)
+ defects_present: list[str] = Field(default_factory=list)
+ caps: list[str] = Field(default_factory=list)
+ passed: bool
+ n_used: int
+ geometry_views: bool = False
+ cost_usd: float = 0.0
+ duration_s: float = 0.0
+ summary: str = ""
+ error: str = ""
+
+
+class CalibrationTable(BaseModel):
+ model_id: str
+ n_samples: int
+ rows: list[CalibrationRow]
+ pearson_errors_vs_score: float | None = None
+ spearman_errors_vs_score: float | None = None
+ pearson_stored_vs_new: float | None = None
+ mean_std: float = 0.0
+ mean_criterion_std: float = 0.0
+ total_cost_usd: float = 0.0
+
+ def to_markdown(self) -> str:
+ head = ("| run | round | kind | gate err/warn | stored | new mean ± std | uncapped | penalty | defects | caps | pass | geo | cost |\n"
+ "|---|---|---|---|---|---|---|---|---|---|---|---|---|")
+ lines = [head]
+ for r in self.rows:
+ stored = f"{r.stored_overall:.3f}" if r.stored_overall is not None else "-"
+ lines.append(
+ f"| {r.run} | r{r.round:02d} | {r.kind} | {r.gate_errors}/{r.gate_warnings} | {stored} | "
+ f"{r.mean:.3f} ± {r.std:.3f} | {r.uncapped:.3f} | -{r.defect_penalty:.2f} | "
+ f"{', '.join(r.defects_present) or '-'} | {', '.join(r.caps) or '-'} | {'Y' if r.passed else 'n'} | "
+ f"{'Y' if r.geometry_views else '-'} | ${r.cost_usd:.3f} |" + (f" ERROR {r.error}" if r.error else "")
+ )
+ crit = sorted({k for r in self.rows for k in r.per_criterion_mean})
+ if crit:
+ lines.append("")
+ lines.append("| run/round | " + " | ".join(crit) + " |")
+ lines.append("|---|" + "---|" * len(crit))
+ for r in self.rows:
+ cells = [f"{r.per_criterion_mean.get(c, float('nan')):.2f}±{r.per_criterion_std.get(c, 0.0):.2f}" if c in r.per_criterion_mean else "-" for c in crit]
+ lines.append(f"| {r.run}/r{r.round:02d} | " + " | ".join(cells) + " |")
+ fmt = lambda v: "n/a" if v is None else f"{v:+.3f}" # noqa: E731
+ lines.append("")
+ lines.append(
+ f"model {self.model_id}, n_samples {self.n_samples}: pearson(gate errors, new score) = {fmt(self.pearson_errors_vs_score)}; "
+ f"spearman = {fmt(self.spearman_errors_vs_score)}; pearson(stored, new) = {fmt(self.pearson_stored_vs_new)}; "
+ f"mean overall std {self.mean_std:.3f}; mean per-criterion std {self.mean_criterion_std:.3f}; cost ${self.total_cost_usd:.3f}"
+ )
+ return "\n".join(lines)
+
+
+# --------------------------------------------------------------------------- loading runs
+def plan_digest(plan: dict[str, Any]) -> str:
+ """A track-agnostic plan summary (parts / joints / zones / assets / cameras) from ``plan.json``."""
+ bits: list[str] = []
+ title = plan.get("object_name") or plan.get("title") or ""
+ if title:
+ bits.append(f"{title}: {plan.get('summary', '')}".strip())
+ bbox = plan.get("overall_bbox") or {}
+ if isinstance(bbox, dict) and bbox.get("extents"):
+ e = bbox["extents"]
+ bits.append(f"Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m.")
+ parts = plan.get("parts") or []
+ if parts:
+ bits.append("Parts: " + ", ".join(f"{p['name']}×{p['instances']}" if p.get("instances", 1) > 1 else p["name"] for p in parts) + ".")
+ if plan.get("root_link"):
+ bits.append(f"Root link {plan['root_link']}.")
+ joints = plan.get("joints") or []
+ if joints:
+ bits.append("Joints: " + "; ".join(
+ f"{j['name']} ({j.get('type', '?')} {j.get('parent', '?')}→{j.get('child', '?')}, [{j.get('lower', 0):.2f},{j.get('upper', 0):.2f}])"
+ for j in joints) + ".")
+ for key, label in (("zones", "Zones"), ("assets", "Assets"), ("cameras", "Cameras")):
+ items = plan.get(key) or []
+ if items:
+ bits.append(f"{label}: " + ", ".join(str(i.get("name", "?")) for i in items) + ".")
+ if plan.get("setting"):
+ bits.append(f"Setting: {plan['setting']}.")
+ return " ".join(bits)
+
+
+def _read_json(path: Path) -> dict[str, Any]:
+ return json.loads(path.read_text())
+
+
+def load_run_cases(run_dir: Path, *, rounds: list[int] | None = None) -> list[RoundCase]:
+ """Rebuild judge inputs for every judgeable round of a run (rounds with renders)."""
+ run_dir = Path(run_dir)
+ spec = Spec.model_validate_json((run_dir / "spec.json").read_text())
+ plan = _read_json(run_dir / "plan.json") if (run_dir / "plan.json").is_file() else {}
+ record = _read_json(run_dir / "record.json") if (run_dir / "record.json").is_file() else {}
+ best = record.get("best_round")
+ acceptance = plan.get("acceptance") or []
+ digest = plan_digest(plan)
+ glb = run_dir / "artifacts" / "object.glb"
+ cases: list[RoundCase] = []
+ for path in sorted((run_dir / "rounds").glob("r*.json")):
+ rec = RoundRecord.model_validate_json(path.read_text())
+ if rounds is not None and rec.index not in rounds:
+ continue
+ if rec.renders is None or not rec.renders.views:
+ continue
+ rubric = rec.judgment.rubric if rec.judgment else TRACK_RUBRIC.get(spec.track.value, "static_object_v1")
+ inp = JudgeInput(
+ spec=spec, renders=rec.renders, measurement=rec.measurement, gates=rec.gates,
+ acceptance=[AcceptanceItem.model_validate(a) for a in acceptance], plan_summary=digest,
+ round_index=rec.index,
+ )
+ cases.append(RoundCase(
+ run=run_dir.name, round_index=rec.index, kind=rec.kind, rubric=rubric, inp=inp,
+ gate_errors=sum(len(g.errors) for g in rec.gates),
+ gate_warnings=sum(1 for g in rec.gates for f in g.findings if f.severity.value == "warn"),
+ stored=rec.judgment, is_best=(best == rec.index) if best is not None else False,
+ glb=str(glb) if glb.is_file() else None,
+ ))
+ if best is None and cases: # no record: treat the last round as the one the GLB belongs to
+ cases[-1].is_best = True
+ return cases
+
+
+def render_geometry_views(case: RoundCase, out_dir: Path, mode: str) -> RenderSet | None:
+ """Clay/normals renders of the run's final GLB for the best round (object tracks only)."""
+ if not case.glb or case.inp.spec.track.value == "scene":
+ return None
+ from codeverse.conventions import OBJECT_VIEWS
+ from codeverse.spatial.render import render_glb
+
+ views = [v for v in OBJECT_VIEWS if v.name in GEOMETRY_VIEW_NAMES]
+ try:
+ return render_glb(case.glb, out_dir / case.run / f"geometry_{mode}", views=views, mode=mode, sheet=False)
+ except Exception as e: # noqa: BLE001 — calibration must not die on a render hiccup
+ log.warning("geometry render failed for %s: %s", case.run, e)
+ return None
+
+
+# --------------------------------------------------------------------------- statistics
+def pearson(xs: list[float], ys: list[float]) -> float | None:
+ if len(xs) < 2 or len(set(xs)) < 2 or len(set(ys)) < 2:
+ return None
+ mx, my = statistics.fmean(xs), statistics.fmean(ys)
+ num = sum((x - mx) * (y - my) for x, y in zip(xs, ys, strict=True))
+ den = (sum((x - mx) ** 2 for x in xs) * sum((y - my) ** 2 for y in ys)) ** 0.5
+ return round(num / den, 4) if den else None
+
+
+def _ranks(vals: list[float]) -> list[float]:
+ order = sorted(range(len(vals)), key=lambda i: vals[i])
+ ranks = [0.0] * len(vals)
+ i = 0
+ while i < len(order):
+ j = i
+ while j + 1 < len(order) and vals[order[j + 1]] == vals[order[i]]:
+ j += 1
+ for k in range(i, j + 1):
+ ranks[order[k]] = (i + j) / 2 + 1
+ i = j + 1
+ return ranks
+
+
+def spearman(xs: list[float], ys: list[float]) -> float | None:
+ return pearson(_ranks(xs), _ranks(ys))
+
+
+# --------------------------------------------------------------------------- main entry
+def _judge_case(case: RoundCase, judge: VlmJudge, geometry: RenderSet | None, out: Path) -> CalibrationRow:
+ t0 = time.time()
+ j = judge.judge(case.inp, geometry_views=geometry)
+ raw = json.loads(j.raw) if j.raw else {}
+ jdir = out / "judgments"
+ jdir.mkdir(parents=True, exist_ok=True)
+ (jdir / f"{case.run}_r{case.round_index:02d}_{judge.model_id.replace(':', '_')}.json").write_text(j.model_dump_json(indent=1))
+ return CalibrationRow(
+ run=case.run, round=case.round_index, kind=case.kind, gate_errors=case.gate_errors, gate_warnings=case.gate_warnings,
+ stored_overall=case.stored.overall if case.stored else None,
+ stored_backend=case.stored.judge_backend if case.stored else "",
+ mean=j.overall, std=j.score_std, uncapped=float(raw.get("overall_uncapped", j.overall)),
+ defect_penalty=float(raw.get("defect_penalty", 0.0)),
+ per_criterion_mean=dict(j.scores), per_criterion_std=dict(raw.get("per_criterion_std", {})),
+ defects_present=[d for d, on in raw.get("defects", {}).items() if on],
+ caps=[c["rule"] for c in raw.get("caps", {}).get("caps_applied", [])],
+ passed=j.passed, n_used=j.n_samples, geometry_views=geometry is not None,
+ cost_usd=j.usage.cost_usd, duration_s=round(time.time() - t0, 1), summary=j.summary,
+ error=j.summary if is_degraded(j) else "",
+ )
+
+
+def calibrate(
+ run_dirs: list[Path | str],
+ *,
+ model_id: str | None = None,
+ n_samples: int = 3,
+ out_dir: Path | str | None = None,
+ geometry_mode: str | None = "clay",
+ rounds: list[int] | None = None,
+ thinking: str = "low",
+ max_workers: int = 4,
+ chat_model: Any = None,
+) -> CalibrationTable:
+ """Re-judge every round of ``run_dirs`` with ``n_samples`` and tabulate separation/noise.
+
+ Writes ``calibration_<model>.json`` / ``.md`` into ``out_dir`` (default: cwd) and
+ never touches the run directories. ``chat_model`` injects a ChatModel (tests).
+ """
+ from codeverse.config import get_settings
+
+ model_id = model_id or get_settings().default_judge
+ out = Path(out_dir) if out_dir else Path.cwd()
+ out.mkdir(parents=True, exist_ok=True)
+ cases: list[RoundCase] = []
+ for rd in run_dirs:
+ cases.extend(load_run_cases(Path(rd), rounds=rounds))
+ if not cases:
+ raise ValueError(f"no judgeable rounds found under {list(map(str, run_dirs))}")
+ geometry: dict[int, RenderSet | None] = {}
+ for i, c in enumerate(cases):
+ geometry[i] = render_geometry_views(c, out, geometry_mode) if (geometry_mode and c.is_best) else None
+ judges = {c.rubric: VlmJudge(c.rubric, model_id=model_id, n_samples=n_samples, thinking=thinking, # type: ignore[arg-type]
+ cache_dir=out / "cache", label="calibrate", chat_model=chat_model) for c in cases}
+ with ThreadPoolExecutor(max_workers=max(1, max_workers)) as pool:
+ rows = list(pool.map(lambda ic: _judge_case(ic[1], judges[ic[1].rubric], geometry[ic[0]], out), enumerate(cases)))
+ ok = [r for r in rows if not r.error]
+ table = CalibrationTable(
+ model_id=model_id, n_samples=n_samples, rows=rows,
+ pearson_errors_vs_score=pearson([float(r.gate_errors) for r in ok], [r.mean for r in ok]),
+ spearman_errors_vs_score=spearman([float(r.gate_errors) for r in ok], [r.mean for r in ok]),
+ pearson_stored_vs_new=pearson([r.stored_overall for r in ok if r.stored_overall is not None],
+ [r.mean for r in ok if r.stored_overall is not None]),
+ mean_std=round(statistics.fmean([r.std for r in ok]), 4) if ok else 0.0,
+ mean_criterion_std=round(statistics.fmean([v for r in ok for v in r.per_criterion_std.values()] or [0.0]), 4),
+ total_cost_usd=round(sum(r.cost_usd for r in rows), 4),
+ )
+ stem = "calibration_" + model_id.replace(":", "_").replace("/", "_")
+ (out / f"{stem}.json").write_text(json.dumps(table.model_dump(mode="json"), indent=1, ensure_ascii=False))
+ (out / f"{stem}.md").write_text(table.to_markdown() + "\n")
+ return table
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description="Re-judge finished runs to calibrate the VLM judge.")
+ ap.add_argument("run_dirs", nargs="+")
+ ap.add_argument("--model", default=None, help="chat model id, e.g. gemini:gemini-3.7-flash")
+ ap.add_argument("--n", type=int, default=3, help="samples per round")
+ ap.add_argument("--out", default=".", help="output directory (json + md)")
+ ap.add_argument("--geometry", default="clay", help="clay | normals | none (geometry montage for the best round)")
+ ap.add_argument("--rounds", default="", help="comma-separated round indices (default all)")
+ ap.add_argument("--thinking", default="low")
+ ap.add_argument("--workers", type=int, default=4)
+ a = ap.parse_args(argv)
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
+ rounds = [int(x) for x in a.rounds.split(",") if x.strip()] or None
+ table = calibrate(a.run_dirs, model_id=a.model, n_samples=a.n, out_dir=a.out,
+ geometry_mode=None if a.geometry == "none" else a.geometry, rounds=rounds,
+ thinking=a.thinking, max_workers=a.workers)
+ print(table.to_markdown())
+ return 0
+
+
+if __name__ == "__main__": # pragma: no cover
+ raise SystemExit(main())
diff --git a/harness/codeverse/judges/caps.py b/harness/codeverse/judges/caps.py
index 9bf609d2..9cdf6b2e 100644
--- a/harness/codeverse/judges/caps.py
+++ b/harness/codeverse/judges/caps.py
@@ -10,7 +10,7 @@ from fnmatch import fnmatch
from pydantic import BaseModel, Field
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.artifacts import GateFinding, GateReport, RenderView, Severity
from codeverse.contracts.plan import AcceptanceItem
from codeverse.judges.rubrics import CapRule, Rubric
@@ -64,17 +64,30 @@ def apply_caps(
acceptance_items: list[AcceptanceItem] | None = None,
*,
console_errors: list[str] | None = None,
+ views: list[RenderView] | None = None,
+ defects_present: dict[str, bool] | None = None,
) -> CapResult:
"""Apply every rubric cap rule; the overall becomes ``min(overall, caps...)``.
Only the first matching finding per rule is recorded as evidence (one ledger
- line per rule), but all rules are evaluated.
+ line per rule), but all rules are evaluated. ``defects_present`` (checklist
+ id → True) adds one ``defect:<id>`` ledger line per present defect that
+ carries a ``cap``.
"""
applied: list[CapApplied] = []
for rule in rubric.caps:
- evidence = _rule_evidence(rule, gates, acceptance_results, acceptance_items or [], console_errors or [])
+ evidence = _rule_evidence(rule, gates, acceptance_results, acceptance_items or [], console_errors or [], views or [])
if evidence is not None:
applied.append(CapApplied(rule=rule.id, cap=rule.cap, evidence=evidence))
+ for did, present in (defects_present or {}).items():
+ if not present:
+ continue
+ try:
+ item = rubric.defect(did)
+ except KeyError:
+ continue
+ if item.cap is not None:
+ applied.append(CapApplied(rule=f"defect:{did}", cap=item.cap, evidence=f"judge checklist: {item.text[:120]}"))
capped = overall
for a in applied:
capped = min(capped, a.cap)
@@ -87,7 +100,13 @@ def _rule_evidence(
acceptance_results: dict[str, bool],
acceptance_items: list[AcceptanceItem],
console_errors: list[str],
+ views: list[RenderView],
) -> str | None:
+ if rule.when == "missing_views":
+ tokens = [k.lower() for k in rule.kinds]
+ if any(any(t in f"{v.name} {v.mode}".lower() for t in tokens) for v in views):
+ return None
+ return f"no render view matching {rule.kinds} among {len(views)} view(s)"
if rule.when == "acceptance":
missing = missing_must_items(acceptance_items, acceptance_results)
if missing:
diff --git a/harness/codeverse/judges/images.py b/harness/codeverse/judges/images.py
index b7571adf..7f4521e1 100644
--- a/harness/codeverse/judges/images.py
+++ b/harness/codeverse/judges/images.py
@@ -11,6 +11,8 @@ from __future__ import annotations
import hashlib
import math
+import os
+import threading
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
@@ -100,9 +102,9 @@ def prepare_image(
im = im.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.LANCZOS)
if label:
im = _with_label_strip(im, label)
- tmp = out.with_suffix(".tmp.png")
+ tmp = out.with_name(f"{out.stem}.{os.getpid()}-{threading.get_ident()}.tmp.png") # unique per writer: concurrent judges share the cache
im.save(tmp, format="PNG", optimize=True)
- tmp.replace(out)
+ tmp.replace(out) # atomic; a concurrent identical write simply wins last
return out
diff --git a/harness/codeverse/judges/montage.py b/harness/codeverse/judges/montage.py
new file mode 100644
index 00000000..f996061e
--- /dev/null
+++ b/harness/codeverse/judges/montage.py
@@ -0,0 +1,269 @@
+"""Judge montages: ≤ 2×2 labelled grids built from a ``RenderSet``.
+
+Research finding applied here: VLM judges get position-biased and saturate when
+shown many tiles, so every judge image carries **at most four views**. A judge
+call sees, in priority order and capped at ``max_montages``:
+
+1. ``shaded`` primary — the 4 most informative shaded views (3/4 views, top,
+ underside for objects; authored cameras for scenes);
+2. ``poses`` — the articulation pose sheet (harness-made) or a 2×2 of ``pose_*``
+ views, when the render set has them;
+3. ``geometry`` — a 2×2 of clay / normals renders (from ``geometry_views`` or from
+ non-shaded views inside the set) so holes, inverted faces and intersections
+ are visible without shading/material noise;
+4. ``shaded`` secondary — the remaining shaded views (then a 2×2 of ``pose_*``
+ views when a pose sheet was already shown);
+
+plus 0–2 ``detail`` crops (centre of the best 3/4 view at 2×; the ground-contact
+band of the lowest view). ``shuffle_montages`` permutes montage order *and* tile
+order per n-sample so judge noise from position bias averages out.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import random
+import threading
+from dataclasses import dataclass, replace
+from pathlib import Path
+from typing import Literal
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.judges.images import JudgeImageError, default_cache_dir, view_az_el
+from codeverse.spatial.sheet import crop_region, montage_2x2
+
+MontageKind = Literal["shaded", "geometry", "poses", "pose_sheet", "detail"]
+
+#: modes that show geometry without material/lighting noise
+GEOMETRY_MODES = ("clay", "normals", "wire", "silhouette", "depth")
+#: most-informative-first order for the object rig (names from conventions.OBJECT_VIEWS)
+OBJECT_RANK = ("front_right_34", "back_left_34", "top", "low_front_left", "front", "right", "back", "left")
+#: scene rig: authored cameras first (graded for composition), then overview rig
+SCENE_OVERVIEW_RANK = ("overview_front_right", "overview_back_left", "eye_front", "overview_top", "eye_right", "eye_back_left")
+POSE_PREFIX = "pose_"
+POSE_SHEET_NAMES = ("articulation_sheet", "pose_sheet")
+_POSITIONS = {
+ 1: ("single",),
+ 2: ("left", "right"),
+ 3: ("top-left", "top-right", "bottom-left"),
+ 4: ("top-left", "top-right", "bottom-left", "bottom-right"),
+}
+MAX_TILES = 4
+
+
+@dataclass(frozen=True)
+class Montage:
+ """One judge image: 1–4 tiles (or a pass-through sheet / a detail crop)."""
+
+ kind: MontageKind
+ tiles: tuple[RenderView, ...]
+ title: str
+ passthrough: bool = False
+ crop: tuple[float, float, float, float] | None = None
+ hint: str = ""
+
+ @property
+ def is_detail(self) -> bool:
+ return self.kind == "detail"
+
+
+# --------------------------------------------------------------------------- view grouping / ranking
+def is_pose_view(v: RenderView) -> bool:
+ return v.name.startswith(POSE_PREFIX)
+
+
+def is_pose_sheet(v: RenderView) -> bool:
+ return v.name in POSE_SHEET_NAMES
+
+
+def is_geometry_view(v: RenderView) -> bool:
+ return v.mode in GEOMETRY_MODES
+
+
+def rank_views(views: list[RenderView], *, scene: bool) -> list[RenderView]:
+ """Most informative first; unknown names keep their given order after the known ones."""
+ if scene:
+ def key(iv: tuple[int, RenderView]) -> tuple[int, int, int]:
+ i, v = iv
+ if v.name.startswith("cam_"):
+ return (0, 0, i)
+ if v.name in SCENE_OVERVIEW_RANK:
+ return (1, SCENE_OVERVIEW_RANK.index(v.name), i)
+ return (2, 0, i)
+ else:
+ def key(iv: tuple[int, RenderView]) -> tuple[int, int, int]:
+ i, v = iv
+ return (0, OBJECT_RANK.index(v.name), i) if v.name in OBJECT_RANK else (1, 0, i)
+ return [v for _, v in sorted(enumerate(views), key=key)]
+
+
+def _chunks(views: list[RenderView], n: int) -> list[list[RenderView]]:
+ return [views[i : i + n] for i in range(0, len(views), n)]
+
+
+def plan_montages(
+ renders: RenderSet,
+ *,
+ geometry_views: RenderSet | None = None,
+ scene: bool = False,
+ max_montages: int = 3,
+ detail_crops: int = 2,
+) -> list[Montage]:
+ """Decide which montages a judge call gets (see module docstring for the priority)."""
+ shaded = [v for v in renders.views if not (is_pose_view(v) or is_pose_sheet(v) or is_geometry_view(v))]
+ poses = [v for v in renders.views if is_pose_view(v)]
+ sheets = [v for v in renders.views if is_pose_sheet(v)]
+ geometry = [v for v in renders.views if is_geometry_view(v)]
+ if geometry_views is not None:
+ geometry = list(geometry_views.views) + geometry
+ shaded = rank_views(shaded, scene=scene)
+ shaded_groups = _chunks(shaded, MAX_TILES)
+
+ candidates: list[Montage] = []
+ if shaded_groups:
+ candidates.append(Montage("shaded", tuple(shaded_groups[0]), "SHADED views"))
+ if sheets:
+ candidates.append(Montage("pose_sheet", (sheets[0],), "POSE SHEET (rows = poses, columns = views; tile labels name the joint and its value)", passthrough=True))
+ elif poses:
+ candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the harness; tile label = pose)"))
+ if geometry:
+ geo = _match_geometry(geometry, candidates[0].tiles if candidates else ())
+ candidates.append(Montage("geometry", tuple(geo), f"GEOMETRY-ONLY views ({geo[0].mode}: no materials — look for holes, black/inverted faces, intersections, gaps)"))
+ for extra in shaded_groups[1:]:
+ candidates.append(Montage("shaded", tuple(extra), "SHADED views (remaining)"))
+ if sheets and poses: # the sheet already shows the poses; the 2×2 is a larger-tile duplicate, lowest priority
+ candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the harness; tile label = pose)"))
+ chosen = candidates[: max(0, max_montages)]
+ chosen.extend(plan_detail_crops(shaded, scene=scene)[: max(0, detail_crops)])
+ return chosen
+
+
+def _match_geometry(geometry: list[RenderView], primary: tuple[RenderView, ...]) -> list[RenderView]:
+ """Prefer geometry views whose names match the primary shaded montage, then the rest."""
+ names = [v.name for v in primary]
+ by_name = {v.name: v for v in geometry}
+ out = [by_name[n] for n in names if n in by_name]
+ out += [v for v in geometry if v not in out]
+ return out[:MAX_TILES]
+
+
+def plan_detail_crops(shaded: list[RenderView], *, scene: bool) -> list[Montage]:
+ """Centre crop of the best view at 2× (detail legibility) + ground band of the lowest view (objects only)."""
+ if not shaded:
+ return []
+ out = [Montage("detail", (shaded[0],), f"DETAIL CROP — centre of {shaded[0].name} at 2×",
+ crop=(0.25, 0.25, 0.75, 0.75),
+ hint="look for bevels, seams, gaps and surface artefacts; judge detail at this scale")]
+ if scene:
+ return out
+ lowest = min(shaded, key=lambda v: (view_az_el(v) or (0.0, 90.0))[1])
+ if lowest is not shaded[0] or len(shaded) == 1:
+ out.append(Montage("detail", (lowest,), f"DETAIL CROP — ground-contact band of {lowest.name}",
+ crop=(0.0, 0.55, 1.0, 1.0),
+ hint="look for feet/legs that do not reach the ground and parts hovering above their support"))
+ return out
+
+
+# --------------------------------------------------------------------------- shuffling
+def shuffle_montages(montages: list[Montage], seed: int | None) -> list[Montage]:
+ """Permute montage order and the tile order inside each grid; detail crops stay last."""
+ if seed is None:
+ return list(montages)
+ rng = random.Random(seed)
+ grids = [m for m in montages if not m.is_detail]
+ details = [m for m in montages if m.is_detail]
+ rng.shuffle(grids)
+ out = []
+ for m in grids:
+ if m.passthrough or len(m.tiles) < 2:
+ out.append(m)
+ continue
+ tiles = list(m.tiles)
+ rng.shuffle(tiles)
+ out.append(replace(m, tiles=tuple(tiles)))
+ return out + details
+
+
+# --------------------------------------------------------------------------- labels
+def tile_label(v: RenderView) -> str:
+ bits = [v.name]
+ azel = view_az_el(v)
+ if azel is not None:
+ bits.append(f"az {azel[0]:.0f}° el {azel[1]:.0f}°")
+ if v.mode and v.mode != "shaded":
+ bits.append(v.mode)
+ if v.time_s is not None:
+ bits.append(f"t={v.time_s:g}s")
+ return " · ".join(bits)
+
+
+def montage_strip(m: Montage, index: int, total: int) -> str:
+ """Short label burnt into the image's top strip (``MONTAGE 2/3 — SHADED views``)."""
+ if m.is_detail:
+ return f"{m.title} [{index}/{total}]"
+ title = m.title.split(" (")[0]
+ return f"MONTAGE {index}/{total} — {title}"
+
+
+def montage_label(m: Montage, index: int, total: int) -> str:
+ """Full label for the text part: strip + tile layout (``…: top-left = front_right_34 · az 35° el 22°, …``)."""
+ head = montage_strip(m, index, total)
+ if m.is_detail:
+ return head + (f" — {m.hint}" if m.hint else "")
+ if m.passthrough:
+ return f"MONTAGE {index}/{total} — {m.title}"
+ pos = _POSITIONS[len(m.tiles)]
+ return f"MONTAGE {index}/{total} — {m.title}: " + ", ".join(f"{p} = {tile_label(v)}" for p, v in zip(pos, m.tiles, strict=True))
+
+
+# --------------------------------------------------------------------------- rendering
+def _key(parts: list[str]) -> str:
+ return hashlib.sha1("|".join(parts).encode()).hexdigest()[:20]
+
+
+def _stat(p: str) -> str:
+ path = Path(p)
+ if not path.is_file():
+ raise JudgeImageError(f"judge image missing: {path}")
+ st = path.stat()
+ return f"{path.resolve()}|{st.st_mtime_ns}|{st.st_size}"
+
+
+def _tmp(out: Path) -> Path:
+ return out.with_name(f"{out.stem}.{os.getpid()}-{threading.get_ident()}.tmp.png")
+
+
+def render_montage(m: Montage, *, cache_dir: Path | None = None, tile_px: int = 512) -> Path:
+ """Build (or fetch from cache) the PNG for one montage; pass-through sheets return their source.
+
+ Writes go through a per-writer temp file + atomic replace so concurrent
+ judges sharing a cache directory never read a half-written PNG.
+ """
+ if m.passthrough:
+ _stat(m.tiles[0].path)
+ return Path(m.tiles[0].path)
+ cache = Path(cache_dir) if cache_dir else default_cache_dir()
+ cache.mkdir(parents=True, exist_ok=True)
+ if m.is_detail:
+ v = m.tiles[0]
+ out = cache / f"crop_{_key([_stat(v.path), str(m.crop), str(tile_px)])}.png"
+ if not out.is_file():
+ tmp = crop_region(v.path, _tmp(out), m.crop or (0.0, 0.0, 1.0, 1.0), min_px=tile_px)
+ tmp.replace(out)
+ return out
+ images = [(tile_label(v), v.path) for v in m.tiles]
+ out = cache / f"montage_{_key([_stat(p) + '|' + lbl for lbl, p in images] + [str(tile_px)])}.png"
+ if not out.is_file():
+ tmp = montage_2x2(images, _tmp(out), tile=tile_px)
+ tmp.replace(out)
+ return out
+
+
+def describe_montages(montages: list[Montage]) -> str:
+ """One line per image for the VIEW RIG paragraph (what each image is, in send order)."""
+ grids = [m for m in montages if not m.is_detail]
+ details = [m for m in montages if m.is_detail]
+ lines = [f"- image {i}: {m.title}" for i, m in enumerate(grids, 1)]
+ lines += [f"- detail crop {i}: {m.title.replace('DETAIL CROP — ', '')}" for i, m in enumerate(details, 1)]
+ return "\n".join(lines)
diff --git a/harness/codeverse/judges/output_schema.py b/harness/codeverse/judges/output_schema.py
index fe9f71d1..8c47e48a 100644
--- a/harness/codeverse/judges/output_schema.py
+++ b/harness/codeverse/judges/output_schema.py
@@ -33,8 +33,13 @@ class AcceptanceVerdict(BaseModel):
evidence: str = Field(default="", description="which view / number proves or disproves it")
+class DefectVerdict(BaseModel):
+ present: bool = Field(description="true only if the defect is VISIBLE in the images or stated by a gate/measurement")
+ evidence: str = Field(default="", description="which image / tile / number shows it (or why it is absent)")
+
+
class JudgeOutput(BaseModel):
- """Provider-neutral parsed judge reply (criteria + acceptance as dicts)."""
+ """Provider-neutral parsed judge reply (criteria + acceptance + defect checklist as dicts)."""
criteria: dict[str, CriterionScore]
summary: str = ""
@@ -42,6 +47,8 @@ class JudgeOutput(BaseModel):
issues: list[JudgeIssue] = Field(default_factory=list)
improvement_plan: list[ImprovementItem] = Field(default_factory=list)
acceptance: dict[str, AcceptanceVerdict] = Field(default_factory=dict)
+ defects: dict[str, bool] = Field(default_factory=dict, description="checklist id → defect present")
+ defect_evidence: dict[str, str] = Field(default_factory=dict)
@property
def scores(self) -> dict[str, float]:
@@ -63,16 +70,19 @@ def build_wire_model(rubric: Rubric, acceptance_ids: list[str]) -> type[BaseMode
for c in rubric.visual_criteria()
}
Criteria = create_model("Criteria", **crit_fields)
+ # Field order = generation order for JSON-mode models: observe (summary, strengths, issues, defect
+ # checklist, acceptance) BEFORE scoring, so the scores follow the evidence rather than the reverse.
fields: dict[str, Any] = {
- "criteria": (Criteria, Field(description="one entry per criterion id")),
"summary": (str, Field(description="2-4 sentences: what it is, what is right, what is most wrong")),
"strengths": (list[str], Field(default_factory=list, description="≤ 5 short bullets")),
"issues": (list[JudgeIssue], Field(default_factory=list, description="observable defects, most severe first")),
- "improvement_plan": (
- list[ImprovementItem],
- Field(default_factory=list, description="≤ 6 concrete instructions for the builder, priority 1 first"),
- ),
}
+ if rubric.defects:
+ def_fields: dict[str, Any] = {
+ d.id: (DefectVerdict, Field(description=d.text.strip()[:200])) for d in rubric.defects
+ }
+ Defects = create_model("Defects", **def_fields)
+ fields["defects"] = (Defects, Field(description="binary checklist: one entry per defect id, present=true ONLY when seen"))
if acceptance_ids:
acc_fields: dict[str, Any] = {
f"acc_{i}": (AcceptanceVerdict, Field(alias=aid, description=f"acceptance item {aid}"))
@@ -80,6 +90,11 @@ def build_wire_model(rubric: Rubric, acceptance_ids: list[str]) -> type[BaseMode
}
Acceptance = create_model("Acceptance", **acc_fields)
fields["acceptance"] = (Acceptance, Field(description="one entry per acceptance item id"))
+ fields["criteria"] = (Criteria, Field(description="one entry per criterion id, scored AFTER the observations above"))
+ fields["improvement_plan"] = (
+ list[ImprovementItem],
+ Field(default_factory=list, description="≤ 6 concrete instructions for the builder, priority 1 first"),
+ )
return create_model("JudgeReply", **fields)
@@ -148,6 +163,27 @@ def _coerce_acceptance(value: Any) -> dict[str, Any]:
return out
+def _coerce_defects(value: Any) -> tuple[dict[str, bool], dict[str, str]]:
+ """``{id: bool}`` or ``{id: {present, evidence}}`` or a list of records → (present, evidence)."""
+ if value is None:
+ return {}, {}
+ recs = _records_to_dict(value, ("id", "defect", "item"))
+ present: dict[str, bool] = {}
+ evidence: dict[str, str] = {}
+ for k, v in recs.items():
+ if isinstance(v, bool):
+ present[k] = v
+ elif isinstance(v, dict):
+ flag = v.get("present", v.get("value", v.get("verified")))
+ if not isinstance(flag, bool):
+ raise JudgeParseError(f"defect {k!r}: 'present' must be a boolean, got {flag!r}")
+ present[k] = flag
+ evidence[k] = str(v.get("evidence", "") or "")
+ else:
+ raise JudgeParseError(f"defect item {k!r}: unexpected value {v!r}")
+ return present, evidence
+
+
def parse_judge_output(
payload: Any, rubric: Rubric, acceptance_ids: list[str], *, measured_scores: dict[str, float] | None = None
) -> JudgeOutput:
@@ -169,6 +205,7 @@ def parse_judge_output(
k: ({"score": v, "evidence": ""} if isinstance(v, (int, float)) else v) for k, v in criteria.items()
}
acceptance = _coerce_acceptance(data.get("acceptance", {}))
+ defects, defect_evidence = _coerce_defects(data.get("defects", {}))
out = JudgeOutput(
criteria=criteria,
summary=str(data.get("summary", "") or ""),
@@ -176,6 +213,8 @@ def parse_judge_output(
issues=data.get("issues", []) or [],
improvement_plan=data.get("improvement_plan", []) or [],
acceptance=acceptance,
+ defects=defects,
+ defect_evidence=defect_evidence,
)
except ValidationError as e:
raise JudgeParseError(f"judge reply failed validation: {e}") from e
@@ -191,4 +230,12 @@ def parse_judge_output(
missing_acc = [a for a in acceptance_ids if a not in out.acceptance]
for a in missing_acc: # unanswered acceptance items count as NOT verified
out.acceptance[a] = AcceptanceVerdict(verified=False, evidence="not answered by judge")
+ known = {d.id for d in rubric.defects}
+ for k in [k for k in out.defects if k not in known]: # unknown checklist ids are ignored
+ out.defects.pop(k)
+ out.defect_evidence.pop(k, None)
+ for d in rubric.defects:
+ if d.id not in out.defects: # unanswered defect → absent (the conservative direction for a penalty)
+ out.defects[d.id] = False
+ out.defect_evidence[d.id] = "not answered by judge"
return out
diff --git a/harness/codeverse/judges/pairwise.py b/harness/codeverse/judges/pairwise.py
index d8b41342..fae077e9 100644
--- a/harness/codeverse/judges/pairwise.py
+++ b/harness/codeverse/judges/pairwise.py
@@ -2,8 +2,10 @@
Position bias is real, so the comparison runs TWICE with A/B swapped; the
winner is declared only when both orderings agree, otherwise ``tie``. Each
-call sees the brief, the rubric's criteria (titles + descriptions) and each
-candidate's contact sheet (or up to 4 views when there is no sheet).
+call sees the brief, the rubric's criteria (titles + descriptions) and ONE
+2×2 montage per candidate (the 4 most informative views — never a big sheet:
+VLM judges flip with many tiles). ``compare_many`` ranks N candidates by a
+round-robin of such comparisons (best-of-N).
"""
from __future__ import annotations
@@ -11,6 +13,7 @@ from __future__ import annotations
import logging
import re
import statistics
+from dataclasses import replace
from pathlib import Path
from typing import Literal
@@ -21,9 +24,10 @@ from codeverse.contracts.artifacts import RenderSet
from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart, TextPart
from codeverse.contracts.common import Usage
from codeverse.contracts.spec import Spec
-from codeverse.judges.images import image_part, prepare_image, view_label
+from codeverse.judges.images import image_part, prepare_image
+from codeverse.judges.montage import montage_label, plan_montages, render_montage
from codeverse.judges.output_schema import JudgeParseError, extract_json
-from codeverse.judges.prompt_builder import brief_section
+from codeverse.judges.prompt_builder import MONTAGE_TILE_PX, brief_section
from codeverse.judges.rubrics import Rubric, load_rubric
from codeverse.models.base import ChatModel, ModelError
@@ -55,6 +59,21 @@ class PairwiseResult(BaseModel):
error: str = ""
+class RankingResult(BaseModel):
+ """Round-robin ranking of N candidates (``compare_many``)."""
+
+ order: list[int] = Field(description="candidate indices, best first")
+ points: dict[int, float] = Field(description="win = 1, tie = 0.5 per pair")
+ confidence: dict[int, float] = Field(default_factory=dict, description="mean confidence of the pairs a candidate won")
+ pairs: list[dict] = Field(default_factory=list, description="{a, b, winner, confidence, error} per pair")
+ usage: Usage = Field(default_factory=Usage)
+ errors: list[str] = Field(default_factory=list)
+
+ @property
+ def best(self) -> int:
+ return self.order[0]
+
+
_SYSTEM = """You are a BLIND comparative judge for a 3D-code harness. You see a brief, a rubric and renders of TWO candidates, labelled A and B. Decide which candidate better satisfies the brief, judging ONLY what is visible. Position carries no information: A is not better for being first.
Compare criterion by criterion (intent, structure, detail, proportions, fit, materials, cleanliness as listed), then decide overall. Prefer the candidate with no major defect over the one with more detail but a floating or broken part. Say 'tie' only when the two are genuinely equivalent. Reply with one JSON object: winner ('A'|'B'|'tie'), confidence 0..1, reasons[], criteria_won[{criterion, winner}]."""
@@ -74,8 +93,8 @@ class PairwiseJudge:
):
self.model_id = model_id or get_settings().default_judge
self.temperature = temperature
- self.max_px = max_px
- self.views_per_side = views_per_side
+ self.max_px = max(max_px, 1024) # a 2×2 montage needs the resolution
+ self.views_per_side = min(4, views_per_side)
self._model = chat_model
self.cache_dir = cache_dir
@@ -121,6 +140,43 @@ class PairwiseJudge:
return PairwiseResult(winner="tie", confidence=0.0, usage=usage, error=" || ".join(errors))
return _combine(verdicts, orderings, usage, errors)
+ def compare_many(
+ self, spec: Spec, candidates: list[RenderSet], *, rubric: str | Rubric = "static_object_v1"
+ ) -> RankingResult:
+ """Rank ``candidates`` by round-robin pairwise comparison (each pair in both orders).
+
+ Points: win = 1, tie = 0.5. Ties in points are broken by the mean confidence
+ of won pairs, then by the lower index (earlier candidate). One candidate →
+ trivial ranking without any call.
+ """
+ n = len(candidates)
+ if n == 0:
+ raise ValueError("compare_many needs at least one candidate")
+ points = {i: 0.0 for i in range(n)}
+ conf_won: dict[int, list[float]] = {i: [] for i in range(n)}
+ pairs: list[dict] = []
+ usage = Usage()
+ errors: list[str] = []
+ for i in range(n):
+ for j in range(i + 1, n):
+ res = self.compare(spec, candidates[i], candidates[j], rubric=rubric)
+ usage = usage + res.usage
+ if res.error:
+ errors.append(f"{i}v{j}: {res.error}")
+ if res.winner == "a":
+ points[i] += 1.0
+ conf_won[i].append(res.confidence)
+ elif res.winner == "b":
+ points[j] += 1.0
+ conf_won[j].append(res.confidence)
+ else:
+ points[i] += 0.5
+ points[j] += 0.5
+ pairs.append({"a": i, "b": j, "winner": res.winner, "confidence": res.confidence, "error": res.error})
+ confidence = {i: (round(statistics.fmean(v), 3) if v else 0.0) for i, v in conf_won.items()}
+ order = sorted(range(n), key=lambda i: (-points[i], -confidence[i], i))
+ return RankingResult(order=order, points=points, confidence=confidence, pairs=pairs, usage=usage, errors=errors)
+
# ------------------------------------------------------------------ prompt
def _request(self, spec: Spec, rub: Rubric, first: RenderSet, second: RenderSet) -> ChatRequest:
crit = "\n".join(f"- {c.id}: {c.description.strip()}" for c in rub.visual_criteria())
@@ -141,15 +197,16 @@ class PairwiseJudge:
)
def _side_images(self, tag: str, rs: RenderSet) -> list[tuple[str, ImagePart]]:
+ """One 2×2 montage of the candidate's most informative views (plus its pose sheet / geometry montage if any)."""
+ montages = plan_montages(rs, scene=False, max_montages=2, detail_crops=0)
out: list[tuple[str, ImagePart]] = []
- if rs.contact_sheet:
- lbl = f"CANDIDATE {tag} — contact sheet ({len(rs.views)} views)"
- out.append((lbl, image_part(prepare_image(rs.contact_sheet, label=lbl, max_px=max(self.max_px, 1024), cache_dir=self.cache_dir), lbl)))
- return out
- views = rs.views[: self.views_per_side]
- for i, v in enumerate(views, 1):
- lbl = f"CANDIDATE {tag} — " + view_label(v, i, len(views))
- out.append((lbl, image_part(prepare_image(v.path, label=lbl, max_px=self.max_px, cache_dir=self.cache_dir), lbl)))
+ for i, m in enumerate(montages, 1):
+ if len(m.tiles) > self.views_per_side:
+ m = replace(m, tiles=m.tiles[: self.views_per_side])
+ lbl = f"CANDIDATE {tag} — " + montage_label(m, i, len(montages))
+ strip = f"CANDIDATE {tag} — {m.title.split(' (')[0]}"
+ png = render_montage(m, cache_dir=self.cache_dir, tile_px=MONTAGE_TILE_PX)
+ out.append((lbl, image_part(prepare_image(png, label=strip, max_px=self.max_px, cache_dir=self.cache_dir), lbl)))
return out
diff --git a/harness/codeverse/judges/prompt_builder.py b/harness/codeverse/judges/prompt_builder.py
index 108bfe55..deae162e 100644
--- a/harness/codeverse/judges/prompt_builder.py
+++ b/harness/codeverse/judges/prompt_builder.py
@@ -1,39 +1,56 @@
-"""Build the judge conversation: system (role + rubric + output rules) and ONE
-user message (brief, plan digest, acceptance checklist, measurement table, gate
-digest, previous-verdict framing, view-rig paragraph, then labelled images).
-
-Text is budgeted to ≈6k tokens; images to ≤ ``max_images`` at ≤ ``max_px``.
-The builder's code and reasoning are never included (blind judge).
+"""Build the judge conversation: system (role + rubric + defect checklist +
+output rules) and ONE user message (brief, plan digest, acceptance checklist,
+measurement table, gate digest, previous-verdict framing, view-rig paragraph,
+then the labelled images).
+
+Images are ≤ 2×2 **montages** (see ``montage.py``): at most ``max_montages``
+grids (shaded primary, pose sheet, geometry-only, shaded secondary) plus 0–2
+detail crops, every tile labelled, whole-image label strips burnt in. Text is
+budgeted to ≈6k tokens. The builder's code and reasoning are never included
+(blind judge).
"""
from __future__ import annotations
-import random
from pathlib import Path
from typing import TYPE_CHECKING
-from codeverse.contracts.artifacts import GateReport, Measurement, RenderSet, RenderView, Severity
+from codeverse.contracts.artifacts import GateReport, Measurement, RenderSet, Severity
from codeverse.contracts.chat import ChatMessage, ImagePart, TextPart
from codeverse.contracts.judgment import Judgment
from codeverse.contracts.plan import AcceptanceItem
from codeverse.contracts.spec import Spec
-from codeverse.judges.images import image_part, prepare_image, view_label
+from codeverse.judges.images import image_part, prepare_image
+from codeverse.judges.montage import (
+ Montage,
+ describe_montages,
+ montage_label,
+ montage_strip,
+ plan_montages,
+ render_montage,
+ shuffle_montages,
+)
from codeverse.judges.rubrics import Rubric
if TYPE_CHECKING: # pragma: no cover
from codeverse.judges.base import JudgeInput
TEXT_BUDGET_CHARS = 24_000 # ≈ 6k tokens
-MAX_IMAGES = 10
-MAX_PX = 768
+MAX_MONTAGES = 3
+MAX_DETAIL_CROPS = 2
+MAX_PX = 1024 # montages are 2×2 grids: keep them legible
+MONTAGE_TILE_PX = 512
_ROLE = """You are the BLIND JUDGE of a 3D-code harness: exacting but fair.
You see only the brief, a plan digest, measured numbers, deterministic gate findings and labelled renders of the result — never the builder's code or reasoning. Judge what is visible and measured; do not invent faults and do not credit what you cannot see.
+Gate findings describe the exported FILE (names, node hierarchy, contacts); the renders show the actual geometry. When they seem to disagree about something VISIBLE (a part moves in a posed tile, a part is present), trust the images for the visual criteria and report the file-level fact as an issue — never infer "nothing moves" or "part missing" from text alone when the tiles show otherwise.
+Work in this order: observe (summary, strengths, issues), answer the defect checklist and the acceptance items, and only THEN score the criteria against their anchors.
SCORING RULES
-- Score each criterion 0..1 against its anchors (interpolate between anchors). Use the whole range: competent work sits at 0.8+, one clearly visible major defect pulls the affected criterion to ~0.4, broken work sits at 0.1-0.3. Do not compress everything into 0.5-0.7.
-- Every score needs evidence that cites the VIEW label(s) and/or the measurement that shows it (e.g. "VIEW 4 (right): rear leg ends 3 cm above ground; measurement ground_gap 0.03").
-- Do NOT compute an overall or decide pass/fail; the harness computes the weighted overall, applies floors and caps.
+- Score each criterion 0..1 against its anchors (interpolate between anchors). Use the WHOLE range: competent work sits at 0.8+, one clearly visible major defect pulls the affected criterion to ~0.4, broken work sits at 0.1-0.3. Do not compress everything into 0.5-0.7 — a primitive box-stack and a crafted product must be 0.4 apart, not 0.1.
+- Every score needs evidence that cites the image and tile (e.g. "MONTAGE 1 top-left (front_right_34): rear leg ends 3 cm above ground; measurement ground_gap 0.03").
+- DEFECT CHECKLIST: answer EVERY item with present=true/false. true ONLY when the defect is visible in an image, or a gate finding of severity ERROR / a measurement states it; gate WARNINGS (e.g. a few-mm weld overlap) are informational and never make a defect present. Cite where. These answers drive penalties and caps computed by the harness, so be literal: do not mark a defect to "be safe", and do not hide one to be kind.
+- Do NOT compute an overall or decide pass/fail; the harness computes the weighted overall, subtracts defect penalties, applies floors and caps.
- Issues: observable defects, most severe first, with target = the part / zone / joint / asset name from the plan digest (or "overall"), a kind, a severity and evidence.
- Improvement plan: at most 6 concrete, imperative instructions for the builder ("taper the four legs from 45 mm at the seat to 30 mm at the foot and extend them to touch y=0"), priority 1 first, each with a target name from the plan digest and an expected_gain estimate. Give items even for passing work if a named change would raise the score; leave empty only when nothing would.
- Acceptance items: answer verified=true ONLY when the renders or measurements prove the item; otherwise false with what is missing.
@@ -50,6 +67,16 @@ def _rubric_block(rubric: Rubric) -> str:
lines.append(f"{i}. {c.id} (weight {c.weight:.2f}{floor}) — {c.label}: {c.description.strip()}")
for lvl in ("1.0", "0.7", "0.4", "0.1"):
lines.append(f" {lvl}: {c.anchors[lvl]}")
+ if rubric.defects:
+ lines.append("")
+ lines.append("DEFECT CHECKLIST (binary; answer every id):")
+ for d in rubric.defects:
+ cost = []
+ if d.penalty:
+ cost.append(f"-{d.penalty:.2f}")
+ if d.cap is not None:
+ cost.append(f"cap {d.cap:.2f}")
+ lines.append(f"- {d.id}: {d.text.strip()}" + (f" [{', '.join(cost)}]" if cost else ""))
if rubric.extra_instructions.strip():
lines.append("")
lines.append("RUBRIC NOTES: " + rubric.extra_instructions.strip())
@@ -175,58 +202,61 @@ def previous_section(prev: Judgment | None, round_index: int) -> str:
return "\n".join(lines)
-def view_rig_section(renders: RenderSet, n_views: int, *, scene: bool) -> str:
+def view_rig_section(renders: RenderSet, montages: list[Montage], *, scene: bool) -> str:
+ n_grids = sum(1 for m in montages if not m.is_detail)
+ n_detail = len(montages) - n_grids
bits = [
- "VIEW RIG: the first image is a CONTACT SHEET of all views (tiles are labelled); it is followed by the individual views, each with a burnt-in label 'VIEW k/N — name · az/el'." if renders.contact_sheet else
- "VIEW RIG: each image carries a burnt-in label 'VIEW k/N — name · az/el'.",
+ f"VIEW RIG: {n_grids} MONTAGE image(s) follow" + (f" plus {n_detail} DETAIL CROP(s)" if n_detail else "") + ". "
+ "Each montage is a ≤2×2 grid; every tile carries a label under it ('name · az/el[· mode][· t=]') and the "
+ "montage's own label strip lists which view sits top-left / top-right / bottom-left / bottom-right. "
+ "Cite evidence as 'MONTAGE k <position> (<view name>)'. Detail crops are zoomed regions of a view, labelled with what to look for.",
"Azimuth 0° = looking at the FRONT of the object, increasing counter-clockwise seen from above (90° = the object's right side, 180° = back); elevation is degrees above the horizon (negative = looking up from below the ground plane, which reveals undersides and ground contact).",
]
+ if any(m.kind == "geometry" for m in montages):
+ bits.append("The GEOMETRY-ONLY montage shows the same object without materials/lighting: use it for holes, inverted (black) faces, intersections and floating parts; use the SHADED montage for materials and detail.")
+ if any(m.kind in ("poses", "pose_sheet") for m in montages):
+ bits.append("POSE tiles show the SAME object with joints moved by the harness (tile label = joint@value or rest). Judge articulation only from them and the joint table.")
if scene:
bits.append("Views named overview_* are harness cameras fitted to the scene bounds (layout X-ray); views named cam_* are the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.")
else:
- bits.append("All views show the same object; cite the view label when you report a defect. Use top + low views for symmetry, footprint and ground contact.")
+ bits.append("All views show the same object. Use top + low views for symmetry, footprint and ground contact.")
if renders.console_errors:
bits.append(f"PROBE: {len(renders.console_errors)} console error(s) during rendering, first: {_clip(renders.console_errors[0], 200)}")
if renders.fps is not None:
bits.append(f"PROBE: measured {renders.fps:.0f} fps.")
- bits.append(f"{n_views} view(s) follow.")
+ bits.append("Images in send order:\n" + describe_montages(montages))
return "\n".join(bits)
# --------------------------------------------------------------------------- images
-def select_views(views: list[RenderView], max_views: int, *, shuffle_seed: int | None) -> list[RenderView]:
- """Evenly sub-sample to ``max_views`` (keeps rig diversity) then optionally shuffle the order."""
- chosen = list(views)
- if len(chosen) > max_views:
- step = len(chosen) / max_views
- chosen = [chosen[int(i * step)] for i in range(max_views)]
- if shuffle_seed is not None:
- random.Random(shuffle_seed).shuffle(chosen)
- return chosen
-
-
-def image_parts_for_renders(
+def montage_image_parts(
renders: RenderSet,
*,
- max_images: int = MAX_IMAGES,
- max_px: int = MAX_PX,
+ geometry_views: RenderSet | None = None,
+ scene: bool = False,
shuffle_seed: int | None = None,
+ max_montages: int = MAX_MONTAGES,
+ detail_crops: int = MAX_DETAIL_CROPS,
+ max_px: int = MAX_PX,
cache_dir: Path | None = None,
- reserved: int = 0,
-) -> tuple[list[tuple[str, ImagePart]], list[RenderView]]:
- """(label, ImagePart) pairs: contact sheet first, then labelled views; plus the chosen views."""
- budget = max_images - reserved
+) -> tuple[list[tuple[str, ImagePart]], list[Montage]]:
+ """(label, ImagePart) pairs for the montages of a render set, plus the montage plan (in send order)."""
+ montages = shuffle_montages(
+ plan_montages(renders, geometry_views=geometry_views, scene=scene, max_montages=max_montages, detail_crops=detail_crops),
+ shuffle_seed,
+ )
+ grids = [m for m in montages if not m.is_detail]
+ details = [m for m in montages if m.is_detail]
out: list[tuple[str, ImagePart]] = []
- if renders.contact_sheet and budget > 0:
- lbl = f"CONTACT SHEET — all {len(renders.views)} views"
- out.append((lbl, image_part(prepare_image(renders.contact_sheet, label=lbl, max_px=max(max_px, 1024), cache_dir=cache_dir), lbl)))
- budget -= 1
- chosen = select_views(renders.views, max(budget, 0), shuffle_seed=shuffle_seed)
- n = len(chosen)
- for i, v in enumerate(chosen, 1):
- lbl = view_label(v, i, n)
- out.append((lbl, image_part(prepare_image(v.path, label=lbl, max_px=max_px, cache_dir=cache_dir), lbl)))
- return out, chosen
+ for i, m in enumerate(grids, 1):
+ lbl, strip = montage_label(m, i, len(grids)), montage_strip(m, i, len(grids))
+ png = render_montage(m, cache_dir=cache_dir, tile_px=MONTAGE_TILE_PX)
+ out.append((lbl, image_part(prepare_image(png, label=strip, max_px=max_px, cache_dir=cache_dir), lbl)))
+ for i, m in enumerate(details, 1):
+ lbl, strip = montage_label(m, i, len(details)), montage_strip(m, i, len(details))
+ png = render_montage(m, cache_dir=cache_dir, tile_px=MONTAGE_TILE_PX)
+ out.append((lbl, image_part(prepare_image(png, label=strip, max_px=min(max_px, 768), cache_dir=cache_dir), lbl)))
+ return out, montages
# --------------------------------------------------------------------------- assembly
@@ -235,7 +265,9 @@ def build_judge_messages(
rubric: Rubric,
*,
shuffle_seed: int | None = None,
- max_images: int = MAX_IMAGES,
+ geometry_views: RenderSet | None = None,
+ max_montages: int = MAX_MONTAGES,
+ detail_crops: int = MAX_DETAIL_CROPS,
max_px: int = MAX_PX,
cache_dir: Path | None = None,
extra_images: list[tuple[str, str | Path]] | None = None,
@@ -243,8 +275,13 @@ def build_judge_messages(
) -> tuple[str, list[ChatMessage]]:
"""Return ``(system, [user_message])`` for a rubric judge call.
- ``extra_images`` (label, path) are placed BEFORE the renders (e.g. reference
- images); ``extra_text`` is appended to the text block (e.g. measured silhouette).
+ ``geometry_views`` is an optional second RenderSet rendered with
+ ``mode='clay'`` / ``'normals'`` (tracks may pass it); when absent, geometry
+ views embedded in ``inp.renders`` (by ``RenderView.mode``) are used, else the
+ geometry montage is skipped. ``shuffle_seed`` permutes montage and tile
+ order (n-sample noise control). ``extra_images`` (label, path) are placed
+ BEFORE the montages (e.g. reference images); ``extra_text`` is appended to
+ the text block (e.g. measured silhouette).
"""
system = build_system_prompt(rubric)
is_scene = inp.spec.track.value == "scene"
@@ -259,20 +296,20 @@ def build_judge_messages(
_clip(extra_text, 2500) if extra_text.strip() else "",
]
extras = extra_images or []
- images, chosen = image_parts_for_renders(
- inp.renders, max_images=max_images, max_px=max_px, shuffle_seed=shuffle_seed, cache_dir=cache_dir,
- reserved=len(extras),
+ images, montages = montage_image_parts(
+ inp.renders, geometry_views=geometry_views, scene=is_scene, shuffle_seed=shuffle_seed,
+ max_montages=max_montages, detail_crops=detail_crops, max_px=max_px, cache_dir=cache_dir,
)
- sections.append(view_rig_section(inp.renders, len(chosen), scene=is_scene))
+ sections.append(view_rig_section(inp.renders, montages, scene=is_scene))
text = "\n\n".join(s for s in sections if s)
if len(text) > TEXT_BUDGET_CHARS:
text = _clip(text, TEXT_BUDGET_CHARS)
parts: list[TextPart | ImagePart] = [TextPart(text=text)]
for lbl, p in extras:
parts.append(TextPart(text=lbl))
- parts.append(image_part(prepare_image(p, label=lbl, max_px=max_px, cache_dir=cache_dir), lbl))
+ parts.append(image_part(prepare_image(p, label=lbl, max_px=min(max_px, 768), cache_dir=cache_dir), lbl))
for lbl, ip in images:
parts.append(TextPart(text=lbl))
parts.append(ip)
- parts.append(TextPart(text="Now score every criterion with evidence, answer every acceptance item, and return the JSON object."))
+ parts.append(TextPart(text="Now score every criterion with evidence, answer every defect-checklist item and every acceptance item, and return the JSON object."))
return system, [ChatMessage(role="user", parts=parts)]
diff --git a/harness/codeverse/judges/rubrics.py b/harness/codeverse/judges/rubrics.py
index 829ec0d7..491c5008 100644
--- a/harness/codeverse/judges/rubrics.py
+++ b/harness/codeverse/judges/rubrics.py
@@ -8,6 +8,12 @@ the weighted mean) and a ``kind`` (``visual`` = scored by the VLM,
``caps`` are rules that bound the overall score from deterministic gate
findings (build error → 0.0, floating part → ≤ 0.6 ...) — see ``caps.py``.
+
+``defects`` is a fixed **binary checklist** the VLM answers (present / absent)
+— "a part floats", "lying on its back", "flat untextured" … — and the code
+turns into arithmetic: ``penalty`` is subtracted from the weighted overall and
+``cap`` bounds it. Binary items survive the compressed dynamic range of
+flash-class judges far better than 0..1 scores do.
"""
from __future__ import annotations
@@ -63,6 +69,28 @@ class Criterion(BaseModel):
return self.title or self.id.replace("_", " ")
+class DefectItem(BaseModel):
+ """One binary checklist item the judge answers; scored in code.
+
+ ``penalty`` is subtracted from the weighted overall when the defect is
+ present (majority vote over samples); ``cap`` bounds the overall. Either may
+ be absent (a purely informational item has penalty 0 and no cap).
+ """
+
+ id: str
+ text: str = Field(description="concrete, visually checkable statement of the defect")
+ penalty: float = Field(default=0.0, ge=0.0, le=1.0)
+ cap: float | None = Field(default=None, ge=0.0, le=1.0)
+ note: str = ""
+
+ @field_validator("id")
+ @classmethod
+ def _ident(cls, v: str) -> str:
+ if not _IDENT.match(v):
+ raise ValueError(f"defect id must be snake_case identifier, got {v!r}")
+ return v
+
+
class CapRule(BaseModel):
"""Bounds the overall score when a deterministic signal fires.
@@ -72,11 +100,14 @@ class CapRule(BaseModel):
/ ``finding.data.code`` or, as a fallback, in the lower-cased message.
``when="acceptance"`` fires when any ``must`` acceptance item is not verified.
``when="console"`` fires when the render set reports console errors (scenes).
+ ``when="missing_views"`` fires when NO render view has a name/mode containing
+ any of ``kinds`` (e.g. ``kinds: [pose_, articulation_sheet]`` = the articulated
+ rubric requires posed views).
"""
id: str
cap: float = Field(ge=0.0, le=1.0)
- when: Literal["gate", "acceptance", "console"] = "gate"
+ when: Literal["gate", "acceptance", "console", "missing_views"] = "gate"
gate: str = Field(default="*", description="fnmatch pattern on GateFinding.gate")
severity: Severity = Severity.ERROR
kinds: list[str] = Field(default_factory=list)
@@ -90,6 +121,7 @@ class Rubric(BaseModel):
pass_threshold: float = Field(ge=0.0, le=1.0)
criteria: list[Criterion] = Field(min_length=1)
caps: list[CapRule] = Field(default_factory=list)
+ defects: list[DefectItem] = Field(default_factory=list, description="binary checklist scored in code")
extra_instructions: str = ""
description: str = ""
@@ -104,6 +136,9 @@ class Rubric(BaseModel):
cap_ids = [c.id for c in self.caps]
if len(cap_ids) != len(set(cap_ids)):
raise ValueError(f"duplicate cap ids in rubric {self.name}")
+ d_ids = [d.id for d in self.defects]
+ if len(d_ids) != len(set(d_ids)):
+ raise ValueError(f"duplicate defect ids in rubric {self.name}")
return self
# ------------------------------------------------------------------ helpers
@@ -117,6 +152,12 @@ class Rubric(BaseModel):
return c
raise KeyError(f"rubric {self.name} has no criterion {cid!r}")
+ def defect(self, did: str) -> DefectItem:
+ for d in self.defects:
+ if d.id == did:
+ return d
+ raise KeyError(f"rubric {self.name} has no defect {did!r}")
+
def visual_criteria(self) -> list[Criterion]:
return [c for c in self.criteria if c.kind == "visual"]
diff --git a/harness/codeverse/judges/rubrics/articulated_v1.yaml b/harness/codeverse/judges/rubrics/articulated_v1.yaml
index af3f4b39..3afa892c 100644
--- a/harness/codeverse/judges/rubrics/articulated_v1.yaml
+++ b/harness/codeverse/judges/rubrics/articulated_v1.yaml
@@ -3,18 +3,22 @@ version: 1
track_hint: articulated_object
pass_threshold: 0.7
description: 'Rubric for an ARTICULATED object (cabinet with doors/drawers, laptop, folding chair, robot arm, scissors...)
- judged on the rest-pose render rig PLUS a pose sheet: views of the object with joints swept to sampled values
- (labelled with joint names and values). Static criteria are inherited from static_object_v1 at reduced weight;
- articulation criteria score whether the joints are real, placed right and move plausibly.
-
- '
-extra_instructions: 'Views whose label says POSE or names a joint value show the SAME object with joints moved by
- the harness (forward kinematics from the authored URDF). Judge articulation ONLY from those views and the joint
- table: a door that swings through its frame, a drawer that slides sideways, a lid that rotates about the wrong
- edge, or a hinge placed in mid-air are articulation defects even when the rest pose looks perfect. Judge static
- criteria from the rest-pose views. Links are named in the plan digest; use link and joint names as targets.
-
- '
+ judged on the rest-pose render rig PLUS the POSE SHEET: a harness-made grid whose rows are poses (rest, then each
+ joint at a swept value, labelled ''<joint>@<value>'') and whose columns are views (3/4, back 3/4, front), with
+ optional 2x2 montages of pose_* tiles. The pose sheet is REQUIRED: without it the overall is capped (see caps)
+ because articulation cannot be judged. Static criteria are inherited from static_object_v1 at reduced weight;
+ articulation criteria score whether the joints are real, placed right and move plausibly.'
+extra_instructions: 'POSE tiles (the POSE SHEET image and any tile whose label starts with ''pose_'' or names a
+ joint@value) show the SAME object with joints moved by the harness (forward kinematics from the authored URDF);
+ ''rest'' is the rest pose, ''<joint>@upper'' / ''@lower'' / ''@mid'' the joint at that limit or midpoint. Compare
+ each posed tile with the rest tile of the SAME column: what moved, which way, by how much. A door that swings
+ through its frame, a drawer that slides sideways or up, a lid that rotates about the wrong edge, a hinge placed
+ in mid-air, or a pose identical to rest are articulation defects even when the rest pose looks perfect. Judge
+ static criteria from the rest-pose montage; use the joint table (axis, pivot, limits) in the plan digest / context. Links
+ are named in the plan digest; use link and joint names as targets. CALIBRATION: 0.9+ = photographs of the object
+ in use (door open on its hinge edge, drawer out on its rails, clearances visible, crisp parts); 0.5 = joints move
+ but one moves wrongly or the object is a primitive stack; 0.2 = nothing moves / parts explode when posed / wrong
+ object. The DEFECT CHECKLIST is binary and literal.'
criteria:
- id: intent_fidelity
weight: 0.16
@@ -52,9 +56,12 @@ criteria:
'
anchors:
- '1.0': Every joint moves like the real mechanism; posed views look like photographs of the object in use.
- '0.7': All joints move the right way; one moves a little too far / too little or looks slightly stiff.
- '0.4': One joint moves the wrong way (slides instead of swings, opens into the body) or in the wrong direction.
+ '1.0': Every joint moves like the real mechanism in the posed tiles (door swings open about its hinge edge,
+ drawer slides straight out of its opening, lid lifts up); posed tiles look like photographs of the object
+ in use.
+ '0.7': All joints move the right way; one moves a little too far / too little, or a clearance looks tight.
+ '0.4': One joint moves the wrong way (slides instead of swings, opens into the body, drawer moves sideways or
+ up) or a posed tile is identical to rest although the joint has range.
'0.1': Joints do nothing visible, move the wrong links, or the object falls apart when posed.
- id: joint_placement_and_range
weight: 0.12
@@ -65,10 +72,12 @@ criteria:
'
anchors:
- '1.0': Every pivot sits on the real hinge/rail line; extremes are collision-free and natural.
- '0.7': A pivot is slightly off its edge or a limit is a bit generous, without visible clipping.
- '0.4': A pivot is clearly off (door rotates about its centre, drawer pivots), or an extreme pose clips through
- the body.
+ '1.0': Every pivot sits on the real hinge/rail line (the door's edge stays against the carcass while open; the
+ drawer box stays inside its opening); extremes are collision-free and natural.
+ '0.7': A pivot is slightly off its edge (a few mm gap appears when open) or a limit is a bit generous, without
+ visible clipping.
+ '0.4': A pivot is clearly off (door rotates about its centre or detaches from the frame, drawer pivots), or
+ an extreme pose clips through the body.
'0.1': Pivots in mid-air, joints on the wrong links, or poses that explode the object.
- id: geometry_detail
weight: 0.12
@@ -159,13 +168,14 @@ caps:
- disconnected
- unsupported
- island
+ - touches nothing
cap: 0.6
- id: penetration_error
when: gate
gate: '*'
severity: error
kinds:
- - penetration
+ - penetrat
- intersect
- overlap
cap: 0.7
@@ -180,3 +190,66 @@ caps:
- unattached
cap: 0.6
note: a link is not physically attached to its parent as its joint type requires
+- id: missing_pose_sheet
+ when: missing_views
+ kinds:
+ - articulation_sheet
+ - pose_sheet
+ - pose_
+ cap: 0.5
+ note: the articulated rubric requires posed views; without them articulation is unjudged
+defects:
+- id: wrong_object
+ text: The renders show a different object category than the brief (or nothing recognisable).
+ cap: 0.25
+- id: missing_named_part
+ text: A link or part the brief/plan names is absent (no handle, no second drawer, no lid).
+ penalty: 0.1
+ cap: 0.6
+- id: floating_part
+ text: In the REST pose a link visibly hovers or is detached from its parent (daylight between them; check the
+ low view and the geometry montage).
+ penalty: 0.1
+ cap: 0.6
+- id: interpenetration
+ text: In the REST pose a link visibly passes through another in a render, or a gate ERROR reports it; few-mm weld overlaps reported as warnings are NOT this defect.
+ penalty: 0.08
+ cap: 0.7
+- id: wrong_proportions
+ text: Part ratios or overall size clearly wrong (> 20%) against the brief / measurement table.
+ penalty: 0.08
+ cap: 0.7
+- id: wrong_orientation
+ text: The object lies on its back or side, is upside down, or faces away from the front view.
+ penalty: 0.1
+ cap: 0.5
+- id: no_articulation_visible
+ text: Posed tiles look identical to the rest tile for a joint that has range (nothing moves).
+ penalty: 0.15
+ cap: 0.4
+- id: wrong_motion_type
+ text: 'A joint moves the wrong way: a door slides, a drawer swings or moves sideways/up, a lid drops into the
+ body, a link rotates about the wrong axis.'
+ penalty: 0.12
+ cap: 0.5
+- id: pivot_misplaced
+ text: A part rotates about its centre or a point in mid-air instead of its hinge edge / rail (a gap opens between
+ door and carcass at the hinge side when open).
+ penalty: 0.1
+ cap: 0.6
+- id: pose_clips_body
+ text: In a posed tile a moving part passes through the carcass / frame / another link.
+ penalty: 0.08
+ cap: 0.6
+- id: primitive_only
+ text: Every part is an unmodified box / cylinder with sharp 90° edges — no handles, bevels, insets, rails or thickness
+ anywhere.
+ penalty: 0.08
+- id: untextured_flat
+ text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
+ penalty: 0.05
+ cap: 0.75
+- id: holes_or_inverted_faces
+ text: Missing faces, see-through walls or black inverted faces are visible.
+ penalty: 0.08
+ cap: 0.6
diff --git a/harness/codeverse/judges/rubrics/asset_v1.yaml b/harness/codeverse/judges/rubrics/asset_v1.yaml
index ed324dfc..673ddc41 100644
--- a/harness/codeverse/judges/rubrics/asset_v1.yaml
+++ b/harness/codeverse/judges/rubrics/asset_v1.yaml
@@ -21,7 +21,7 @@ criteria:
title: Identity and silhouette
description: >
Does the asset read as the thing its plan entry names, from its silhouette alone
- (the contact sheet at a glance) as well as up close?
+ (the shaded montage at a glance) as well as up close?
anchors:
"1.0": Instantly recognisable from every view; the silhouette alone names it.
"0.7": Recognisable from the 3/4 views; one view is ambiguous.
@@ -120,8 +120,37 @@ caps:
when: gate
gate: "*"
severity: error
- kinds: [penetration, intersect, overlap, collision]
+ kinds: [penetrat, intersect, overlap, collision]
cap: 0.7
- id: missing_must_acceptance
when: acceptance
cap: 0.6
+
+# Binary checklist (judge answers, code scores: penalty subtracted, cap applied).
+defects:
+ - id: wrong_object
+ text: The renders show a different object than the plan entry / reference (or nothing recognisable).
+ cap: 0.25
+ - id: floating_part
+ text: A part visibly hovers or is detached from the rest (daylight between it and its support).
+ penalty: 0.10
+ cap: 0.60
+ - id: interpenetration
+ text: A part visibly passes through another in a render (a rail poking out of the far side of a leg, a leg through the seat) or a gate ERROR reports it; weld overlaps of a few mm reported as gate warnings are NOT this defect.
+ penalty: 0.08
+ cap: 0.70
+ - id: unfinished_side
+ text: The back / underside / a side is missing, open or untextured where the front is finished.
+ penalty: 0.08
+ cap: 0.65
+ - id: primitive_only
+ text: Every part is an unmodified box / cylinder / sphere with sharp edges — no bevel, taper, profile or cut-out.
+ penalty: 0.08
+ - id: untextured_flat
+ text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
+ penalty: 0.05
+ cap: 0.75
+ - id: holes_or_inverted_faces
+ text: Missing faces, see-through walls or black inverted faces are visible.
+ penalty: 0.08
+ cap: 0.60
diff --git a/harness/codeverse/judges/rubrics/reference_v1.yaml b/harness/codeverse/judges/rubrics/reference_v1.yaml
index b66c4c39..b3155345 100644
--- a/harness/codeverse/judges/rubrics/reference_v1.yaml
+++ b/harness/codeverse/judges/rubrics/reference_v1.yaml
@@ -108,8 +108,37 @@ caps:
when: gate
gate: "*"
severity: error
- kinds: [penetration, intersect, overlap, collision]
+ kinds: [penetrat, intersect, overlap, collision]
cap: 0.7
- id: missing_must_acceptance
when: acceptance
cap: 0.6
+
+# Binary checklist (judge answers, code scores: penalty subtracted, cap applied).
+defects:
+ - id: wrong_object
+ text: The renders show a different object than the plan entry / reference (or nothing recognisable).
+ cap: 0.25
+ - id: floating_part
+ text: A part visibly hovers or is detached from the rest (daylight between it and its support).
+ penalty: 0.10
+ cap: 0.60
+ - id: interpenetration
+ text: A part visibly passes through another in a render (a rail poking out of the far side of a leg, a leg through the seat) or a gate ERROR reports it; weld overlaps of a few mm reported as gate warnings are NOT this defect.
+ penalty: 0.08
+ cap: 0.70
+ - id: unfinished_side
+ text: The back / underside / a side is missing, open or untextured where the front is finished.
+ penalty: 0.08
+ cap: 0.65
+ - id: primitive_only
+ text: Every part is an unmodified box / cylinder / sphere with sharp edges — no bevel, taper, profile or cut-out.
+ penalty: 0.08
+ - id: untextured_flat
+ text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
+ penalty: 0.05
+ cap: 0.75
+ - id: holes_or_inverted_faces
+ text: Missing faces, see-through walls or black inverted faces are visible.
+ penalty: 0.08
+ cap: 0.60
diff --git a/harness/codeverse/judges/rubrics/scene_v1.yaml b/harness/codeverse/judges/rubrics/scene_v1.yaml
index 8ac2662d..c17a54a4 100644
--- a/harness/codeverse/judges/rubrics/scene_v1.yaml
+++ b/harness/codeverse/judges/rubrics/scene_v1.yaml
@@ -129,6 +129,37 @@ criteria:
"0.4": Visible z-fighting / missing faces / hard world edge, or a console error.
"0.1": Broken renders, shader failures, or the scene does not run.
+# Binary checklist (judge answers, code scores: penalty subtracted, cap applied).
+defects:
+ - id: wrong_place
+ text: The scene is a different kind of place than the brief describes (or an unreadable world).
+ cap: 0.30
+ - id: camera_unusable
+ text: An authored camera (cam_*) shows only sky / ground / the inside of a wall, or is clipped by the near plane.
+ penalty: 0.08
+ cap: 0.60
+ - id: unlit_or_blown
+ text: A view is near-black, blown to white, or the light direction contradicts the sky.
+ penalty: 0.08
+ cap: 0.60
+ - id: floating_or_sunken_asset
+ text: An asset clearly hovers above or sinks into the ground / terrain in an overview view.
+ penalty: 0.06
+ cap: 0.70
+ - id: empty_zone
+ text: A zone named in the plan is empty or contains only a ground plane.
+ penalty: 0.06
+ - id: placeholder_material
+ text: Magenta / default-grey / untextured flat surfaces dominate a view.
+ penalty: 0.05
+ cap: 0.75
+ - id: nothing_moves
+ text: Frames at different times (t=) are identical although motion was planned.
+ penalty: 0.05
+ - id: world_edge_visible
+ text: A hard world edge / terrain cliff / missing horizon is visible from an authored camera.
+ penalty: 0.04
+
caps:
- id: build_error
when: gate
@@ -149,8 +180,39 @@ caps:
when: gate
gate: "*"
severity: error
- kinds: [camera_in_geometry, camera_clipped, camera_inside, point_blank, blank_view, dead_render]
+ kinds: [camera_in_geometry, camera_clipped, camera_inside, camera_underground, point_blank, blank_view, dead_render]
cap: 0.5
+ # scene_frames gate (codeverse.spatial.frame_metrics): deterministic frame quality of the
+ # authored cameras — a crushed dusk, a blown sky, a one-colour frame or an establishing shot
+ # that shows a tiny island of content can never score as a finished picture.
+ - id: dark_frame
+ when: gate
+ gate: "scene_frames"
+ severity: error
+ kinds: [dark_frame]
+ cap: 0.55
+ note: mean luminance < 0.12 or > 35 % near-black pixels on an authored camera
+ - id: blown_frame
+ when: gate
+ gate: "scene_frames"
+ severity: error
+ kinds: [blown_frame]
+ cap: 0.6
+ note: "> 20 % pure-white pixels on an authored camera"
+ - id: flat_frame
+ when: gate
+ gate: "scene_frames"
+ severity: error
+ kinds: [flat_frame]
+ cap: 0.65
+ note: one luminance band holds > 92 % of an authored frame
+ - id: content_small
+ when: gate
+ gate: "scene_frames"
+ severity: error
+ kinds: [content_small]
+ cap: 0.6
+ note: establishing shot covers < 20 % content (rest is sky/ground)
- id: floating_part
when: gate
gate: "*"
diff --git a/harness/codeverse/judges/rubrics/shader_v1.yaml b/harness/codeverse/judges/rubrics/shader_v1.yaml
new file mode 100644
index 00000000..9a57108b
--- /dev/null
+++ b/harness/codeverse/judges/rubrics/shader_v1.yaml
@@ -0,0 +1,188 @@
+name: shader_v1
+version: 1
+track_hint: graphics
+pass_threshold: 0.70
+description: >
+ Rubric for the GRAPHICS track: a real-time effect (Shadertoy-style fragment shader or a
+ raw OpenGL program) judged on a contact sheet of frames sampled at t = 0, 1, 2.5, 4, 6 s
+ plus the harness frame metrics (luminance, colourfulness, edge density, frame-to-frame
+ motion, NaN detection). Grade the picture AND the motion; the metrics are facts.
+
+extra_instructions: >
+ Every view is the SAME program rendered at a different time (label t=...s); there are no
+ camera angles. Compare the frames to judge motion: identical frames mean the effect is
+ static; wildly unrelated frames mean flicker. The frame-metrics digest (mean luminance,
+ colourfulness, edge density, mean |Δ| between frames, NaN count) is measured by the
+ harness — treat it as truth over your impression. Grade what the brief asked for:
+ subject, mood, palette, named elements (rain, city lights, bokeh, sun, clouds ...) and
+ whether the frames read as a designed effect a person would screenshot (0.8+), a
+ recognisable but crude attempt (≈0.5), or a flat gradient / noise blob / black frames
+ (0.1-0.3). Use the pass / key-visual names from the plan digest as targets.
+
+criteria:
+ - id: brief_fidelity
+ weight: 0.24
+ floor: 0.30
+ title: Brief fidelity
+ description: >
+ Does the effect depict what the brief describes — subject, named elements, setting,
+ mood — so that a stranger would describe the frames the way the brief does? Every
+ key visual in the plan should be recognisable.
+ anchors:
+ "1.0": Subject and every named element are unmistakable; mood and setting match.
+ "0.7": Subject reads right; one named element is weak or hard to find.
+ "0.4": Subject is recognisable only with goodwill, or a named element is missing / contradicted.
+ "0.1": Unrelated abstract pattern, noise, or nothing recognisable.
+
+ - id: visual_richness
+ weight: 0.18
+ title: Visual richness and detail
+ description: >
+ Is there structure at several scales — layered shapes, noise/fbm detail, particles,
+ highlights, depth cues (parallax, fog, size falloff) — rather than a single flat
+ gradient or one repeated primitive? Credit only what is visible.
+ anchors:
+ "1.0": Multiple layers and scales of detail; the image rewards a closer look.
+ "0.7": Two or three distinct layers; some areas plain.
+ "0.4": One dominant element on a flat background; little detail.
+ "0.1": A flat gradient, a blob, or uniform noise.
+
+ - id: composition
+ weight: 0.12
+ title: Composition and framing
+ description: >
+ Is the frame composed — focal area, horizon / vanishing point placed deliberately,
+ balance between empty and busy regions, no important element cut off or crammed
+ into a corner, aspect ratio respected (no stretched circles)?
+ anchors:
+ "1.0": Deliberate composition with a clear focal area and depth layering.
+ "0.7": Readable composition; slightly flat or off-balance.
+ "0.4": Elements stretched / off-screen / centred by accident; no focal area.
+ "0.1": Unreadable arrangement.
+
+ - id: motion_quality
+ weight: 0.14
+ floor: 0.20
+ title: Motion quality
+ description: >
+ Across the time samples, does the effect move the way the brief / plan says
+ (rain falls, clouds drift, lights pulse, camera glides) — continuous, paced,
+ and plausible — neither frozen nor strobing?
+ anchors:
+ "1.0": Planned motion is visible, continuous and natural across all samples.
+ "0.7": Motion visible but subtle, uniform or partly missing.
+ "0.4": Frames nearly identical although motion was planned, or jumps/strobes between samples.
+ "0.1": Static effect (all frames identical) or incoherent flicker.
+
+ - id: colour_light
+ weight: 0.12
+ title: Colour and light
+ description: >
+ Is the palette intentional (harmonious, fitting the mood) with readable contrast
+ and lighting — exposure neither crushed to black nor blown to white, highlights and
+ shadows, glow / bloom where appropriate, no raw saturated RGB primaries unless asked?
+ anchors:
+ "1.0": Cohesive palette and lighting that sells the mood; good tonal range.
+ "0.7": Pleasant colours; slightly flat lighting or tonal range.
+ "0.4": Garish or muddy colours, heavy under/over-exposure, or banding.
+ "0.1": Near-black, blown white, or random colours.
+
+ - id: technical_cleanliness
+ weight: 0.12
+ floor: 0.30
+ title: Technical cleanliness
+ description: >
+ No NaN / garbage pixels, no hard aliasing staircase on edges, no visible banding in
+ gradients, no tiling seams, no obvious z-fighting / depth errors, no flicker, no
+ frame that is solid black or white. The harness digest lists NaN counts and gate
+ findings — treat those as facts.
+ anchors:
+ "1.0": Clean frames; no artefacts in any sample; no gate findings.
+ "0.7": One minor artefact (slight aliasing / banding) in one area.
+ "0.4": A clearly visible artefact (seam, banding, aliasing, a black frame) or a gate warning.
+ "0.1": NaN / garbage pixels, or frames are broken.
+
+ - id: originality
+ weight: 0.08
+ title: Originality and craft
+ description: >
+ Does the effect go beyond the textbook demo (plain plasma, rainbow spiral, raw
+ noise) with a distinctive idea, a specific look, or an unexpected detail that fits
+ the brief?
+ anchors:
+ "1.0": Distinctive, crafted look with a memorable idea.
+ "0.7": Competent and tasteful; some familiar ingredients.
+ "0.4": A stock demo with the brief's colours swapped in.
+ "0.1": Generic noise / gradient with no idea.
+
+caps:
+ - id: build_error
+ when: gate
+ gate: "build*"
+ severity: error
+ cap: 0.0
+ note: the shader/program did not compile or render; nothing to score
+ - id: lint_error
+ when: gate
+ gate: "lint*"
+ severity: error
+ cap: 0.6
+ - id: nan_pixels
+ when: gate
+ gate: "gl_frames"
+ severity: error
+ kinds: [nan]
+ cap: 0.0
+ note: NaN/Inf pixels detected in the float readback
+ - id: black_or_blown
+ when: gate
+ gate: "gl_frames"
+ severity: error
+ kinds: [black, blown]
+ cap: 0.5
+ - id: static_frames
+ when: gate
+ gate: "gl_frames"
+ severity: warn
+ kinds: [static]
+ cap: 0.5
+ note: motion was planned but frames do not change over time
+ - id: flicker
+ when: gate
+ gate: "gl_frames"
+ severity: warn
+ kinds: [flicker]
+ cap: 0.7
+ - id: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
+
+defects:
+ - id: wrong_subject
+ text: The frames do not depict the subject of the brief (an unrelated abstract pattern, or nothing recognisable).
+ cap: 0.40
+ - id: black_or_blown_frame
+ text: At least one sampled frame is essentially solid black or blown-out white.
+ penalty: 0.10
+ cap: 0.50
+ - id: static_effect
+ text: The sampled frames are visually identical although the brief implies motion.
+ penalty: 0.10
+ cap: 0.50
+ - id: flicker_or_strobe
+ text: Consecutive samples are unrelated (hard cuts, strobing, random per-frame colours) rather than continuous motion.
+ penalty: 0.08
+ cap: 0.70
+ - id: garbage_pixels
+ text: Visible garbage — NaN speckles, blocky corruption, uninitialised regions, magenta/error colour.
+ penalty: 0.10
+ cap: 0.30
+ - id: banding_or_aliasing
+ text: Clearly visible banding in gradients or staircase aliasing on edges / thin lines.
+ penalty: 0.05
+ - id: stretched_aspect
+ text: Circles are ellipses / the image is stretched — aspect ratio not corrected.
+ penalty: 0.06
+ - id: placeholder_look
+ text: The effect is a textbook demo (plain plasma, uv gradient, rainbow rings) with no connection to the brief beyond colour.
+ penalty: 0.10
diff --git a/harness/codeverse/judges/rubrics/static_object_v1.yaml b/harness/codeverse/judges/rubrics/static_object_v1.yaml
index b278a6d6..c7359bd5 100644
--- a/harness/codeverse/judges/rubrics/static_object_v1.yaml
+++ b/harness/codeverse/judges/rubrics/static_object_v1.yaml
@@ -8,14 +8,20 @@ description: >
measurement table. Scores are per criterion; the overall is computed in code.
extra_instructions: >
- Judge what is VISIBLE in the renders and what the measurement table states; do not
+ Judge what is VISIBLE in the montages and what the measurement table states; do not
credit detail you cannot see and do not invent faults. Use the underside / low
- views for ground contact and hidden gaps, the top view for symmetry and footprint,
- and the 3/4 views for overall read. Hidden connectors (a bracket inside a shade, a
- dowel inside a joint) are NOT defects when the parts visibly meet. Spread scores
- across the range: a competent, correct object belongs at 0.8+, one clearly visible
- major defect pulls the affected criterion to ~0.4, several major defects or a wrong
- object sit at 0.1-0.3.
+ views and the ground-contact crop for ground contact and hidden gaps, the top view
+ for symmetry and footprint, the 3/4 views and the centre crop for overall read and
+ detail, and the GEOMETRY-ONLY montage (when present) for holes, inverted faces and
+ intersections. Hidden connectors (a bracket inside a shade, a dowel inside a joint)
+ are NOT defects when the parts visibly meet. CALIBRATION — use these fixed points:
+ 0.9+ = every part crisp with bevels/chamfers/tapers/profiles, correct proportions,
+ clean joins, sensible materials (a product photo); 0.7 = correct and complete but
+ plain; 0.5 = recognisable but a stack of primitives, or one major defect (a gap, a
+ floating part, a wrong proportion); 0.2 = wrong object, flat blobs, parts exploded
+ or lying on its back. A primitive box-stack and a crafted product must be ≥ 0.4
+ apart. The DEFECT CHECKLIST is binary and literal: mark an item present only when
+ an image or a gate finding shows it, and cite it.
criteria:
- id: intent_fidelity
@@ -27,10 +33,10 @@ criteria:
attribute (counts, style, features, materials named in the brief)? A stranger
shown only these renders should describe the object the way the brief does.
anchors:
- "1.0": Right category and every named attribute is present and unmistakable; nothing the brief asked for is missing or contradicted.
- "0.7": Right category; one named attribute is weak, generic or hard to confirm, none is contradicted.
- "0.4": Right category but a named attribute is missing or clearly wrong (wrong count of legs, no armrests when asked, wrong style).
- "0.1": Wrong category or unrecognisable; the renders would not be described as the brief.
+ "1.0": Right category and every named attribute is present and unmistakable from the 3/4 views alone; nothing the brief asked for is missing or contradicted.
+ "0.7": Right category; one named attribute is weak, generic or hard to confirm (a "slatted" back with only two slats, "mid-century" that reads merely plain), none is contradicted.
+ "0.4": Right category but a named attribute is missing or clearly wrong (three legs when four were asked, no armrests when asked, wrong style or colour family).
+ "0.1": Wrong category (a table for a chair), unrecognisable blobs, or the object lies on its back/side so it cannot be read as the brief.
- id: structure_plausibility
weight: 0.18
@@ -42,10 +48,10 @@ criteria:
reach (legs reach the ground, a shade sits on its harp, wheels sit at the hubs),
and nothing floats, hovers, or points the wrong way.
anchors:
- "1.0": Every part is where a real example has it, correctly oriented, visibly supported; the object would stand and function.
- "0.7": One part is slightly misplaced or ambiguous in support, but nothing floats and the object clearly stands.
- "0.4": One part visibly floats, hovers off its mount, or is clearly in the wrong place or orientation.
- "0.1": Several parts float, are exploded apart, or the assembly is not a plausible object.
+ "1.0": Every part is where a real example has it, correctly oriented, visibly supported (all feet touch the ground in the low view and the ground-contact crop); the object would stand and function.
+ "0.7": One part is slightly misplaced or ambiguous in support (a stretcher that ends a few mm short of a leg), but nothing floats and the object clearly stands.
+ "0.4": One part visibly floats (daylight between it and its support), hovers off its mount, or is clearly in the wrong place or orientation (a backrest attached to the front edge).
+ "0.1": Several parts float, the assembly is exploded apart, the object rests on its back or side, or it is not a plausible object.
- id: geometry_detail
weight: 0.16
@@ -55,9 +61,9 @@ criteria:
Look for bevels/chamfers, tapers, curves, wall thickness, cut-outs, profiles,
mouldings, hardware. Credit only what is visible in the renders.
anchors:
- "1.0": Multiple refinements at once — profiles, bevels, tapers, thickness, hardware — the object reads as a designed product or natural form.
- "0.7": At least two visible refinements (e.g. bevelled edges and a tapered leg), the rest is plain but acceptable.
- "0.4": A stack of plain boxes/cylinders with sharp 90° corners; at most one token detail.
+ "1.0": Multiple refinements visible at once in the centre crop — rounded/bevelled edges, tapered legs, curved rails or seats, visible wall thickness, mouldings, hardware, cut-outs — the object reads as a designed product or natural form.
+ "0.7": At least two visible refinements (e.g. bevelled seat edge AND tapered legs), the rest plain but acceptable.
+ "0.4": A stack of plain boxes/cylinders with sharp 90° corners; at most one token detail (one chamfer, one rounded top).
"0.1": Primitive blobs or a single lump; parts are not individually shaped.
- id: proportions_scale
@@ -68,10 +74,10 @@ criteria:
(use the measurement table and any stated dimensions)? Seat height, leg
thickness, wheel diameter, handle size must read as real-world correct.
anchors:
- "1.0": Overall size and every part ratio are believable; stated dimensions are met within tolerance.
- "0.7": One part is somewhat thick/thin/short/long but the object still reads correctly at the stated size.
- "0.4": A clearly wrong proportion (legs twice as thick as they should be, a tiny seat on a huge frame) or the size is off by more than ~20%.
- "0.1": Proportions are absurd or the object is the wrong order of magnitude.
+ "1.0": Overall size and every part ratio are believable against the measurement table; stated dimensions are met within tolerance (±5%).
+ "0.7": One part is somewhat thick/thin/short/long (legs 30% heavier than typical) but the object still reads correctly at the stated size.
+ "0.4": A clearly wrong proportion (legs twice as thick as they should be, a tiny seat on a huge frame, a 1.2 m tall dining chair) or the size is off by more than ~20%.
+ "0.1": Proportions are absurd (seat thicker than it is wide) or the object is the wrong order of magnitude.
- id: assembly_fit
weight: 0.12
@@ -82,9 +88,9 @@ criteria:
a finger-wide gap, a part jammed through another, or a sunken/protruding join
is not.
anchors:
- "1.0": All joins are clean and tight; no visible gaps, no visible penetration, no z-fighting at contacts.
- "0.7": One small gap or shallow overlap at a join; the rest is clean.
- "0.4": A visible gap a part should not have, or an obvious penetration of one part through another.
+ "1.0": All joins are clean and tight in the centre crop and the geometry montage; no visible gaps, no visible penetration, no z-fighting at contacts.
+ "0.7": One small gap (≈ a few mm at object scale) or one shallow overlap at a join; the rest is clean.
+ "0.4": A finger-wide gap a part should not have, or an obvious penetration of one part through another (a rail poking out of the far side of a leg).
"0.1": Multiple gaps/penetrations; parts clearly not fitted to each other.
- id: materials
@@ -96,9 +102,9 @@ criteria:
A clean flat-colour look with correct assignments is acceptable; wrong or
placeholder surfaces are not.
anchors:
- "1.0": Every part has a convincing material; visible character (grain, brushed metal, fabric) where the real object has it.
- "0.7": Sensible flat or lightly-shaded materials on every part, correctly assigned; little character.
- "0.4": One part has a wrong or contradictory material (metal legs that look like plastic foam, one default grey part).
+ "1.0": Every part has a convincing material with correct roughness/metalness; visible character (wood grain, brushed metal, fabric weave) where the real object has it.
+ "0.7": Sensible flat or lightly-shaded colours on every part, correctly assigned (wood-brown legs, fabric-coloured seat); little character.
+ "0.4": One part has a wrong or contradictory material (metal legs that look like plastic foam, one default grey part), or everything is one uniform colour.
"0.1": Placeholder magenta/default grey everywhere, garbage noise, or materials that contradict the object.
- id: craftsmanship_no_artifacts
@@ -110,9 +116,9 @@ criteria:
missing faces / see-through walls, stretched or torn geometry, stray
slivers, duplicated shells, or degenerate triangles?
anchors:
- "1.0": No visible artefacts in any view; shading is smooth and consistent.
- "0.7": One small artefact (a sliver, a minor shading seam) visible only in one view.
- "0.4": A clearly visible artefact — black faces, a hole in a surface, obvious z-fighting.
+ "1.0": No visible artefacts in any view or crop; shading is smooth and consistent; the geometry montage shows closed, clean surfaces.
+ "0.7": One small artefact (a sliver, a minor shading seam, faint z-fighting on one face) visible only in one view.
+ "0.4": A clearly visible artefact — black/inverted faces, a hole in a surface, a see-through wall, obvious z-fighting stripes.
"0.1": Artefacts dominate; the object is torn, inside-out, or visibly broken.
caps:
@@ -132,7 +138,7 @@ caps:
when: gate
gate: "*"
severity: error
- kinds: [penetration, intersect, overlap, collision]
+ kinds: [penetrat, intersect, overlap, collision]
cap: 0.7
- id: contract_violation
when: gate
@@ -143,3 +149,43 @@ caps:
- id: missing_must_acceptance
when: acceptance
cap: 0.6
+
+# Binary checklist: answered by the judge, scored in code (penalty subtracted, cap applied).
+defects:
+ - id: wrong_object
+ text: The renders show a different object category than the brief (or nothing recognisable).
+ cap: 0.25
+ - id: missing_named_part
+ text: A part the brief or plan names is absent (no armrests when asked, three legs instead of four, no backrest).
+ penalty: 0.10
+ cap: 0.60
+ - id: floating_part
+ text: A part visibly hovers or is detached — daylight between it and what should support it (check the low view, the ground-contact crop and the geometry montage).
+ penalty: 0.10
+ cap: 0.60
+ - id: interpenetration
+ text: A part visibly passes through another in a render (a rail poking out of the far side of a leg, a leg through the seat) or a gate ERROR reports it; weld overlaps of a few mm reported as gate warnings are NOT this defect.
+ penalty: 0.08
+ cap: 0.70
+ - id: wrong_proportions
+ text: Part ratios or overall size clearly wrong (> 20%) — legs twice too thick, a tiny seat on a huge frame, the measured height far from the brief.
+ penalty: 0.08
+ cap: 0.70
+ - id: wrong_orientation
+ text: The object lies on its back or side, is upside down, or faces away from the front view (az 0°).
+ penalty: 0.10
+ cap: 0.50
+ - id: primitive_only
+ text: Every part is an unmodified box / cylinder / sphere with sharp 90° edges — no bevel, taper, profile, curve or cut-out anywhere.
+ penalty: 0.08
+ - id: untextured_flat
+ text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
+ penalty: 0.05
+ cap: 0.75
+ - id: holes_or_inverted_faces
+ text: Missing faces, see-through walls or black inverted faces are visible (especially in the geometry montage).
+ penalty: 0.08
+ cap: 0.60
+ - id: render_artifacts
+ text: Z-fighting stripes, torn or stretched geometry, or stray slivers are visible.
+ penalty: 0.05
diff --git a/harness/codeverse/judges/scoring.py b/harness/codeverse/judges/scoring.py
index 02ee0a7f..ab572ed6 100644
--- a/harness/codeverse/judges/scoring.py
+++ b/harness/codeverse/judges/scoring.py
@@ -3,7 +3,11 @@
* per-criterion score = mean over samples; overall = rubric-weighted mean;
``score_std`` = std of the per-sample overalls;
* floors: any criterion mean below its floor → verdict fails;
-* caps: deterministic bounds from gate findings / acceptance (``caps.py``);
+* defects: the rubric's binary checklist, majority vote over samples (ties →
+ present); each present item subtracts its ``penalty`` from the overall and
+ its ``cap`` (if any) bounds it — arithmetic the VLM never does;
+* caps: deterministic bounds from gate findings / acceptance / missing views
+ (``caps.py``) plus the defect caps;
* acceptance: majority vote over samples (ties → False);
* narrative (summary / issues / plan / strengths) is taken from the sample whose
overall is closest to the mean (the *representative* sample) so it is coherent.
@@ -17,7 +21,7 @@ from typing import Any
from pydantic import BaseModel, Field
-from codeverse.contracts.artifacts import GateReport
+from codeverse.contracts.artifacts import GateReport, RenderView
from codeverse.contracts.common import Usage
from codeverse.contracts.judgment import Judgment
from codeverse.contracts.plan import AcceptanceItem
@@ -33,12 +37,16 @@ class ScoreBreakdown(BaseModel):
per_criterion_mean: dict[str, float]
per_criterion_std: dict[str, float]
per_sample_overall: list[float]
- overall_uncapped: float
+ overall_uncapped: float = Field(description="rubric-weighted mean of the per-criterion means, before defects/caps")
+ overall_after_defects: float = Field(default=0.0, description="overall_uncapped minus defect penalties")
overall: float
floors_hit: list[dict[str, Any]] = Field(default_factory=list)
caps: CapResult
must_missing: list[str] = Field(default_factory=list)
acceptance_votes: dict[str, list[bool]] = Field(default_factory=dict)
+ defects: dict[str, bool] = Field(default_factory=dict, description="checklist id → present (majority vote)")
+ defect_votes: dict[str, list[bool]] = Field(default_factory=dict)
+ defect_penalty: float = 0.0
n_requested: int
n_used: int
sample_errors: list[str] = Field(default_factory=list)
@@ -62,12 +70,17 @@ def aggregate_samples(
gates: list[GateReport],
acceptance_items: list[AcceptanceItem],
console_errors: list[str] | None = None,
+ views: list[RenderView] | None = None,
usage: Usage | None = None,
judge_backend: str = "",
n_requested: int | None = None,
sample_errors: list[str] | None = None,
) -> Judgment:
- """Combine ≥ 1 parsed samples into a Judgment (raises ValueError on zero samples)."""
+ """Combine ≥ 1 parsed samples into a Judgment (raises ValueError on zero samples).
+
+ ``views`` feeds ``missing_views`` cap rules (e.g. the articulated rubric's
+ required pose sheet).
+ """
if not samples:
raise ValueError("aggregate_samples needs at least one sample")
per_crit: dict[str, list[float]] = {c.id: [] for c in rubric.criteria}
@@ -93,13 +106,22 @@ def aggregate_samples(
acceptance = {aid: (sum(v) * 2 > len(v)) for aid, v in votes.items()}
must_missing = missing_must_items(acceptance_items, acceptance)
- caps = apply_caps(rubric, overall_uncapped, gates, acceptance, acceptance_items, console_errors=console_errors)
+ d_votes: dict[str, list[bool]] = {d.id: [] for d in rubric.defects}
+ 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()}
+ penalty = round(sum(rubric.defect(did).penalty for did, on in defects.items() if on), 4)
+ after_defects = max(0.0, overall_uncapped - penalty)
+
+ caps = apply_caps(rubric, after_defects, gates, acceptance, acceptance_items, console_errors=console_errors,
+ views=views, defects_present=defects)
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)
+ tail = _verdict_tail(rubric, overall, passed, floors, caps, must_missing, defects=defects, penalty=penalty)
if tail:
summary = (summary + " " if summary else "") + tail
@@ -108,11 +130,15 @@ def aggregate_samples(
per_criterion_std=std_scores,
per_sample_overall=[round(o, 4) for o in overalls],
overall_uncapped=round(overall_uncapped, 4),
+ overall_after_defects=round(after_defects, 4),
overall=round(overall, 4),
floors_hit=floors,
caps=caps,
must_missing=must_missing,
acceptance_votes=votes,
+ defects=defects,
+ defect_votes=d_votes,
+ defect_penalty=penalty,
n_requested=n_requested or len(samples),
n_used=len(samples),
sample_errors=sample_errors or [],
@@ -138,9 +164,13 @@ def aggregate_samples(
def _verdict_tail(
- rubric: Rubric, overall: float, passed: bool, floors: list[dict[str, Any]], caps: CapResult, must_missing: list[str]
+ rubric: Rubric, overall: float, passed: bool, floors: list[dict[str, Any]], caps: CapResult, must_missing: list[str],
+ *, defects: dict[str, bool] | None = None, penalty: float = 0.0,
) -> str:
bits = [f"[verdict: overall {overall:.2f} vs threshold {rubric.pass_threshold:.2f} → {'PASS' if passed else 'FAIL'}"]
+ present = [d for d, on in (defects or {}).items() if on]
+ if present:
+ bits.append(f"defects (-{penalty:.2f}): " + ", ".join(present))
if caps.caps_applied:
bits.append("caps: " + "; ".join(f"{c.rule}≤{c.cap:.2f} ({c.evidence})" for c in caps.caps_applied))
if floors:
diff --git a/harness/codeverse/judges/vlm_judge.py b/harness/codeverse/judges/vlm_judge.py
index 8a9092ec..b302b362 100644
--- a/harness/codeverse/judges/vlm_judge.py
+++ b/harness/codeverse/judges/vlm_judge.py
@@ -1,9 +1,11 @@
"""``VlmJudge``: rubric YAML + labelled renders + measurements → ``Judgment``.
Per sample: one ``ChatRequest`` with a per-rubric JSON schema (criteria scored
-0..1 with evidence, issues, improvement plan, acceptance verdicts); samples
-differ by view order (shuffle seed) so n-sample mean/std measures judge noise.
-Score/floors/caps/pass are computed in code (``scoring.py``). Retries: up to
+0..1 with evidence, the rubric's binary defect checklist, issues, improvement
+plan, acceptance verdicts); samples differ by montage/tile order (shuffle seed)
+so n-sample mean/std measures judge noise. Score/defect penalties/floors/caps
+/pass are computed in code (``scoring.py``). Images are ≤2×2 montages
+(``montage.py``); tracks may pass a clay/normals ``geometry_views`` RenderSet. Retries: up to
``max_attempts`` per sample on ``ModelError`` / parse failure; if no sample
succeeds, a *degraded* Judgment (``passed=False, overall=0, summary
'judge_error: …'``, ``raw.status='degraded'``) is returned for the orchestrator
@@ -19,6 +21,7 @@ from pathlib import Path
from typing import Literal
from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderSet
from codeverse.contracts.chat import ChatRequest, ChatResponse
from codeverse.contracts.common import Usage
from codeverse.contracts.judgment import Judgment
@@ -60,8 +63,9 @@ class VlmJudge:
*,
thinking: Literal["off", "low", "medium", "high"] = "low",
max_attempts: int = 3,
- max_images: int = 10,
- max_px: int = 768,
+ max_montages: int = 3,
+ detail_crops: int = 2,
+ max_px: int = 1024,
chat_model: ChatModel | None = None,
cache_dir: Path | None = None,
label: str = "judge",
@@ -72,7 +76,8 @@ class VlmJudge:
self.temperature = temperature
self.thinking = thinking
self.max_attempts = max(1, int(max_attempts))
- self.max_images = max_images
+ self.max_montages = max(1, int(max_montages))
+ self.detail_crops = max(0, int(detail_crops))
self.max_px = max_px
self._model = chat_model
self.cache_dir = cache_dir
@@ -88,7 +93,15 @@ class VlmJudge:
return self._model
# ------------------------------------------------------------------ API
- def judge(self, inp: JudgeInput) -> Judgment:
+ def judge(self, inp: JudgeInput, *, geometry_views: RenderSet | None = None) -> Judgment:
+ """Judge one round.
+
+ ``geometry_views``: optional clay/normals RenderSet for the geometry montage
+ (falls back to ``inp.geometry_views`` if the input model carries that field;
+ clay/normals views embedded in ``inp.renders`` by ``RenderView.mode`` are
+ always routed to the geometry montage).
+ """
+ geometry_views = geometry_views or getattr(inp, "geometry_views", None)
acceptance_ids = [a.id for a in inp.acceptance]
schema = wire_schema(self.rubric, acceptance_ids)
ctx = self.context(inp)
@@ -100,8 +113,9 @@ class VlmJudge:
seed = None if (self.n_samples == 1 and k == 0) else (inp.round_index * 1000 + k)
# a missing render is a pipeline bug, not a judge glitch → JudgeImageError propagates
system, messages = build_judge_messages(
- inp, self.rubric, shuffle_seed=seed, max_images=self.max_images, max_px=self.max_px,
- cache_dir=self.cache_dir, extra_images=extra_images, extra_text=extra_text,
+ inp, self.rubric, shuffle_seed=seed, geometry_views=geometry_views, max_montages=self.max_montages,
+ detail_crops=self.detail_crops, max_px=self.max_px, cache_dir=self.cache_dir,
+ extra_images=extra_images, extra_text=extra_text,
)
req = ChatRequest(
messages=messages, system=system, response_schema=schema, temperature=self.temperature,
@@ -119,8 +133,8 @@ class VlmJudge:
)
return aggregate_samples(
self.rubric, samples, gates=inp.gates, acceptance_items=inp.acceptance,
- console_errors=inp.renders.console_errors, usage=usage, judge_backend=self.model_id,
- n_requested=self.n_samples, sample_errors=errors,
+ console_errors=inp.renders.console_errors, views=list(inp.renders.views), usage=usage,
+ judge_backend=self.model_id, n_requested=self.n_samples, sample_errors=errors,
)
# ------------------------------------------------------------------ hook (ReferenceJudge overrides)
diff --git a/harness/codeverse/languages/base.py b/harness/codeverse/languages/base.py
index ebf78dc9..47801058 100644
--- a/harness/codeverse/languages/base.py
+++ b/harness/codeverse/languages/base.py
@@ -60,6 +60,14 @@ def get_runtime(language: Language | str) -> LanguageRuntime:
from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
return UrdfBlenderRuntime()
+ if lang is Language.GLSL_SHADER:
+ from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+
+ return GlslShaderRuntime()
+ if lang is Language.OPENGL_PYTHON:
+ from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
+
+ return OpenGLPythonRuntime()
from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
return SceneThreeJsRuntime()
diff --git a/harness/codeverse/languages/blender/CONTRACT.md b/harness/codeverse/languages/blender/CONTRACT.md
index 2574e18e..b8b732e3 100644
--- a/harness/codeverse/languages/blender/CONTRACT.md
+++ b/harness/codeverse/languages/blender/CONTRACT.md
@@ -1,8 +1,18 @@
# Blender (bpy) authoring contract
-You write ONE file, `src/model.py`, in **raw bpy** (Blender 5.x Python API). The harness runs it with
-`blender -b --factory-startup --python run_bpy.py -- --script src/model.py` in an **EMPTY scene**
-(no Cube/Camera/Light) and then exports `artifacts/object.glb` (+ `object.stl`) itself.
+You write **raw bpy** (Blender 5.x Python API) in a multi-file layout:
+
+* `src/model.py` — the ENTRY: imports the part builders, calls them in plan order, self-checks.
+ No geometry of its own beyond small glue.
+* `src/parts/<snake>.py` — ONE per plan part (`SeatCushion` → `src/parts/seat_cushion.py`), exporting
+ `def build_seat_cushion() -> bpy.types.Object` that builds the part at its WORLD pose with the exact
+ object name(s) and returns it (instances `Leg_0..Leg_3` looped inside that one file). Self-contained;
+ it only DEFINES — never builds at import time. `src/` is on `sys.path`:
+ `from parts.seat_cushion import build_seat_cushion`. Small objects (1–2 parts) may use one `src/model.py`.
+
+The harness runs `blender -b --factory-startup --python run_bpy.py -- --script src/model.py` in an
+**EMPTY scene** (no Cube/Camera/Light), reports errors as `src/parts/<file>.py:<line>`, and exports
+`artifacts/object.glb` (+ `object.stl`) itself.
## Frame, units, placement
* **Z is up, -Y is the front** of the object, +X is its right. **Units are meters.**
@@ -11,7 +21,9 @@ You write ONE file, `src/model.py`, in **raw bpy** (Blender 5.x Python API). The
## Objects and names
* One mesh object per part, **named exactly as the plan's PascalCase part name** (`SeatCushion`).
- Instances: `Leg_0 … Leg_3`, optionally parented to an Empty named `Legs`.
+ Instances: `Leg_0 … Leg_3`, each a TOP-LEVEL object. **Never parent instances under an
+ Empty** — the harness measures top-level GLB nodes as parts, so an Empty parent merges all
+ instances into one part and the plan part is reported missing.
* Helper objects (boolean cutters) must be removed or hidden
(`cutter.hide_set(True); cutter.hide_render = True`) — visible objects are exported as-is.
* Modifiers (bevel, subdivision, boolean, array, solidify, mirror) may stay unapplied:
@@ -43,7 +55,7 @@ You write ONE file, `src/model.py`, in **raw bpy** (Blender 5.x Python API). The
* Context dict overrides `bpy.ops.x({...})` are gone: `with bpy.context.temp_override(object=obj): ...`.
* World AABB: `[obj.matrix_world @ Vector(c) for c in obj.bound_box]` after `bpy.context.view_layer.update()`.
-## Minimal example (copy the pattern)
+## Minimal example (copy the pattern; as a part file: wrap the body in `def build_table_top():` and return `top`)
```python
import bpy
import math
diff --git a/harness/codeverse/languages/blender/__init__.py b/harness/codeverse/languages/blender/__init__.py
index f9a2acbc..1bcfe7ff 100644
--- a/harness/codeverse/languages/blender/__init__.py
+++ b/harness/codeverse/languages/blender/__init__.py
@@ -1,14 +1,31 @@
-"""Blender (bpy) language: runtime, lint, skeleton; wrappers run inside Blender."""
+"""Blender (bpy) language: runtime, lint, layout, skeleton; wrappers run inside Blender."""
+from codeverse.languages.blender.layout import (
+ build_fn_name,
+ lint_workspace,
+ part_file_rel,
+ part_files,
+)
from codeverse.languages.blender.lint import lint_blender_file, lint_blender_source
from codeverse.languages.blender.runtime import BlenderNotFoundError, BlenderRuntime
-from codeverse.languages.blender.skeleton import blender_skeleton_source, write_blender_skeleton
+from codeverse.languages.blender.skeleton import (
+ blender_skeleton_source,
+ model_file_source,
+ part_file_source,
+ write_blender_skeleton,
+)
__all__ = [
"BlenderNotFoundError",
"BlenderRuntime",
"blender_skeleton_source",
+ "build_fn_name",
"lint_blender_file",
"lint_blender_source",
+ "lint_workspace",
+ "model_file_source",
+ "part_file_rel",
+ "part_file_source",
+ "part_files",
"write_blender_skeleton",
]
diff --git a/harness/codeverse/languages/blender/layout.py b/harness/codeverse/languages/blender/layout.py
new file mode 100644
index 00000000..3a0070a0
--- /dev/null
+++ b/harness/codeverse/languages/blender/layout.py
@@ -0,0 +1,153 @@
+"""Multi-file layout of a blender workspace: ``src/model.py`` + ``src/parts/<snake>.py``.
+
+One place states the file convention so the runtime (``file_for_part``), the skeleton,
+the workspace lint and the prompts agree:
+
+* ``src/model.py`` — entry. Imports the part builders, calls them in order, runs the
+ self-check. No geometry of its own beyond small glue.
+* ``src/parts/<snake>.py`` — one per plan part; exports ``def build_<snake>() -> bpy.types.Object``
+ returning the named object at its world pose (instances ``Name_0..N-1`` built inside).
+* ``src/parts/_<anything>.py`` — optional shared helpers (not a part; no export required).
+* A single-file ``src/model.py`` (no ``parts/`` directory) stays valid for small objects.
+"""
+
+from __future__ import annotations
+
+import ast
+import time
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.conventions import to_snake
+from codeverse.languages.blender.lint import GATE, lint_blender_source
+from codeverse.workspace import Workspace
+
+ENTRY_REL = "src/model.py"
+PARTS_DIR = "parts"
+PARTS_PKG = "parts"
+
+
+def part_file_rel(part_name: str) -> str:
+ """``'Seat Cushion'`` → ``'src/parts/seat_cushion.py'`` (workspace-relative)."""
+ return f"src/{PARTS_DIR}/{to_snake(part_name)}.py"
+
+
+def build_fn_name(part_name: str) -> str:
+ """``'SeatCushion'`` → ``'build_seat_cushion'`` (the function a part file must export)."""
+ return f"build_{to_snake(part_name)}"
+
+
+def part_files(ws: Workspace) -> list[Path]:
+ """Part modules present in the workspace (sorted; underscore helper modules excluded)."""
+ d = ws.src / PARTS_DIR
+ if not d.is_dir():
+ return []
+ return sorted(p for p in d.glob("*.py") if not p.name.startswith("_"))
+
+
+def helper_files(ws: Workspace) -> list[Path]:
+ """Underscore-prefixed shared modules under ``src/parts/`` (linted, not required to export)."""
+ d = ws.src / PARTS_DIR
+ return sorted(d.glob("_*.py")) if d.is_dir() else []
+
+
+def source_files(ws: Workspace) -> list[Path]:
+ """Every agent-authored python file under ``src/`` (entry first), including nested dirs."""
+ entry = ws.src / "model.py"
+ rest = sorted(p for p in ws.src.rglob("*.py") if p != entry)
+ return ([entry] if entry.is_file() else []) + rest
+
+
+def _rel(ws: Workspace, p: Path) -> str:
+ return p.relative_to(ws.root).as_posix()
+
+
+def _finding(sev: Severity, target: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint,
+ data={"line": line} if line else {})
+
+
+def _exported_functions(tree: ast.Module) -> set[str]:
+ return {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+
+
+def _imported_part_modules(tree: ast.Module) -> set[str]:
+ """snake names of ``parts.<snake>`` modules the entry references via import statements."""
+ out: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module:
+ dotted = node.module.split(".")
+ if dotted[0] == PARTS_PKG:
+ if len(dotted) > 1:
+ out.add(dotted[1])
+ else: # ``from parts import seat, leg``
+ out.update(a.name for a in node.names)
+ elif isinstance(node, ast.Import):
+ for a in node.names:
+ dotted = a.name.split(".")
+ if dotted[0] == PARTS_PKG and len(dotted) > 1:
+ out.add(dotted[1])
+ return out
+
+
+def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | None) -> list[GateFinding]:
+ """Cross-file rules: naming, exported builders, import-time side effects, unused part files."""
+ out: list[GateFinding] = []
+ E, W = Severity.ERROR, Severity.WARN
+ imported = _imported_part_modules(entry_tree) if entry_tree is not None else set()
+ for p in parts:
+ target = _rel(ws, p)
+ stem = p.stem
+ if stem != to_snake(stem):
+ out.append(_finding(E, target, f"part file name '{p.name}' is not snake_case",
+ f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
+ f"'{stem}' → that file) and fix the import in model.py"))
+ continue
+ try:
+ tree = ast.parse(p.read_text(), filename=target)
+ except SyntaxError:
+ continue # reported by the per-file lint
+ fn = f"build_{stem}"
+ if fn not in _exported_functions(tree):
+ out.append(_finding(E, target, f"{target} does not define `def {fn}()`",
+ f"every part file exports `def {fn}() -> bpy.types.Object` returning the named object "
+ f"at its world pose; model.py calls it (`from {PARTS_PKG}.{stem} import {fn}`)"))
+ for node in tree.body:
+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
+ name = getattr(node.value.func, "id", "")
+ if name.startswith("build_") or name == "main":
+ out.append(_finding(W, target, f"{target} calls `{name}()` at import time",
+ "part files only DEFINE builders; model.py calls them once (a module-level "
+ "call here builds the part twice → auto-suffixed 'Name.001')", node.lineno))
+ if entry_tree is not None and stem not in imported:
+ out.append(_finding(W, target, f"{target} is never imported by src/model.py → its part is not built",
+ f"add `from {PARTS_PKG}.{stem} import {fn}` to model.py and call `{fn}()` in main()"))
+ return out
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ """Lint every python file under ``src/`` + the multi-file layout rules (one merged report)."""
+ t0 = time.monotonic()
+ entry = ws.src / "model.py"
+ if not entry.is_file():
+ return GateReport(gate=GATE, passed=False, duration_ms=0, findings=[_finding(
+ Severity.ERROR, ENTRY_REL, f"{ENTRY_REL} is missing",
+ "create src/model.py (entry: imports src/parts/<snake>.py builders and calls them; see the skeleton)")])
+ parts = part_files(ws)
+ findings: list[GateFinding] = []
+ for p in source_files(ws):
+ target = _rel(ws, p)
+ is_entry = p == entry
+ is_helper = p.name.startswith("_")
+ rep = lint_blender_source(p.read_text(), target=target,
+ expect_names=not (is_helper or (is_entry and bool(parts))),
+ expect_bpy=not is_helper)
+ findings.extend(rep.findings)
+ entry_tree: ast.Module | None
+ try:
+ entry_tree = ast.parse(entry.read_text(), filename=ENTRY_REL)
+ except SyntaxError:
+ entry_tree = None
+ findings.extend(_layout_rules(ws, parts, entry_tree))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
diff --git a/harness/codeverse/languages/blender/lint.py b/harness/codeverse/languages/blender/lint.py
index b97b839d..7d5cb579 100644
--- a/harness/codeverse/languages/blender/lint.py
+++ b/harness/codeverse/languages/blender/lint.py
@@ -1,4 +1,4 @@
-"""Static lint for agent-authored bpy scripts (``src/model.py``).
+"""Static lint for agent-authored bpy scripts (``src/model.py`` and ``src/parts/*.py``).
AST based, offline, milliseconds. Catches what the build would only reveal
after a 2-10 s Blender round-trip — and the contract violations the build
@@ -23,6 +23,7 @@ ALLOWED_IMPORTS = {
"bpy", "bmesh", "mathutils", "math", "random", "numpy", "np", "itertools", "functools",
"collections", "typing", "dataclasses", "colorsys", "statistics", "operator", "enum", "copy",
"sys", "os", "__future__", "bpy_extras",
+ "parts", # the workspace's own src/parts/<snake>.py modules (multi-file layout)
}
FORBIDDEN_IMPORTS = {
"subprocess", "urllib", "requests", "socket", "http", "shutil", "ctypes", "pickle",
@@ -53,11 +54,13 @@ WARN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
("bpy.ops.screen.", "screen operators fail in background mode"),
("sys.exit", "do not exit; let the script fall off the end"),
)
+# Principled BSDF inputs that raise KeyError in Blender 4.x/5.x → their replacement.
+# Verified against Blender 5.0.1: 'Anisotropic' and 'Specular Tint' STILL EXIST (do not list them).
REMOVED_BSDF_INPUTS = {
"Specular": "Specular IOR Level", "Subsurface": "Subsurface Weight", "Transmission": "Transmission Weight",
"Emission": "Emission Color (+ 'Emission Strength')", "Subsurface Color": "Base Color (subsurface tint removed)",
"Clearcoat": "Coat Weight", "Clearcoat Roughness": "Coat Roughness", "Sheen": "Sheen Weight",
- "Transmission Roughness": "(removed) use Roughness", "Anisotropic": "Anisotropic", "Specular Tint": "Specular Tint (now a color)",
+ "Transmission Roughness": "(removed) use Roughness",
}
KNOWN_BINDINGS = ("Vector", "Matrix", "Euler", "Quaternion", "bmesh", "math", "random", "np", "numpy", "bpy")
PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
@@ -86,7 +89,8 @@ class _Collector(ast.NodeVisitor):
self.calls: list[tuple[str, ast.Call]] = []
self.attr_stores: list[tuple[str, int]] = [] # dotted target of assignments
self.name_loads: list[tuple[str, int]] = []
- self.bm_subscripts: list[int] = []
+ self.bm_names: set[str] = set() # names bound from bmesh.new() / bmesh.from_edit_mesh()
+ self.bm_subscripts: list[tuple[str, int]] = [] # (base name, line) of <name>.verts/edges/faces[i]
self.bsdf_inputs: list[tuple[str, int]] = []
self.names_assigned: list[str] = [] # string constants assigned to .name / name=
self.constants: list[tuple[str, int]] = []
@@ -153,6 +157,8 @@ class _Collector(ast.NodeVisitor):
if d:
self.attr_stores.append((d, node.lineno))
v = node.value
+ if isinstance(v, ast.Call) and dotted(v.func) in ("bmesh.new", "bmesh.from_edit_mesh"):
+ self.bm_names.update(t.id for t in node.targets if isinstance(t, ast.Name))
if isinstance(v, ast.Constant) and isinstance(v.value, str):
self.names_assigned.append(v.value)
elif isinstance(v, ast.JoinedStr) and v.values and isinstance(v.values[0], ast.Constant):
@@ -161,8 +167,11 @@ class _Collector(ast.NodeVisitor):
def visit_Subscript(self, node: ast.Subscript) -> None:
if isinstance(node.value, ast.Attribute):
- if node.value.attr in ("verts", "edges", "faces") and not isinstance(node.slice, ast.Slice):
- self.bm_subscripts.append(node.lineno)
+ # only <Name>.verts/edges/faces[i] — e.verts[0] (BMEdge) / me.edges[i] (Mesh) are
+ # filtered later against the names actually bound to a bmesh (BMElemSeq).
+ if (node.value.attr in ("verts", "edges", "faces") and not isinstance(node.slice, ast.Slice)
+ and isinstance(node.value.value, ast.Name)):
+ self.bm_subscripts.append((node.value.value.id, node.lineno))
if node.value.attr == "inputs" and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str):
self.bsdf_inputs.append((node.slice.value, node.lineno))
self.generic_visit(node)
@@ -177,11 +186,11 @@ def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target:
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
-def _rules(c: _Collector, source: str) -> list[GateFinding]:
+def _rules(c: _Collector, source: str, *, target: str, expect_names: bool, expect_bpy: bool) -> list[GateFinding]:
out: list[GateFinding] = []
E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
- if "bpy" not in c.imports:
- out.append(_f(E, "model.py never imports bpy", 1, "start the file with `import bpy`"))
+ if expect_bpy and "bpy" not in c.imports:
+ out.append(_f(E, f"{target} never imports bpy", 1, "start the file with `import bpy`"))
for mod, line in c.imports.items():
if mod in FORBIDDEN_IMPORTS:
out.append(_f(E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed"))
@@ -234,9 +243,15 @@ def _rules(c: _Collector, source: str) -> list[GateFinding]:
if key in REMOVED_BSDF_INPUTS:
out.append(_f(E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
f"use inputs['{REMOVED_BSDF_INPUTS[key]}']"))
+ elif key == "Specular Tint":
+ out.append(_f(I, "'Specular Tint' is an RGBA colour in Blender 4.x/5.x (a float raises TypeError)", line,
+ 'assign a 4-tuple: inputs["Specular Tint"].default_value = (r, g, b, 1.0)'))
has_lookup = any(n.endswith("ensure_lookup_table") for n, _ in c.calls)
- if "bmesh" in c.imports and c.bm_subscripts and not has_lookup:
- out.append(_f(E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", c.bm_subscripts[0],
+ # only subscripts on a BMESH object need ensure_lookup_table (BMElemSeq); e.verts[0]
+ # (BMEdge/BMFace tuples) and me.edges[i] (Mesh collections) are always fine.
+ bm_subs = [line for base, line in c.bm_subscripts if base in c.bm_names or base == "bm"]
+ if "bmesh" in c.imports and bm_subs and not has_lookup:
+ out.append(_f(E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", bm_subs[0],
"after bm.from_mesh()/any topology change call `bm.verts.ensure_lookup_table(); bm.edges.ensure_lookup_table(); bm.faces.ensure_lookup_table()` before indexing"))
for name, line in c.name_loads:
if name in KNOWN_BINDINGS and name not in c.bound:
@@ -251,16 +266,24 @@ def _rules(c: _Collector, source: str) -> list[GateFinding]:
if const == "BLENDER_EEVEE_NEXT":
out.append(_f(W, "'BLENDER_EEVEE_NEXT' is not a valid engine id in Blender 5.0", line, "render settings are owned by the harness; delete the line"))
pascal = [n for n in c.names_assigned if PASCAL_RE.match(n) and n not in ("Cube", "Cylinder", "Sphere", "Plane")]
- if not pascal:
+ if pascal:
+ out.append(_f(I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
+ elif expect_names:
out.append(_f(W, "no PascalCase object names found (e.g. obj.name = 'SeatCushion')", None,
"name every visible mesh after its part: `obj.name = 'SeatCushion'`; instances `Leg_0..Leg_3`"))
- else:
- out.append(_f(I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
return out
-def lint_blender_source(source: str, *, target: str = "src/model.py") -> GateReport:
- """Lint one bpy script; returns ``GateReport(gate='lint:blender')``."""
+def lint_blender_source(
+ source: str, *, target: str = "src/model.py", expect_names: bool = True, expect_bpy: bool = True,
+) -> GateReport:
+ """Lint one bpy script; returns ``GateReport(gate='lint:blender')``.
+
+ ``expect_names=False`` silences the PascalCase-name warning (multi-file entry files
+ only import and call builders); ``expect_bpy=False`` allows helper modules that do
+ not touch bpy. :func:`codeverse.languages.blender.layout.lint_workspace` lints a
+ whole ``src/`` tree with these set per file.
+ """
t0 = time.monotonic()
findings: list[GateFinding] = []
try:
@@ -270,7 +293,7 @@ def lint_blender_source(source: str, *, target: str = "src/model.py") -> GateRep
return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
c = _Collector()
c.visit(tree)
- findings = _rules(c, source)
+ findings = _rules(c, source, target=target, expect_names=expect_names, expect_bpy=expect_bpy)
for f in findings:
f.target = target
passed = not any(f.severity == Severity.ERROR for f in findings)
diff --git a/harness/codeverse/languages/blender/runtime.py b/harness/codeverse/languages/blender/runtime.py
index 7bdd2440..f911184d 100644
--- a/harness/codeverse/languages/blender/runtime.py
+++ b/harness/codeverse/languages/blender/runtime.py
@@ -1,8 +1,11 @@
"""BlenderRuntime: lint → build (headless Blender subprocess) → BuildResult.
-The agent's ``src/model.py`` is never imported here; ``wrappers/run_bpy.py`` runs
-it inside Blender, writes ``artifacts/build.json`` + ``census.json`` and exports
-``artifacts/object.glb`` (Y-up, +Z front) and ``object.stl`` (Z-up).
+Layout (see ``layout.py``): ``src/model.py`` is the entry; ``src/parts/<snake>.py`` hold
+one ``build_<snake>()`` per plan part (``file_for_part`` maps a part to its file so the
+tracks can refine parts in parallel); a single-file ``model.py`` stays valid. The
+agent's code is never imported here; ``wrappers/run_bpy.py`` runs it inside Blender
+(with ``src/`` on ``sys.path``), writes ``artifacts/build.json`` + ``census.json`` and
+exports ``artifacts/object.glb`` (Y-up, +Z front) and ``object.stl`` (Z-up).
"""
from __future__ import annotations
@@ -21,7 +24,7 @@ from codeverse.languages._common import (
run_subprocess,
strip_blender_noise,
)
-from codeverse.languages.blender.lint import lint_blender_file
+from codeverse.languages.blender.layout import ENTRY_REL, lint_workspace, part_file_rel
from codeverse.languages.blender.skeleton import write_blender_skeleton
from codeverse.prompts import PROMPTS_DIR
from codeverse.workspace import Workspace
@@ -32,7 +35,7 @@ RENDER_WRAPPER = _PKG_DIR / "wrappers" / "render_bpy.py"
class BlenderNotFoundError(RuntimeError):
- """No usable Blender binary (configure ``C3V_BINARIES__BLENDER`` or put blender on PATH)."""
+ """No usable Blender binary (configure ``CV3D_BINARIES__BLENDER`` or put blender on PATH)."""
def blender_env() -> dict[str, str]:
@@ -49,7 +52,7 @@ class BlenderRuntime:
"""LanguageRuntime for ``Language.BLENDER``."""
language = Language.BLENDER
- entry_globs: tuple[str, ...] = ("src/model.py",)
+ entry_globs: tuple[str, ...] = (ENTRY_REL, "src/parts/*.py")
def __init__(self, *, blender: str | None = None, settings: Settings | None = None):
self._settings = settings or get_settings()
@@ -59,11 +62,28 @@ class BlenderRuntime:
def blender_binary(self) -> str:
b = self._blender or self._settings.resolve_blender()
if not b or not Path(b).exists():
- raise BlenderNotFoundError("Blender binary not found; set C3V_BINARIES__BLENDER=/path/to/blender")
+ raise BlenderNotFoundError("Blender binary not found; set CV3D_BINARIES__BLENDER=/path/to/blender")
return b
def entry_file(self, ws: Workspace) -> Path:
- return ws.src / "model.py"
+ return ws.root / ENTRY_REL
+
+ @staticmethod
+ def file_for_part(part_name: str) -> str:
+ """Workspace-relative file that owns a plan part: ``src/parts/<snake>.py``
+ (the tracks call this via ``getattr`` to fan out per-part refinement)."""
+ return part_file_rel(part_name)
+
+ def part_file(self, ws: Workspace, part_name: str) -> Path:
+ return ws.root / self.file_for_part(part_name)
+
+ @staticmethod
+ def file_for_target(target: str) -> list[str]:
+ """Refine target → files: whole-object targets (``overall``/``assembly``/``object``/'')
+ map to the entry ``src/model.py``; anything else is treated as a part name."""
+ if target.strip().lower() in ("", "overall", "assembly", "object", "model"):
+ return [ENTRY_REL]
+ return [part_file_rel(target)]
def build_command(
self, ws: Workspace, *, stl: bool = True, blend: bool = False, seed: int = 0,
@@ -88,7 +108,8 @@ class BlenderRuntime:
return write_blender_skeleton(ws, plan)
def lint(self, ws: Workspace) -> GateReport:
- return lint_blender_file(self.entry_file(ws))
+ """Lint every python file under ``src/`` + the multi-file layout rules."""
+ return lint_workspace(ws)
def build(
self, ws: Workspace, *, timeout_s: int | None = None, stl: bool = True, blend: bool = False,
@@ -98,7 +119,7 @@ class BlenderRuntime:
entry = self.entry_file(ws)
if not entry.is_file():
return BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
- error_message="src/model.py does not exist", error_file="src/model.py")
+ error_message=f"{ENTRY_REL} does not exist", error_file=ENTRY_REL)
ws.artifacts.mkdir(parents=True, exist_ok=True)
build_json = ws.artifacts / "build.json"
census_json = ws.artifacts / "census.json"
diff --git a/harness/codeverse/languages/blender/skeleton.py b/harness/codeverse/languages/blender/skeleton.py
index 6d19d4a5..ce691ae7 100644
--- a/harness/codeverse/languages/blender/skeleton.py
+++ b/harness/codeverse/languages/blender/skeleton.py
@@ -1,9 +1,19 @@
-"""Starter ``src/model.py`` for the blender language, generated from a plan.
-
-The skeleton is *buildable as written*: every part is a placeholder box at its
-plan bbox (instances laid out by the plan's symmetry), with a Principled BSDF
-material, so the agent starts from a passing build and replaces bodies one
-function at a time. Only raw bpy in the output — no harness imports.
+"""Starter files for the blender language, generated from a plan.
+
+Default layout (multi-file, refinable part-by-part in parallel):
+
+* ``src/parts/<snake>.py`` — one per plan part. Self-contained (own tiny helpers),
+ plan numbers as constants on top, description/role/material/attach_to in the
+ docstring, and ``def build_<snake>() -> bpy.types.Object`` that builds a placeholder
+ box at the plan bbox (instances ``Name_0..N-1`` as TOP-LEVEL objects — never under a
+ parent Empty: the harness measures top-level GLB nodes as parts, and an Empty parent
+ would merge all instances into one part).
+* ``src/model.py`` — entry: imports the builders, calls them in order, self-checks.
+
+``blender_skeleton_source(plan)`` still renders the same model as ONE file (small
+objects may use a single ``src/model.py``). Both layouts build as written: the agent
+starts from a passing build and replaces placeholder bodies one function at a time.
+Only raw bpy in the output — no harness imports.
"""
from __future__ import annotations
@@ -13,6 +23,7 @@ from pathlib import Path
from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
from codeverse.conventions import to_pascal, to_snake
+from codeverse.languages.blender.layout import PARTS_DIR, PARTS_PKG, build_fn_name, part_file_rel
from codeverse.workspace import Workspace
# keyword → (rgb, roughness, metallic) placeholder finishes so the first render is not all-grey
@@ -64,85 +75,12 @@ def _fmt(v: tuple[float, float, float]) -> str:
return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
-def _part_function(p: PartPlan) -> str:
- pascal, snake = to_pascal(p.name), to_snake(p.name)
- rgb, rough, metal = finish_for(f"{p.material} {p.description}")
- mn, mx = p.bbox.min, p.bbox.max
- lines = [
- f"def build_{snake}(index=0, center={_fmt(p.bbox.center)}):",
- f' """{pascal} — {p.role}',
- f" {p.description}",
- f" Material: {p.material or 'n/a'}",
- f" Plan bbox: center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
- f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
- ]
- if p.attach_to:
- lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surfaces must touch, no gap)")
- if p.instances > 1:
- lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, parented to Empty '{pascal}s'")
- lines += [
- ' """',
- f' name = "{pascal}"' if p.instances == 1 else f' name = f"{pascal}_{{index}}"',
- f" mat = make_material(name + \"Mat\", {_fmt(rgb)}, roughness={rough}, metallic={metal})",
- " # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
- f" return add_box(name, center, {_fmt(p.bbox.extents)}, mat, bevel={_bevel(p.bbox):.4f})",
- "",
- "",
- ]
- return "\n".join(lines)
-
-
def _bevel(bbox: BBox) -> float:
return max(0.0, min(0.01, 0.08 * min(bbox.extents)))
-def _main_body(plan: StaticPlan) -> str:
- lines = ["def main():"]
- for p in plan.parts:
- pascal, snake = to_pascal(p.name), to_snake(p.name)
- if p.instances == 1:
- lines.append(f" build_{snake}()")
- continue
- centers = instance_centers(p.bbox, p.instances, p.symmetry)
- lines.append(f" {snake}_parent = add_empty(\"{pascal}s\")")
- lines.append(f" for i, c in enumerate({[tuple(round(x, 4) for x in c) for c in centers]}): # TODO: exact placement")
- lines.append(f" obj = build_{snake}(i, c)")
- lines.append(f" obj.parent = {snake}_parent")
- lines += ["", "", "main()", ""]
- return "\n".join(lines)
-
-
-def blender_skeleton_source(plan: StaticPlan) -> str:
- """Return the complete starter ``model.py`` text for ``plan``."""
- ob = plan.overall_bbox
- parts_doc = "\n".join(
- f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}"
- for p in plan.parts
- )
- accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
- header = f'''"""{plan.object_name} — Blender (bpy) model.
-
-{plan.summary}
-Style: {plan.style_notes or "n/a"}
-
-CONTRACT (the harness runs this file in an EMPTY scene with `blender -b --factory-startup`):
- * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
- * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
- -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
- * One mesh object per part, named EXACTLY as below (PascalCase); instances Name_0..Name_N-1.
- * Materials: Principled BSDF (Base Color / Roughness / Metallic). GLB keeps flat PBR + image
- textures only (procedural node textures are NOT exported) — rely on geometry + flat PBR.
- * Modifiers may stay unapplied (the exporter applies them). Keep < 500k triangles, < 120 s.
- * NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
- * Only bpy / bmesh / mathutils / math / random (seeded). No other imports.
-
-PARTS:
-{parts_doc}
-
-ACCEPTANCE:
-{accept}
-"""
-import math
+# ----------------------------------------------------------------------------- shared text blocks
+IMPORTS = '''import math
import random
import bpy
@@ -150,8 +88,9 @@ import bmesh # noqa: F401 (available for custom meshes: bm = bmesh.new(); ...
from mathutils import Vector, Matrix # noqa: F401
random.seed(0)
+'''
-
+HELPERS = '''
# ----------------------------------------------------------------------------- helpers (plain bpy)
def make_material(name, rgb, roughness=0.5, metallic=0.0):
"""Principled BSDF material with flat PBR values (what the GLB keeps)."""
@@ -178,23 +117,172 @@ def add_box(name, center, extents, material=None, bevel=0.0):
mod.limit_method = "ANGLE"
return obj
+'''
+
+SELFCHECK = '''
+def _selfcheck():
+ """What the harness checks first: meshes exist, no auto-suffixed names, stands on z=0."""
+ bpy.context.view_layer.update()
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+ assert meshes, "no mesh objects built"
+ for o in meshes:
+ assert "." not in o.name, f"auto-suffixed name {o.name!r}: give every instance its own name"
+ z_min = min((o.matrix_world @ Vector(c)).z for o in meshes for c in o.bound_box)
+ assert abs(z_min) < 0.002, f"lowest point z={z_min:.4f}: the object must stand on z=0"
+ print(f"[selfcheck] {len(meshes)} mesh objects, z_min={z_min:.4f}")
-def add_empty(name):
- """Parent Empty for instance groups (exported as a named node)."""
- empty = bpy.data.objects.new(name, None)
- bpy.context.collection.objects.link(empty)
- return empty
+'''
-# ----------------------------------------------------------------------------- parts
+def _constants(p: PartPlan) -> str:
+ mn, mx = p.bbox.min, p.bbox.max
+ pre = to_snake(p.name).upper()
+ return (
+ f"# ---- plan numbers (metres) for {to_pascal(p.name)} — keep the finished part inside this bbox\n"
+ f"{pre}_CENTER = {_fmt(p.bbox.center)}\n"
+ f"{pre}_EXTENTS = {_fmt(p.bbox.extents)}\n"
+ f"{pre}_MIN = {_fmt(mn)}\n"
+ f"{pre}_MAX = {_fmt(mx)}\n"
+ f"{pre}_INSTANCES = {p.instances}\n"
+ )
+
+
+def _part_function(p: PartPlan) -> str:
+ """``def build_<snake>() -> bpy.types.Object`` (placeholder box; instances looped inside)."""
+ pascal, snake, fn = to_pascal(p.name), to_snake(p.name), build_fn_name(p.name)
+ pre = snake.upper()
+ rgb, rough, metal = finish_for(f"{p.material} {p.description}")
+ mn, mx = p.bbox.min, p.bbox.max
+ lines = [
+ f"def {fn}():",
+ f' """{pascal} — {p.role}',
+ f" {p.description}",
+ f" Material: {p.material or 'n/a'}",
+ f" Plan bbox: center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
+ f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
+ ]
+ if p.attach_to:
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surfaces must touch, no gap)")
+ if p.instances > 1:
+ lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, "
+ f"each TOP-LEVEL (no parent Empty — it would merge them into one measured part); returns the list")
+ lines += [' Returns the object(s) at WORLD pose (Z up, -Y front, metres).', ' """']
+ lines.append(f" mat = make_material(\"{pascal}Mat\", {_fmt(rgb)}, roughness={rough}, metallic={metal})")
+ if p.instances == 1:
+ lines += [
+ " # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
+ f" return add_box(\"{pascal}\", {pre}_CENTER, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f})",
+ ]
+ else:
+ centers = [tuple(round(x, 4) for x in c) for c in instance_centers(p.bbox, p.instances, p.symmetry)]
+ lines += [
+ " objs = []",
+ f" for i, c in enumerate({centers}): # TODO: exact placement",
+ " # TODO: replace this placeholder box with the real geometry (keep the names + bbox)",
+ f" objs.append(add_box(f\"{pascal}_{{i}}\", c, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f}))",
+ " return objs",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def _plan_header(plan: StaticPlan, *, multi_file: bool) -> str:
+ ob = plan.overall_bbox
+ parts_doc = "\n".join(
+ f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} "
+ f"extents {_fmt(p.bbox.extents)}" + (f" [{part_file_rel(p.name)}]" if multi_file else "")
+ for p in plan.parts
+ )
+ accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
+ layout = (
+ f" * LAYOUT: this file is the ENTRY. Each part lives in src/{PARTS_DIR}/<snake>.py and exports\n"
+ f" build_<snake>() -> bpy.types.Object; main() below imports and calls them in order.\n"
+ " Edit geometry in the part files; keep this file to imports + calls + self-check.\n"
+ if multi_file else
+ " * LAYOUT: single file (small object). One build_<snake>() per part, called from main().\n"
+ )
+ return f'''"""{plan.object_name} — Blender (bpy) model.
+
+{plan.summary}
+Style: {plan.style_notes or "n/a"}
+
+CONTRACT (the harness runs this file in an EMPTY scene with `blender -b --factory-startup`):
+ * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
+ * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
+ -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
+ * One mesh object per part, named EXACTLY as below (PascalCase); instances Name_0..Name_N-1,
+ each TOP-LEVEL (never parented under an Empty — that merges them into ONE measured part).
+{layout} * Materials: Principled BSDF (Base Color / Roughness / Metallic). GLB keeps flat PBR + image
+ textures only (procedural node textures are NOT exported) — rely on geometry + flat PBR.
+ * Modifiers may stay unapplied (the exporter applies them). Keep < 500k triangles, < 120 s.
+ * NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
+ * Only bpy / bmesh / mathutils / math / random (seeded). No other imports.
+
+PARTS:
+{parts_doc}
+
+ACCEPTANCE:
+{accept}
+"""
'''
- body = "".join(_part_function(p) for p in plan.parts)
- return header + body + _main_body(plan)
-def write_blender_skeleton(ws: Workspace, plan: StaticPlan) -> list[Path]:
- """Write ``src/model.py`` (overwrites) and return the written paths."""
+# ----------------------------------------------------------------------------- public renderers
+def part_file_source(p: PartPlan) -> str:
+ """Complete ``src/parts/<snake>.py`` text for one plan part (self-contained, runnable)."""
+ pascal, fn = to_pascal(p.name), build_fn_name(p.name)
+ doc = (
+ f'"""{pascal} — {p.role} (part module; imported by src/model.py).\n\n'
+ f"{p.description}\n"
+ f"Material: {p.material or 'n/a'}. Instances: {p.instances}"
+ + (f" ({p.symmetry})" if p.instances > 1 else "")
+ + (f". Attaches to: {to_pascal(p.attach_to)} (must touch, no gap)" if p.attach_to else "")
+ + f".\n\nExports `{fn}() -> bpy.types.Object`: builds the part at its WORLD pose (Z up, -Y front,\n"
+ "metres) with the exact object name(s) and returns it (list of TOP-LEVEL objects when\n"
+ "instanced — never parent instances under an Empty). Do NOT call it here — model.py does.\n"
+ "Keep this file self-contained (its own helpers); only bpy/bmesh/mathutils/math/random.\n"
+ '"""\n'
+ )
+ return doc + IMPORTS + "\n" + _constants(p) + HELPERS + "\n# ----------------------------------------------------------------------------- part\n" + _part_function(p)
+
+
+def model_file_source(plan: StaticPlan) -> str:
+ """Complete multi-file entry ``src/model.py``: imports, ordered calls, self-check."""
+ imports = "\n".join(f"from {PARTS_PKG}.{to_snake(p.name)} import {build_fn_name(p.name)}" for p in plan.parts)
+ calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
+ return (
+ _plan_header(plan, multi_file=True)
+ + "import bpy\nfrom mathutils import Vector\n\n"
+ + imports + "\n\n"
+ + SELFCHECK
+ + "\ndef main():\n # build every part (order = plan order); parts are placed at world pose by their builders\n"
+ + calls + "\n _selfcheck()\n\n\nmain()\n"
+ )
+
+
+def blender_skeleton_source(plan: StaticPlan) -> str:
+ """The same model as ONE ``src/model.py`` (small objects may use a single file)."""
+ body = "\n# ----------------------------------------------------------------------------- parts\n"
+ for p in plan.parts:
+ body += _constants(p) + "\n\n" + _part_function(p) + "\n\n"
+ calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
+ return (
+ _plan_header(plan, multi_file=False) + IMPORTS + HELPERS + body + SELFCHECK
+ + "\ndef main():\n" + calls + "\n _selfcheck()\n\n\nmain()\n"
+ )
+
+
+def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, multi_file: bool = True) -> list[Path]:
+ """Write the starter files (overwrites) and return the written paths (entry first)."""
ws.src.mkdir(parents=True, exist_ok=True)
- path = ws.src / "model.py"
- path.write_text(blender_skeleton_source(plan))
- return [path]
+ entry = ws.src / "model.py"
+ if not multi_file:
+ entry.write_text(blender_skeleton_source(plan))
+ return [entry]
+ entry.write_text(model_file_source(plan))
+ written = [entry]
+ for p in plan.parts:
+ path = ws.root / part_file_rel(p.name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(part_file_source(p))
+ written.append(path)
+ return written
diff --git a/harness/codeverse/languages/blender/wrappers/_census.py b/harness/codeverse/languages/blender/wrappers/_census.py
new file mode 100644
index 00000000..f8b4f4c1
--- /dev/null
+++ b/harness/codeverse/languages/blender/wrappers/_census.py
@@ -0,0 +1,154 @@
+"""Scene census for the Blender build wrapper — executed BY Blender, never imported by the harness.
+
+``run_bpy.py`` puts its own directory on ``sys.path`` and does ``import _census``; this
+module must therefore stay standalone (no ``codeverse`` imports). It inspects the scene
+after the agent script ran: evaluated triangle counts, world bboxes, materials, parents,
+and the contract warnings the build cannot otherwise see (cameras, lights, visible
+boolean cutters, unlinked meshes, default primitive names).
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+DEFAULT_NAME_RE = re.compile(
+ r"^(Cube|Cylinder|Sphere|Plane|Cone|Torus|Icosphere|Circle|Grid|Monkey|Mesh|Text|Curve)(\.\d+)?$"
+)
+MEASURABLE_TYPES = ("MESH", "CURVE", "SURFACE", "FONT", "META")
+
+
+def world_bbox(obj_eval: Any, Vector: Any) -> tuple[list[float], list[float]] | None:
+ """World-space AABB of an evaluated object (rounded to 0.01 mm); None when it has no bounds."""
+ corners = [obj_eval.matrix_world @ Vector(c) for c in obj_eval.bound_box]
+ if not corners:
+ return None
+ mn = [min(c[i] for c in corners) for i in range(3)]
+ mx = [max(c[i] for c in corners) for i in range(3)]
+ return [round(v, 5) for v in mn], [round(v, 5) for v in mx]
+
+
+def is_hidden(obj: Any, vl_names: set[str] | None = None) -> bool:
+ """True when the object will not render/export (hidden or not in the view layer).
+
+ ``vl_names`` is ``set(bpy.context.view_layer.objects.keys())``: objects that are not in
+ the view layer (e.g. their collection has ``layer_collection.exclude = True``) report
+ ``hide_get() == False`` yet are NOT exported — the census must not count them either.
+ """
+ if vl_names is not None and obj.name not in vl_names:
+ return True
+ try:
+ return bool(obj.hide_render or obj.hide_viewport or obj.hide_get())
+ except RuntimeError: # object not in the view layer
+ return True
+
+
+def _object_record(obj: Any, dg: Any, scene_objects: set[str], vl_names: set[str], Vector: Any) -> dict[str, Any]:
+ rec: dict[str, Any] = {
+ "name": obj.name,
+ "type": obj.type,
+ "parent": obj.parent.name if obj.parent else None,
+ "in_scene": obj.name in scene_objects,
+ "in_view_layer": obj.name in vl_names,
+ "hidden": is_hidden(obj, vl_names),
+ "materials": [s.material.name for s in obj.material_slots if s.material],
+ "modifiers": [m.type for m in obj.modifiers],
+ "location": [round(v, 5) for v in obj.matrix_world.translation],
+ }
+ if obj.type in MEASURABLE_TYPES:
+ try:
+ ob_eval = obj.evaluated_get(dg)
+ me = ob_eval.to_mesh()
+ me.calc_loop_triangles()
+ rec["tri_count"] = len(me.loop_triangles)
+ rec["vert_count"] = len(me.vertices)
+ rec["has_uv"] = bool(me.uv_layers)
+ rec["has_vertex_colors"] = bool(me.color_attributes)
+ bb = world_bbox(ob_eval, Vector)
+ ob_eval.to_mesh_clear()
+ except RuntimeError as e:
+ rec["tri_count"] = 0
+ rec["census_error"] = str(e)
+ bb = None
+ if bb:
+ rec["bbox_min"], rec["bbox_max"] = bb
+ return rec
+
+
+def _warnings(bpy: Any, objects: list[dict[str, Any]], boolean_operands: dict[str, list[str]],
+ scene_objects: set[str], vl_names: set[str], total_tris: int, tri_limit: int) -> list[str]:
+ warnings: list[str] = []
+ excluded = [o["name"] for o in objects if o["in_scene"] and not o["in_view_layer"]]
+ if excluded:
+ warnings.append(f"object(s) {excluded} are in a collection excluded from the view layer → NOT exported "
+ "and not counted; re-enable the collection (layer_collection.exclude = False) or remove them")
+ cams = [o.name for o in bpy.data.objects if o.type == "CAMERA"]
+ lights = [o.name for o in bpy.data.objects if o.type == "LIGHT"]
+ if cams:
+ warnings.append(f"script created camera(s) {cams}: not exported; remove camera code (the harness owns cameras)")
+ if lights:
+ warnings.append(f"script created light(s) {lights}: not exported; remove light code (the harness owns lighting)")
+ for cutter, users in boolean_operands.items():
+ o = bpy.data.objects.get(cutter)
+ if o is not None and not is_hidden(o, vl_names) and o.name in scene_objects:
+ warnings.append(
+ f"object '{cutter}' is a boolean operand of {users} but is still visible and WILL be exported as "
+ f"geometry; hide it: obj.hide_set(True); obj.hide_render = True (or bpy.data.objects.remove(obj))"
+ )
+ visible = [o for o in objects if o["in_scene"] and not o["hidden"] and o["type"] == "MESH"]
+ if not visible:
+ warnings.append("no visible mesh objects in the scene — nothing to export")
+ for o in visible:
+ if not o["materials"]:
+ warnings.append(f"mesh '{o['name']}' has no material (will export grey)")
+ if DEFAULT_NAME_RE.match(o["name"]):
+ warnings.append(f"mesh '{o['name']}' keeps a default primitive name; set obj.name = '<PartName>'")
+ unlinked = [o["name"] for o in objects if o["type"] == "MESH" and not o["in_scene"]]
+ if unlinked:
+ warnings.append(f"mesh object(s) {unlinked} were created but never linked to the scene → not exported; "
+ "call bpy.context.collection.objects.link(obj)")
+ if total_tris > tri_limit:
+ warnings.append(f"triangle budget exceeded: {total_tris} > {tri_limit}")
+ return warnings
+
+
+def collect_census(bpy: Any, tri_limit: int) -> dict[str, Any]:
+ """Census of every object in ``bpy.data`` (visible meshes count toward the scene bbox / tris)."""
+ from mathutils import Vector
+
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ scene_objects = set(bpy.context.scene.objects.keys())
+ vl_names = set(bpy.context.view_layer.objects.keys()) # what the exporter can actually see
+ boolean_operands: dict[str, list[str]] = {}
+ objects: list[dict[str, Any]] = []
+ total_tris = 0
+ mins: list[list[float]] = []
+ maxs: list[list[float]] = []
+ for obj in bpy.data.objects:
+ for m in obj.modifiers:
+ if m.type == "BOOLEAN" and getattr(m, "object", None) is not None:
+ boolean_operands.setdefault(m.object.name, []).append(obj.name)
+ rec = _object_record(obj, dg, scene_objects, vl_names, Vector)
+ if rec["in_scene"] and not rec["hidden"] and obj.type in MEASURABLE_TYPES:
+ total_tris += rec["tri_count"]
+ if "bbox_min" in rec:
+ mins.append(rec["bbox_min"])
+ maxs.append(rec["bbox_max"])
+ objects.append(rec)
+ visible = [o for o in objects if o["in_scene"] and not o["hidden"] and o["type"] == "MESH"]
+ census = {
+ "objects": objects,
+ "n_mesh_objects": len(visible),
+ "tri_count": total_tris,
+ "tri_limit": tri_limit,
+ "materials": [m.name for m in bpy.data.materials],
+ "cameras": [o.name for o in bpy.data.objects if o.type == "CAMERA"],
+ "lights": [o.name for o in bpy.data.objects if o.type == "LIGHT"],
+ "warnings": _warnings(bpy, objects, boolean_operands, scene_objects, vl_names, total_tris, tri_limit),
+ "frame": "z_up_neg_y_front",
+ }
+ if mins:
+ census["scene_bbox_min"] = [round(min(m[i] for m in mins), 5) for i in range(3)]
+ census["scene_bbox_max"] = [round(max(m[i] for m in maxs), 5) for i in range(3)]
+ return census
diff --git a/harness/codeverse/languages/blender/wrappers/run_bpy.py b/harness/codeverse/languages/blender/wrappers/run_bpy.py
index 01174d27..5c3223f2 100644
--- a/harness/codeverse/languages/blender/wrappers/run_bpy.py
+++ b/harness/codeverse/languages/blender/wrappers/run_bpy.py
@@ -8,35 +8,44 @@ What it does (in order):
1. caps the address space (RLIMIT_AS) so geometry bombs die in-process;
2. empties the factory scene (Cube/Camera/Light + orphan data), sets metric units;
3. seeds ``random`` / numpy / mathutils.noise;
- 4. runs the agent script with ``runpy`` and maps any exception to a line of model.py;
- 5. collects a census (evaluated tri counts, world bboxes, materials, parents);
+ 4. puts ``<ws>/src`` on ``sys.path`` (so ``from parts.seat import build_seat`` and
+ ``import parts.seat`` work), runs the agent's ``model.py`` with ``runpy`` and maps
+ any exception to ``<file under src/>:<line>`` (model.py or a part file);
+ 5. collects a census (``_census.py`` next to this file: evaluated tri counts, world
+ bboxes, materials, parents);
6. warns on leftovers (cameras, lights, touched render settings, visible cutters);
7. exports ``object.glb`` (Y-up, +Z front) and optionally ``object.stl`` (Z-up);
8. writes ``build.json`` + ``census.json`` atomically and exits 0.
Exit codes: 0 = reported (even if the script failed); 2 = wrapper bug (no report).
-This file must stay standalone: Blender's python cannot import ``codeverse``.
+This file must stay standalone: Blender's python cannot import ``codeverse``
+(the only sibling import is ``_census``, resolved via this file's own directory).
"""
from __future__ import annotations
import argparse
import contextlib
+import importlib
import json
import os
import random
-import re
import runpy
import sys
import time
import traceback
from typing import Any
+_WRAPPER_DIR = os.path.dirname(os.path.abspath(__file__))
+if _WRAPPER_DIR not in sys.path:
+ sys.path.insert(0, _WRAPPER_DIR)
+from _census import collect_census, is_hidden # noqa: E402 (sibling module, Blender-executed)
+
GLB_NAME = "object.glb"
STL_NAME = "object.stl"
BLEND_NAME = "object.blend"
EXPORT_TYPES = {"MESH", "CURVE", "SURFACE", "FONT", "META", "EMPTY"}
-DEFAULT_NAME_RE = re.compile(r"^(Cube|Cylinder|Sphere|Plane|Cone|Torus|Icosphere|Circle|Grid|Monkey|Mesh|Text|Curve)(\.\d+)?$")
+PARTS_PKG = "parts" # src/parts/<snake>.py → ``from parts.<snake> import build_<snake>``
# ----------------------------------------------------------------------------- args / io
@@ -123,22 +132,51 @@ def render_fingerprint(bpy: Any) -> dict[str, Any]:
# ----------------------------------------------------------------------------- exec + error mapping
+def src_relative(path: str, src_dir: str) -> str | None:
+ """``/ws/src/parts/leg.py`` → ``src/parts/leg.py`` when ``path`` lives under ``src_dir``; else None."""
+ real_src = os.path.realpath(src_dir)
+ real = os.path.realpath(path)
+ if real == real_src or not real.startswith(real_src + os.sep):
+ return None
+ return os.path.join(os.path.basename(real_src), os.path.relpath(real, real_src)).replace(os.sep, "/")
+
+
+def import_hint(exc: BaseException, src_dir: str) -> str:
+ """Extra guidance for the two import mistakes a multi-file model makes."""
+ msg = str(exc)
+ if isinstance(exc, ModuleNotFoundError) and (f"'{PARTS_PKG}." in msg or f"'{PARTS_PKG}'" in msg):
+ mod = msg.split("'")[1].split(".")[-1]
+ return f" — create {os.path.basename(src_dir)}/{PARTS_PKG}/{mod}.py (snake_case file name) or fix the import"
+ if isinstance(exc, ImportError) and "cannot import name" in msg:
+ name = msg.split("'")[1]
+ where = msg.split("'")[3] if msg.count("'") >= 4 else PARTS_PKG
+ return f" — define `def {name}():` in {where.replace('.', '/')}.py (every part file exports build_<snake>)"
+ return ""
+
+
def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:
- """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}."""
- real = os.path.realpath(script_path)
+ """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}.
+
+ ``error_file`` is workspace-relative (``src/model.py``, ``src/parts/leg.py``): the
+ innermost traceback frame inside ``src/`` wins, so a failure in a part file is
+ reported against that file, not against the ``from parts.x import …`` line.
+ """
+ src_dir = os.path.dirname(os.path.abspath(script_path))
info: dict[str, Any] = {
"error_type": type(exc).__name__,
- "error_message": str(exc) or type(exc).__name__,
+ "error_message": (str(exc) or type(exc).__name__) + import_hint(exc, src_dir),
"error_file": "",
"error_line": None,
"error_source": "",
}
- if isinstance(exc, SyntaxError) and exc.filename and os.path.realpath(exc.filename) == real:
- info.update(error_file=os.path.basename(script_path), error_line=exc.lineno, error_source=(exc.text or "").strip())
+ syntax_rel = src_relative(exc.filename, src_dir) if isinstance(exc, SyntaxError) and exc.filename else None
+ if syntax_rel:
+ info.update(error_file=syntax_rel, error_line=exc.lineno, error_source=(exc.text or "").strip())
else:
for frame in reversed(traceback.extract_tb(exc.__traceback__)):
- if os.path.realpath(frame.filename) == real:
- info.update(error_file=os.path.basename(script_path), error_line=frame.lineno, error_source=(frame.line or "").strip())
+ rel = src_relative(frame.filename, src_dir)
+ if rel:
+ info.update(error_file=rel, error_line=frame.lineno, error_source=(frame.line or "").strip())
break
if isinstance(exc, MemoryError):
info["error_message"] = (
@@ -151,10 +189,21 @@ def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:
def run_script(script_path: str) -> dict[str, Any] | None:
- """Execute the agent script as ``__main__``; return error info or None."""
- script_dir = os.path.dirname(os.path.abspath(script_path))
- if script_dir not in sys.path:
- sys.path.insert(0, script_dir)
+ """Execute the agent's entry script as ``__main__``; return error info or None.
+
+ ``<ws>/src`` goes first on ``sys.path`` so the entry can import its part modules
+ (``src/parts/<snake>.py``) either way: ``from parts.leg import build_leg`` or
+ ``import parts.leg``. A single-file ``model.py`` keeps working unchanged.
+ """
+ src_dir = os.path.dirname(os.path.abspath(script_path))
+ if _WRAPPER_DIR in sys.path: # the agent's code must not see the wrapper's helpers
+ sys.path.remove(_WRAPPER_DIR)
+ sys.path[:] = [p for p in sys.path if os.path.realpath(p) != os.path.realpath(src_dir)]
+ sys.path.insert(0, src_dir)
+ sys.dont_write_bytecode = True # no __pycache__ inside the agent's git-tracked src/
+ for name in [m for m in sys.modules if m == PARTS_PKG or m.startswith(PARTS_PKG + ".")]:
+ del sys.modules[name] # never reuse a stale module from somewhere else on the path
+ importlib.invalidate_caches()
saved_argv = sys.argv
sys.argv = [script_path]
try:
@@ -169,122 +218,13 @@ def run_script(script_path: str) -> dict[str, Any] | None:
return None
-# ----------------------------------------------------------------------------- census
-def world_bbox(obj_eval: Any, Vector: Any) -> tuple[list[float], list[float]] | None:
- corners = [obj_eval.matrix_world @ Vector(c) for c in obj_eval.bound_box]
- if not corners:
- return None
- mn = [min(c[i] for c in corners) for i in range(3)]
- mx = [max(c[i] for c in corners) for i in range(3)]
- return [round(v, 5) for v in mn], [round(v, 5) for v in mx]
-
-
-def is_hidden(obj: Any) -> bool:
- try:
- return bool(obj.hide_render or obj.hide_viewport or obj.hide_get())
- except RuntimeError: # object not in the view layer
- return True
-
-
-def collect_census(bpy: Any, tri_limit: int) -> dict[str, Any]:
- from mathutils import Vector
-
- bpy.context.view_layer.update()
- dg = bpy.context.evaluated_depsgraph_get()
- scene_objects = set(bpy.context.scene.objects.keys())
- boolean_operands: dict[str, list[str]] = {}
- objects: list[dict[str, Any]] = []
- total_tris = 0
- mins: list[list[float]] = []
- maxs: list[list[float]] = []
- for obj in bpy.data.objects:
- rec: dict[str, Any] = {
- "name": obj.name,
- "type": obj.type,
- "parent": obj.parent.name if obj.parent else None,
- "in_scene": obj.name in scene_objects,
- "hidden": is_hidden(obj),
- "materials": [s.material.name for s in obj.material_slots if s.material],
- "modifiers": [m.type for m in obj.modifiers],
- "location": [round(v, 5) for v in obj.matrix_world.translation],
- }
- for m in obj.modifiers:
- if m.type == "BOOLEAN" and getattr(m, "object", None) is not None:
- boolean_operands.setdefault(m.object.name, []).append(obj.name)
- if obj.type in ("MESH", "CURVE", "SURFACE", "FONT", "META"):
- try:
- ob_eval = obj.evaluated_get(dg)
- me = ob_eval.to_mesh()
- me.calc_loop_triangles()
- rec["tri_count"] = len(me.loop_triangles)
- rec["vert_count"] = len(me.vertices)
- rec["has_uv"] = bool(me.uv_layers)
- rec["has_vertex_colors"] = bool(me.color_attributes)
- bb = world_bbox(ob_eval, Vector)
- ob_eval.to_mesh_clear()
- except RuntimeError as e:
- rec["tri_count"] = 0
- rec["census_error"] = str(e)
- bb = None
- if bb:
- rec["bbox_min"], rec["bbox_max"] = bb
- if rec["in_scene"] and not rec["hidden"]:
- mins.append(bb[0])
- maxs.append(bb[1])
- if rec["in_scene"] and not rec["hidden"]:
- total_tris += rec["tri_count"]
- objects.append(rec)
- warnings: list[str] = []
- cams = [o.name for o in bpy.data.objects if o.type == "CAMERA"]
- lights = [o.name for o in bpy.data.objects if o.type == "LIGHT"]
- if cams:
- warnings.append(f"script created camera(s) {cams}: not exported; remove camera code (the harness owns cameras)")
- if lights:
- warnings.append(f"script created light(s) {lights}: not exported; remove light code (the harness owns lighting)")
- for cutter, users in boolean_operands.items():
- o = bpy.data.objects.get(cutter)
- if o is not None and not is_hidden(o) and o.name in scene_objects:
- warnings.append(
- f"object '{cutter}' is a boolean operand of {users} but is still visible and WILL be exported as "
- f"geometry; hide it: obj.hide_set(True); obj.hide_render = True (or bpy.data.objects.remove(obj))"
- )
- visible = [o for o in objects if o["in_scene"] and not o["hidden"] and o["type"] == "MESH"]
- if not visible:
- warnings.append("no visible mesh objects in the scene — nothing to export")
- for o in visible:
- if not o["materials"]:
- warnings.append(f"mesh '{o['name']}' has no material (will export grey)")
- if DEFAULT_NAME_RE.match(o["name"]):
- warnings.append(f"mesh '{o['name']}' keeps a default primitive name; set obj.name = '<PartName>'")
- unlinked = [o["name"] for o in objects if o["type"] == "MESH" and not o["in_scene"]]
- if unlinked:
- warnings.append(f"mesh object(s) {unlinked} were created but never linked to the scene → not exported; "
- "call bpy.context.collection.objects.link(obj)")
- if total_tris > tri_limit:
- warnings.append(f"triangle budget exceeded: {total_tris} > {tri_limit}")
- census = {
- "objects": objects,
- "n_mesh_objects": len(visible),
- "tri_count": total_tris,
- "tri_limit": tri_limit,
- "materials": [m.name for m in bpy.data.materials],
- "cameras": cams,
- "lights": lights,
- "warnings": warnings,
- "frame": "z_up_neg_y_front",
- }
- if mins:
- census["scene_bbox_min"] = [round(min(m[i] for m in mins), 5) for i in range(3)]
- census["scene_bbox_max"] = [round(max(m[i] for m in maxs), 5) for i in range(3)]
- return census
-
-
# ----------------------------------------------------------------------------- export
def select_exportables(bpy: Any) -> list[Any]:
bpy.ops.object.select_all(action="DESELECT")
chosen = []
+ vl_names = set(bpy.context.view_layer.objects.keys()) # same predicate as the census
for obj in bpy.context.scene.objects:
- if obj.type in EXPORT_TYPES and not is_hidden(obj):
+ if obj.type in EXPORT_TYPES and not is_hidden(obj, vl_names):
with contextlib.suppress(RuntimeError): # not in the view layer (excluded collection)
obj.select_set(True)
chosen.append(obj)
diff --git a/harness/codeverse/languages/cadquery/lint.py b/harness/codeverse/languages/cadquery/lint.py
index 80da23cd..74a58653 100644
--- a/harness/codeverse/languages/cadquery/lint.py
+++ b/harness/codeverse/languages/cadquery/lint.py
@@ -48,6 +48,46 @@ def dotted(node: ast.AST) -> str:
return ""
+RADIAN_CONSTS = {"pi", "tau"}
+TO_RADIANS_FUNCS = {"radians", "deg2rad"}
+TO_DEGREES_FUNCS = {"degrees", "rad2deg"}
+
+
+def looks_like_radians(expr: ast.expr) -> bool:
+ """True when ``expr`` is a radians expression (``math.pi``, ``math.pi / 2``, ``i * 2 * math.pi / n``,
+ ``math.radians(a)``) — never a plain name/number, never a conversion TO degrees
+ (``a * 180 / math.pi``, ``math.degrees(a)``). Only the ``pi``/``tau`` constants and the
+ radians/degrees helpers are inspected, so identifiers such as ``n_pins`` or ``pitch`` cannot match.
+ """
+ hit = False
+
+ def walk(node: ast.AST, inverted: bool) -> bool:
+ """Return True to stop: the expression is a conversion to degrees."""
+ nonlocal hit
+ if isinstance(node, ast.Call):
+ fn = dotted(node.func).rsplit(".", 1)[-1]
+ if fn in TO_DEGREES_FUNCS:
+ return True
+ if fn in TO_RADIANS_FUNCS:
+ hit = True
+ return any(walk(a, inverted) for a in node.args)
+ if isinstance(node, ast.BinOp):
+ if walk(node.left, inverted):
+ return True
+ return walk(node.right, inverted != isinstance(node.op, ast.Div))
+ is_const = (isinstance(node, ast.Attribute) and node.attr in RADIAN_CONSTS) or (isinstance(node, ast.Name) and node.id in RADIAN_CONSTS)
+ if is_const:
+ if inverted: # ``x * 180 / math.pi`` → degrees
+ return True
+ hit = True
+ return False
+ return any(walk(ch, inverted) for ch in ast.iter_child_nodes(node))
+
+ if walk(expr, False):
+ return False
+ return hit
+
+
def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"line": line} if line else {})
@@ -130,7 +170,7 @@ def _rules(c: _Collector, tree: ast.Module, source: str) -> list[GateFinding]:
if name.endswith("Solid.makeSphere") and not any(k.arg and k.arg.startswith("angle") for k in call.keywords):
out.append(_f(W, "cq.Solid.makeSphere(r) without angle args builds a partial sphere in some versions", call.lineno,
"use `cq.Workplane('XY').sphere(r)` or pass angleDegrees1=-90, angleDegrees2=90, angleDegrees3=360"))
- if name.endswith(".rotate") and len(call.args) == 3 and isinstance(call.args[2], ast.BinOp) and "pi" in ast.dump(call.args[2]).lower():
+ if name.endswith(".rotate") and len(call.args) == 3 and looks_like_radians(call.args[2]):
out.append(_f(E, ".rotate(...) takes DEGREES; this argument looks like radians (math.pi expression)", call.lineno,
"pass degrees: `.rotate((0,0,0), (0,0,1), 90)` or `math.degrees(angle_rad)`"))
if name.endswith(".fillet") or name.endswith(".chamfer"):
diff --git a/harness/codeverse/languages/cadquery/wrappers/run_cq.py b/harness/codeverse/languages/cadquery/wrappers/run_cq.py
index e250aa2f..b66bb656 100644
--- a/harness/codeverse/languages/cadquery/wrappers/run_cq.py
+++ b/harness/codeverse/languages/cadquery/wrappers/run_cq.py
@@ -64,16 +64,41 @@ def apply_rlimit(gb: float) -> str:
# ----------------------------------------------------------------------------- exec + errors
+def src_relative(path: str, src_dir: str) -> str | None:
+ """``/ws/src/helpers.py`` → ``src/helpers.py`` when ``path`` lives under ``src_dir``; else None.
+
+ Every runtime reports ``error_file`` workspace-relative (``src/...``) so the repair
+ loop can open the file; the bare basename would resolve to ``<ws>/model.py``.
+ """
+ real_src = os.path.realpath(src_dir)
+ real = os.path.realpath(path)
+ if real == real_src or not real.startswith(real_src + os.sep):
+ return None
+ return os.path.join(os.path.basename(real_src), os.path.relpath(real, real_src)).replace(os.sep, "/")
+
+
+def entry_relative(script_path: str) -> str:
+ """``src/model.py`` for the entry script itself."""
+ return src_relative(script_path, os.path.dirname(os.path.abspath(script_path))) or os.path.basename(script_path)
+
+
def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:
- real = os.path.realpath(script_path)
+ """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}.
+
+ The innermost frame under ``src/`` wins, so an exception raised in a helper module
+ (``src/helpers.py``) is reported against that file, not the ``model.py`` call site.
+ """
+ src_dir = os.path.dirname(os.path.abspath(script_path))
info: dict[str, Any] = {"error_type": type(exc).__name__, "error_message": str(exc) or type(exc).__name__,
"error_file": "", "error_line": None, "error_source": ""}
- if isinstance(exc, SyntaxError) and exc.filename and os.path.realpath(exc.filename) == real:
- info.update(error_file=os.path.basename(script_path), error_line=exc.lineno, error_source=(exc.text or "").strip())
+ syntax_rel = src_relative(exc.filename, src_dir) if isinstance(exc, SyntaxError) and exc.filename else None
+ if syntax_rel:
+ info.update(error_file=syntax_rel, error_line=exc.lineno, error_source=(exc.text or "").strip())
else:
for fr in reversed(traceback.extract_tb(exc.__traceback__)):
- if os.path.realpath(fr.filename) == real:
- info.update(error_file=os.path.basename(script_path), error_line=fr.lineno, error_source=(fr.line or "").strip())
+ rel = src_relative(fr.filename, src_dir)
+ if rel:
+ info.update(error_file=rel, error_line=fr.lineno, error_source=(fr.line or "").strip())
break
msg = info["error_message"]
if "BRep_API: command not done" in msg or "StdFail_NotDone" in info["error_type"]:
@@ -98,7 +123,7 @@ def run_script(script_path: str) -> tuple[dict[str, Any] | None, dict[str, Any]]
except SystemExit as e:
if e.code in (None, 0):
return {"error_type": "SystemExit", "error_message": "script called sys.exit() before `result` could be read; remove it",
- "error_file": os.path.basename(script_path), "error_line": None, "error_source": "", "traceback": ""}, {}
+ "error_file": entry_relative(script_path), "error_line": None, "error_source": "", "traceback": ""}, {}
return map_exception(e, script_path), {}
except BaseException as e: # noqa: BLE001
return map_exception(e, script_path), {}
@@ -107,19 +132,35 @@ def run_script(script_path: str) -> tuple[dict[str, Any] | None, dict[str, Any]]
# ----------------------------------------------------------------------------- parts
-def _as_shape(cq: Any, obj: Any) -> Any:
- """Workplane / Shape → one Shape (compound when several solids)."""
+def _as_shape(cq: Any, obj: Any, warnings: list[str] | None = None, label: str = "result") -> Any:
+ """Workplane / Shape → one Shape (compound when several solids).
+
+ A Workplane whose stack holds only Faces/Edges/Wires/Vertices (a trailing selector such
+ as ``.faces(">Z")``) is NOT exported as a sheet: the solid it was selected from is used
+ (``findSolid``) with a warning, or an error names the stack types when there is none.
+ """
if isinstance(obj, cq.Workplane):
vals = [v for v in obj.vals() if isinstance(v, cq.Shape)]
if not vals:
- raise ValueError("Workplane holds no shapes (did you forget .extrude()/.box()?)")
+ raise ValueError(f"{label}: Workplane holds no shapes (did you forget .extrude()/.box()?)")
+ if not any(isinstance(v, (cq.Solid, cq.Compound, cq.Shell)) for v in vals):
+ kinds = sorted({type(v).__name__ for v in vals})
+ try:
+ solid = obj.findSolid(searchStack=True, searchParents=True)
+ except Exception as e: # noqa: BLE001 — ValueError from cadquery; anything else is equally "no solid"
+ raise ValueError(f"{label}: Workplane stack holds only {'/'.join(kinds)} objects, not a Solid — "
+ f"end the chain with a solid (.extrude()/.box()/.revolve(); drop the trailing selector) [{e}]") from e
+ if warnings is not None:
+ warnings.append(f"{label}: Workplane stack held {'/'.join(kinds)} objects (trailing selector) — exported the parent "
+ "solid instead; end the chain with the solid (drop the selector or call .end())")
+ return solid
return vals[0] if len(vals) == 1 else cq.Compound.makeCompound(vals)
if isinstance(obj, cq.Shape):
return obj
- raise TypeError(f"unsupported object of type {type(obj).__name__}; expected cq.Workplane or cq.Shape")
+ raise TypeError(f"{label}: unsupported object of type {type(obj).__name__}; expected cq.Workplane or cq.Shape")
-def flatten_assembly(cq: Any, assy: Any) -> list[dict[str, Any]]:
+def flatten_assembly(cq: Any, assy: Any, warnings: list[str] | None = None) -> list[dict[str, Any]]:
"""Depth-first leaves: {name, shape (world-located), rgba, path}."""
out: list[dict[str, Any]] = []
@@ -127,7 +168,7 @@ def flatten_assembly(cq: Any, assy: Any) -> list[dict[str, Any]]:
loc = parent_loc * node.loc
rgba = node.color.toTuple() if node.color is not None else parent_rgba
if node.obj is not None:
- shape = _as_shape(cq, node.obj).moved(loc)
+ shape = _as_shape(cq, node.obj, warnings, f"part {node.name!r}").moved(loc)
out.append({"name": node.name, "shape": shape, "rgba": rgba, "path": "/".join(path + [node.name])})
for child in node.children:
walk(child, loc, rgba, path + [node.name])
@@ -136,10 +177,10 @@ def flatten_assembly(cq: Any, assy: Any) -> list[dict[str, Any]]:
return out
-def collect_parts(cq: Any, result: Any) -> tuple[list[dict[str, Any]], str]:
+def collect_parts(cq: Any, result: Any, warnings: list[str] | None = None) -> tuple[list[dict[str, Any]], str]:
if isinstance(result, cq.Assembly):
- return flatten_assembly(cq, result), "assembly"
- shape = _as_shape(cq, result)
+ return flatten_assembly(cq, result, warnings), "assembly"
+ shape = _as_shape(cq, result, warnings, "result")
return [{"name": "Object", "shape": shape, "rgba": None, "path": "Object"}], "single"
@@ -201,7 +242,7 @@ def export_step_stl(cq: Any, result: Any, parts: list[dict[str, Any]], out_dir:
if isinstance(result, cq.Assembly):
result.export(step) if hasattr(result, "export") else result.save(step)
else:
- cq.exporters.export(_as_shape(cq, result), step)
+ cq.exporters.export(_as_shape(cq, result, None, "result"), step)
report["exported"]["step"] = step
except Exception as e: # noqa: BLE001
report["warnings"].append(f"STEP export failed: {e}")
@@ -238,12 +279,12 @@ def main() -> int:
report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
census: dict[str, Any] = {"parts": [], "tri_count": 0, "warnings": report["warnings"], "frame": "z_up_neg_y_front"}
if err is None and "result" not in ns:
- err = {"error_type": "MissingResult", "error_file": os.path.basename(script),
+ err = {"error_type": "MissingResult", "error_file": entry_relative(script),
"error_message": "model.py must assign a module-level `result` (cq.Assembly or cq.Workplane); "
"it must exist at import time, not only under `if __name__ == '__main__':`"}
if err is None:
try:
- parts, kind = collect_parts(cq, ns["result"])
+ parts, kind = collect_parts(cq, ns["result"], report["warnings"])
census["result_kind"] = kind
if kind == "single":
report["warnings"].append("result is a bare Workplane/Shape: exported as ONE node 'Object' — prefer cq.Assembly with named, coloured parts")
@@ -251,11 +292,15 @@ def main() -> int:
for p in parts:
verts, tris = tessellate(p, args.tolerance, args.angular_tolerance)
meshes.append((p, verts, tris))
- census["parts"].append(part_census(p, len(tris)))
+ rec = part_census(p, len(tris))
+ census["parts"].append(rec)
if not PASCAL_RE.match(p["name"]):
report["warnings"].append(f"part name {p['name']!r} is not PascalCase (give every .add(...) a name='PartName')")
if not tris:
report["warnings"].append(f"part {p['name']!r} tessellated to 0 triangles (empty/degenerate shape)")
+ elif rec.get("n_solids") == 0:
+ report["warnings"].append(f"part {p['name']!r} contains no solid (a face/shell/wire set, volume 0) — "
+ "build it as a solid (.extrude()/.box()/.shell()) so it has thickness")
census["tri_count"] = sum(len(m[2]) for m in meshes)
if census["parts"]:
census["scene_bbox_min"] = [min(p["bbox_min"][i] for p in census["parts"]) for i in range(3)]
@@ -273,6 +318,8 @@ def main() -> int:
err["error_type"], err["error_message"] = "ExportError", f"{type(e).__name__}: {e}"
if err:
report.update({k: v for k, v in err.items() if k in report or k == "traceback"})
+ if err.get("traceback"):
+ print(err["traceback"], file=sys.stderr, end="")
census["n_parts"] = len(census["parts"])
write_json_atomic(census_path, census)
report["ok"] = not report["error_type"] and "glb" in report["exported"]
diff --git a/harness/codeverse/languages/glsl_shader/__init__.py b/harness/codeverse/languages/glsl_shader/__init__.py
new file mode 100644
index 00000000..f7ae15dd
--- /dev/null
+++ b/harness/codeverse/languages/glsl_shader/__init__.py
@@ -0,0 +1,5 @@
+"""glsl_shader language: Shadertoy-style fragment shaders rendered by moderngl."""
+
+from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+
+__all__ = ["GlslShaderRuntime"]
diff --git a/harness/codeverse/languages/glsl_shader/gl_build.py b/harness/codeverse/languages/glsl_shader/gl_build.py
new file mode 100644
index 00000000..da26f27b
--- /dev/null
+++ b/harness/codeverse/languages/glsl_shader/gl_build.py
@@ -0,0 +1,119 @@
+"""Shared build plumbing for the two graphics languages (glsl_shader, opengl_python).
+
+``finish_build`` turns a :class:`GlResult` into the canonical artifact set —
+``artifacts/frames/*.png`` (written by the runner), ``artifacts/frames_sheet.png``,
+``artifacts/preview.gif``, ``artifacts/metrics.json`` (frame stats + the
+``gl_frames`` gate), ``artifacts/build.json`` — and a typed :class:`BuildResult`
+(``glb_path`` is always None: the deliverable is code + frames).
+``judge_times`` / ``preview_times`` derive the sampled times from the plan's duration.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.plan import GraphicsPlan
+from codeverse.spatial.frame_stats import SequenceStats, frame_gate, sequence_stats
+from codeverse.spatial.gl_render import GlResult, gif_times, write_contact_sheet, write_gif
+from codeverse.workspace import Workspace
+
+JUDGE_TIMES: tuple[float, ...] = (0.0, 1.0, 2.5, 4.0, 6.0)
+SHEET_NAME = "frames_sheet.png"
+GIF_NAME = "preview.gif"
+METRICS_NAME = "metrics.json"
+BUILD_JSON = "build.json"
+DEFAULT_RESOLUTION: tuple[int, int] = (1280, 720)
+MAX_PIXELS = 1920 * 1080
+
+
+def load_plan(ws: Workspace) -> GraphicsPlan | None:
+ p = ws.plan_path
+ if not p.is_file():
+ return None
+ try:
+ return GraphicsPlan.model_validate(json.loads(p.read_text()))
+ except Exception: # noqa: BLE001 — not a graphics plan (or invalid) → defaults
+ return None
+
+
+def resolution_for(plan: GraphicsPlan | None, *, fallback: tuple[int, int] = DEFAULT_RESOLUTION) -> tuple[int, int]:
+ if plan is None:
+ return fallback
+ w, h = int(plan.resolution[0]), int(plan.resolution[1])
+ if w < 64 or h < 64 or w * h > MAX_PIXELS:
+ return fallback
+ return w, h
+
+
+def judge_times(duration_s: float | None) -> list[float]:
+ """t ∈ {0, 1, 2.5, 4, 6} clipped to the loop duration (always ≥ 3 samples)."""
+ d = float(duration_s or 8.0)
+ ts = [t for t in JUDGE_TIMES if t <= d + 1e-9]
+ if len(ts) < 3:
+ ts = [round(i * d / 4, 3) for i in range(5)]
+ return ts
+
+
+def preview_times(duration_s: float | None, n: int = 12) -> list[float]:
+ return gif_times(float(duration_s or 8.0), n)
+
+
+def finish_build(ws: Workspace, res: GlResult, *, language: str, error_file: str = "", error_line: int | None = None,
+ error_message: str | None = None, census: dict | None = None, motion_expected: bool = True) -> BuildResult:
+ """Write derived artifacts + build.json and return the BuildResult."""
+ art = ws.artifacts
+ art.mkdir(parents=True, exist_ok=True)
+ extras: dict[str, str] = {}
+ cen: dict = {"renderer": res.renderer, "gpu": res.gpu, "feedback": res.feedback, "n_frames": len(res.frames),
+ "gl_duration_ms": res.duration_ms, **(census or {})}
+ if res.ok and res.judge_frames:
+ frames = res.judge_frames
+ extras["frames"] = str(art / "frames")
+ sheet = write_contact_sheet(frames, art / SHEET_NAME)
+ extras["sheet"] = str(sheet)
+ gif = write_gif(res.frames, art / GIF_NAME)
+ if gif is not None:
+ extras["gif"] = str(gif)
+ seq = sequence_stats([(f.time, f.path) for f in frames], nan_counts=[(f.nan, f.inf) for f in frames])
+ gate = frame_gate(seq, motion_expected=motion_expected)
+ metrics = art / METRICS_NAME
+ metrics.write_text(json.dumps({"stats": seq.model_dump(mode="json"), "gate": gate.model_dump(mode="json")}, indent=1))
+ extras["metrics"] = str(metrics)
+ cen["frame_stats"] = {"mean_lum": seq.mean_lum, "mean_diff": seq.mean_diff, "static": seq.static, "any_nan": seq.any_nan,
+ "colourfulness": seq.mean_colourfulness, "edge_density": seq.mean_edge_density}
+ result = BuildResult(
+ ok=bool(res.ok and res.judge_frames), language=language, glb_path=None, extra_paths=extras,
+ stdout_tail=res.stdout_tail, stderr_tail=(res.traceback or res.stderr_tail)[-4000:],
+ error_type="" if res.ok else (res.error_type or "RenderError"),
+ error_message="" if res.ok else (error_message if error_message is not None else res.error_message)[:4000],
+ error_file=error_file if not res.ok else "", error_line=error_line if not res.ok else None,
+ duration_ms=res.duration_ms, census=cen,
+ )
+ if res.ok and not res.judge_frames:
+ result.error_type, result.error_message = "NoFrames", "the renderer produced no frames"
+ ws.write_json(art / BUILD_JSON, result)
+ return result
+
+
+def read_metrics(ws: Workspace) -> tuple[SequenceStats, GateReport] | None:
+ p = ws.artifacts / METRICS_NAME
+ if not p.is_file():
+ return None
+ data = json.loads(p.read_text())
+ return SequenceStats.model_validate(data["stats"]), GateReport.model_validate(data["gate"])
+
+
+_TB_LINE = re.compile(r'File "(?P<file>[^"]+)", line (?P<line>\d+)')
+
+
+def traceback_location(tb: str, program_path: Path) -> tuple[str, int | None]:
+ """Last traceback frame inside the agent's program → (rel path, line)."""
+ hits = [(m.group("file"), int(m.group("line"))) for m in _TB_LINE.finditer(tb or "")]
+ name = program_path.name
+ for f, line in reversed(hits):
+ if Path(f).name == name or f.endswith(str(program_path)):
+ return "src/" + name, line
+ return "", None
diff --git a/harness/codeverse/languages/glsl_shader/lint.py b/harness/codeverse/languages/glsl_shader/lint.py
new file mode 100644
index 00000000..c5d17801
--- /dev/null
+++ b/harness/codeverse/languages/glsl_shader/lint.py
@@ -0,0 +1,145 @@
+"""Static checks for ``src/shader.frag`` (+ ``common.glsl`` / ``buffer_a.frag``).
+
+Catches what the compiler reports confusingly (or too late): a ``#version`` line
+(the harness prepends one), redeclared harness uniforms / outputs, Shadertoy
+inputs that do not exist here (``iChannel2``, ``iDate`` …), ``texture()`` on
+undeclared samplers, GLSL 1.x syntax (``gl_FragColor`` / ``varying`` /
+``texture2D``), ``%`` on floats, a missing ``mainImage``/``main``.
+Gate name ``lint:glsl_shader``; ``data["kind"]`` names the rule.
+"""
+
+from __future__ import annotations
+
+import re
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.languages.glsl_shader.wrap import (
+ _MAIN_IMAGE,
+ _PLAIN_MAIN,
+ UNIFORM_NAMES,
+ strip_comments,
+)
+from codeverse.workspace import Workspace
+
+GATE = "lint:glsl_shader"
+SHADER = "src/shader.frag"
+COMMON = "src/common.glsl"
+BUFFER_A = "src/buffer_a.frag"
+SAMPLERS = {"u_prev", "u_noise", "u_buffer_a", "iChannel0", "iChannel1"}
+MAX_CHARS = 60_000
+
+_VERSION = re.compile(r"^[ \t]*#[ \t]*version\b", re.M)
+_INCLUDE = re.compile(r"^[ \t]*#[ \t]*include\b", re.M)
+_UNIFORM_DECL = re.compile(r"\buniform\s+\w+\s+(\w+)")
+_OUT_DECL = re.compile(r"^[ \t]*(?:layout\s*\([^)]*\)\s*)?out\s+vec4\s+(\w+)\s*;", re.M)
+_TEXTURE = re.compile(r"\btexture(?:Lod|Grad|Proj)?\s*\(\s*(\w+)")
+_MISSING_INPUTS = re.compile(r"\b(iChannel[23]|iChannelResolution|iChannelTime|iDate|iSampleRate|iFrameRate)\b")
+_LEGACY = {
+ "gl_FragColor": "write `fragColor` (declared by the harness) instead of gl_FragColor",
+ "texture2D(": "use `texture(sampler, uv)` — GLSL 330 has no texture2D",
+ "varying ": "fragment-only shader: no varyings; use gl_FragCoord / uniforms",
+ "attribute ": "fragment-only shader: no attributes",
+}
+_FLOAT_LITERAL_MOD = re.compile(r"(\d\.\d*|\.\d+)\s*%|%\s*(\d\.\d*|\.\d+)")
+_PRECISION = re.compile(r"^[ \t]*precision\s+(lowp|mediump|highp)\s+\w+\s*;", re.M)
+def _line_of(text: str, pos: int) -> int:
+ return text.count("\n", 0, pos) + 1
+
+
+def _check_file(rel: str, text: str, *, role: str) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ raw_len = len(text)
+ text = strip_comments(text)
+
+ def add(sev: Severity, kind: str, msg: str, hint: str, line: int | None = None) -> None:
+ out.append(GateFinding(gate=GATE, severity=sev, target=rel, message=(f"{rel}:{line}: " if line else f"{rel}: ") + msg,
+ fix_hint=hint, data={"kind": kind, "line": line, "file": rel}))
+
+ if raw_len > MAX_CHARS:
+ add(Severity.WARN, "too_long", f"file is {raw_len} chars; keep shaders compact", "remove dead code; move helpers to src/common.glsl")
+ for m in _VERSION.finditer(text):
+ add(Severity.ERROR, "version_line", "contains a #version line; the harness prepends `#version 330 core`",
+ "delete the #version line", _line_of(text, m.start()))
+ for m in _INCLUDE.finditer(text):
+ add(Severity.ERROR, "include", "#include is not GLSL; src/common.glsl is pasted in automatically",
+ "delete the #include line; functions in src/common.glsl are already visible", _line_of(text, m.start()))
+ for m in _UNIFORM_DECL.finditer(text):
+ name = m.group(1)
+ if name in UNIFORM_NAMES:
+ add(Severity.ERROR, "redeclared_uniform", f"redeclares harness uniform `{name}`",
+ f"delete the declaration; `{name}` is provided by the harness header", _line_of(text, m.start()))
+ else:
+ add(Severity.ERROR, "custom_uniform", f"declares uniform `{name}` which nothing will set",
+ "only u_time / u_resolution / u_mouse / u_frame / u_prev / u_noise / u_buffer_a exist; turn it into a `const`",
+ _line_of(text, m.start()))
+ for m in _OUT_DECL.finditer(text):
+ add(Severity.ERROR, "redeclared_output", f"declares output `{m.group(1)}`; the harness already declares `out vec4 fragColor`",
+ "delete the `out vec4 ...;` line and write to fragColor", _line_of(text, m.start()))
+ for m in _TEXTURE.finditer(text):
+ name = m.group(1)
+ if name not in SAMPLERS:
+ add(Severity.ERROR, "undeclared_sampler", f"texture() reads sampler `{name}` which does not exist",
+ "only u_prev (previous frame), u_noise (256² RGBA noise) and u_buffer_a (buffer pass) can be sampled; "
+ "generate patterns procedurally (hash/noise/fbm from the cookbook)", _line_of(text, m.start()))
+ for m in _MISSING_INPUTS.finditer(text):
+ add(Severity.ERROR, "missing_input", f"`{m.group(1)}` is not available in this harness",
+ "available: u_time/iTime, u_resolution/iResolution, u_frame/iFrame, u_mouse (always 0), u_prev/iChannel0, u_noise/iChannel1",
+ _line_of(text, m.start()))
+ for needle, hint in _LEGACY.items():
+ pos = text.find(needle)
+ if pos >= 0:
+ add(Severity.ERROR, "legacy_glsl", f"uses `{needle.strip()}` (GLSL 1.x)", hint, _line_of(text, pos))
+ for m in _FLOAT_LITERAL_MOD.finditer(text):
+ add(Severity.ERROR, "float_modulo", "`%` on a float literal — GLSL `%` is integer-only", "use mod(x, y)", _line_of(text, m.start()))
+ if role in ("shader", "buffer_a"):
+ if not _MAIN_IMAGE.search(text) and not _PLAIN_MAIN.search(text):
+ add(Severity.ERROR, "no_entry", "neither `void mainImage(out vec4 fragColor, in vec2 fragCoord)` nor `void main()` found",
+ "define `void mainImage(out vec4 fragColor, in vec2 fragCoord) { ... fragColor = vec4(col, 1.0); }`")
+ if "fragColor" not in text and "gl_FragColor" not in text:
+ add(Severity.ERROR, "no_output", "never writes fragColor", "end mainImage()/main() with `fragColor = vec4(col, 1.0);`")
+ if role == "common" and (_MAIN_IMAGE.search(text) or _PLAIN_MAIN.search(text)):
+ add(Severity.ERROR, "entry_in_common", "src/common.glsl must not define main()/mainImage()",
+ "move the entry point to src/shader.frag; keep only helper functions / constants in common.glsl")
+ if role == "buffer_a" and "u_buffer_a" in text:
+ add(Severity.WARN, "buffer_self_ref", "buffer_a.frag samples u_buffer_a; inside the buffer pass the previous buffer is `u_prev`",
+ "use texture(u_prev, uv) for feedback inside buffer_a.frag")
+ for m in _PRECISION.finditer(text):
+ add(Severity.INFO, "precision", "precision qualifier is ignored on desktop GLSL 330", "safe to delete", _line_of(text, m.start()))
+ if "u_mouse" in text or "iMouse" in text:
+ add(Severity.INFO, "mouse", "u_mouse is always (0,0) when rendered headless", "do not depend on the mouse for the look")
+ return out
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ findings: list[GateFinding] = []
+ shader = ws.root / SHADER
+ if not shader.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=SHADER, message=f"{SHADER} is missing",
+ fix_hint="create src/shader.frag with a mainImage(out vec4 fragColor, in vec2 fragCoord) function",
+ data={"kind": "missing_entry", "file": SHADER}))
+ else:
+ findings.extend(_check_file(SHADER, shader.read_text(errors="replace"), role="shader"))
+ for rel, role in ((COMMON, "common"), (BUFFER_A, "buffer_a")):
+ p = ws.root / rel
+ if p.is_file():
+ findings.extend(_check_file(rel, p.read_text(errors="replace"), role=role))
+ stray = [str(p.relative_to(ws.root)) for p in ws.src.rglob("*") if p.is_file()
+ and str(p.relative_to(ws.root)) not in (SHADER, COMMON, BUFFER_A) and p.suffix in (".frag", ".glsl", ".vert", ".py", ".js")]
+ for rel in stray:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel} is not part of the shader contract and is ignored",
+ fix_hint="keep code in src/shader.frag (+ src/common.glsl, src/buffer_a.frag)", data={"kind": "stray_file", "file": rel}))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings)
+
+
+def lint_text(shader_src: str, common_src: str | None = None, buffer_a_src: str | None = None) -> list[GateFinding]:
+ """Lint in-memory sources (tools / tests)."""
+ out = _check_file(SHADER, shader_src, role="shader")
+ if common_src is not None:
+ out += _check_file(COMMON, common_src, role="common")
+ if buffer_a_src is not None:
+ out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a")
+ return out
+
+
+__all__ = ["GATE", "SHADER", "COMMON", "BUFFER_A", "lint_workspace", "lint_text", "strip_comments"]
diff --git a/harness/codeverse/languages/glsl_shader/runtime.py b/harness/codeverse/languages/glsl_shader/runtime.py
new file mode 100644
index 00000000..40f0999e
--- /dev/null
+++ b/harness/codeverse/languages/glsl_shader/runtime.py
@@ -0,0 +1,110 @@
+"""GlslShaderRuntime: skeleton → lint → build (moderngl frames) for Shadertoy-style shaders.
+
+``src/shader.frag`` (+ optional ``src/common.glsl``, ``src/buffer_a.frag``) is
+wrapped by :mod:`wrap` (header with the uniform contract + main trampoline),
+compiled and rendered in a subprocess by :class:`GlHost` at the plan's
+resolution for t ∈ {0, 1, 2.5, 4, 6}s (+ preview frames for the GIF).
+Compile errors come back mapped to ``src/shader.frag:LINE``.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan
+from codeverse.languages.glsl_shader.gl_build import (
+ finish_build,
+ judge_times,
+ load_plan,
+ preview_times,
+ resolution_for,
+)
+from codeverse.languages.glsl_shader.lint import BUFFER_A, COMMON, SHADER, lint_workspace
+from codeverse.languages.glsl_shader.skeleton import write_skeleton
+from codeverse.languages.glsl_shader.wrap import Composed, compose, first_error, parse_glsl_log
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.gl_render import GlHost, GlResult
+from codeverse.workspace import Workspace
+
+CONTRACT_FALLBACK = """src/shader.frag — GLSL 330 fragment shader body (NO #version line, NO uniform declarations):
+write `void mainImage(out vec4 fragColor, in vec2 fragCoord)` using the harness uniforms u_time, u_resolution,
+u_mouse, u_frame, u_prev (previous frame), u_noise (256² noise), u_buffer_a (src/buffer_a.frag output).
+Optional src/common.glsl (helpers, pasted in first) and src/buffer_a.frag (one feedback pass). Animate with u_time."""
+
+
+class GlslShaderRuntime:
+ language = Language.GLSL_SHADER
+ entry_globs: tuple[str, ...] = ("src/shader.frag", "src/common.glsl", "src/buffer_a.frag")
+
+ def __init__(self, *, host: GlHost | None = None):
+ self._host = host
+
+ # ------------------------------------------------------------------ contract
+ def contract_doc(self) -> str:
+ try:
+ return load_text("glsl_shader/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_FALLBACK
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "glsl_shader" / "cookbook.md"
+
+ # ------------------------------------------------------------------ skeleton / lint
+ def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ # ------------------------------------------------------------------ build
+ def host(self, timeout_s: float | None = None) -> GlHost:
+ if self._host is not None:
+ return self._host
+ settings = get_settings()
+ return GlHost(gpu=settings.render.gpu, timeout_s=float(timeout_s or settings.limits.render_timeout_s))
+
+ def compose_sources(self, ws: Workspace) -> tuple[Composed, Composed | None]:
+ shader = (ws.root / SHADER).read_text(errors="replace")
+ common_p = ws.root / COMMON
+ common = common_p.read_text(errors="replace") if common_p.is_file() else None
+ image = compose(shader, common)
+ buf_p = ws.root / BUFFER_A
+ buffer_a = compose(buf_p.read_text(errors="replace"), common, shader_file=BUFFER_A) if buf_p.is_file() else None
+ return image, buffer_a
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
+ preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ if not (ws.root / SHADER).is_file():
+ res = GlResult(ok=False, mode="shader", stage="lint", error_type="MissingEntry", error_message=f"{SHADER} is missing")
+ return finish_build(ws, res, language=self.language.value, error_file=SHADER)
+ plan = load_plan(ws)
+ w, h = resolution_for(plan)
+ if width and height:
+ w, h = int(width), int(height)
+ duration = plan.duration_s if plan else None
+ image, buffer_a = self.compose_sources(ws)
+ host = self.host(timeout_s)
+ res = host.render_fragment_shader(
+ image.source, ws.artifacts, width=w, height=h, times=times or judge_times(duration),
+ buffer_a_src=buffer_a.source if buffer_a else None, feedback=image.uses_feedback or buffer_a is not None,
+ extra_times=preview_times(duration) if preview else (),
+ )
+ census = {"convention": image.convention, "has_common": (ws.root / COMMON).is_file(), "has_buffer_a": buffer_a is not None,
+ "resolution": [w, h]}
+ err_file, err_line, err_msg = "", None, None
+ if not res.ok and res.stage in ("compile", "compile_buffer_a"):
+ comp = buffer_a if res.stage == "compile_buffer_a" and buffer_a else image
+ msgs = parse_glsl_log(res.error_message, comp.line_map)
+ first = first_error(msgs)
+ if first is not None:
+ err_file, err_line = first.file, first.file_line
+ listed = "\n".join(m.text() for m in msgs[:12]) or res.error_message.strip()
+ err_msg = f"GLSL compile error ({'buffer_a' if res.stage == 'compile_buffer_a' else 'shader'}):\n{listed}"
+ res.error_type = "GlslCompileError"
+ motion_expected = bool(plan.motion.strip()) if plan else True
+ return finish_build(ws, res, language=self.language.value, error_file=err_file, error_line=err_line,
+ error_message=err_msg, census=census, motion_expected=motion_expected)
diff --git a/harness/codeverse/languages/glsl_shader/skeleton.py b/harness/codeverse/languages/glsl_shader/skeleton.py
new file mode 100644
index 00000000..aabd3f2c
--- /dev/null
+++ b/harness/codeverse/languages/glsl_shader/skeleton.py
@@ -0,0 +1,108 @@
+"""Skeleton for the glsl_shader language: a RUNNABLE starter pair
+(``src/common.glsl`` helpers + ``src/shader.frag`` entry) carrying the plan's
+passes / key visuals / motion as TODO comments and the uniform contract as a
+header comment. The baseline generator rewrites it; the harness can already
+build and render it (gradient sky + fbm haze + moving sun)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.plan import GraphicsPlan, Plan
+from codeverse.workspace import Workspace
+
+COMMON_GLSL = """// src/common.glsl — helpers pasted above shader.frag by the harness (no #include needed).
+// Keep ONLY functions / constants here; no main(), no uniforms, no #version.
+#define PI 3.14159265359
+#define TAU 6.28318530718
+
+float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); }
+float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
+
+// value noise 2D (smooth, 0..1)
+float noise(vec2 p) {
+ vec2 i = floor(p), f = fract(p);
+ vec2 u = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x),
+ mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
+}
+
+// fractal brownian motion, 5 octaves (constant loop bound)
+float fbm(vec2 p) {
+ float v = 0.0, a = 0.5;
+ mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
+ for (int i = 0; i < 5; i++) { v += a * noise(p); p = rot * p * 2.02; a *= 0.5; }
+ return v;
+}
+
+mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }
+
+// cosine palette (IQ): t in 0..1
+vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(TAU * (c * t + d)); }
+
+// filmic-ish tonemap + gamma
+vec3 tonemap(vec3 c) { c = c / (1.0 + c); return pow(clamp(c, 0.0, 1.0), vec3(1.0 / 2.2)); }
+"""
+
+_SHADER_TEMPLATE = """// src/shader.frag — {title}
+// CONTRACT (the harness prepends `#version 330 core` + these uniforms + `out vec4 fragColor`; DO NOT redeclare them):
+// uniform float u_time; uniform vec2 u_resolution; uniform vec2 u_mouse; uniform int u_frame;
+// uniform sampler2D u_prev; (previous frame of this pass) uniform sampler2D u_noise; (256x256 RGBA noise, repeat)
+// uniform sampler2D u_buffer_a; (output of src/buffer_a.frag when that file exists)
+// iTime / iResolution / iFrame / iMouse / iChannel0(=u_prev) / iChannel1(=u_noise) are #defined for Shadertoy ports.
+// Entry: void mainImage(out vec4 fragColor, in vec2 fragCoord) — fragCoord in pixels, origin BOTTOM-LEFT.
+// Helpers available from src/common.glsl: hash11 hash12 hash22 noise fbm rot2 palette tonemap PI TAU.
+// Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s. Everything must MOVE with u_time.
+//
+// PLAN — {summary}
+// Style: {style}
+{passes}
+{visuals}
+// Motion: {motion}
+
+void mainImage(out vec4 fragColor, in vec2 fragCoord) {{
+ vec2 uv = fragCoord / u_resolution.xy; // 0..1
+ vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // aspect-correct, centred
+ float t = u_time;
+
+ // TODO replace this placeholder look with the plan's passes above
+ vec3 sky = mix(vec3(0.95, 0.55, 0.25), vec3(0.10, 0.20, 0.45), smoothstep(-0.2, 0.6, p.y));
+ vec2 sunPos = vec2(0.35 * cos(t * 0.3), 0.15 + 0.1 * sin(t * 0.3));
+ float sun = exp(-40.0 * length(p - sunPos));
+ float haze = fbm(p * 3.0 + vec2(t * 0.15, 0.0));
+ vec3 col = sky + vec3(1.0, 0.8, 0.5) * sun + 0.25 * haze * vec3(0.9, 0.7, 0.6);
+ col *= 1.0 - 0.35 * length(p); // vignette
+ fragColor = vec4(tonemap(col), 1.0);
+}}
+"""
+
+
+def _comment_lines(prefix: str, items: list[str]) -> str:
+ if not items:
+ return f"// {prefix}: (none)"
+ return "\n".join(f"// TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
+
+
+def shader_source(plan: GraphicsPlan | None) -> str:
+ title = plan.title if plan else "untitled shader"
+ summary = plan.summary if plan else ""
+ style = plan.style if plan else ""
+ motion = plan.motion if plan else "animate with u_time"
+ duration = plan.duration_s if plan else 8.0
+ passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
+ visuals = list(plan.key_visuals) if plan else []
+ return _SHADER_TEMPLATE.format(
+ title=title, summary=summary, style=style, motion=motion, duration=duration,
+ passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
+ )
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
+ gplan = plan if isinstance(plan, GraphicsPlan) else None
+ ws.src.mkdir(parents=True, exist_ok=True)
+ common = ws.src / "common.glsl"
+ shader = ws.src / "shader.frag"
+ common.write_text(COMMON_GLSL)
+ shader.write_text(shader_source(gplan))
+ return [common, shader]
diff --git a/harness/codeverse/languages/glsl_shader/wrap.py b/harness/codeverse/languages/glsl_shader/wrap.py
new file mode 100644
index 00000000..ebd4d2ff
--- /dev/null
+++ b/harness/codeverse/languages/glsl_shader/wrap.py
@@ -0,0 +1,170 @@
+"""Wrap an agent's Shadertoy-style fragment shader into a compilable GLSL 330 program.
+
+The harness owns the ``#version`` line, the uniform block and the ``main``
+trampoline; the agent writes only the body (``mainImage(out vec4 fragColor,
+in vec2 fragCoord)`` or a plain ``main()`` writing the harness-declared ``fragColor``).
+``compose`` returns the full source plus a :class:`LineMap` so compiler
+messages (``0:LINE(COL)`` / ``0(LINE)`` / ``ERROR: 0:LINE:`` variants) map back
+to ``src/shader.frag`` / ``src/common.glsl`` line numbers.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+
+UNIFORM_NAMES: tuple[str, ...] = ("u_time", "u_resolution", "u_mouse", "u_frame", "u_prev", "u_noise", "u_buffer_a")
+
+HEADER = """#version 330 core
+// ---- harness header (do not write these lines yourself) ----
+uniform float u_time; // seconds
+uniform vec2 u_resolution; // pixels
+uniform vec2 u_mouse; // pixels (always 0,0 headless)
+uniform int u_frame; // frame counter
+uniform sampler2D u_prev; // previous frame of THIS pass (feedback)
+uniform sampler2D u_noise; // 256x256 RGBA white noise, repeat, linear
+uniform sampler2D u_buffer_a;// output of src/buffer_a.frag (when present)
+#define iTime u_time
+#define iResolution vec3(u_resolution, 1.0)
+#define iFrame u_frame
+#define iMouse vec4(u_mouse, 0.0, 0.0)
+#define iTimeDelta (1.0/30.0)
+#define iChannel0 u_prev
+#define iChannel1 u_noise
+out vec4 fragColor; // the ONLY output; write it in mainImage()/main()
+"""
+
+MAIN_IMAGE_TRAILER = """
+// ---- harness trailer ----
+void main() { mainImage(fragColor, gl_FragCoord.xy); }
+"""
+
+_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.S)
+_LINE_COMMENT = re.compile(r"//[^\n]*")
+_MAIN_IMAGE = re.compile(r"\bvoid\s+mainImage\s*\(")
+_PLAIN_MAIN = re.compile(r"\bvoid\s+main\s*\(\s*(void)?\s*\)")
+_OUT_DECL = re.compile(r"\bout\s+vec4\s+\w+\s*;")
+
+
+@dataclass(frozen=True)
+class Segment:
+ file: str # "src/shader.frag" | "src/common.glsl" | "harness"
+ start: int # 1-based first line in the composed source
+ n_lines: int
+
+ @property
+ def end(self) -> int:
+ return self.start + self.n_lines - 1
+
+
+@dataclass
+class LineMap:
+ segments: list[Segment] = field(default_factory=list)
+
+ def locate(self, line: int) -> tuple[str, int]:
+ """Composed line → (file, line-in-file); harness lines map to ("harness", line)."""
+ for s in self.segments:
+ if s.start <= line <= s.end:
+ return s.file, line - s.start + 1
+ return "harness", line
+
+
+@dataclass
+class Composed:
+ source: str
+ line_map: LineMap
+ convention: str # "mainImage" | "main"
+ uses_feedback: bool
+
+
+def strip_comments(text: str) -> str:
+ """Blank out comments but keep every newline so line numbers stay valid."""
+ def _blank(m: re.Match[str]) -> str:
+ return re.sub(r"[^\n]", " ", m.group(0))
+
+ return _LINE_COMMENT.sub(_blank, _BLOCK_COMMENT.sub(_blank, text))
+
+
+def detect_convention(shader_src: str) -> str:
+ shader_src = strip_comments(shader_src)
+ if _MAIN_IMAGE.search(shader_src):
+ return "mainImage"
+ if _PLAIN_MAIN.search(shader_src):
+ return "main"
+ return "mainImage" # trailer will surface "mainImage undeclared" at compile time → clear error
+
+
+def _count(text: str) -> int:
+ return text.count("\n") + (0 if text.endswith("\n") else 1)
+
+
+def compose(shader_src: str, common_src: str | None = None, *, shader_file: str = "src/shader.frag",
+ common_file: str = "src/common.glsl") -> Composed:
+ """Header + common + shader (+ trailer) with a line map back to the agent files."""
+ convention = detect_convention(shader_src)
+ pieces: list[tuple[str, str]] = [("harness", HEADER)]
+ if common_src and common_src.strip():
+ body = common_src if common_src.endswith("\n") else common_src + "\n"
+ pieces.append((common_file, body))
+ body = shader_src if shader_src.endswith("\n") else shader_src + "\n"
+ pieces.append((shader_file, body))
+ if convention == "mainImage":
+ pieces.append(("harness", MAIN_IMAGE_TRAILER))
+ segments: list[Segment] = []
+ cursor = 1
+ out: list[str] = []
+ for name, text in pieces:
+ n = _count(text)
+ segments.append(Segment(name, cursor, n))
+ cursor += n
+ out.append(text)
+ src = "".join(out)
+ code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "")
+ uses_feedback = "u_prev" in code or "iChannel0" in code
+ return Composed(source=src, line_map=LineMap(segments), convention=convention, uses_feedback=uses_feedback)
+
+
+# --------------------------------------------------------------------------- compiler messages
+# Mesa: "0:12(5): error: `foo' undeclared" · NVIDIA: "0(12) : error C1008: ..." · ANGLE/ES: "ERROR: 0:12: 'foo' : undeclared"
+_MSG_PATTERNS = (
+ re.compile(r"^\s*(?P<src>\d+):(?P<line>\d+)\((?P<col>\d+)\):\s*(?P<kind>error|warning):\s*(?P<msg>.*)$"),
+ re.compile(r"^\s*(?P<src>\d+)\((?P<line>\d+)\)\s*:\s*(?P<kind>error|warning)\s*(?P<msg>.*)$"),
+ re.compile(r"^\s*(?P<kind>ERROR|WARNING):\s*(?P<src>\d+):(?P<line>\d+):\s*(?P<msg>.*)$"),
+)
+
+
+@dataclass(frozen=True)
+class GlslMessage:
+ kind: str # error | warning
+ line: int # composed line
+ message: str
+ file: str = ""
+ file_line: int = 0
+
+ def text(self) -> str:
+ loc = f"{self.file}:{self.file_line}" if self.file else f"line {self.line}"
+ return f"{loc}: {self.kind}: {self.message}"
+
+
+def parse_glsl_log(log: str, line_map: LineMap | None = None) -> list[GlslMessage]:
+ """Parse a GLSL info log (any driver dialect) into messages mapped to agent files."""
+ out: list[GlslMessage] = []
+ for raw in (log or "").splitlines():
+ for pat in _MSG_PATTERNS:
+ m = pat.match(raw)
+ if not m:
+ continue
+ line = int(m.group("line"))
+ kind = m.group("kind").lower()
+ msg = m.group("msg").strip()
+ f, fl = line_map.locate(line) if line_map else ("", 0)
+ out.append(GlslMessage(kind=kind, line=line, message=msg, file=f, file_line=fl))
+ break
+ return out
+
+
+def first_error(messages: list[GlslMessage]) -> GlslMessage | None:
+ for m in messages:
+ if m.kind == "error":
+ return m
+ return None
diff --git a/harness/codeverse/languages/opengl_python/__init__.py b/harness/codeverse/languages/opengl_python/__init__.py
new file mode 100644
index 00000000..67eb7eb8
--- /dev/null
+++ b/harness/codeverse/languages/opengl_python/__init__.py
@@ -0,0 +1,5 @@
+"""opengl_python language: raw OpenGL (moderngl) programs rendered headless by the harness."""
+
+from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
+
+__all__ = ["OpenGLPythonRuntime"]
diff --git a/harness/codeverse/languages/opengl_python/lint.py b/harness/codeverse/languages/opengl_python/lint.py
new file mode 100644
index 00000000..9a154658
--- /dev/null
+++ b/harness/codeverse/languages/opengl_python/lint.py
@@ -0,0 +1,162 @@
+"""AST lint for ``src/program.py`` (raw moderngl program).
+
+Rules (gate ``lint:opengl_python``, ``data["kind"]`` names the rule):
+* syntax must parse; ``setup(ctx, width, height)`` and ``render(ctx, state, t, frame, fbo)`` must exist;
+* imports restricted to an allow-list (moderngl, numpy, math, random, struct, array, pathlib,
+ typing, dataclasses, itertools, functools, collections, colorsys);
+* no window / input libs (glfw, pygame, pyglet, PyQt…), no os / sys / subprocess / socket / requests;
+* no ``open()`` / exec / eval / __import__ / compile (GLSL travels as inline strings or via
+ ``Path(__file__).with_name("x.glsl").read_text()``);
+* no ``time.time()`` / ``datetime.now()`` / unseeded randomness (frames must be deterministic in ``t``);
+* ``moderngl.create_context`` / ``create_standalone_context`` inside the program (the harness owns the context);
+* GLSL strings in the file get a light ``#version`` check (must be ``330 core`` or absent → warn).
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.workspace import Workspace
+
+GATE = "lint:opengl_python"
+PROGRAM = "src/program.py"
+ALLOWED_MODULES: frozenset[str] = frozenset({
+ "moderngl", "numpy", "math", "random", "struct", "array", "pathlib", "typing", "dataclasses", "itertools",
+ "functools", "collections", "colorsys", "__future__", "enum",
+})
+WINDOW_LIBS = {"glfw", "pygame", "pyglet", "PyQt5", "PyQt6", "PySide2", "PySide6", "tkinter", "moderngl_window", "sdl2", "wx", "OpenGL"}
+DANGEROUS_MODULES = {"os", "sys", "subprocess", "socket", "requests", "urllib", "http", "shutil", "ctypes", "importlib",
+ "multiprocessing", "threading", "signal", "pickle", "tempfile", "io", "time", "datetime"}
+FORBIDDEN_CALLS = {"open", "exec", "eval", "compile", "__import__", "input", "exit", "quit", "breakpoint"}
+MAX_CHARS = 120_000
+_VERSION_RE = re.compile(r"#\s*version\s+(\d+)(?:\s+(\w+))?")
+
+
+def _finding(sev: Severity, kind: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=PROGRAM, message=(f"{PROGRAM}:{line}: " if line else f"{PROGRAM}: ") + msg,
+ fix_hint=hint, data={"kind": kind, "line": line, "file": PROGRAM})
+
+
+def _root(name: str) -> str:
+ return name.split(".", 1)[0]
+
+
+class _Visitor(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.findings: list[GateFinding] = []
+ self.funcs: dict[str, ast.FunctionDef] = {}
+ self.seeded = False
+ self.uses_random = False
+
+ # imports -------------------------------------------------------------
+ def _check_module(self, name: str, line: int) -> None:
+ root = _root(name)
+ if root in WINDOW_LIBS:
+ self.findings.append(_finding(Severity.ERROR, "window_lib", f"imports `{name}` (window / input library)",
+ "the harness creates the context and framebuffer; draw into the fbo it passes — no window", line))
+ elif root in DANGEROUS_MODULES:
+ self.findings.append(_finding(Severity.ERROR, "forbidden_import", f"imports `{name}` (not allowed in a rendering program)",
+ "allowed: moderngl, numpy, math, random, struct, array, pathlib, typing, dataclasses, itertools, "
+ "functools, collections, colorsys", line))
+ elif root not in ALLOWED_MODULES:
+ self.findings.append(_finding(Severity.ERROR, "forbidden_import", f"imports `{name}` which is outside the allow-list",
+ "use only moderngl + numpy + stdlib math/random/struct/array/pathlib", line))
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ self._check_module(a.name, node.lineno)
+ self.generic_visit(node)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ if node.module:
+ self._check_module(node.module, node.lineno)
+ self.generic_visit(node)
+
+ # calls ---------------------------------------------------------------
+ def visit_Call(self, node: ast.Call) -> None:
+ fn = node.func
+ name = fn.id if isinstance(fn, ast.Name) else None
+ attr = fn.attr if isinstance(fn, ast.Attribute) else None
+ base = fn.value.id if isinstance(fn, ast.Attribute) and isinstance(fn.value, ast.Name) else None
+ if name in FORBIDDEN_CALLS:
+ self.findings.append(_finding(Severity.ERROR, "forbidden_call", f"calls `{name}()`",
+ "no file/console IO: put GLSL in triple-quoted strings, or Path(__file__).with_name('x.glsl').read_text()",
+ node.lineno))
+ if attr in ("create_context", "create_standalone_context") and base == "moderngl":
+ self.findings.append(_finding(Severity.ERROR, "own_context", "creates its own moderngl context",
+ "use the `ctx` passed to setup()/render(); never create a context or window", node.lineno))
+ if base == "time" and attr in ("time", "perf_counter", "monotonic"):
+ self.findings.append(_finding(Severity.ERROR, "wall_clock", "reads the wall clock", "use the `t` argument of render(); frames must be a pure function of t", node.lineno))
+ if base == "random" and attr == "seed":
+ self.seeded = True
+ if base == "random" and attr in ("random", "uniform", "randint", "gauss", "choice", "shuffle"):
+ self.uses_random = True
+ if base in ("np", "numpy") and attr == "seed":
+ self.seeded = True
+ if attr in ("write_text", "write_bytes", "unlink", "mkdir", "rmdir", "rename"):
+ self.findings.append(_finding(Severity.ERROR, "file_write", f"calls `.{attr}()` (file system write)", "programs never write files", node.lineno))
+ if attr == "read_text" or attr == "read_bytes":
+ self.findings.append(_finding(Severity.INFO, "read_file", f"reads a file via `.{attr}()` — only src/*.glsl shipped next to program.py is allowed",
+ "Path(__file__).with_name('x.glsl').read_text()", node.lineno))
+ self.generic_visit(node)
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ self.funcs[node.name] = node
+ self.generic_visit(node)
+
+ def visit_Constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str) and "#version" in node.value:
+ m = _VERSION_RE.search(node.value)
+ if m and (m.group(1) != "330" or (m.group(2) or "core") != "core"):
+ self.findings.append(_finding(Severity.WARN, "glsl_version", f"GLSL string uses `#version {m.group(1)} {m.group(2) or ''}`; the context is GL 3.3 core",
+ "use `#version 330 core` in every shader string", node.lineno))
+ if isinstance(node.value, str) and "gl_FragColor" in node.value:
+ self.findings.append(_finding(Severity.ERROR, "legacy_glsl", "GLSL string uses gl_FragColor (GLSL 1.x)",
+ "declare `out vec4 fragColor;` and write it (GLSL 330 core)", node.lineno))
+ if isinstance(node.value, str) and ("attribute " in node.value or "varying " in node.value) and "#version" in node.value:
+ self.findings.append(_finding(Severity.ERROR, "legacy_glsl", "GLSL string uses attribute/varying (GLSL 1.x)",
+ "use `in` / `out` qualifiers (GLSL 330 core)", node.lineno))
+
+
+def lint_source(text: str) -> list[GateFinding]:
+ findings: list[GateFinding] = []
+ if len(text) > MAX_CHARS:
+ findings.append(_finding(Severity.WARN, "too_long", f"file is {len(text)} chars", "keep the program focused"))
+ try:
+ tree = ast.parse(text)
+ except SyntaxError as e:
+ findings.append(_finding(Severity.ERROR, "syntax", f"SyntaxError: {e.msg}", "fix the syntax at this line", e.lineno))
+ return findings
+ v = _Visitor()
+ v.visit(tree)
+ findings.extend(v.findings)
+ for fn, nargs in (("setup", 3), ("render", 5)):
+ node = v.funcs.get(fn)
+ if node is None:
+ findings.append(_finding(Severity.ERROR, "missing_entry", f"missing `def {fn}(...)`",
+ "def setup(ctx, width, height) -> state and def render(ctx, state, t, frame, fbo) -> None"))
+ elif len(node.args.args) != nargs and node.args.vararg is None:
+ findings.append(_finding(Severity.ERROR, "bad_signature", f"`{fn}` takes {len(node.args.args)} positional args, expected {nargs}",
+ "setup(ctx, width, height) / render(ctx, state, t, frame, fbo)", node.lineno))
+ if v.uses_random and not v.seeded:
+ findings.append(_finding(Severity.WARN, "unseeded_random", "uses random.* without random.seed(...)",
+ "call random.seed(0) / np.random.default_rng(0) in setup() so frames are reproducible"))
+ return findings
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ p = ws.root / PROGRAM
+ if not p.is_file():
+ f = [_finding(Severity.ERROR, "missing_entry", f"{PROGRAM} is missing",
+ "create src/program.py with setup(ctx, width, height) and render(ctx, state, t, frame, fbo)")]
+ return GateReport(gate=GATE, passed=False, findings=f)
+ findings = lint_source(p.read_text(errors="replace"))
+ for extra in sorted(ws.src.rglob("*.py")):
+ rel = str(extra.relative_to(ws.root))
+ if rel != PROGRAM:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel}: extra python module is ignored by the harness",
+ fix_hint="keep all code in src/program.py (GLSL may live in src/*.glsl)", data={"kind": "stray_file", "file": rel}))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings)
diff --git a/harness/codeverse/languages/opengl_python/runtime.py b/harness/codeverse/languages/opengl_python/runtime.py
new file mode 100644
index 00000000..d2a8d9a1
--- /dev/null
+++ b/harness/codeverse/languages/opengl_python/runtime.py
@@ -0,0 +1,97 @@
+"""OpenGLPythonRuntime: skeleton → AST lint → build (import + render frames in a moderngl subprocess).
+
+``src/program.py`` defines ``setup(ctx, width, height) -> state`` and
+``render(ctx, state, t, frame, fbo)``. The harness runner imports it by path
+(cwd = ``src/``), binds + clears a float RGBA framebuffer per frame, calls
+``render`` at the judged times, reads back (y-flipped) PNGs, detects NaN/Inf.
+Python exceptions are mapped to ``src/program.py:LINE``; GLSL compile errors
+inside the program surface as moderngl ``Error`` with the driver's info log.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan
+from codeverse.languages.glsl_shader.gl_build import (
+ finish_build,
+ judge_times,
+ load_plan,
+ preview_times,
+ resolution_for,
+ traceback_location,
+)
+from codeverse.languages.glsl_shader.wrap import parse_glsl_log
+from codeverse.languages.opengl_python.lint import PROGRAM, lint_workspace
+from codeverse.languages.opengl_python.skeleton import write_skeleton
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.gl_render import GlHost, GlResult
+from codeverse.workspace import Workspace
+
+CONTRACT_FALLBACK = """src/program.py — raw moderngl program: `def setup(ctx, width, height) -> state` (programs, VAOs, textures,
+FBOs; GLSL 330 core inline strings) and `def render(ctx, state, t, frame, fbo)` (draw the frame at time t into the given,
+already bound framebuffer; multi-pass via your own FBOs, finish with fbo.use()). No window, no context creation, no clock,
+no file IO (except src/*.glsl next to program.py). Imports: moderngl, numpy, math, random, struct, array, pathlib."""
+
+
+class OpenGLPythonRuntime:
+ language = Language.OPENGL_PYTHON
+ entry_globs: tuple[str, ...] = ("src/program.py", "src/*.glsl")
+
+ def __init__(self, *, host: GlHost | None = None):
+ self._host = host
+
+ # ------------------------------------------------------------------ contract
+ def contract_doc(self) -> str:
+ try:
+ return load_text("opengl_python/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_FALLBACK
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "opengl_python" / "cookbook.md"
+
+ # ------------------------------------------------------------------ skeleton / lint
+ def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ # ------------------------------------------------------------------ build
+ def host(self, timeout_s: float | None = None) -> GlHost:
+ if self._host is not None:
+ return self._host
+ settings = get_settings()
+ return GlHost(gpu=settings.render.gpu, timeout_s=float(timeout_s or settings.limits.render_timeout_s))
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
+ preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ program = ws.root / PROGRAM
+ if not program.is_file():
+ res = GlResult(ok=False, mode="program", stage="lint", error_type="MissingEntry", error_message=f"{PROGRAM} is missing")
+ return finish_build(ws, res, language=self.language.value, error_file=PROGRAM)
+ plan = load_plan(ws)
+ w, h = resolution_for(plan)
+ if width and height:
+ w, h = int(width), int(height)
+ duration = plan.duration_s if plan else None
+ res = self.host(timeout_s).run_program(program, ws.artifacts, width=w, height=h, times=times or judge_times(duration),
+ extra_times=preview_times(duration) if preview else (), cwd=ws.src)
+ err_file, err_line, err_msg = "", None, None
+ if not res.ok:
+ err_file, err_line = traceback_location(res.traceback, program)
+ err_msg = f"{res.stage} failed: {res.error_type}: {res.error_message}"
+ glsl = parse_glsl_log(res.error_message)
+ if glsl:
+ res.error_type = "GlslCompileError"
+ err_msg += "\n(GLSL line numbers refer to the shader STRING inside program.py: " + \
+ "; ".join(f"line {m.line}: {m.message}" for m in glsl[:8]) + ")"
+ census = {"resolution": [w, h]}
+ motion_expected = bool(plan.motion.strip()) if plan else True
+ return finish_build(ws, res, language=self.language.value, error_file=err_file, error_line=err_line,
+ error_message=err_msg, census=census, motion_expected=motion_expected)
diff --git a/harness/codeverse/languages/opengl_python/skeleton.py b/harness/codeverse/languages/opengl_python/skeleton.py
new file mode 100644
index 00000000..b4b7ccae
--- /dev/null
+++ b/harness/codeverse/languages/opengl_python/skeleton.py
@@ -0,0 +1,164 @@
+"""Skeleton for the opengl_python language: a RUNNABLE ``src/program.py`` (background
+gradient pass + one rotating lit cube) that shows the exact API the harness calls —
+``setup(ctx, width, height) -> state`` and ``render(ctx, state, t, frame, fbo)`` —
+with the plan's passes / key visuals / motion as TODO comments."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.plan import GraphicsPlan, Plan
+from codeverse.workspace import Workspace
+
+_TEMPLATE = '''"""src/program.py — {title}
+
+CONTRACT (the harness imports this module in a headless moderngl process):
+ def setup(ctx, width, height) -> state create programs / VAOs / textures / FBOs ONCE; return any object
+ def render(ctx, state, t, frame, fbo) draw the frame at time t (seconds) into `fbo` (already bound + cleared)
+* `ctx` is a moderngl.Context (GL 3.3 core). Never create a context or window; never read the clock.
+* Multi-pass: render into your own FBOs, then call `fbo.use()` and draw the final image into it.
+* Deterministic: same t → same frame. Seed randomness. GLSL strings use `#version 330 core`.
+* Allowed imports: moderngl, numpy, math, random, struct, array, pathlib (+typing/dataclasses).
+Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s — everything must MOVE with t.
+
+PLAN — {summary}
+Style: {style}
+{passes}
+{visuals}
+Motion: {motion}
+"""
+import math
+
+import moderngl
+import numpy as np
+
+BACKGROUND_VERT = """#version 330 core
+in vec2 in_pos;
+out vec2 v_uv;
+void main() {{ v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }}
+"""
+BACKGROUND_FRAG = """#version 330 core
+uniform float u_time;
+in vec2 v_uv;
+out vec4 fragColor;
+void main() {{
+ vec3 top = vec3(0.08, 0.10, 0.25), bottom = vec3(0.85, 0.45, 0.30);
+ vec3 col = mix(bottom, top, smoothstep(0.0, 1.0, v_uv.y + 0.1 * sin(u_time * 0.5 + v_uv.x * 6.0)));
+ fragColor = vec4(col, 1.0);
+}}
+"""
+CUBE_VERT = """#version 330 core
+uniform mat4 u_mvp;
+uniform mat4 u_model;
+in vec3 in_pos;
+in vec3 in_normal;
+out vec3 v_normal;
+void main() {{ v_normal = mat3(u_model) * in_normal; gl_Position = u_mvp * vec4(in_pos, 1.0); }}
+"""
+CUBE_FRAG = """#version 330 core
+uniform vec3 u_color;
+in vec3 v_normal;
+out vec4 fragColor;
+void main() {{
+ vec3 n = normalize(v_normal);
+ float diff = max(dot(n, normalize(vec3(0.4, 0.8, 0.5))), 0.0);
+ fragColor = vec4(u_color * (0.25 + 0.75 * diff), 1.0);
+}}
+"""
+
+
+def _cube() -> np.ndarray:
+ """36 vertices: position (3) + normal (3), interleaved float32."""
+ faces = [((0, 0, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)),
+ ((0, 0, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1)),
+ ((1, 0, 0), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1)),
+ ((-1, 0, 0), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1)),
+ ((0, 1, 0), (-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1)),
+ ((0, -1, 0), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1))]
+ out = []
+ for n, a, b, c, d in faces:
+ for v in (a, b, c, a, c, d):
+ out.extend(v)
+ out.extend(n)
+ return np.array(out, dtype="f4") * np.tile([0.5, 0.5, 0.5, 1, 1, 1], 36).astype("f4")
+
+
+def _perspective(fov_deg: float, aspect: float, near: float, far: float) -> np.ndarray:
+ f = 1.0 / math.tan(math.radians(fov_deg) / 2.0)
+ m = np.zeros((4, 4), dtype="f4")
+ m[0, 0], m[1, 1] = f / aspect, f
+ m[2, 2], m[2, 3] = (far + near) / (near - far), (2 * far * near) / (near - far)
+ m[3, 2] = -1.0
+ return m
+
+
+def _look_at(eye, target, up=(0, 1, 0)) -> np.ndarray:
+ eye, target, up = np.array(eye, dtype="f4"), np.array(target, dtype="f4"), np.array(up, dtype="f4")
+ f = target - eye
+ f /= np.linalg.norm(f)
+ s = np.cross(f, up)
+ s /= np.linalg.norm(s)
+ u = np.cross(s, f)
+ m = np.identity(4, dtype="f4")
+ m[0, :3], m[1, :3], m[2, :3] = s, u, -f
+ m[:3, 3] = -m[:3, :3] @ eye
+ return m
+
+
+def _rot_y(a: float) -> np.ndarray:
+ c, s = math.cos(a), math.sin(a)
+ return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")
+
+
+def setup(ctx: moderngl.Context, width: int, height: int):
+ bg_prog = ctx.program(vertex_shader=BACKGROUND_VERT, fragment_shader=BACKGROUND_FRAG)
+ quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
+ bg_vao = ctx.vertex_array(bg_prog, [(quad, "2f", "in_pos")])
+ cube_prog = ctx.program(vertex_shader=CUBE_VERT, fragment_shader=CUBE_FRAG)
+ vbo = ctx.buffer(_cube().tobytes())
+ cube_vao = ctx.vertex_array(cube_prog, [(vbo, "3f 3f", "in_pos", "in_normal")])
+ proj = _perspective(45.0, width / height, 0.1, 100.0)
+ view = _look_at((0.0, 1.2, 3.0), (0.0, 0.0, 0.0))
+ # TODO build the plan's passes here (instancing, extra FBOs for post-processing, textures)
+ return {{"bg_prog": bg_prog, "bg_vao": bg_vao, "cube_prog": cube_prog, "cube_vao": cube_vao, "proj": proj, "view": view}}
+
+
+def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
+ fbo.use()
+ ctx.disable(moderngl.DEPTH_TEST)
+ state["bg_prog"]["u_time"].value = t
+ state["bg_vao"].render(mode=moderngl.TRIANGLE_STRIP)
+ ctx.enable(moderngl.DEPTH_TEST)
+ model = _rot_y(t * 0.8)
+ mvp = state["proj"] @ state["view"] @ model
+ state["cube_prog"]["u_mvp"].write(mvp.T.astype("f4").tobytes()) # column-major for GLSL
+ state["cube_prog"]["u_model"].write(model.T.astype("f4").tobytes())
+ state["cube_prog"]["u_color"].value = (0.9, 0.6, 0.2)
+ state["cube_vao"].render(mode=moderngl.TRIANGLES)
+ # TODO replace the placeholder cube with the plan's content; keep drawing into `fbo` last
+'''
+
+
+def _comment_lines(prefix: str, items: list[str]) -> str:
+ if not items:
+ return f"{prefix}: (none)"
+ return "\n".join(f" TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
+
+
+def program_source(plan: GraphicsPlan | None) -> str:
+ title = plan.title if plan else "untitled program"
+ passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
+ visuals = list(plan.key_visuals) if plan else []
+ return _TEMPLATE.format(
+ title=title, summary=plan.summary if plan else "", style=plan.style if plan else "",
+ motion=plan.motion if plan else "animate with t", duration=plan.duration_s if plan else 8.0,
+ passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
+ )
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
+ gplan = plan if isinstance(plan, GraphicsPlan) else None
+ ws.src.mkdir(parents=True, exist_ok=True)
+ p = ws.src / "program.py"
+ p.write_text(program_source(gplan))
+ return [p]
diff --git a/harness/codeverse/languages/opengl_python/wrappers/run_gl.py b/harness/codeverse/languages/opengl_python/wrappers/run_gl.py
new file mode 100644
index 00000000..5c0de2be
--- /dev/null
+++ b/harness/codeverse/languages/opengl_python/wrappers/run_gl.py
@@ -0,0 +1,291 @@
+"""Standalone moderngl runner (never imports codeverse).
+
+Usage: ``python run_gl.py --job job.json``
+
+``job.json``::
+
+ {"mode": "shader" | "program",
+ "out_dir": "...", # frames/ + result.json are written here
+ "width": 1280, "height": 720,
+ "times": [0.0, 1.0, 2.5], # judged frames
+ "extra_times": [0.5, 1.5], # gif-only frames (optional)
+ "fps": 30, # simulation step for feedback shaders
+ "max_steps": 240,
+ # shader mode: fully wrapped sources (header already prepended by the harness)
+ "frag_src": "...", "buffer_a_src": "..." | null, "feedback": false,
+ # program mode
+ "program_path": "/abs/src/program.py", "program_cwd": "/abs/src"}
+
+Writes ``<out_dir>/frames/f<NN>_t<T>.png`` (8-bit RGB, top-down) and
+``<out_dir>/gl_result.json``::
+
+ {"ok": bool, "stage": "context|compile|compile_buffer_a|setup|render|import",
+ "error_type": "", "error_message": "", "traceback": "", "renderer": "...",
+ "frames": [{"index", "time", "path", "judge": bool, "nan": int, "inf": int,
+ "mean": float}], "duration_ms": int}
+
+Exit code 0 whenever gl_result.json was written (even for agent errors); 3 when the
+GL context could not be created (the harness retries with another driver env).
+"""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import importlib.util
+import io
+import json
+import os
+import sys
+import time
+import traceback
+from pathlib import Path
+
+import numpy as np
+
+VERT = """#version 330 core
+in vec2 in_pos;
+void main() { gl_Position = vec4(in_pos, 0.0, 1.0); }
+"""
+
+EXIT_CONTEXT = 3
+
+
+RESULT_NAME = "gl_result.json"
+
+
+def _write_result(out_dir: Path, data: dict) -> None:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / RESULT_NAME).write_text(json.dumps(data, indent=1, default=str))
+
+
+def _frame_path(out_dir: Path, index: int, t: float) -> Path:
+ return out_dir / "frames" / f"f{index:02d}_t{t:06.2f}.png"
+
+
+def _save_frame(raw: bytes, w: int, h: int, path: Path) -> dict:
+ """float32 RGBA readback (bottom-up) → top-down 8-bit PNG + nan/inf counts."""
+ from PIL import Image
+
+ arr = np.frombuffer(raw, dtype=np.float32).reshape(h, w, 4)[::-1]
+ nan = int(np.isnan(arr).sum())
+ inf = int(np.isinf(arr).sum())
+ rgb = np.nan_to_num(arr[..., :3], nan=0.0, posinf=1.0, neginf=0.0)
+ rgb = np.clip(rgb, 0.0, 1.0)
+ img = (rgb * 255.0 + 0.5).astype(np.uint8)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.fromarray(img, "RGB").save(path)
+ return {"nan": nan, "inf": inf, "mean": float(rgb.mean())}
+
+
+def _noise_texture(ctx, size: int = 256):
+ rng = np.random.default_rng(12345)
+ data = rng.integers(0, 256, size=(size, size, 4), dtype=np.uint8)
+ tex = ctx.texture((size, size), 4, data.tobytes())
+ tex.repeat_x = tex.repeat_y = True
+ tex.filter = (ctx.LINEAR, ctx.LINEAR)
+ return tex
+
+
+def _set_uniforms(prog, *, t: float, frame: int, w: int, h: int, units: dict) -> None:
+ members = set(prog)
+ if "u_time" in members:
+ prog["u_time"].value = float(t)
+ if "u_resolution" in members:
+ prog["u_resolution"].value = (float(w), float(h))
+ if "u_mouse" in members:
+ prog["u_mouse"].value = (0.0, 0.0)
+ if "u_frame" in members:
+ prog["u_frame"].value = int(frame)
+ for name, unit in units.items():
+ if name in members:
+ prog[name].value = unit
+
+
+class Pass:
+ """One fullscreen fragment pass with ping-pong float targets."""
+
+ def __init__(self, ctx, frag_src: str, w: int, h: int, quad):
+ self.prog = ctx.program(vertex_shader=VERT, fragment_shader=frag_src)
+ self.vao = ctx.vertex_array(self.prog, [(quad, "2f", "in_pos")])
+ self.tex = [ctx.texture((w, h), 4, dtype="f4") for _ in range(2)]
+ for t in self.tex:
+ t.filter = (ctx.LINEAR, ctx.LINEAR)
+ t.repeat_x = t.repeat_y = False
+ self.fbo = [ctx.framebuffer(color_attachments=[t]) for t in self.tex]
+ self.cur = 0
+
+ @property
+ def prev_tex(self):
+ return self.tex[1 - self.cur]
+
+ @property
+ def out_tex(self):
+ return self.tex[self.cur]
+
+ def draw(self, ctx, *, w: int, h: int, t: float, frame: int, samplers: dict):
+ units: dict = {}
+ for unit, (name, tex) in enumerate(samplers.items()):
+ tex.use(location=unit)
+ units[name] = unit
+ self.fbo[self.cur].use()
+ ctx.viewport = (0, 0, w, h)
+ self.fbo[self.cur].clear(0.0, 0.0, 0.0, 1.0)
+ _set_uniforms(self.prog, t=t, frame=frame, w=w, h=h, units=units)
+ self.vao.render(mode=ctx.TRIANGLE_STRIP)
+
+ def swap(self) -> None:
+ self.cur = 1 - self.cur
+
+
+def _schedule(job: dict) -> list[tuple[float, bool]]:
+ """(time, is_judge_frame) sorted by time."""
+ times = {float(t): True for t in job.get("times", [])}
+ for t in job.get("extra_times", []) or []:
+ times.setdefault(float(t), False)
+ return sorted(times.items())
+
+
+def run_shader(ctx, job: dict, out_dir: Path) -> dict:
+ import moderngl # noqa: F401 (already imported by caller; explicit for clarity)
+
+ w, h = int(job["width"]), int(job["height"])
+ quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
+ noise = _noise_texture(ctx)
+ try:
+ buffer_a = Pass(ctx, job["buffer_a_src"], w, h, quad) if job.get("buffer_a_src") else None
+ except Exception as e: # noqa: BLE001 — GLSL compile error → typed result
+ return {"ok": False, "stage": "compile_buffer_a", "error_type": type(e).__name__, "error_message": str(e)}
+ try:
+ image = Pass(ctx, job["frag_src"], w, h, quad)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "stage": "compile", "error_type": type(e).__name__, "error_message": str(e)}
+
+ schedule = _schedule(job)
+ feedback = bool(job.get("feedback")) or buffer_a is not None
+ fps = float(job.get("fps", 30))
+ frames: list[dict] = []
+
+ def step(t: float, frame: int) -> None:
+ if buffer_a is not None:
+ buffer_a.draw(ctx, w=w, h=h, t=t, frame=frame, samplers={"u_prev": buffer_a.prev_tex, "u_noise": noise})
+ buffer_a.swap()
+ samplers = {"u_prev": image.prev_tex, "u_noise": noise}
+ if buffer_a is not None:
+ samplers["u_buffer_a"] = buffer_a.prev_tex # just-rendered output (after swap)
+ image.draw(ctx, w=w, h=h, t=t, frame=frame, samplers=samplers)
+ image.swap()
+
+ def capture(index: int, t: float, judge: bool) -> None:
+ raw = image.fbo[1 - image.cur].read(components=4, dtype="f4") # last drawn
+ p = _frame_path(out_dir, index, t)
+ info = _save_frame(raw, w, h, p)
+ frames.append({"index": index, "time": t, "path": str(p), "judge": judge, **info})
+
+ try:
+ if not feedback:
+ for i, (t, judge) in enumerate(schedule):
+ step(t, int(round(t * fps)))
+ capture(i, t, judge)
+ else:
+ t_end = schedule[-1][0] if schedule else 0.0
+ n_steps = int(round(t_end * fps)) + 1
+ max_steps = int(job.get("max_steps", 240))
+ dt = 1.0 / fps
+ if n_steps > max_steps:
+ n_steps, dt = max_steps, t_end / max(1, max_steps - 1)
+ pending = list(schedule)
+ idx = 0
+ for k in range(n_steps):
+ t = k * dt
+ step(t, k)
+ while pending and (pending[0][0] <= t + 1e-9 or k == n_steps - 1):
+ target, judge = pending.pop(0)
+ capture(idx, target, judge)
+ idx += 1
+ ctx.finish()
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "stage": "render", "error_type": type(e).__name__, "error_message": str(e),
+ "traceback": traceback.format_exc()[-3000:], "frames": frames}
+ return {"ok": True, "stage": "render", "frames": frames, "feedback": feedback}
+
+
+def run_program(ctx, job: dict, out_dir: Path) -> dict:
+ w, h = int(job["width"]), int(job["height"])
+ path = Path(job["program_path"])
+ cwd = Path(job.get("program_cwd") or path.parent)
+ os.chdir(cwd)
+ sys.path.insert(0, str(cwd))
+ try:
+ spec = importlib.util.spec_from_file_location("agent_program", str(path))
+ if spec is None or spec.loader is None:
+ raise ImportError(f"cannot load {path}")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ setup = getattr(module, "setup", None)
+ render = getattr(module, "render", None)
+ if not callable(setup) or not callable(render):
+ raise AttributeError("program.py must define setup(ctx, width, height) and render(ctx, state, t, frame, fbo)")
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "stage": "import", "error_type": type(e).__name__, "error_message": str(e),
+ "traceback": traceback.format_exc()[-4000:]}
+ color = ctx.texture((w, h), 4, dtype="f4")
+ depth = ctx.depth_renderbuffer((w, h))
+ fbo = ctx.framebuffer(color_attachments=[color], depth_attachment=depth)
+ try:
+ fbo.use()
+ state = setup(ctx, w, h)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "stage": "setup", "error_type": type(e).__name__, "error_message": str(e),
+ "traceback": traceback.format_exc()[-4000:]}
+ frames: list[dict] = []
+ try:
+ for i, (t, judge) in enumerate(_schedule(job)):
+ fbo.use()
+ ctx.viewport = (0, 0, w, h)
+ fbo.clear(0.0, 0.0, 0.0, 1.0, depth=1.0)
+ render(ctx, state, float(t), i, fbo)
+ ctx.finish()
+ raw = fbo.read(components=4, dtype="f4")
+ p = _frame_path(out_dir, i, t)
+ info = _save_frame(raw, w, h, p)
+ frames.append({"index": i, "time": t, "path": str(p), "judge": judge, **info})
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "stage": "render", "error_type": type(e).__name__, "error_message": str(e),
+ "traceback": traceback.format_exc()[-4000:], "frames": frames}
+ return {"ok": True, "stage": "render", "frames": frames}
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--job", required=True)
+ ns = ap.parse_args(argv)
+ job = json.loads(Path(ns.job).read_text())
+ out_dir = Path(job["out_dir"])
+ t0 = time.time()
+ try:
+ import moderngl
+
+ ctx = moderngl.create_standalone_context(backend=job.get("backend", "egl"))
+ except Exception as e: # noqa: BLE001 — no GL at all: let the harness retry another driver env
+ _write_result(out_dir, {"ok": False, "stage": "context", "error_type": type(e).__name__, "error_message": str(e),
+ "traceback": traceback.format_exc()[-2000:], "duration_ms": int((time.time() - t0) * 1000)})
+ return EXIT_CONTEXT
+ renderer = str(ctx.info.get("GL_RENDERER", ""))
+ # agent prints must not corrupt anything: capture them
+ captured = io.StringIO()
+ real_stdout = sys.stdout
+ sys.stdout = captured
+ try:
+ res = run_program(ctx, job, out_dir) if job["mode"] == "program" else run_shader(ctx, job, out_dir)
+ finally:
+ sys.stdout = real_stdout
+ res.update({"renderer": renderer, "duration_ms": int((time.time() - t0) * 1000), "stdout": captured.getvalue()[-4000:]})
+ _write_result(out_dir, res)
+ with contextlib.suppress(Exception):
+ ctx.release()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/harness/codeverse/languages/scene_threejs/assemble.py b/harness/codeverse/languages/scene_threejs/assemble.py
index 644ac575..33677c69 100644
--- a/harness/codeverse/languages/scene_threejs/assemble.py
+++ b/harness/codeverse/languages/scene_threejs/assemble.py
@@ -27,7 +27,7 @@ from codeverse.conventions import to_pascal, to_snake
from codeverse.workspace import Workspace
PROBE_REL = "src/_c3v_assemble_probe.js"
-_PREFIX = "[c3v-assemble]"
+_PREFIX = "[3dcv-assemble]"
_SUN_RE = re.compile(r"export\s+const\s+SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)")
@@ -240,9 +240,10 @@ def _cam_literal(c: CameraPlan) -> str:
def render_scene_js(zones: list[str], cameras: list[CameraPlan], glbs: list[str], *, env_ok: bool = True) -> str:
"""Deterministic src/scene.js source for the given healthy zone snake names."""
imports = "\n".join(f"import {{ build as build{to_pascal(z)} }} from './zones/{z}.js';" for z in zones)
- calls = "\n".join(f" addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
+ calls = "\n".join(f" await addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
env_import = "import { buildEnv, heightAt } from './env.js';" if env_ok else ""
- env_build = " const env = buildEnv(ctx) || {};\n ctx.env = env;" if env_ok else " const env = {};"
+ # buildEnv/build may be async (lint + the assembler probe both accept it): await consistently
+ env_build = " const env = (await buildEnv(ctx)) || {};\n ctx.env = env;" if env_ok else " const env = {};"
height = "heightAt" if env_ok else "() => 0"
glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
cams = "\n".join(_cam_literal(c) for c in cameras)
@@ -262,8 +263,8 @@ export async function createScene({{ renderer, loaders }}) {{
{env_build}
const zones = [];
- const addZone = (build, name) => {{
- const g = build(ctx);
+ const addZone = async (build, name) => {{
+ const g = await build(ctx);
if (!g || !g.isObject3D) throw new Error(`zone ${{name}}: build(ctx) must return a THREE.Group`);
if (!g.name) g.name = name;
scene.add(g);
diff --git a/harness/codeverse/languages/threejs/contract.py b/harness/codeverse/languages/threejs/contract.py
index 1a5c3abe..a2a8fa63 100644
--- a/harness/codeverse/languages/threejs/contract.py
+++ b/harness/codeverse/languages/threejs/contract.py
@@ -31,5 +31,8 @@ triangles well under 600k. Parts must physically touch (no floating pieces) and
interpenetrate visibly.
Build: the harness runs `build(THREE)` in node, validates the group (≥1 mesh, finite
-bbox, no NaN), and exports `artifacts/object.glb` with one named node per part.
+bbox, no NaN), calls an optional exported `selfcheck(THREE, root)` (a throw fails the
+build with your message), bakes `InstancedMesh` copies into named meshes, and exports
+`artifacts/object.glb` with one named node per part — exactly where you placed it (no
+automatic drop-to-ground / re-centring; off-placement is warned and gated instead).
"""
diff --git a/harness/codeverse/languages/threejs/runtime.py b/harness/codeverse/languages/threejs/runtime.py
index d9ec5af7..32a698da 100644
--- a/harness/codeverse/languages/threejs/runtime.py
+++ b/harness/codeverse/languages/threejs/runtime.py
@@ -11,6 +11,7 @@ from codeverse.config import get_settings
from codeverse.contracts.artifacts import BuildResult, GateReport
from codeverse.contracts.common import Language
from codeverse.contracts.plan import Plan
+from codeverse.conventions import to_snake
from codeverse.languages.threejs.contract import CONTRACT_FALLBACK
from codeverse.languages.threejs.lint import lint_workspace
from codeverse.languages.threejs.skeleton import write_skeleton
@@ -82,7 +83,7 @@ class ThreeJsRuntime:
return result
if res.rc != 0 or not (res.last_json or {}).get("ok") or not glb.is_file():
- result = self._from_error_record(res)
+ result = self._from_error_record(res, ws)
else:
census_data: dict[str, Any] = {}
if census.is_file():
@@ -111,18 +112,31 @@ class ThreeJsRuntime:
error_type=etype, error_message=message[:2000], duration_ms=res.duration_ms,
)
- def _from_error_record(self, res: NodeResult) -> BuildResult:
+ def _from_error_record(self, res: NodeResult, ws: Workspace | None = None) -> BuildResult:
rec = res.last_json or {}
err = rec.get("error") if isinstance(rec.get("error"), dict) else None
if err is None:
tail = res.stderr_tail.strip().splitlines()
return self._failure(res, "ExportError", tail[-1] if tail else f"export_glb exited {res.rc} without an error record")
result = self._failure(res, str(err.get("type", "Error")), str(err.get("message", "")))
- result.error_file = str(err.get("file", "") or ("" if err.get("frames") else ENTRY))
+ result.error_file = str(err.get("file", "") or self._part_file(ws, err.get("part")) or ("" if err.get("frames") else ENTRY))
result.error_line = err.get("line") if isinstance(err.get("line"), int) else None
- result.census = {"frames": err.get("frames", []), "stack": err.get("stack", "")}
+ result.census = {"frames": err.get("frames", []), "stack": err.get("stack", ""), "part": str(err.get("part", "") or "")}
return result
+ @staticmethod
+ def _part_file(ws: Workspace | None, part: object) -> str:
+ """``src/parts/<snake>.js`` for the plan part named in a validation error (when that file exists).
+
+ Contract errors raised by the exporter (NaN geometry, empty bbox) carry no src
+ frame — the throw site is export_glb.mjs — but name the offending part; the
+ naming convention (``conventions.to_snake``) turns that into the file to repair.
+ """
+ if ws is None or not isinstance(part, str) or not part.strip():
+ return ""
+ rel = Path("src") / "parts" / f"{to_snake(part)}.js"
+ return rel.as_posix() if (ws.root / rel).is_file() else ""
+
@staticmethod
def _write_build_json(ws: Workspace, result: BuildResult) -> None:
ws.write_json(ws.artifacts / BUILD_JSON, result)
diff --git a/harness/codeverse/languages/urdf/CONTRACT.md b/harness/codeverse/languages/urdf/CONTRACT.md
index 06c05942..0978b395 100644
--- a/harness/codeverse/languages/urdf/CONTRACT.md
+++ b/harness/codeverse/languages/urdf/CONTRACT.md
@@ -16,7 +16,8 @@ its range looking for collisions / floating parts, and renders an articulation s
* Z is UP, **-Y is the FRONT** of the object, +X its right. Meters. Radians.
* The object stands on the ground: lowest point at z = 0, footprint centred on the Z axis.
-* Link names are `snake_case` part names: `base`, `door`, `drawer`, `lid`, `handle_left`.
+* Link names are `snake_case` part names: `base`, `door`, `drawer`, `lid`, `handle_left`
+ (the plan's PascalCase spelling is accepted too — identical in both files, never `Door.001`).
Never state words (`door_open`): states come from joints.
* The bpy object for a link is named **exactly** like the link (case-sensitive).
@@ -56,8 +57,10 @@ door = box("door", (0, -0.21, 0.40), (0.58, 0.02, 0.78)) # front panel (fron
URDF semantics (standard): a joint's `<origin>` places the joint frame in the PARENT link
frame; `<axis>` is in the joint frame; the CHILD link frame coincides with the joint frame at
-`q = 0`; `q = 0` is YOUR authored rest pose. Positive revolute `q` rotates by the right-hand
-rule about `<axis>`; positive prismatic `q` slides along `<axis>`.
+`q = 0`; `q = 0` is YOUR authored rest pose (the pose the plan's bboxes/pivots describe, so URDF
+limits are the plan's `lower − rest .. upper − rest` — the plan's numbers when `rest` is 0).
+Positive revolute `q` rotates by the right-hand rule about `<axis>`; positive prismatic `q`
+slides along `<axis>`.
### The recipe we enforce (link frames at pivots, meshes authored in world)
diff --git a/harness/codeverse/languages/urdf/lint.py b/harness/codeverse/languages/urdf/lint.py
index bbb50af3..d87cc847 100644
--- a/harness/codeverse/languages/urdf/lint.py
+++ b/harness/codeverse/languages/urdf/lint.py
@@ -16,14 +16,16 @@ from pathlib import Path
from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
from codeverse.conventions import to_snake
-from codeverse.spatial.joints_model import JOINT_TYPES, MOVABLE_TYPES
+from codeverse.spatial.joints_model import JOINT_TYPES, MOVABLE_TYPES, RESERVED_LINK_NAMES
from codeverse.workspace import Workspace
GATE = "lint:urdf"
URDF_REL = "src/robot.urdf"
MODEL_REL = "src/model.py"
_STATE_WORDS = ("open", "closed", "opened", "extended", "retracted", "raised", "lowered", "folded", "unfolded")
-_SNAKE = re.compile(r"^[a-z][a-z0-9]*(_[a-z0-9]+)*$")
+#: link names double as Blender object names and ``meshes/<link>.glb`` stems: plain
+#: identifiers only (``door``, ``handle_left``, ``DoorHandle``) — never ``Door.001`` / spaces.
+_IDENT = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
#: attribute chains that must not appear in model.py (harness owns these)
FORBIDDEN_BPY_PREFIXES: tuple[tuple[str, str], ...] = (
@@ -123,9 +125,13 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
- if not _SNAKE.match(name):
- out.append(_f(Severity.WARN, f"link name '{name}' is not snake_case", target=name,
- fix=f"Rename to '{to_snake(name)}' in BOTH robot.urdf and model.py (object names are case-sensitive)."))
+ if name in RESERVED_LINK_NAMES:
+ out.append(_f(Severity.ERROR, f"link name '{name}' is reserved by the GLB scene graph (glTF readers use it as the base frame)",
+ target=name, fix="Rename the link (e.g. 'base' or the part's name) in BOTH robot.urdf and model.py."))
+ if not _IDENT.match(name):
+ out.append(_f(Severity.WARN, f"link name '{name}' is not a plain identifier (letters/digits/underscore)", target=name,
+ fix=f"Rename to '{to_snake(name)}' in BOTH robot.urdf and model.py (object names are case-sensitive; "
+ "Blender's auto-suffix '.001' means two objects shared a name)."))
if any(w in to_snake(name).split("_") for w in _STATE_WORDS):
out.append(_f(Severity.WARN, f"link name '{name}' contains a state word — links are parts, states come from joints", target=name,
fix="Name the part (door, drawer, lid), not its state."))
diff --git a/harness/codeverse/languages/urdf/runtime.py b/harness/codeverse/languages/urdf/runtime.py
index ad9471bc..c687f500 100644
--- a/harness/codeverse/languages/urdf/runtime.py
+++ b/harness/codeverse/languages/urdf/runtime.py
@@ -103,7 +103,7 @@ class UrdfBlenderRuntime:
# 2. Blender wrapper
blender = settings.resolve_blender()
if not blender:
- return fail("BlenderNotFound", "no Blender binary (set C3V_BINARIES__BLENDER)", file="", census=census)
+ return fail("BlenderNotFound", "no Blender binary (set CV3D_BINARIES__BLENDER)", file="", census=census)
for stale in ("build.json", "census.json"):
(art / stale).unlink(missing_ok=True)
shutil.rmtree(art / "meshes", ignore_errors=True)
diff --git a/harness/codeverse/languages/urdf/skeleton.py b/harness/codeverse/languages/urdf/skeleton.py
index e15e5bcb..9dd18f62 100644
--- a/harness/codeverse/languages/urdf/skeleton.py
+++ b/harness/codeverse/languages/urdf/skeleton.py
@@ -9,7 +9,11 @@ origins / visual origins follow the enforced convention (see CONTRACT.md):
* joint ``<origin xyz>`` = pivot_world(child) − link_frame_world(parent);
* visual ``<origin xyz>`` = −link_frame_world(link) (meshes are exported in
world coordinates at the authored rest pose);
-* URDF ``q = 0`` is the authored rest pose, so plan limits are shifted by ``rest``.
+* URDF ``q = 0`` is the authored rest pose (the pose the plan's bboxes / pivots
+ describe), so plan limits are shifted by ``rest``: ``lower-rest .. upper-rest``
+ (identical to the plan's when ``rest == 0``, the usual case). The rendered URDF
+ says so in a comment next to every shifted ``<limit>`` so the agent who reads the
+ plan table (unshifted values) and the skeleton sees one consistent rule.
"""
from __future__ import annotations
@@ -46,6 +50,7 @@ class JointRow:
axis: tuple[float, float, float]
lower: float | None
upper: float | None
+ rest: float = 0.0 # plan rest value the limits were shifted by (0 → limits == plan limits)
@dataclass
@@ -101,7 +106,8 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
if j.type in ("revolute", "prismatic"):
lower, upper = j.lower - j.rest, j.upper - j.rest
joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
- origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper))
+ origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper,
+ rest=float(j.rest) if lower is not None else 0.0))
for j in plan.joints:
parent, child = to_snake(j.parent), to_snake(j.child)
@@ -124,15 +130,24 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
cf = links[jr.child].frame_xyz
fixed.append(JointRow(name=jr.name, type=jr.type, parent=jr.parent, child=jr.child,
origin_xyz=tuple(c - p for c, p in zip(cf, pf, strict=True)), axis=jr.axis,
- lower=jr.lower, upper=jr.upper))
+ lower=jr.lower, upper=jr.upper, rest=jr.rest))
return UrdfFrames(robot_name=to_snake(plan.object_name), root=root, links=links, joints=fixed)
# ------------------------------------------------------------------ text renderers
+def _limit_note(jr: JointRow) -> str:
+ """Comment explaining a rest-shifted limit (empty when the plan's rest is 0)."""
+ if jr.lower is None or jr.upper is None or abs(jr.rest) < 1e-12:
+ return ""
+ return (f" <!-- plan lower={_fmt(jr.lower + jr.rest)} upper={_fmt(jr.upper + jr.rest)} rest={_fmt(jr.rest)}: "
+ f"the mesh is authored at rest, so q=0 = plan {_fmt(jr.rest)} and the limits are shifted by -rest -->")
+
+
def render_urdf(frames: UrdfFrames) -> str:
lines = ['<?xml version="1.0"?>', f'<robot name="{frames.robot_name}">']
lines.append(" <!-- link frames: root at the world origin; every other link frame sits at its joint pivot (world, rest pose). -->")
lines.append(" <!-- visual/collision origin = -(link frame world) because meshes/<link>.glb hold WORLD coordinates at rest. -->")
+ lines.append(" <!-- q=0 is the authored pose (the plan's rest pose); limits are the plan's lower-rest .. upper-rest. -->")
for name, lf in frames.links.items():
vis = tuple(-v for v in lf.frame_xyz)
lines.append(f' <link name="{name}"> <!-- frame at world {_vec(lf.frame_xyz)} -->')
@@ -149,7 +164,7 @@ def render_urdf(frames: UrdfFrames) -> str:
lim = f'effort="{_fmt(DEFAULT_EFFORT)}" velocity="{_fmt(DEFAULT_VELOCITY)}"'
if jr.lower is not None and jr.upper is not None:
lim = f'lower="{_fmt(jr.lower)}" upper="{_fmt(jr.upper)}" ' + lim
- lines.append(f" <limit {lim}/>")
+ lines.append(f" <limit {lim}/>" + _limit_note(jr))
lines.append(" </joint>")
lines.append("</robot>")
return "\n".join(lines) + "\n"
@@ -160,8 +175,9 @@ def render_model_py(plan: ArticulatedPlan, frames: UrdfFrames) -> str:
head = f'''"""{plan.object_name} — link meshes for robot.urdf (pure bpy, Z-up, -Y front, meters).
CONTRACT: build ONE mesh object per URDF link, named EXACTLY like the link, placed
-at its REST-POSE WORLD position. Extra helper objects must be parented under a
-link object (they are joined into it). No cameras / lights / render / export calls.
+at its REST-POSE WORLD position (= URDF q=0, the pose the plan's bboxes describe).
+Extra helper objects must be parented under a link object (they are joined into
+it). No cameras / lights / render / export calls.
Replace every placeholder box below with real, detailed geometry; keep the names.
"""
import bpy
@@ -188,7 +204,9 @@ def box(name, center, size):
desc = (p.description or "").replace("\n", " ")
body.append(f"# link '{name}': {role}\n# {desc}")
if lf.parent_joint:
- body.append(f"# joint '{lf.parent_joint}' pivot (world) = {lf.frame_xyz}")
+ jr = next(j for j in frames.joints if j.name == lf.parent_joint)
+ note = f" (plan rest={_fmt(jr.rest)} → this pose is URDF q=0)" if abs(jr.rest) > 1e-12 else ""
+ body.append(f"# joint '{lf.parent_joint}' pivot (world) = {lf.frame_xyz}{note}")
body.append(f"{name} = box({name!r}, center={tuple(round(v, 4) for v in lf.bbox_center)}, "
f"size={tuple(round(v, 4) for v in lf.bbox_extents)})\n")
tail = f"\n# Sanity: every link object exists\nfor _n in {list(frames.links)!r}:\n assert _n in bpy.data.objects, _n\n"
diff --git a/harness/codeverse/models/gemini.py b/harness/codeverse/models/gemini.py
index bb75b26f..3bacb831 100644
--- a/harness/codeverse/models/gemini.py
+++ b/harness/codeverse/models/gemini.py
@@ -2,8 +2,12 @@
* one ``genai.Client`` per API key (cached, thread-safe),
* ``KeyPool`` shared by every GeminiModel built on the same key list,
-* up to ``max_attempts`` tries: 429 → rotate key (short pause), 5xx / timeouts
- / empty candidates → exponential backoff with jitter,
+* 429 → rotate to a fresh key (short pause; free while an untried key remains),
+ then up to ``max_attempts`` tries with exponential backoff + jitter for 5xx /
+ timeouts / empty candidates / 429s once every key has been tried,
+* key-scoped auth failures (401/403, ``API_KEY_INVALID`` …) → rotate for free and
+ bench the key in the pool (``dead``) once a sibling key proves the request is
+ fine; only when every key fails the same way is the error raised,
* ``thinking`` → ``ThinkingConfig(thinking_budget=…)``; models that reject the
field get one retry without it and a warning in ``response.raw["warnings"]``.
"""
@@ -32,7 +36,7 @@ from codeverse.models.gemini_convert import (
parse_usage,
to_contents,
)
-from codeverse.models.keypool import KeyPool, KeyPoolExhausted
+from codeverse.models.keypool import KeyPool, KeyPoolExhausted, Outcome
from codeverse.models.parts import Stopwatch
from codeverse.models.pricing import estimate_cost
from codeverse.models.retry import backoff_delay
@@ -83,6 +87,42 @@ def classify_exception(exc: BaseException) -> ModelError:
return ModelError(f"Gemini unexpected error: {type(exc).__name__}: {exc}", retryable=False)
+# message fragments of key-scoped failures (revoked / suspended / expired / disabled
+# project); HTTP 401 / 403 are key-scoped regardless of wording
+_DEAD_KEY_MARKERS = (
+ "api_key_invalid",
+ "api key not valid",
+ "api key expired",
+ "permission_denied",
+ "unauthenticated",
+ "suspended",
+ "leaked",
+ "service_disabled",
+ "has not been used in project",
+)
+
+
+def is_dead_key_error(err: ModelError) -> bool:
+ """True when ``err`` indicts the API key rather than the request, so the call
+ should move to another key instead of failing."""
+ if err.status in (401, 403):
+ return True
+ text = str(err).lower()
+ return err.status == 400 and any(m in text for m in _DEAD_KEY_MARKERS)
+
+
+def failure_outcome(err: ModelError) -> Outcome:
+ """``KeyPool.report`` outcome for a failed call (content-level failures such as
+ bad JSON / empty candidates carry no status and are not the key's fault)."""
+ if err.status == 429:
+ return "429"
+ if (err.status or 0) >= 500:
+ return "5xx"
+ if is_dead_key_error(err):
+ return "dead"
+ return "error" if err.status else "ok"
+
+
def _retry_after_s(exc: BaseException) -> float | None:
"""Gemini 429 bodies carry ``details[].retryDelay: "7s"``; honour it (capped)."""
m = _RETRY_DELAY_RE.search(str(exc))
@@ -148,16 +188,18 @@ class GeminiModel:
def generate(self, request: ChatRequest) -> ChatResponse:
contents = to_contents(request.messages)
warnings: list[str] = []
- failed_keys: set[str] = set()
+ failed_keys: set[str] = set() # keys that 429'd or looked dead during this call
+ dead_keys: set[str] = set()
last_err: ModelError | None = None
attempt = 0
config = self._config(request, warnings)
while attempt < self.max_attempts:
attempt += 1
+ # never go back to a key that looked dead this call; throttled keys are
+ # excluded while an untried one remains, else acquire() waits for a cooldown
+ exclude = dead_keys | (failed_keys if len(failed_keys) < len(self.pool) else set())
try:
- key = self.pool.acquire(
- exclude=failed_keys if len(failed_keys) < len(self.pool) else None
- )
+ key = self.pool.acquire(exclude=exclude)
except KeyPoolExhausted as exc:
raise classify_exception(exc) from exc
try:
@@ -165,6 +207,7 @@ class GeminiModel:
self.pool.report(
key, "ok", tokens=resp.usage.input_tokens + resp.usage.output_tokens
)
+ self._bench(dead_keys)
return resp
except Exception as exc: # noqa: BLE001 - classified below
err = classify_exception(exc)
@@ -179,34 +222,40 @@ class GeminiModel:
config = self._config(request, warnings)
attempt -= 1
continue
- # content-level failures (bad JSON, empty candidates) are not the key's fault
- outcome = (
- "429"
- if err.status == 429
- else "5xx"
- if (err.status or 0) >= 500
- else "error"
- if err.status
- else "ok"
- )
+ outcome = failure_outcome(err)
+ if outcome == "dead":
+ # key-scoped: move on at once (no budget, no sleep); the key is only
+ # benched once another key proves the request itself is fine
+ dead_keys.add(key)
+ failed_keys.add(key)
+ self.pool.report(key, "error")
+ if len(dead_keys) < len(self.pool):
+ log.warning(
+ "gemini %s key …%s looks dead (%s); rotating", self.model, key[-4:], err
+ )
+ attempt -= 1
+ continue
+ raise err from exc # every key failed the same way: not the keys' fault
self.pool.report(
key, outcome, retry_after_s=_retry_after_s(exc) if outcome == "429" else None
)
- if not err.retryable or attempt >= self.max_attempts:
- raise err from exc
if outcome == "429":
failed_keys.add(key)
- delay = (
- 0.5
- if len(self.pool) > 1
- else backoff_delay(
- attempt, base_delay=self.base_delay, max_delay=self.max_delay
+ if len(failed_keys) < len(self.pool):
+ # an untried key remains: rotation is free, only a courtesy pause
+ attempt -= 1
+ log.warning(
+ "gemini %s key …%s throttled (%s); rotating to a fresh key",
+ self.model,
+ key[-4:],
+ err,
)
- )
- else:
- delay = backoff_delay(
- attempt, base_delay=self.base_delay, max_delay=self.max_delay
- )
+ self._sleep(0.5)
+ continue
+ if not err.retryable or attempt >= self.max_attempts:
+ self._bench(dead_keys)
+ raise err from exc
+ delay = backoff_delay(attempt, base_delay=self.base_delay, max_delay=self.max_delay)
log.warning(
"gemini %s attempt %d/%d failed (%s); retrying in %.1fs",
self.model,
@@ -217,8 +266,16 @@ class GeminiModel:
)
self._sleep(delay)
assert last_err is not None
+ self._bench(dead_keys)
raise last_err
+ def _bench(self, dead_keys: set[str]) -> None:
+ """Mark keys that failed with key-scoped errors dead — called once the call
+ got past the auth layer on some other key (success, 429, 5xx, bad JSON …)."""
+ for key in dead_keys:
+ self.pool.report(key, "dead")
+ dead_keys.clear()
+
def _config(self, request: ChatRequest, warnings: list[str]) -> types.GenerateContentConfig:
return build_config(
request,
diff --git a/harness/codeverse/models/gemini_image.py b/harness/codeverse/models/gemini_image.py
new file mode 100644
index 00000000..c580e17f
--- /dev/null
+++ b/harness/codeverse/models/gemini_image.py
@@ -0,0 +1,329 @@
+"""``GeminiImageModel`` — text (+ reference images) → PIL images via google-genai
+``generate_content(response_modalities=["IMAGE"])``.
+
+Shares the process-wide ``KeyPool`` / client cache / error classification with
+``GeminiModel`` (``models/gemini.py``), including its key-rotation semantics
+(``failure_outcome``): a 429 while an untried key remains is a FREE rotation
+(does not consume ``max_attempts``, 0.5 s courtesy pause); auth/permission
+errors classify as ``dead`` → rotate at once and bench the key only after a
+sibling key proves the request itself is fine (all keys dead → raise); 5xx /
+timeouts → exponential backoff; fatal finish reasons (safety) →
+``ModelError(retryable=False)``.
+A *fallback* model (default ``gemini-2.5-flash-image``) is tried when the primary
+model is rejected (404 / 400 "not found") or every attempt on it failed retryably.
+
+Cost: Gemini bills generated images as output tokens (≈1.1–1.3 k tokens per 1024²
+image) but the published per-image price is higher than the text-output rate, so
+``Usage.cost_usd`` is ``max(estimate_cost(tokens), n_images × IMAGE_USD[model])``
+(approximate; see ``IMAGE_USD``).
+
+Protocol (``ImageModel``): ``generate(prompt, *, size, n, seed, reference_images)
+-> list[PIL.Image]`` and ``generate_with_usage(...) -> (images, Usage)``. Tests
+use ``codeverse.texturing.generate.FakeImageModel`` which implements the same.
+"""
+
+from __future__ import annotations
+
+import io
+import logging
+import threading
+import time
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any, Protocol, runtime_checkable
+
+from google.genai import types
+from PIL import Image
+
+from codeverse.contracts.common import Usage
+from codeverse.models.base import ModelError
+from codeverse.models.gemini import (
+ GeminiModel,
+ _default_keys,
+ _retry_after_s,
+ classify_exception,
+ failure_outcome,
+ shared_pool,
+)
+from codeverse.models.gemini_convert import FATAL_FINISH, parse_usage
+from codeverse.models.keypool import KeyPool, KeyPoolExhausted
+from codeverse.models.parts import Stopwatch
+from codeverse.models.pricing import estimate_cost
+from codeverse.models.retry import backoff_delay
+
+log = logging.getLogger(__name__)
+
+DEFAULT_IMAGE_MODEL = "gemini-3.1-flash-image"
+FALLBACK_IMAGE_MODEL = "gemini-2.5-flash-image"
+
+#: approximate USD per generated 1024² image (floor for cost accounting)
+IMAGE_USD: dict[str, float] = {
+ "gemini-3.1-flash-image": 0.067,
+ "gemini-2.5-flash-image": 0.039,
+}
+
+#: requested pixel size → Gemini ``image_size`` token
+_IMAGE_SIZE_TOKEN: dict[int, str] = {512: "1K", 1024: "1K", 2048: "2K", 4096: "4K"}
+
+
+@runtime_checkable
+class ImageModel(Protocol):
+ """Text-to-image backend. Implementations must be thread-safe."""
+
+ model: str
+
+ @property
+ def id(self) -> str: ...
+
+ def generate(
+ self,
+ prompt: str,
+ *,
+ size: int = 1024,
+ n: int = 1,
+ seed: int | None = None,
+ reference_images: Sequence[Image.Image | Path | str] = (),
+ ) -> list[Image.Image]: ...
+
+ def generate_with_usage(
+ self,
+ prompt: str,
+ *,
+ size: int = 1024,
+ n: int = 1,
+ seed: int | None = None,
+ reference_images: Sequence[Image.Image | Path | str] = (),
+ ) -> tuple[list[Image.Image], Usage]: ...
+
+
+def image_cost(model: str, usage: Usage, n_images: int) -> float:
+ """Token-priced cost floored by the per-image price (approximate)."""
+ token_cost = estimate_cost("gemini", model, usage)
+ per_image = IMAGE_USD.get(model.strip().lower(), 0.0)
+ return max(token_cost, per_image * max(0, n_images))
+
+
+def _to_part(ref: Image.Image | Path | str) -> types.Part:
+ if isinstance(ref, Image.Image):
+ buf = io.BytesIO()
+ ref.convert("RGB").save(buf, format="PNG")
+ return types.Part.from_bytes(data=buf.getvalue(), mime_type="image/png")
+ p = Path(ref)
+ if not p.is_file():
+ raise ModelError(f"reference image not found: {p}")
+ mime = "image/jpeg" if p.suffix.lower() in (".jpg", ".jpeg") else "image/png"
+ return types.Part.from_bytes(data=p.read_bytes(), mime_type=mime)
+
+
+def _is_model_missing(err: ModelError) -> bool:
+ s = str(err).lower()
+ return err.status == 404 or (err.status == 400 and ("not found" in s or "not supported" in s))
+
+
+class GeminiImageModel:
+ """See module docstring. ``model`` is the primary; ``fallback`` the second try."""
+
+ provider = "gemini"
+
+ def __init__(
+ self,
+ model: str = DEFAULT_IMAGE_MODEL,
+ *,
+ fallback: str | None = FALLBACK_IMAGE_MODEL,
+ keys: list[str] | None = None,
+ pool: KeyPool | None = None,
+ timeout_s: float = 180.0,
+ max_attempts: int = 4,
+ base_delay: float = 2.0,
+ max_delay: float = 30.0,
+ sleep: Callable[[float], None] = time.sleep,
+ client_factory: Callable[[str], Any] | None = None,
+ ) -> None:
+ self.model = model
+ self.fallback = fallback if fallback and fallback != model else None
+ keys = list(keys) if keys is not None else _default_keys()
+ if pool is None and not keys:
+ raise ModelError("no Gemini API keys configured (GEMINI_API_KEYS / ~/.config/astra3d/gemini_keys.env)")
+ self.pool = pool or shared_pool(keys)
+ self.timeout_s = timeout_s
+ self.max_attempts = max(1, max_attempts)
+ self.base_delay = base_delay
+ self.max_delay = max_delay
+ self._sleep = sleep
+ # reuse GeminiModel's cached clients (same key → same genai.Client)
+ self._clients = GeminiModel(model, pool=self.pool, timeout_s=timeout_s, client_factory=client_factory)
+ self._lock = threading.Lock()
+ self._primary_dead = False
+
+ @property
+ def id(self) -> str:
+ return f"gemini-image:{self.model}"
+
+ # ------------------------------------------------------------------ API
+ def generate(
+ self,
+ prompt: str,
+ *,
+ size: int = 1024,
+ n: int = 1,
+ seed: int | None = None,
+ reference_images: Sequence[Image.Image | Path | str] = (),
+ ) -> list[Image.Image]:
+ images, _ = self.generate_with_usage(prompt, size=size, n=n, seed=seed, reference_images=reference_images)
+ return images
+
+ def generate_with_usage(
+ self,
+ prompt: str,
+ *,
+ size: int = 1024,
+ n: int = 1,
+ seed: int | None = None,
+ reference_images: Sequence[Image.Image | Path | str] = (),
+ ) -> tuple[list[Image.Image], Usage]:
+ if not prompt.strip():
+ raise ModelError("empty image prompt")
+ if n < 1:
+ raise ModelError("n must be >= 1")
+ images: list[Image.Image] = []
+ usage = Usage(backend="gemini-image", model=self.model)
+ for i in range(n):
+ got, u = self._one(prompt, size=size, seed=None if seed is None else seed + i, refs=reference_images)
+ images.extend(got)
+ usage = usage + u
+ if len(images) > n:
+ images = images[:n]
+ return images, usage
+
+ # ------------------------------------------------------------------ internals
+ def _models(self) -> list[str]:
+ with self._lock:
+ dead = self._primary_dead
+ order = [self.model] if not dead else []
+ if self.fallback:
+ order.append(self.fallback)
+ if not order:
+ order = [self.model]
+ return order
+
+ def _one(
+ self, prompt: str, *, size: int, seed: int | None, refs: Sequence[Image.Image | Path | str]
+ ) -> tuple[list[Image.Image], Usage]:
+ last: ModelError | None = None
+ for model in self._models():
+ try:
+ return self._attempts(model, prompt, size=size, seed=seed, refs=refs)
+ except ModelError as err:
+ last = err
+ if model == self.model and self.fallback and (err.retryable or _is_model_missing(err)):
+ if _is_model_missing(err):
+ with self._lock:
+ self._primary_dead = True
+ log.warning("image model %s failed (%s); falling back to %s", model, err, self.fallback)
+ continue
+ raise
+ assert last is not None
+ raise last
+
+ def _attempts(
+ self, model: str, prompt: str, *, size: int, seed: int | None, refs: Sequence[Image.Image | Path | str]
+ ) -> tuple[list[Image.Image], Usage]:
+ parts: list[types.Part] = [_to_part(r) for r in refs]
+ parts.append(types.Part.from_text(text=prompt))
+ contents = [types.Content(role="user", parts=parts)]
+ config = types.GenerateContentConfig(
+ response_modalities=["IMAGE"],
+ image_config=types.ImageConfig(aspect_ratio="1:1", image_size=_IMAGE_SIZE_TOKEN.get(int(size), "1K")),
+ seed=seed,
+ http_options=types.HttpOptions(timeout=int(self.timeout_s * 1000)),
+ )
+ failed_keys: set[str] = set() # keys that 429'd or looked dead during this call
+ dead_keys: set[str] = set()
+ last: ModelError | None = None
+ attempt = 0
+ while attempt < self.max_attempts:
+ attempt += 1
+ # never go back to a key that looked dead this call; throttled keys are
+ # excluded while an untried one remains, else acquire() waits for a cooldown
+ exclude = dead_keys | (failed_keys if len(failed_keys) < len(self.pool) else set())
+ try:
+ key = self.pool.acquire(exclude=exclude)
+ except KeyPoolExhausted as exc:
+ raise classify_exception(exc) from exc
+ try:
+ images, usage = self._call(key, model, contents, config, size)
+ self.pool.report(key, "ok", tokens=usage.input_tokens + usage.output_tokens)
+ self._bench(dead_keys)
+ return images, usage
+ except Exception as exc: # noqa: BLE001 — classified below
+ err = classify_exception(exc)
+ last = err
+ outcome = failure_outcome(err)
+ if outcome == "dead":
+ # key-scoped: move on at once (no budget, no sleep); the key is only
+ # benched once another key proves the request itself is fine
+ dead_keys.add(key)
+ failed_keys.add(key)
+ self.pool.report(key, "error")
+ if len(dead_keys) < len(self.pool):
+ log.warning("image %s key …%s looks dead (%s); rotating", model, key[-4:], err)
+ attempt -= 1
+ continue
+ raise err from exc # every key failed the same way: not the keys' fault
+ self.pool.report(key, outcome, retry_after_s=_retry_after_s(exc) if outcome == "429" else None)
+ if outcome == "429":
+ failed_keys.add(key)
+ if len(failed_keys) < len(self.pool):
+ # an untried key remains: rotation is free, only a courtesy pause
+ attempt -= 1
+ log.warning("image %s key …%s throttled (%s); rotating to a fresh key", model, key[-4:], err)
+ self._sleep(0.5)
+ continue
+ if not err.retryable or attempt >= self.max_attempts:
+ self._bench(dead_keys)
+ raise err from exc
+ delay = backoff_delay(attempt, base_delay=self.base_delay, max_delay=self.max_delay)
+ log.warning("image %s attempt %d/%d failed (%s); retrying in %.1fs", model, attempt, self.max_attempts, err, delay)
+ self._sleep(delay)
+ assert last is not None
+ self._bench(dead_keys)
+ raise last
+
+ def _bench(self, dead_keys: set[str]) -> None:
+ """Mark keys that failed with key-scoped errors dead — called once the call
+ as a whole succeeded or failed for a non-key reason."""
+ for key in dead_keys:
+ self.pool.report(key, "dead")
+ dead_keys.clear()
+
+ def _call(
+ self, key: str, model: str, contents: list[types.Content], config: types.GenerateContentConfig, size: int
+ ) -> tuple[list[Image.Image], Usage]:
+ client = self._clients._client(key)
+ with Stopwatch() as sw:
+ resp = client.models.generate_content(model=model, contents=contents, config=config)
+ pf = resp.prompt_feedback
+ if pf is not None and pf.block_reason:
+ raise ModelError(f"image prompt blocked: {pf.block_reason}", retryable=False)
+ if not resp.candidates:
+ raise ModelError("image model returned no candidates", retryable=True)
+ cand = resp.candidates[0]
+ finish = str(cand.finish_reason.name if cand.finish_reason is not None else "")
+ images: list[Image.Image] = []
+ for part in (cand.content.parts if cand.content and cand.content.parts else []):
+ blob = getattr(part, "inline_data", None)
+ if blob is not None and blob.data:
+ img = Image.open(io.BytesIO(blob.data))
+ img.load()
+ images.append(img.convert("RGB"))
+ if not images:
+ if finish in FATAL_FINISH:
+ raise ModelError(f"image generation refused (finish_reason={finish})", retryable=False)
+ raise ModelError(f"image model returned no image (finish_reason={finish or 'unknown'})", retryable=True)
+ usage = parse_usage(resp, model)
+ usage.backend = "gemini-image"
+ usage.latency_ms = sw.ms
+ usage.cost_usd = image_cost(model, usage, len(images))
+ if int(size) not in (0, 1024) and images[0].size != (size, size):
+ images = [im.resize((int(size), int(size)), Image.LANCZOS) for im in images]
+ return images, usage
diff --git a/harness/codeverse/models/keypool.py b/harness/codeverse/models/keypool.py
index c0974ece..1737c042 100644
--- a/harness/codeverse/models/keypool.py
+++ b/harness/codeverse/models/keypool.py
@@ -5,9 +5,12 @@ Used by ``GeminiModel`` (22 keys on the owner's box) but provider-neutral.
* ``acquire()`` picks the next healthy key round-robin, honouring per-key
RPM / TPM token buckets and 429 cool-downs; it blocks (bounded) when every
key is throttled and raises ``KeyPoolExhausted`` after ``timeout_s``.
-* ``report(key, outcome)`` feeds back ``ok | 429 | 5xx | error`` so the pool
- can cool a key down and adjust its health score.
-* ``stats()`` exposes counters for logs / ``c3v doctor``.
+* ``report(key, outcome)`` feeds back ``ok | 429 | 5xx | error | dead`` so the
+ pool can cool a key down and adjust its health score. ``dead`` is for
+ key-scoped auth/permission failures (revoked / suspended / invalid key): the
+ key is benched for ``dead_cooldown_s`` (default one hour) and re-probed once
+ that elapses — a dead key must never keep failing its share of calls.
+* ``stats()`` exposes counters for logs / ``3dcv doctor``.
Thread-safe; ``clock`` / ``sleep`` are injectable for deterministic tests.
"""
@@ -20,7 +23,7 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Literal
-Outcome = Literal["ok", "429", "5xx", "error"]
+Outcome = Literal["ok", "429", "5xx", "error", "dead"]
class KeyPoolExhausted(RuntimeError):
@@ -66,10 +69,12 @@ class _KeyState:
tpm: TokenBucket | None
health: float = 1.0
cooldown_until: float = 0.0
+ dead_until: float = 0.0
n_ok: int = 0
n_429: int = 0
n_5xx: int = 0
n_error: int = 0
+ n_dead: int = 0
n_acquired: int = 0
last_used: float = 0.0
health_ts: float = 0.0
@@ -99,6 +104,7 @@ class KeyPool:
rpm_per_key: int = 900,
tpm_per_key: int | None = None,
cooldown_s: float = 30.0,
+ dead_cooldown_s: float = 3600.0,
min_health: float = 0.3,
clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], None] = time.sleep,
@@ -109,6 +115,7 @@ class KeyPool:
self._clock = clock
self._sleep = sleep
self._cooldown_s = float(cooldown_s)
+ self._dead_cooldown_s = float(dead_cooldown_s)
self._min_health = min_health
self._lock = threading.Lock()
self._rr = 0
@@ -138,7 +145,9 @@ class KeyPool:
timeout_s: float | None = 120.0,
) -> str:
"""Return the next usable key, blocking (bounded by ``timeout_s``) while all
- keys are throttled. ``exclude`` skips keys that already failed this call."""
+ keys are throttled. ``exclude`` skips keys that already failed this call.
+ Raises ``KeyPoolExhausted`` at once when no key can become available before
+ the deadline (e.g. every key is dead) — availability only moves later."""
deadline = None if timeout_s is None else self._clock() + timeout_s
while True:
with self._lock:
@@ -161,6 +170,11 @@ class KeyPool:
)
if soonest == float("inf"):
raise KeyPoolExhausted("all keys excluded")
+ if deadline is not None and soonest > deadline:
+ raise KeyPoolExhausted(
+ f"all {len(self._states)} keys throttled or dead; the earliest becomes "
+ f"available in {soonest - now:.0f}s (> {timeout_s}s wait budget)"
+ )
wait = max(0.01, min(soonest - now, 5.0))
if deadline is not None and self._clock() + wait > deadline:
raise KeyPoolExhausted(
@@ -194,6 +208,12 @@ class KeyPool:
elif outcome == "5xx":
st.n_5xx += 1
st.health *= 0.8
+ elif outcome == "dead":
+ # key-scoped failure: bench it; re-probed once the long cooldown passes
+ st.n_dead += 1
+ st.health = 0.0
+ st.dead_until = max(st.dead_until, now + self._dead_cooldown_s)
+ st.cooldown_until = max(st.cooldown_until, st.dead_until)
else:
st.n_error += 1
st.health *= 0.9
@@ -217,17 +237,20 @@ class KeyPool:
"429": s.n_429,
"5xx": s.n_5xx,
"error": s.n_error,
+ "dead": s.n_dead,
}
for s in self._states
]
return {
"n_keys": len(self._states),
"n_cooling": sum(1 for s in self._states if s.cooldown_until > now),
+ "n_dead": sum(1 for s in self._states if s.dead_until > now),
"acquired": sum(s.n_acquired for s in self._states),
"ok": sum(s.n_ok for s in self._states),
"429": sum(s.n_429 for s in self._states),
"5xx": sum(s.n_5xx for s in self._states),
"error": sum(s.n_error for s in self._states),
+ "dead": sum(s.n_dead for s in self._states),
"keys": per_key,
}
diff --git a/harness/codeverse/models/pricing.py b/harness/codeverse/models/pricing.py
index b5399767..debfcaad 100644
--- a/harness/codeverse/models/pricing.py
+++ b/harness/codeverse/models/pricing.py
@@ -49,6 +49,9 @@ PRICES: dict[tuple[str, str], Price] = {
("gemini", "gemini-2.5-pro"): Price(1.25, 10.00, 0.125),
("gemini", "gemini-2.5-flash"): Price(0.30, 2.50, 0.075),
("gemini", "gemini-2.5-flash-lite"): Price(0.10, 0.40, 0.025),
+ # (texturing) image-output model: output tokens ARE the image (~1.3k tokens ≈ $0.039 / image);
+ # models/gemini_image.py additionally floors cost at IMAGE_USD per image. approximate.
+ ("gemini", "gemini-2.5-flash-image"): Price(0.30, 30.00, 0.075, approximate=True),
# ------------------------------------------------------------- anthropic
("anthropic", "claude-fable-5"): Price(10.00, 50.00, 1.00, cache_write=12.50),
("anthropic", "claude-opus-5"): Price(5.00, 25.00, 0.50, cache_write=6.25),
@@ -71,17 +74,25 @@ PRICES: dict[tuple[str, str], Price] = {
("openai", "gpt-5.5"): Price(5.00, 30.00, 0.50, approximate=True),
("openai", "gpt-5.4"): Price(2.50, 15.00, 0.25, approximate=True),
("openai", "gpt-5.3-codex"): Price(1.75, 14.00, 0.175, approximate=True),
+ ("openai", "gpt-5.2-codex"): Price(1.75, 14.00, 0.175, approximate=True),
("openai", "gpt-5.2"): Price(1.75, 14.00, 0.175, approximate=True),
+ ("openai", "gpt-5.1-codex"): Price(1.25, 10.00, 0.125),
("openai", "gpt-5.1"): Price(1.25, 10.00, 0.125),
+ ("openai", "gpt-5-codex"): Price(1.25, 10.00, 0.125),
("openai", "gpt-5-mini"): Price(0.25, 2.00, 0.025),
("openai", "gpt-5-nano"): Price(0.05, 0.40, 0.005),
("openai", "gpt-5"): Price(1.25, 10.00, 0.125),
("openai", "gpt-4.1"): Price(2.00, 8.00, 0.50),
("openai", "gpt-4.1-mini"): Price(0.40, 1.60, 0.10),
+ ("openai", "gpt-4.1-nano"): Price(0.10, 0.40, 0.025),
("openai", "gpt-4o"): Price(2.50, 10.00, 1.25),
("openai", "gpt-4o-mini"): Price(0.15, 0.60, 0.075),
("openai", "o3"): Price(2.00, 8.00, 0.50),
+ ("openai", "o3-mini"): Price(1.10, 4.40, 0.55),
+ ("openai", "o3-pro"): Price(20.00, 80.00),
("openai", "o4-mini"): Price(1.10, 4.40, 0.275),
+ ("openai", "o1"): Price(15.00, 60.00, 7.50),
+ ("openai", "o1-mini"): Price(1.10, 4.40, 0.55),
}
# fmt: on
@@ -93,19 +104,33 @@ def _normalise(model: str) -> str:
return model.strip().lower()
+# words that may follow a priced model id without changing which model it is
+_VERSION_WORDS = frozenset({"latest", "preview", "exp", "beta", "alpha", "stable", "snapshot"})
+
+
+def _is_version_suffix(rest: str) -> bool:
+ """True when ``rest`` (what follows a table key in a model id) is only a
+ version / date / channel tag — ``-20260301``, ``@001``, ``-preview-05-20``,
+ ``-latest`` — and not a sibling model name (``-nano``, ``-mini``, ``-codex``,
+ ``.5``), which must price separately or be reported unknown."""
+ if not rest or rest[0] not in "-_@:":
+ return False
+ segments = rest[1:].split("-")
+ return all(seg.isdigit() or seg in _VERSION_WORDS for seg in segments)
+
+
def lookup_price(provider: str, model: str) -> Price | None:
- """Exact match first, then the longest table key that is a prefix of ``model``
- (so ``claude-opus-5-20260301`` or ``gemini-3.7-flash-preview-xx`` still price)."""
+ """Exact match first, then the longest table key that ``model`` extends by a
+ pure version/date suffix (``claude-opus-5-20260301``, ``gemini-3.7-flash-preview-09``).
+ A different family name after the key (``gpt-4.1-nano`` vs ``gpt-4.1``) is NOT a
+ match: unknown → ``None`` so the caller prices 0.0 and warns, never a sibling's rate."""
m = _normalise(model)
exact = PRICES.get((provider, m))
if exact is not None:
return exact
best: tuple[int, Price] | None = None
for (prov, key), price in PRICES.items():
- if prov != provider or not m.startswith(key):
- continue
- # require a boundary so "gpt-5" doesn't swallow "gpt-5.5" when a longer key exists
- if len(m) > len(key) and m[len(key)] not in "-_.@:":
+ if prov != provider or not m.startswith(key) or not _is_version_suffix(m[len(key) :]):
continue
if best is None or len(key) > best[0]:
best = (len(key), price)
diff --git a/harness/codeverse/models/schema_utils.py b/harness/codeverse/models/schema_utils.py
index 187d41b1..e52acf5c 100644
--- a/harness/codeverse/models/schema_utils.py
+++ b/harness/codeverse/models/schema_utils.py
@@ -8,7 +8,11 @@ provider accepts a different subset:
no ``$ref``, no ``additionalProperties``, no ``const``, no ``prefixItems``;
``nullable`` instead of null unions; ``propertyOrdering`` controls key order.
* OpenAI strict ``json_schema``: every object needs ``additionalProperties:
- false`` and ``required`` listing every property; ``$defs`` are fine.
+ false`` and ``required`` listing every property; ``$defs`` are fine. Optional
+ fields keep their own type — null is allowed only where the source schema
+ already allows it (``anyOf [T, null]``); a non-null ``default`` is hinted in
+ the description. So the wire contract equals the pydantic one and the model
+ never returns ``null`` where the contract wants ``""`` / ``1`` / ``[]``.
* Anthropic tool ``input_schema`` / ``output_config.format``: standard JSON
schema; we inline refs to be safe and set ``additionalProperties: false``.
@@ -185,9 +189,11 @@ def _json_type(value: Any) -> str:
# --------------------------------------------------------------------- openai
def to_openai_strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
"""OpenAI *strict* structured outputs: every object gets
- ``additionalProperties: false`` and ``required`` = all properties; optional
- fields become nullable (``anyOf [T, null]``) so the contract still holds.
- ``$defs`` are kept (supported) but inlined when a sibling ``$ref`` exists."""
+ ``additionalProperties: false`` and ``required`` = all properties. Optional
+ fields keep their type: null is accepted only where the source already says
+ so (``x: T | None``), never added — the consumer validates with the original
+ pydantic model, which rejects ``null`` for ``x: str = ""`` / ``list = []``.
+ A non-null ``default`` becomes a ``[default: …]`` hint. ``$defs`` are inlined."""
root = inline_refs(schema)
def walk(node: Any) -> Any:
@@ -204,8 +210,11 @@ def to_openai_strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
props = {k: walk(v) for k, v in node["properties"].items()}
required = set(node.get("required", []))
for name, sub in props.items():
- if name not in required:
- props[name] = _nullable_union(sub)
+ original = node["properties"][name]
+ if name in required or not isinstance(original, dict):
+ continue
+ if original.get("default") is not None:
+ props[name] = _with_default_hint(sub, original["default"])
node["properties"] = props
node["required"] = list(props.keys())
node["additionalProperties"] = False
@@ -220,16 +229,11 @@ def to_openai_strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
return walk(root)
-def _nullable_union(sub: dict[str, Any]) -> dict[str, Any]:
- if "anyOf" in sub:
- if any(_is_null(v) for v in sub["anyOf"]):
- return sub
- return {**sub, "anyOf": sub["anyOf"] + [{"type": "null"}]}
- if isinstance(sub.get("type"), list):
- return sub if "null" in sub["type"] else {**sub, "type": sub["type"] + ["null"]}
- if "type" in sub:
- return {**sub, "type": [sub["type"], "null"]}
- return {"anyOf": [sub, {"type": "null"}]}
+def _with_default_hint(sub: dict[str, Any], default: Any) -> dict[str, Any]:
+ """Keep the field non-null; tell the model what to emit when it has nothing."""
+ hint = f"[default: {json.dumps(default)}]"
+ desc = str(sub.get("description") or "").strip()
+ return {**sub, "description": f"{desc} {hint}".strip()}
# ------------------------------------------------------------------ anthropic
diff --git a/harness/codeverse/orchestrator/budget.py b/harness/codeverse/orchestrator/budget.py
index a28b6b40..a3f17381 100644
--- a/harness/codeverse/orchestrator/budget.py
+++ b/harness/codeverse/orchestrator/budget.py
@@ -40,11 +40,20 @@ class BudgetGuard:
# ----------------------------------------------------------------- accounting
def charge(self, usage: Usage | None) -> None:
"""Add ``usage`` to the running total, then enforce the ceilings."""
+ self.add(usage)
+ self.check()
+
+ def add(self, usage: Usage | None) -> None:
+ """Accumulate ``usage`` WITHOUT enforcing the ceilings.
+
+ For work that is already done and persisted (a completed judge verdict,
+ a pairwise tie-break, the texture pass): the money is spent either way,
+ and raising here would throw away a finished, paid-for result. The
+ round loop stops at its next ``ok()`` check instead."""
if usage is not None:
with self._lock:
self.spent = self.spent + usage
self.calls += 1
- self.check()
def elapsed_minutes(self) -> float:
return (time.time() - self.start_time) / 60.0
diff --git a/harness/codeverse/orchestrator/candidates.py b/harness/codeverse/orchestrator/candidates.py
new file mode 100644
index 00000000..929c4dc7
--- /dev/null
+++ b/harness/codeverse/orchestrator/candidates.py
@@ -0,0 +1,118 @@
+"""Choosing between alternatives: best-of-N candidates and pairwise tie-breaks.
+
+Pure decision logic (no I/O, no models) shared by the tracks:
+
+* ``CandidateRecord`` — what one baseline candidate produced (commit, quick
+ score, gate errors, cost); ``rank_candidates`` orders them.
+* ``decide_best`` — when a new round's score is within ``margin`` of the
+ current best the absolute delta is judge noise (flash judges compress their
+ score range), so a position-swapped pairwise comparison decides; the new
+ round replaces the best only when it wins with enough confidence.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable, Sequence
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Usage
+
+log = logging.getLogger(__name__)
+
+
+class CandidateRecord(BaseModel):
+ """One best-of-N baseline candidate (generated in its own sub-workspace)."""
+
+ index: int
+ label: str
+ commit: str = Field(default="", description="commit in the candidate's sub-workspace")
+ workspace: str = ""
+ build_ok: bool = False
+ score: float | None = None
+ gate_errors: int = 0
+ usage: Usage = Field(default_factory=Usage)
+ duration_s: float = 0.0
+ sheet: str = Field(default="", description="quick contact sheet (4 views) used for the quick judge")
+ notes: str = ""
+ selected: bool = False
+
+ def sort_key(self) -> tuple[int, float, int, int]:
+ return (1 if self.build_ok else 0, self.score if self.score is not None else -1.0, -self.gate_errors, -self.index)
+
+
+def rank_candidates(records: Sequence[CandidateRecord]) -> list[int]:
+ """Candidate indices best-first: built > higher quick score > fewer gate errors > earlier."""
+ return [r.index for r in sorted(records, key=lambda r: r.sort_key(), reverse=True)]
+
+
+class PairwiseNote(BaseModel):
+ """What a tie-break compared and what it concluded (persisted in round notes)."""
+
+ a: str = Field(description="label of the incumbent (current best)")
+ b: str = Field(description="label of the challenger (new round / other candidate)")
+ winner: Literal["a", "b", "tie"] = "tie"
+ confidence: float = 0.0
+ accepted: bool = Field(default=False, description="True when the challenger replaces the incumbent")
+ reasons: list[str] = Field(default_factory=list)
+ usage: Usage = Field(default_factory=Usage)
+ error: str = ""
+
+ def line(self) -> str:
+ verdict = {"a": f"{self.a} wins", "b": f"{self.b} wins", "tie": "tie"}[self.winner]
+ return f"pairwise {self.a} vs {self.b}: {verdict} (confidence {self.confidence:.2f}) → {'replace' if self.accepted else 'keep'}"
+
+
+Decision = Literal["score", "pairwise", "keep"]
+
+#: ``compare()`` → any object with ``winner`` ('a'|'b'|'tie'), ``confidence``, ``reasons``, ``usage``.
+CompareFn = Callable[[], Any]
+
+
+def within_margin(a: float | None, b: float | None, margin: float) -> bool:
+ return a is not None and b is not None and abs(a - b) <= margin
+
+
+def decide_best(
+ incumbent_score: float | None,
+ challenger_score: float | None,
+ *,
+ margin: float,
+ min_confidence: float,
+ compare: CompareFn | None,
+ labels: tuple[str, str] = ("best", "new"),
+) -> tuple[Decision, PairwiseNote | None]:
+ """Should the challenger replace the incumbent?
+
+ * scores differ by more than ``margin`` → ``"score"`` (caller uses the
+ ordinary ranking rule);
+ * within the margin and ``compare`` given → run it; ``"pairwise"`` when the
+ challenger wins with ``confidence ≥ min_confidence``, else ``"keep"``;
+ * within the margin without a comparator → ``"keep"`` (ties go to the
+ incumbent: fewer regenerations, stable best commit).
+ """
+ if incumbent_score is None or challenger_score is None:
+ return "score", None
+ if not within_margin(incumbent_score, challenger_score, margin):
+ return "score", None
+ note = PairwiseNote(a=labels[0], b=labels[1])
+ if compare is None:
+ return "keep", note
+ try:
+ res = compare()
+ except Exception as e: # noqa: BLE001 — a judge outage must not pick a worse round
+ log.warning("pairwise tie-break failed: %s", e)
+ note.error = f"{type(e).__name__}: {e}"
+ return "keep", note
+ note.winner = getattr(res, "winner", "tie")
+ note.confidence = float(getattr(res, "confidence", 0.0) or 0.0)
+ note.reasons = list(getattr(res, "reasons", []) or [])[:6]
+ note.usage = getattr(res, "usage", None) or Usage()
+ note.error = getattr(res, "error", "") or ""
+ note.accepted = note.winner == "b" and note.confidence >= min_confidence
+ return ("pairwise" if note.accepted else "keep"), note
+
+
+__all__ = ["CandidateRecord", "CompareFn", "Decision", "PairwiseNote", "decide_best", "rank_candidates", "within_margin"]
diff --git a/harness/codeverse/orchestrator/rounds.py b/harness/codeverse/orchestrator/rounds.py
index 75dc9296..7ce5777f 100644
--- a/harness/codeverse/orchestrator/rounds.py
+++ b/harness/codeverse/orchestrator/rounds.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import logging
from collections.abc import Callable, Sequence
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import Literal
from pydantic import BaseModel, Field
@@ -25,7 +25,7 @@ from codeverse.conventions import to_snake
log = logging.getLogger(__name__)
-StopReason = Literal["pass", "plateau", "budget", "continue", "max_rounds"]
+StopReason = Literal["pass", "plateau", "budget", "continue", "max_rounds", "judge_unavailable"]
@dataclass(frozen=True)
@@ -38,7 +38,18 @@ class RoundPolicy:
target: float = 0.8 # rubric pass threshold (overridden from the rubric when known)
judge_on_gate_errors: bool = True # still judge when gates (not build) fail
max_refine_tasks: int = 6
- parallel_min_tasks: int = 3 # fan out only when >= this many file-disjoint groups
+ max_instructions_per_task: int = 6 # lines handed to ONE generation task (grouped by target)
+ parallel_min_tasks: int = 2 # fan out only when >= this many file-disjoint groups
+ n_candidates: int = 1 # best-of-N baseline (candidates generated in parallel, best kept)
+ pairwise_margin: float = 0.03 # |Δscore| below this = judge noise → pairwise tie-break
+ pairwise_min_confidence: float = 0.6 # new round replaces best only when pairwise is this sure
+ judge_samples: int = 1 # VLM judge samples per round (flash: std ≈ 0.001 between samples → 1 is enough)
+
+ def with_candidates(self, n: int | None) -> RoundPolicy:
+ """Copy with ``n_candidates`` set (``None`` → unchanged)."""
+ if n is None or n == self.n_candidates:
+ return self
+ return replace(self, n_candidates=max(1, int(n)))
class StopPolicy:
@@ -157,10 +168,12 @@ def build_refine_instructions(
*,
file_for_target: FileForTarget | None = None,
max_tasks: int = 6,
+ extra: Sequence[RefineTask] = (),
) -> list[RefineTask]:
- """Gate ERRORS first (with fix hints), then failed *must* acceptance items,
+ """Gate ERRORS first (with fix hints), then ``extra`` harness-derived tasks
+ (e.g. reference-silhouette mismatch), then failed *must* acceptance items,
then the judge's improvement plan; de-duplicated by (target, kind), capped.
- Gate/acceptance tasks are never dropped by the cap unless they alone exceed it."""
+ Gate/acceptance/extra tasks are never dropped by the cap unless they alone exceed it."""
known = _known_targets(plan)
tasks: list[RefineTask] = []
seen: set[tuple[str, str]] = set()
@@ -180,6 +193,8 @@ def build_refine_instructions(
text = f.message if not f.fix_hint else f"{f.message} FIX: {f.fix_hint}"
_add(RefineTask(target=f.target or "overall", kind=f"gate:{g.gate}", instruction=text,
priority=0, source="gate"))
+ for t in extra:
+ _add(t.model_copy())
for a in acceptance_failures:
if a.priority != "must":
continue
@@ -234,7 +249,49 @@ def plan_parallel_groups(tasks: Sequence[RefineTask]) -> list[TaskGroup]:
return out
+def compact_instructions(tasks: Sequence[RefineTask], max_lines: int = 6) -> list[str]:
+ """The instruction lines handed to ONE generation task: grouped by target
+ (instances ``Leg_0``/``Leg_1`` fold into ``Leg``), ordered by priority, capped
+ at ``max_lines``. A flash-class agent given 12 near-identical connectivity
+ errors fixes none; given "FrontLeg: (a) … (b) …" it fixes the part."""
+ if not tasks:
+ return []
+ groups: dict[str, list[RefineTask]] = {}
+ for t in sorted(tasks, key=lambda t: t.priority):
+ groups.setdefault(_instance_base(t.target), []).append(t)
+ lines: list[str] = []
+ for target, members in groups.items():
+ if len(members) == 1:
+ lines.append(members[0].line())
+ continue
+ bits = []
+ for i, t in enumerate(members):
+ who = f" [{t.target}]" if t.target != target else ""
+ bits.append(f"({chr(97 + i % 26)}){who} [{t.source}/{t.kind}] {t.instruction}")
+ files = sorted({f for t in members for f in t.files})
+ tail = f" (files: {', '.join(files)})" if files else ""
+ lines.append(f"{target}: " + "; ".join(bits) + tail)
+ if len(lines) > max_lines:
+ dropped = len(lines) - max_lines
+ lines = lines[:max_lines]
+ log.info("compact_instructions: %d target group(s) deferred to a later round", dropped)
+ return lines
+
+
# ----------------------------------------------------------------------------- helpers
+def _split_instance(target: str) -> tuple[str, str]:
+ """``BackLeg_1`` → (``BackLeg``, ``1``) per the ``Name_0..N-1`` instance naming
+ convention; anything else → (target, "")."""
+ base, sep, suffix = (target or "").rpartition("_")
+ if sep and base and suffix.isdigit():
+ return base, suffix
+ return target or "overall", ""
+
+
+def _instance_base(target: str) -> str:
+ return _split_instance(target)[0]
+
+
def _known_targets(plan: Plan | None) -> dict[str, str]:
"""snake → canonical name for every part/zone/asset/joint/camera in the plan."""
names: dict[str, str] = {}
@@ -247,7 +304,18 @@ def _known_targets(plan: Plan | None) -> dict[str, str]:
def _canon_target(target: str, known: dict[str, str]) -> str:
- return known.get(to_snake(target), target)
+ """Plan name for ``target``; instance suffixes (``Leg_1``, ``leg.2``) keep the
+ suffix but take the plan's spelling of the base name."""
+ hit = known.get(to_snake(target))
+ if hit is not None:
+ return hit
+ base, suffix = _split_instance(target)
+ if suffix and to_snake(base) in known:
+ return f"{known[to_snake(base)]}_{suffix}"
+ snake = to_snake(target)
+ if snake.endswith("s") and snake[:-1] in known: # judges say "Legs" for the plan's "Leg"
+ return known[snake[:-1]]
+ return target
def _acceptance_target(item: AcceptanceItem, known: dict[str, str]) -> str:
diff --git a/harness/codeverse/prompts/blender/contract.md b/harness/codeverse/prompts/blender/contract.md
index f7607270..289619fa 100644
--- a/harness/codeverse/prompts/blender/contract.md
+++ b/harness/codeverse/prompts/blender/contract.md
@@ -1,81 +1,127 @@
# Blender (bpy) authoring contract — track `static_object`, language `blender`
-## Files
-* `src/model.py` — ONE pure-bpy script. The harness runs it with
- `blender -b --factory-startup --python wrappers/run_bpy.py -- --script src/model.py`
- inside an **emptied scene**, then applies transforms, takes a census, exports
- `artifacts/object.glb` (Y-up) and `object.stl`. You never export or render.
+## Files (multi-file: one file per plan part, so parts can be refined in parallel)
+* `src/model.py` — the ENTRY: imports the part builders, calls them in plan order, runs the
+ self-check. No geometry of its own beyond small glue.
+* `src/parts/<snake>.py` — ONE per plan part (`SeatCushion` → `src/parts/seat_cushion.py`),
+ exporting `def build_seat_cushion() -> bpy.types.Object` that builds the part at its WORLD
+ pose with the exact object name and returns it. Instances (`Leg_0 … Leg_3`) are looped
+ INSIDE that one file, each TOP-LEVEL — NEVER under a parent Empty (parts are measured as
+ top-level objects; an Empty merges them into one → part missing). Self-contained (own small
+ helpers); it only DEFINES — never builds at import time (model.py calls each builder once).
+* `src/` is on `sys.path`: `from parts.seat import build_seat` or `import parts.seat`. Optional
+ shared helpers: `src/parts/_common.py` (underscore = not a part). Small objects (1–2 parts)
+ may use a single `src/model.py` (example B).
+* The harness runs `src/model.py` with `blender -b --factory-startup` in an **emptied scene**,
+ takes a census and exports `artifacts/object.glb` (Y-up) + `object.stl`; build errors come
+ back as `src/parts/<file>.py:<line>`. You never export or render.
## Frame, units, placement
* **Z is up, -Y is the front, +X is the right. Meters.** (glTF export maps this to
- Y-up / +Z-front automatically — do not pre-rotate.)
-* The object stands on z = 0 (lowest vertex at z = 0 ± 1 mm), footprint centred on the
- Z axis. Real-world dimensions (a chair seat at z ≈ 0.45, a table top at z ≈ 0.75).
+ Y-up / +Z-front automatically — do not pre-rotate.) The object stands on z = 0 (lowest
+ vertex at z = 0 ± 1 mm), footprint centred on the Z axis; real-world dimensions.
## Naming and structure
-* One Blender **object per plan part**, `obj.name = "<PartName>"` in PascalCase exactly
- as the plan says (`SeatCushion`, `LeftFrontLeg`). Blender auto-suffixes duplicates
- (`Leg.001`) — that is a contract violation: give every instance its own unique plan name
- (`LegFrontLeft`, `LegFrontRight`, …) or the plan's `<Name>1..N`.
-* Meshes only (no empties as parts, no curves left un-converted, no cameras/lights).
- Link every object to `bpy.context.scene.collection` (or a child collection).
-* Put part-local helpers in functions: `build_<snake>() -> bpy.types.Object`; call them
- from a `main()` at the bottom; `main()` is executed at import time (module level call).
-
-## Allowed imports
-`bpy`, `bmesh`, `mathutils`, `math`, `random`, `itertools`, `functools`, `typing`,
-`dataclasses`. Nothing else (no numpy loops over vertices, no os/sys/subprocess/
-urllib/socket/pathlib, no `import codeverse`).
-
-## Forbidden calls
-`bpy.ops.render.*`, `bpy.ops.export_*`, `bpy.ops.import_*`, `bpy.ops.wm.*`,
-`bpy.ops.image.*`, `bpy.ops.screen.*`, `bpy.ops.view3d.*`, `bpy.data.libraries`,
-`bpy.app.timers`, `open(`, `exec(`, `eval(`, `__import__`, any camera / light creation,
-any `input()` / network / file write. Do not touch `bpy.context.scene.render` or
-`scene.world` — the harness owns render settings.
-
-## Limits
-≤ 600 k triangles total (aim 20–150 k); subdivision levels ≤ 2; no boolean chains > 12
-cutters per object; script finishes in < 120 s headless.
-
-## Self-check (do this at the end of `main()`)
-```python
+* One Blender **object per plan part**, `obj.name = "<PartName>"` in PascalCase exactly as the
+ plan says. Auto-suffixed duplicates (`Leg.001`) violate it: name instances `<Name>_0 … <Name>_N-1`.
+* Meshes only (no empties as parts, no un-converted curves, no cameras/lights); link every
+ object to `bpy.context.scene.collection`. Plan numbers = constants at the top of each part
+ file; keep each part inside its plan bbox; attached parts touch (2–4 mm overlap is fine).
+
+## Allowed imports · forbidden calls · limits
+* Imports: `bpy`, `bmesh`, `mathutils`, `math`, `random`, `itertools`, `functools`, `typing`,
+ `dataclasses`, and your own `parts.*` modules. Nothing else (no numpy loops over vertices,
+ no os/sys/subprocess/urllib/socket/pathlib, no `import codeverse`).
+* Forbidden: `bpy.ops.render.*`, `bpy.ops.export_*`, `bpy.ops.import_*`, `bpy.ops.wm.*`,
+ `bpy.ops.image.*`, `bpy.ops.screen.*`, `bpy.ops.view3d.*`, `bpy.data.libraries`,
+ `bpy.app.timers`, `open(`, `exec(`, `eval(`, `__import__`, camera / light creation, `input()`,
+ network, file writes; never touch `bpy.context.scene.render` / `scene.world` (harness-owned).
+* Limits: ≤ 600 k triangles total (aim 20–150 k); subdivision levels ≤ 2; ≤ 12 boolean cutters
+ per object; < 120 s headless. Self-check at the end of `main()` (see the examples).
+
+## COMPLETE minimal example A — multi-file (verified with Blender 5.0 headless)
+`src/parts/seat.py`
+```py
+import bpy, bmesh
+
+SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45 # metres, from the plan (bbox top at 0.45)
+
+def build_seat() -> bpy.types.Object:
+ """Seat — round wooden disc; top face at z = SEAT_Z. Returns the object at world pose."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=SEAT_D / 2, radius2=SEAT_D / 2, depth=SEAT_T)
+ me = bpy.data.meshes.new("Seat"); bm.to_mesh(me); bm.free()
+ seat = bpy.data.objects.new("Seat", me); seat.location = (0, 0, SEAT_Z - SEAT_T / 2)
+ bpy.context.scene.collection.objects.link(seat)
+ bev = seat.modifiers.new("Bevel", 'BEVEL'); bev.width = 0.006; bev.segments = 3
+ wood = bpy.data.materials.new("Wood")
+ bsdf = wood.node_tree.nodes["Principled BSDF"] # nodes exist by default (4.x/5.x)
+ bsdf.inputs["Base Color"].default_value, bsdf.inputs["Roughness"].default_value = (0.55, 0.33, 0.16, 1.0), 0.6
+ seat.data.materials.append(wood)
+ return seat
+```
+`src/parts/leg.py`
+```py
+import bpy, bmesh, math
+
+LEG_R, LEG_N, LEG_RING = 0.02, 3, 0.12 # metres, from the plan
+LEG_H = 0.45 - 0.04 + 0.004 # reaches 4 mm into the seat (weld)
+
+def build_leg() -> list[bpy.types.Object]:
+ """Leg x3 — steel rods Leg_0..Leg_2 on a ring, each TOP-LEVEL (no parent Empty!)."""
+ steel = bpy.data.materials.new("Steel"); bsdf = steel.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (0.6, 0.6, 0.62, 1.0)
+ bsdf.inputs["Roughness"].default_value, bsdf.inputs["Metallic"].default_value = 0.35, 1.0
+ legs = []
+ for i in range(LEG_N):
+ a = 2 * math.pi * i / LEG_N
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=LEG_R, radius2=LEG_R, depth=LEG_H)
+ me = bpy.data.meshes.new(f"Leg_{i}"); bm.to_mesh(me); bm.free()
+ leg = bpy.data.objects.new(f"Leg_{i}", me)
+ leg.location = (LEG_RING * math.cos(a), LEG_RING * math.sin(a), LEG_H / 2)
+ bpy.context.scene.collection.objects.link(leg)
+ leg.data.materials.append(steel); legs.append(leg)
+ return legs
+```
+`src/model.py`
+```py
+"""Stool — entry: imports the part builders, calls them in plan order, self-checks."""
import bpy
+from parts.seat import build_seat
+from parts.leg import build_leg
+
def _selfcheck() -> None:
- meshes = [o for o in bpy.data.objects if o.type == 'MESH']
- assert meshes, "no mesh objects built"
- for o in meshes:
- assert '.' not in o.name, f"auto-suffixed name {o.name!r}: rename the instance"
+ names = [o.name for o in bpy.data.objects if o.type == 'MESH']
+ assert names and all('.' not in n for n in names), f"missing or auto-suffixed meshes: {names}"
+
+def main() -> None:
+ build_seat()
+ build_leg()
+ _selfcheck()
+
+main()
```
-## COMPLETE minimal example (verified with Blender 5.0 headless)
+## COMPLETE minimal example B — single file (small objects; verified with Blender 5.0)
```python
import bpy, bmesh, math
SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45 # metres, from the plan
LEG_R, LEG_N, LEG_RING = 0.02, 3, 0.12
-def _link(obj: bpy.types.Object) -> bpy.types.Object:
- bpy.context.scene.collection.objects.link(obj)
- return obj
-
-def make_cylinder(name: str, radius: float, depth: float, location, segments: int = 32):
+def make_cylinder(name, radius, depth, location, segments=32):
"""Cylinder along Z centred at `location` via bmesh (no operator/context needed)."""
bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=segments,
- radius1=radius, radius2=radius, depth=depth)
- me = bpy.data.meshes.new(name)
- bm.to_mesh(me); bm.free()
- obj = bpy.data.objects.new(name, me)
- obj.location = location
- return _link(obj)
-
-def make_material(name: str, rgb, roughness=0.5, metallic=0.0) -> bpy.types.Material:
- mat = bpy.data.materials.new(name)
- bsdf = mat.node_tree.nodes["Principled BSDF"] # nodes exist by default (4.x/5.x)
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth)
+ me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new(name, me); obj.location = location
+ bpy.context.scene.collection.objects.link(obj); return obj
+
+def make_material(name, rgb, roughness=0.5, metallic=0.0):
+ mat = bpy.data.materials.new(name); bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
- bsdf.inputs["Roughness"].default_value = roughness
- bsdf.inputs["Metallic"].default_value = metallic
+ bsdf.inputs["Roughness"].default_value, bsdf.inputs["Metallic"].default_value = roughness, metallic
return mat
def build_seat() -> bpy.types.Object:
@@ -85,17 +131,20 @@ def build_seat() -> bpy.types.Object:
return seat
def build_leg(i: int) -> bpy.types.Object:
- a = 2 * math.pi * i / LEG_N
- x, y = LEG_RING * math.cos(a), LEG_RING * math.sin(a)
- h = SEAT_Z - SEAT_T + 0.004 # overlaps the seat by 4 mm (weld)
- leg = make_cylinder(f"Leg{i + 1}", LEG_R, h, (x, y, h / 2), 24)
+ a, h = 2 * math.pi * i / LEG_N, SEAT_Z - SEAT_T + 0.004 # 4 mm into the seat (weld)
+ leg = make_cylinder(f"Leg{i + 1}", LEG_R, h, (LEG_RING * math.cos(a), LEG_RING * math.sin(a), h / 2), 24)
leg.data.materials.append(make_material(f"Steel{i + 1}", (0.6, 0.6, 0.62), 0.35, 1.0))
return leg
+def _selfcheck() -> None:
+ names = [o.name for o in bpy.data.objects if o.type == 'MESH']
+ assert names and all('.' not in n for n in names), f"missing or auto-suffixed meshes: {names}"
+
def main() -> None:
build_seat()
for i in range(LEG_N):
build_leg(i)
+ _selfcheck()
main()
```
diff --git a/harness/codeverse/prompts/blender/cookbook.md b/harness/codeverse/prompts/blender/cookbook.md
index c8ca5ee5..043cf0d8 100644
--- a/harness/codeverse/prompts/blender/cookbook.md
+++ b/harness/codeverse/prompts/blender/cookbook.md
@@ -2,12 +2,61 @@
Every snippet below runs as-is in `blender -b --factory-startup` (they are executed in
order by the harness test suite). Z-up, −Y front, meters, PascalCase object names.
-Use `read_cookbook(section="<heading>")` to fetch one chapter.
+Files: `src/model.py` (entry) + `src/parts/<snake>.py` (one `build_<snake>()` per plan part) —
+see "File layout". Use `read_cookbook(section="<heading>")` to fetch one chapter.
-## Skeleton
+## File layout (multi-file: model.py + parts/<snake>.py)
-A well-structured `src/model.py`: constants on top, tiny data-API helpers, one
-`build_<part>()` per plan part returning the object, `main()` at the bottom.
+The harness lays down one file per plan part so parts can be refined in parallel:
+
+```text
+src/model.py ENTRY — imports the builders, calls them in plan order, self-checks
+src/parts/seat.py def build_seat() -> bpy.types.Object (one per plan part, snake_case)
+src/parts/leg.py def build_leg() -> Leg_0..Leg_3, each TOP-LEVEL (instances loop here; no parent Empty)
+src/parts/_common.py optional shared helpers (underscore = not a part; never required)
+```
+
+Rules that the lint enforces: the part file `src/parts/<snake>.py` must define
+`build_<snake>()`; part files only DEFINE (no module-level `build_*()` / `main()` calls —
+model.py calls each builder once); `src/` is on `sys.path`, so model.py does
+`from parts.seat import build_seat` (or `import parts.seat`). Build errors come back as
+`src/parts/<file>.py:<line>`. A complete verified 3-file example is in the contract.
+
+A part file, fully self-contained (own helpers, plan numbers on top):
+
+`src/parts/mug_body.py`
+```py
+import bpy, bmesh
+
+MUG_R, MUG_H, WALL = 0.042, 0.095, 0.004 # plan numbers (metres)
+
+def _link(obj):
+ bpy.context.scene.collection.objects.link(obj); return obj
+
+def build_mug_body() -> bpy.types.Object:
+ """MugBody — cylinder on z=0, hollowed later with a boolean; returns the object at world pose."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=MUG_R, radius2=MUG_R, depth=MUG_H)
+ me = bpy.data.meshes.new("MugBody"); bm.to_mesh(me); bm.free()
+ body = bpy.data.objects.new("MugBody", me); body.location = (0, 0, MUG_H / 2)
+ return _link(body)
+```
+`src/model.py`
+```py
+import bpy
+from parts.mug_body import build_mug_body
+
+def main() -> None:
+ build_mug_body()
+ assert all('.' not in o.name for o in bpy.data.objects), "auto-suffixed names"
+
+main()
+
+```
+
+Small objects (1–2 parts) may keep everything in one `src/model.py`; the rest of this
+cookbook is written that way. Every snippet below assumes these helpers (define them once
+per file that uses them — part files are self-contained):
```python
import bpy, bmesh, math, random
@@ -440,8 +489,10 @@ for o in bpy.data.objects:
if o.name.startswith("Leg"): move_to(o, legs)
```
-Why: parenting is fine for organisation but the exporter bakes world transforms —
-**never leave a part as a child of an empty with a non-identity scale**. `join()` inherits
+Why: use COLLECTIONS for organisation (they are not exported as nodes). **Never parent
+parts or instances under an Empty**: the harness measures top-level GLB nodes as parts, so
+an Empty parent merges its whole subtree into ONE part (plan part reported missing) — and an
+empty with non-identity scale also skews the baked world transforms. `join()` inherits
the ACTIVE object's transform; make the largest/identity object active.
## Proportions and detail (how to look good cheaply)
@@ -565,7 +616,14 @@ fasteners). Name every mass as the plan does; instances by `linked_copy`.
19. **Huge scripts / per-vertex Python loops over 500 k verts** time out → use modifiers,
`foreach_set`, or fewer segments.
20. **Parenting with scaled parents** → children inherit scale; export bakes it, bevels go
- elliptical. Parent only to identity-scale empties, or not at all.
+ elliptical. Do not parent parts at all — an Empty parent also merges its children into
+ ONE measured part (plan part reported missing); group with collections instead.
+21. **`ModuleNotFoundError: No module named 'parts.seat_cushion'`** → the part file must be
+ `src/parts/seat_cushion.py` (snake_case of the plan name); `src/` is on `sys.path`, do
+ not add path hacks. **`ImportError: cannot import name 'build_x'`** → the part file must
+ define exactly `def build_<snake>()`.
+22. **A part appears twice (`Seat.001`)** → the part file calls `build_seat()` at module level
+ AND model.py calls it. Part files only define; model.py calls each builder once.
## Self-check (before you call it done)
diff --git a/harness/codeverse/prompts/glsl_shader/contract.md b/harness/codeverse/prompts/glsl_shader/contract.md
new file mode 100644
index 00000000..6780a53b
--- /dev/null
+++ b/harness/codeverse/prompts/glsl_shader/contract.md
@@ -0,0 +1,109 @@
+# glsl_shader authoring contract (Shadertoy-style fragment shader, GLSL 330 core)
+
+You write ONE fragment shader body; the harness wraps it, compiles it with moderngl (OpenGL 3.3 core,
+headless), renders frames at the plan's resolution for t = 0, 1, 2.5, 4, 6 s (plus a preview GIF) and
+measures / judges the frames. The code is the deliverable.
+
+## Files
+```
+src/shader.frag REQUIRED the image pass (your code; no #version, no uniform/out declarations)
+src/common.glsl optional helper functions / constants, pasted ABOVE shader.frag (and buffer_a.frag) automatically
+src/buffer_a.frag optional ONE feedback buffer pass (Shadertoy "Buffer A"): rendered every frame before the image pass
+```
+Nothing else is read. No textures, no files, no includes.
+
+## What the harness prepends (DO NOT write these lines yourself — redeclaring them is a lint ERROR)
+```glsl
+#version 330 core
+uniform float u_time; // seconds (frames sampled at 0, 1, 2.5, 4, 6 s; preview up to duration_s)
+uniform vec2 u_resolution; // pixels, e.g. 1280x720
+uniform vec2 u_mouse; // always (0,0) headless — do not depend on it
+uniform int u_frame; // frame counter
+uniform sampler2D u_prev; // previous frame of THIS pass (feedback / trails); black at frame 0
+uniform sampler2D u_noise; // 256x256 RGBA white noise, repeat, linear (texture(u_noise, uv*k).r)
+uniform sampler2D u_buffer_a; // output of src/buffer_a.frag (only when that file exists)
+#define iTime u_time // Shadertoy aliases: iTime iResolution iFrame iMouse iChannel0(=u_prev) iChannel1(=u_noise)
+out vec4 fragColor; // the ONLY output
+```
+NOT available: iChannel2/3, iDate, iSampleRate, iChannelResolution, textures/images/videos/sound.
+
+## Entry point (one of the two; the harness detects which)
+```glsl
+void mainImage(out vec4 fragColor, in vec2 fragCoord) { ...; fragColor = vec4(col, 1.0); } // preferred
+// or: void main() { ...; fragColor = vec4(col, 1.0); } using gl_FragCoord.xy
+```
+`fragCoord` / `gl_FragCoord.xy` are PIXEL coordinates with origin BOTTOM-LEFT (y up). Use
+`vec2 p = (fragCoord - 0.5*u_resolution) / u_resolution.y;` for aspect-correct centred coords (|y| ≤ 0.5).
+`uv = fragCoord / u_resolution` for 0..1 (also the coordinate to sample u_prev / u_buffer_a).
+
+## Rules (lint + gates enforce them)
+* GLSL 330 core only: `texture()` not `texture2D`, `in/out` not `varying`, `fragColor` not `gl_FragColor`,
+ `mod(x,y)` not `%` on floats, constant loop bounds, `float` literals with a decimal point when in doubt.
+* Do not declare uniforms, `out` variables, `#version`, `precision`, `#include`.
+* Everything must MOVE with `u_time` (unless the brief says "static"): frames at t=0 and t=1 must differ.
+ A static result caps the score at 0.5; NaN/Inf pixels cap it at 0; all-black / blown-out frames cap at 0.5.
+* Guard the maths: `x / max(d, 1e-4)`, `sqrt(max(x, 0.0))`, `normalize()` only of non-zero vectors,
+ `clamp()` acos/asin inputs, `pow(max(x,0.0), k)`.
+* Keep it real-time: ≤ ~100 raymarch steps, ≤ 8 fbm octaves, no nested 100×100 loops.
+* Feedback (`u_prev`): sample at `uv` (optionally offset / scaled), mix with the new frame, and DECAY it
+ (`prev * 0.9`) — unbounded accumulation blows out. buffer_a.frag reads its own previous frame as `u_prev`;
+ shader.frag reads the buffer as `u_buffer_a` and its own previous frame as `u_prev`.
+* Deterministic: no randomness that changes per frame other than as a function of u_time / u_frame.
+
+## Build errors come back as `src/shader.frag:LINE: error: …` (line numbers refer to YOUR file).
+Common messages: "`x' undeclared" (typo / missing helper), "no matching function" (int vs float args →
+add `.0`), "too few components" (vec4(col) where col is vec3 → vec4(col, 1.0)), "redeclaration" (you declared
+a harness uniform — delete it).
+
+## COMPLETE VERIFIED EXAMPLE — `src/shader.frag` (fbm clouds, drifting, sun on an arc; renders clean)
+```glsl
+// src/shader.frag — "Afternoon cumulus": fbm clouds drifting over a gradient sky with a warm sun.
+// Harness provides: u_time, u_resolution, u_mouse, u_frame, u_prev, u_noise, u_buffer_a, out vec4 fragColor.
+const vec3 SKY_TOP = vec3(0.10, 0.32, 0.78);
+const vec3 SKY_HORIZ = vec3(0.62, 0.78, 0.95);
+const vec3 SUN_COL = vec3(1.00, 0.92, 0.75);
+const vec3 CLOUD_LIT = vec3(1.00, 0.98, 0.95);
+const vec3 CLOUD_SHAD = vec3(0.42, 0.50, 0.68);
+
+float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+float noise(vec2 p) {
+ vec2 i = floor(p), f = fract(p);
+ vec2 u = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x), mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
+}
+float fbm(vec2 p) { // 6 octaves, constant bound
+ float v = 0.0, a = 0.5;
+ mat2 m = mat2(0.8, 0.6, -0.6, 0.8);
+ for (int i = 0; i < 6; i++) { v += a * noise(p); p = m * p * 2.03 + 0.31; a *= 0.5; }
+ return v;
+}
+// cloud density in 0..1 at screen point p (y up), layer k selects parallax speed / scale
+float cloudLayer(vec2 p, float k, float t) {
+ vec2 q = p * (2.2 + 0.8 * k) + vec2(t * (0.04 + 0.03 * k), k * 7.3);
+ float d = fbm(q + 0.35 * fbm(q * 1.7 - t * 0.02)); // domain warp for billowy edges
+ return smoothstep(0.50, 0.70, d);
+}
+
+void mainImage(out vec4 fragColor, in vec2 fragCoord) {
+ vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // aspect-correct, centred, y up
+ float t = u_time;
+ // sky gradient
+ vec3 col = mix(SKY_HORIZ, SKY_TOP, smoothstep(-0.35, 0.55, p.y));
+ // sun: slow arc; disc + soft glow
+ vec2 sunPos = vec2(0.45 * cos(0.12 * t + 2.6), 0.18 + 0.12 * sin(0.12 * t + 2.6));
+ float sd = length(p - sunPos);
+ col += SUN_COL * (smoothstep(0.05, 0.035, sd) + 0.35 * exp(-8.0 * sd) + 0.08 * exp(-2.0 * sd));
+ // two cloud layers, far (dim, slow) then near (bright, fast), lit from the sun side
+ for (int k = 0; k < 2; k++) {
+ float fk = float(k);
+ float dens = cloudLayer(p, fk, t);
+ float lit = cloudLayer(p + 0.03 * normalize(sunPos - p + 1e-4), fk, t); // thinner towards the sun = lit
+ vec3 cloudCol = mix(CLOUD_SHAD, CLOUD_LIT, clamp(0.9 - 2.5 * (lit - dens) - 0.25 * fk, 0.0, 1.0));
+ col = mix(col, cloudCol, dens * (0.55 + 0.45 * fk));
+ }
+ // haze near the horizon + gentle vignette (colours above are already display-space: just clamp)
+ col = mix(col, SKY_HORIZ, 0.25 * smoothstep(0.1, -0.5, p.y));
+ col *= 1.0 - 0.20 * dot(p, p);
+ fragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
+}
+```
diff --git a/harness/codeverse/prompts/glsl_shader/cookbook.md b/harness/codeverse/prompts/glsl_shader/cookbook.md
new file mode 100644
index 00000000..97dd8681
--- /dev/null
+++ b/harness/codeverse/prompts/glsl_shader/cookbook.md
@@ -0,0 +1,179 @@
+# glsl_shader cookbook — copyable snippets (GLSL 330 core, harness uniforms u_time / u_resolution / u_prev / u_noise)
+
+All snippets assume `vec2 p = (fragCoord - 0.5*u_resolution) / u_resolution.y;` (centred, aspect-correct,
+y up) and `vec2 uv = fragCoord / u_resolution;` (0..1) unless stated. Put helpers in `src/common.glsl`.
+
+## Hash / noise / fbm
+```glsl
+float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); }
+float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
+vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); }
+float noise(vec2 p) { // value noise 0..1, smooth
+ vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x), mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
+}
+float noise3(vec3 p) { // 3D value noise (volumes, time as z)
+ vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ float n000 = hash33(i).x, n100 = hash33(i + vec3(1,0,0)).x, n010 = hash33(i + vec3(0,1,0)).x, n110 = hash33(i + vec3(1,1,0)).x;
+ float n001 = hash33(i + vec3(0,0,1)).x, n101 = hash33(i + vec3(1,0,1)).x, n011 = hash33(i + vec3(0,1,1)).x, n111 = hash33(i + vec3(1,1,1)).x;
+ return mix(mix(mix(n000, n100, f.x), mix(n010, n110, f.x), f.y), mix(mix(n001, n101, f.x), mix(n011, n111, f.x), f.y), f.z);
+}
+float fbm(vec2 p) { // 6 octaves, constant bound, rotated per octave
+ float v = 0.0, a = 0.5; mat2 m = mat2(0.8, 0.6, -0.6, 0.8);
+ for (int i = 0; i < 6; i++) { v += a * noise(p); p = m * p * 2.03 + 0.31; a *= 0.5; }
+ return v;
+}
+float ridged(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * (1.0 - abs(2.0 * noise(p) - 1.0)); p *= 2.1; a *= 0.5; } return v; }
+// cheap texture noise (GPU-fast): float n = texture(u_noise, p * 0.37 + u_time * 0.01).r;
+```
+
+## Domain warping (billowy clouds, smoke, marble)
+```glsl
+float warped(vec2 p, float t) {
+ vec2 q = vec2(fbm(p + vec2(0.0, t * 0.05)), fbm(p + vec2(5.2, 1.3)));
+ vec2 r = vec2(fbm(p + 4.0 * q + vec2(1.7, 9.2) + 0.15 * t), fbm(p + 4.0 * q + vec2(8.3, 2.8)));
+ return fbm(p + 4.0 * r);
+}
+```
+
+## Palettes, tonemapping, grading
+```glsl
+vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(6.28318 * (c * t + d)); }
+// e.g. neon: palette(t, vec3(0.5), vec3(0.5), vec3(1.0), vec3(0.0, 0.33, 0.67))
+// sunset: palette(t, vec3(0.5,0.4,0.3), vec3(0.5,0.4,0.3), vec3(1.0), vec3(0.0,0.1,0.2))
+vec3 tonemapACES(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }
+vec3 gamma(vec3 c) { return pow(max(c, 0.0), vec3(1.0 / 2.2)); }
+// final line for HDR-ish accumulations: fragColor = vec4(gamma(tonemapACES(col)), 1.0);
+// vignette: col *= 1.0 - 0.35 * dot(p, p); // dithering against banding: col += (hash12(fragCoord) - 0.5) / 255.0;
+```
+
+## SDF 2D shapes + anti-aliased edges
+```glsl
+float sdCircle(vec2 p, float r) { return length(p) - r; }
+float sdBox(vec2 p, vec2 b) { vec2 d = abs(p) - b; return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); }
+float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0); return length(pa - ba * h); }
+float sdStar(vec2 p, float r, float n) { float a = atan(p.y, p.x), s = 6.28318 / n; a = mod(a + s * 0.5, s) - s * 0.5; return length(p) * cos(a) - r; }
+float fill(float d) { return 1.0 - smoothstep(0.0, 1.5 / u_resolution.y, d); } // 1 px AA edge
+float stroke(float d, float w) { return 1.0 - smoothstep(w, w + 1.5 / u_resolution.y, abs(d)); }
+float glow(float d, float k) { return exp(-k * max(d, 0.0)); }
+mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }
+```
+
+## Raymarching template (3D sdf scene with lighting, fog, sky)
+```glsl
+float sdSphere(vec3 p, float r) { return length(p) - r; }
+float sdBox3(vec3 p, vec3 b) { vec3 q = abs(p) - b; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0); }
+float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; }
+float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }
+float map(vec3 p) { // the scene: ground + bobbing blobs
+ float ground = p.y + 1.0;
+ vec3 q = p; q.xz = mod(q.xz + 2.0, 4.0) - 2.0; // repetition
+ float blob = sdSphere(q - vec3(0.0, 0.3 * sin(u_time + p.x), 0.0), 0.7);
+ return smin(ground, blob, 0.5);
+}
+vec3 calcNormal(vec3 p) { vec2 e = vec2(1e-3, 0.0); return normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx))); }
+float softShadow(vec3 ro, vec3 rd) { float res = 1.0, t = 0.05; for (int i = 0; i < 32; i++) { float h = map(ro + rd * t); res = min(res, 10.0 * h / t); t += clamp(h, 0.02, 0.5); if (h < 1e-3 || t > 20.0) break; } return clamp(res, 0.0, 1.0); }
+void mainImage(out vec4 fragColor, in vec2 fragCoord) {
+ vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y;
+ vec3 ro = vec3(3.0 * cos(0.2 * u_time), 1.0, 3.0 * sin(0.2 * u_time)); // orbiting camera
+ vec3 ta = vec3(0.0, 0.0, 0.0);
+ vec3 ww = normalize(ta - ro), uu = normalize(cross(ww, vec3(0, 1, 0))), vv = cross(uu, ww);
+ vec3 rd = normalize(p.x * uu + p.y * vv + 1.6 * ww);
+ float t = 0.0; bool hit = false;
+ for (int i = 0; i < 96; i++) { float d = map(ro + rd * t); if (d < 1e-3) { hit = true; break; } t += d; if (t > 40.0) break; }
+ vec3 sky = mix(vec3(0.9, 0.8, 0.7), vec3(0.2, 0.4, 0.8), smoothstep(-0.1, 0.5, rd.y));
+ vec3 col = sky;
+ if (hit) {
+ vec3 pos = ro + rd * t, n = calcNormal(pos), lig = normalize(vec3(0.6, 0.8, 0.3));
+ float dif = max(dot(n, lig), 0.0) * softShadow(pos + n * 0.01, lig), amb = 0.5 + 0.5 * n.y;
+ vec3 mat = vec3(0.8, 0.5, 0.3);
+ col = mat * (dif * vec3(1.0, 0.9, 0.7) + amb * vec3(0.2, 0.3, 0.45));
+ col = mix(col, sky, 1.0 - exp(-0.02 * t * t)); // fog
+ }
+ fragColor = vec4(pow(col, vec3(0.4545)), 1.0);
+}
+```
+
+## Gradient sky, sun, stars, water
+```glsl
+vec3 skyGrad(vec2 p) { return mix(vec3(0.95, 0.6, 0.35), vec3(0.1, 0.25, 0.6), smoothstep(-0.3, 0.6, p.y)); }
+float sun(vec2 p, vec2 c, float r) { float d = length(p - c); return smoothstep(r, r * 0.8, d) + 0.3 * exp(-8.0 * d); }
+float stars(vec2 p, float density) { // twinkling hash stars
+ vec2 g = floor(p * density), f = fract(p * density);
+ float h = hash12(g); vec2 o = hash22(g) * 0.8 + 0.1;
+ float d = length(f - o);
+ float tw = 0.5 + 0.5 * sin(u_time * (2.0 + 3.0 * h) + h * 6.28);
+ return step(0.92, h) * smoothstep(0.08, 0.0, d) * tw;
+}
+float waterHeight(vec2 xz, float t) { return 0.05 * sin(xz.x * 4.0 + t * 1.5) + 0.03 * sin(xz.y * 6.0 - t * 1.1) + 0.04 * noise(xz * 3.0 + t * 0.4); }
+// water colour: mix(deep, shallow, fresnel) + specular: pow(max(dot(reflect(-lig, n), -rd), 0.0), 64.0)
+```
+
+## Rain / drops on glass (grid cells + trails, refracted background)
+```glsl
+vec2 dropsLayer(vec2 uv, float t, float scale) { // returns (mask, trail)
+ vec2 asp = vec2(2.0, 1.0); vec2 st = uv * scale * asp; vec2 id = floor(st);
+ float n = hash12(id); t += n * 6.28;
+ st.y += t * 0.25; id = floor(st); n = hash12(id); // scroll cells downward
+ vec2 f = fract(st) - 0.5;
+ float w = sin(t + n * 6.28) * (0.5 - abs(f.y)) ; f.x += w * 0.3; // wobble
+ vec2 d = f * vec2(1.0, 2.0);
+ float drop = smoothstep(0.1, 0.05, length(d));
+ float trail = smoothstep(0.1, 0.0, abs(f.x)) * smoothstep(0.5, -0.1, f.y) * step(0.0, f.y) * 0.5;
+ return vec2(drop, trail) * step(0.3, n);
+}
+// usage: vec2 dr = dropsLayer(uv, u_time, 8.0); vec2 off = dr.x * 0.03 * normalize(p + 1e-3); col = background(uv + off);
+```
+
+## Bokeh city lights (hash-placed discs, depth layers, pulsing)
+```glsl
+vec3 bokeh(vec2 p, float t) {
+ vec3 acc = vec3(0.0);
+ for (int layer = 0; layer < 3; layer++) {
+ float fl = float(layer), scale = 4.0 + 3.0 * fl, blur = 0.08 - 0.02 * fl;
+ vec2 q = p * scale + vec2(t * (0.02 + 0.01 * fl), 0.0);
+ vec2 id = floor(q), f = fract(q) - 0.5;
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
+ vec2 o = vec2(i, j); vec2 h = hash22(id + o); vec2 c = o + h - 0.5;
+ float r = 0.15 + 0.2 * hash12(id + o + 7.0);
+ float d = length(f - c) - r * 0.3;
+ float disc = smoothstep(blur, -blur, d) * (0.6 + 0.4 * sin(t * (0.5 + h.x) + h.y * 6.28));
+ vec3 tint = palette(h.x, vec3(0.5), vec3(0.5), vec3(1.0), vec3(0.0, 0.33, 0.67));
+ acc += disc * tint * (0.25 + 0.25 * fl);
+ }
+ }
+ return acc;
+}
+```
+
+## Feedback trails (u_prev) and Buffer A
+```glsl
+// shader.frag: decayed feedback + new emitter (particles / light streaks)
+vec3 prev = texture(u_prev, uv + vec2(0.0, -0.002)).rgb * 0.94; // drift + decay keeps it bounded
+vec3 col = max(prev, newFrameColour); // or prev + newFrameColour * 0.2
+fragColor = vec4(col, 1.0);
+// buffer_a.frag computes a simulation (e.g. reaction-diffusion, fluid-ish blur) reading texture(u_prev, uv) and its
+// 4 neighbours (uv ± 1.0/u_resolution); shader.frag then colours texture(u_buffer_a, uv).
+```
+
+## Instancing-like repetition in 2D (many shapes cheaply)
+```glsl
+// grid of rotating squares: vec2 g = p * 8.0; vec2 id = floor(g); vec2 f = fract(g) - 0.5;
+// f = rot2(u_time * (0.5 + hash12(id))) * f; float d = sdBox(f, vec2(0.25)); col += fill(d) * palette(hash12(id), ...);
+```
+
+## PITFALLS (each one cost a real run)
+* Integer division / int literals: `1/2 == 0`; `float x = 3;` is fine but `pow(2, 3)` / `mod(x, 2)` may fail on strict
+ drivers → always `2.0`. `%` is integer-only → `mod()`.
+* Loop bounds must be constant expressions (`for (int i = 0; i < 64; i++)`), break early inside.
+* `normalize(vec3(0))` / `0/0` / `sqrt(-x)` / `pow(neg, 0.5)` / `log(0)` → NaN → black speckles → score 0. Guard them.
+* `texture(u_prev, uv)` needs uv in 0..1 (fragCoord / u_resolution), NOT the centred `p`.
+* Aspect: divide by `u_resolution.y`, never by `u_resolution.xy` for shapes (ellipses otherwise).
+* `smoothstep(a, b, x)` needs a < b; AA width ≈ `1.5 / u_resolution.y`.
+* Brightness: accumulations (glow, bokeh sums) blow out → tonemap (`c/(1+c)` or ACES) before gamma; do not gamma twice.
+* Motion: use u_time directly (`sin(u_time)`, `fract(u_time*0.2)`); do NOT use u_frame alone (frames are sampled at
+ arbitrary times) and never seed per-frame randomness with u_frame (flicker).
+* `precision` qualifiers, `#version`, `#extension`, `#include`, `uniform` / `out` declarations: leave them out.
+* gl_FragCoord origin is bottom-left; y up. (The harness flips rows when writing PNGs, so what you compute is what you see.)
+* Symmetric patterns at t=0 (everything at the origin) look dead — offset phases with hashes.
diff --git a/harness/codeverse/prompts/opengl_python/contract.md b/harness/codeverse/prompts/opengl_python/contract.md
new file mode 100644
index 00000000..984d0e85
--- /dev/null
+++ b/harness/codeverse/prompts/opengl_python/contract.md
@@ -0,0 +1,239 @@
+# opengl_python authoring contract (raw OpenGL 3.3 core through moderngl, headless)
+
+You write ONE python module, `src/program.py`, that draws frames with raw OpenGL calls (moderngl API)
+and inline GLSL. The harness imports it in a headless EGL process, creates the context and an output
+framebuffer, calls your two functions, reads the pixels back (PNG per frame at t = 0, 1, 2.5, 4, 6 s +
+preview GIF), measures and judges them. The code is the deliverable.
+
+## Files
+```
+src/program.py REQUIRED defines setup() and render()
+src/*.glsl optional shader sources you ship; read with Path(__file__).with_name("x.glsl").read_text()
+```
+
+## The two entry points (exact signatures)
+```python
+def setup(ctx: moderngl.Context, width: int, height: int): # called ONCE
+ ...create programs, buffers, VAOs, textures, your own FBOs...
+ return state # any object; passed back to render()
+
+def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
+ ...draw the frame for time t (seconds) — multi-pass allowed into your own FBOs...
+ fbo.use() # the harness framebuffer (RGBA float, depth attached) — draw the FINAL image into it LAST
+```
+* `fbo` is already bound and cleared to (0,0,0,1) + depth 1.0 when render() is called; `ctx.viewport` is the
+ full size. If you switch to your own FBOs, call `fbo.use()` and reset `ctx.viewport = (0, 0, width, height)` before the
+ final pass. Never call `ctx.screen`.
+* `t` is absolute time in seconds; `frame` is the sample index (0, 1, 2 …; NOT a 60 fps counter). Frames must be a
+ pure function of `t` (same t → same image). Seed any randomness in setup (`np.random.default_rng(0)`).
+* Width/height come from the plan's resolution (default 1280x720).
+
+## Allowed / forbidden (AST lint enforces)
+* Imports: `moderngl`, `numpy`, `math`, `random`, `struct`, `array`, `pathlib`, `typing`, `dataclasses`, `itertools`,
+ `functools`, `collections`, `colorsys`. Nothing else — no glfw / pygame / pyglet / PyOpenGL / moderngl_window / PIL.
+* No `moderngl.create_context()` / `create_standalone_context()` (the harness owns the context), no windows, no
+ `time.time()` / clocks, no `open()` / file writes / subprocess / network / `os` / `sys`.
+* GLSL strings: `#version 330 core`, `in`/`out` qualifiers, `out vec4 fragColor;` (no gl_FragColor / varying).
+* Keep frame cost sane (≤ 1M instances·vertices, ≤ 4 full-screen passes); the harness times out at a few minutes per build.
+
+## Errors come back as `src/program.py:LINE: <Exception>`. GLSL compile errors show the driver log with line
+numbers inside the shader STRING; moderngl raises `KeyError: 'u_name'` when you set a uniform the compiler
+optimised away (unused) — remove the assignment or guard with `if "u_name" in prog:`.
+
+## Gates on the frames: NaN/Inf pixels → score 0; all frames identical (no motion) → ≤ 0.5; black / blown-out → ≤ 0.5.
+
+## COMPLETE VERIFIED EXAMPLE — `src/program.py` (200 instanced rotating cubes, orbiting camera, separable blur bloom)
+```python
+"""src/program.py — 200 instanced rotating cubes in a swirling cloud, lit, with a bloom-style post blur.
+Harness calls setup(ctx, width, height) once, then render(ctx, state, t, frame, fbo) per frame."""
+import math
+
+import moderngl
+import numpy as np
+
+N_CUBES = 200
+PALETTE = np.array([[0.95, 0.35, 0.25], [0.25, 0.65, 0.95], [0.95, 0.80, 0.30], [0.55, 0.90, 0.55]], dtype="f4")
+
+CUBE_VERT = """#version 330 core
+uniform mat4 u_view_proj;
+uniform float u_time;
+in vec3 in_pos; // per vertex
+in vec3 in_normal; // per vertex
+in vec3 in_offset; // per instance: orbit centre
+in vec3 in_color; // per instance
+in float in_phase; // per instance: spin phase / speed
+out vec3 v_normal;
+out vec3 v_color;
+out vec3 v_world;
+mat3 rotY(float a) { float c = cos(a), s = sin(a); return mat3(c, 0, s, 0, 1, 0, -s, 0, c); }
+mat3 rotX(float a) { float c = cos(a), s = sin(a); return mat3(1, 0, 0, 0, c, -s, 0, s, c); }
+void main() {
+ float spin = u_time * (0.6 + in_phase) + in_phase * 6.2831;
+ mat3 R = rotY(spin) * rotX(spin * 0.7);
+ // orbit the whole cloud slowly around Y and bob
+ vec3 centre = rotY(u_time * 0.25) * in_offset + vec3(0.0, 0.15 * sin(u_time * 1.3 + in_phase * 6.2831), 0.0);
+ vec3 world = centre + R * (in_pos * 0.18);
+ v_normal = R * in_normal;
+ v_color = in_color;
+ v_world = world;
+ gl_Position = u_view_proj * vec4(world, 1.0);
+}
+"""
+CUBE_FRAG = """#version 330 core
+in vec3 v_normal;
+in vec3 v_color;
+in vec3 v_world;
+out vec4 fragColor;
+void main() {
+ vec3 n = normalize(v_normal);
+ vec3 l1 = normalize(vec3(0.5, 0.9, 0.4)), l2 = normalize(vec3(-0.6, -0.2, -0.7));
+ float diff = max(dot(n, l1), 0.0) + 0.35 * max(dot(n, l2), 0.0);
+ float rim = pow(1.0 - max(dot(n, vec3(0.0, 0.0, 1.0)), 0.0), 3.0);
+ vec3 col = v_color * (0.15 + 0.85 * diff) + 0.4 * rim * v_color;
+ float fog = exp(-0.12 * max(0.0, -v_world.z - 4.0));
+ fragColor = vec4(col * fog, 1.0);
+}
+"""
+QUAD_VERT = """#version 330 core
+in vec2 in_pos;
+out vec2 v_uv;
+void main() { v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }
+"""
+BLUR_FRAG = """#version 330 core
+uniform sampler2D u_tex;
+uniform vec2 u_dir; // (1/w, 0) or (0, 1/h)
+in vec2 v_uv;
+out vec4 fragColor;
+void main() {
+ float w[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216);
+ vec3 acc = texture(u_tex, v_uv).rgb * w[0];
+ for (int i = 1; i < 5; i++) {
+ acc += texture(u_tex, v_uv + u_dir * float(i) * 2.0).rgb * w[i];
+ acc += texture(u_tex, v_uv - u_dir * float(i) * 2.0).rgb * w[i];
+ }
+ fragColor = vec4(acc, 1.0);
+}
+"""
+COMPOSITE_FRAG = """#version 330 core
+uniform sampler2D u_scene;
+uniform sampler2D u_blur;
+in vec2 v_uv;
+out vec4 fragColor;
+void main() {
+ vec3 scene = texture(u_scene, v_uv).rgb;
+ vec3 bloom = texture(u_blur, v_uv).rgb;
+ vec2 p = v_uv - 0.5;
+ vec3 bg = mix(vec3(0.05, 0.04, 0.10), vec3(0.12, 0.10, 0.22), 1.0 - length(p) * 1.2); // dark vignette gradient
+ vec3 col = bg + scene + 0.5 * bloom;
+ col = col / (1.0 + col); // tonemap
+ fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0);
+}
+"""
+
+
+def _cube_mesh() -> np.ndarray:
+ """36 vertices × (pos3 + normal3), unit cube centred at origin."""
+ faces = [((0, 0, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)),
+ ((0, 0, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1)),
+ ((1, 0, 0), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1)),
+ ((-1, 0, 0), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1)),
+ ((0, 1, 0), (-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1)),
+ ((0, -1, 0), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1))]
+ data = []
+ for n, a, b, c, d in faces:
+ for v in (a, b, c, a, c, d):
+ data += [v[0] * 0.5, v[1] * 0.5, v[2] * 0.5, *n]
+ return np.array(data, dtype="f4")
+
+
+def _perspective(fov_deg, aspect, near, far):
+ f = 1.0 / math.tan(math.radians(fov_deg) / 2)
+ m = np.zeros((4, 4), dtype="f4")
+ m[0, 0], m[1, 1] = f / aspect, f
+ m[2, 2], m[2, 3], m[3, 2] = (far + near) / (near - far), 2 * far * near / (near - far), -1.0
+ return m
+
+
+def _look_at(eye, target, up=(0.0, 1.0, 0.0)):
+ eye, target, up = (np.array(v, dtype="f4") for v in (eye, target, up))
+ f = target - eye
+ f /= np.linalg.norm(f)
+ s = np.cross(f, up)
+ s /= np.linalg.norm(s)
+ u = np.cross(s, f)
+ m = np.identity(4, dtype="f4")
+ m[0, :3], m[1, :3], m[2, :3] = s, u, -f
+ m[:3, 3] = -m[:3, :3] @ eye
+ return m
+
+
+def setup(ctx: moderngl.Context, width: int, height: int):
+ rng = np.random.default_rng(7) # deterministic layout
+ # instance data: offsets on a thick torus-ish ring, colours from the palette, phases
+ ang = rng.uniform(0, 2 * math.pi, N_CUBES)
+ rad = rng.uniform(1.2, 2.6, N_CUBES)
+ offsets = np.stack([rad * np.cos(ang), rng.uniform(-0.8, 0.8, N_CUBES), rad * np.sin(ang)], axis=1).astype("f4")
+ colors = PALETTE[rng.integers(0, len(PALETTE), N_CUBES)]
+ phases = rng.uniform(0, 1, N_CUBES).astype("f4")
+ inst = np.concatenate([offsets, colors, phases[:, None]], axis=1).astype("f4") # 7 floats per instance
+
+ cube_prog = ctx.program(vertex_shader=CUBE_VERT, fragment_shader=CUBE_FRAG)
+ vbo = ctx.buffer(_cube_mesh().tobytes())
+ ibo = ctx.buffer(inst.tobytes())
+ cube_vao = ctx.vertex_array(cube_prog, [(vbo, "3f 3f", "in_pos", "in_normal"),
+ (ibo, "3f 3f 1f/i", "in_offset", "in_color", "in_phase")])
+ # offscreen scene FBO (with depth) + two half-res blur FBOs (ping-pong)
+ scene_tex = ctx.texture((width, height), 4, dtype="f2")
+ scene_fbo = ctx.framebuffer(color_attachments=[scene_tex], depth_attachment=ctx.depth_renderbuffer((width, height)))
+ bw, bh = width // 2, height // 2
+ blur_tex = [ctx.texture((bw, bh), 4, dtype="f2") for _ in range(2)]
+ for tex in blur_tex + [scene_tex]:
+ tex.filter = (moderngl.LINEAR, moderngl.LINEAR)
+ tex.repeat_x = tex.repeat_y = False
+ blur_fbo = [ctx.framebuffer(color_attachments=[tex]) for tex in blur_tex]
+
+ quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
+ blur_prog = ctx.program(vertex_shader=QUAD_VERT, fragment_shader=BLUR_FRAG)
+ comp_prog = ctx.program(vertex_shader=QUAD_VERT, fragment_shader=COMPOSITE_FRAG)
+ blur_vao = ctx.vertex_array(blur_prog, [(quad, "2f", "in_pos")])
+ comp_vao = ctx.vertex_array(comp_prog, [(quad, "2f", "in_pos")])
+ proj = _perspective(50.0, width / height, 0.1, 50.0)
+ return dict(cube_prog=cube_prog, cube_vao=cube_vao, scene_fbo=scene_fbo, scene_tex=scene_tex, blur_fbo=blur_fbo,
+ blur_tex=blur_tex, blur_prog=blur_prog, blur_vao=blur_vao, comp_prog=comp_prog, comp_vao=comp_vao,
+ proj=proj, size=(width, height), bsize=(bw, bh))
+
+
+def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
+ w, h = state["size"]
+ bw, bh = state["bsize"]
+ # pass 1: cubes into the scene FBO (depth on)
+ state["scene_fbo"].use()
+ ctx.viewport = (0, 0, w, h)
+ state["scene_fbo"].clear(0.0, 0.0, 0.0, 0.0, depth=1.0)
+ ctx.enable(moderngl.DEPTH_TEST)
+ eye = (5.5 * math.cos(t * 0.15), 1.8 + 0.5 * math.sin(t * 0.2), 5.5 * math.sin(t * 0.15))
+ view_proj = state["proj"] @ _look_at(eye, (0.0, 0.0, 0.0))
+ state["cube_prog"]["u_view_proj"].write(view_proj.T.astype("f4").tobytes()) # column-major for GLSL
+ state["cube_prog"]["u_time"].value = t
+ state["cube_vao"].render(mode=moderngl.TRIANGLES, instances=N_CUBES)
+ ctx.disable(moderngl.DEPTH_TEST)
+ # pass 2: separable blur, half resolution, horizontal then vertical
+ ctx.viewport = (0, 0, bw, bh)
+ state["blur_fbo"][0].use()
+ state["scene_tex"].use(location=0)
+ state["blur_prog"]["u_tex"].value = 0
+ state["blur_prog"]["u_dir"].value = (1.0 / bw, 0.0)
+ state["blur_vao"].render(mode=moderngl.TRIANGLE_STRIP)
+ state["blur_fbo"][1].use()
+ state["blur_tex"][0].use(location=0)
+ state["blur_prog"]["u_dir"].value = (0.0, 1.0 / bh)
+ state["blur_vao"].render(mode=moderngl.TRIANGLE_STRIP)
+ # pass 3: composite into the harness framebuffer (ALWAYS the last thing you draw)
+ fbo.use()
+ ctx.viewport = (0, 0, w, h)
+ state["scene_tex"].use(location=0)
+ state["blur_tex"][1].use(location=1)
+ state["comp_prog"]["u_scene"].value = 0
+ state["comp_prog"]["u_blur"].value = 1
+ state["comp_vao"].render(mode=moderngl.TRIANGLE_STRIP)
+```
diff --git a/harness/codeverse/prompts/opengl_python/cookbook.md b/harness/codeverse/prompts/opengl_python/cookbook.md
new file mode 100644
index 00000000..38a6d561
--- /dev/null
+++ b/harness/codeverse/prompts/opengl_python/cookbook.md
@@ -0,0 +1,156 @@
+# opengl_python cookbook — copyable moderngl snippets (GL 3.3 core, headless; harness calls setup()/render())
+
+## Fullscreen quad (every post-process / procedural pass starts here)
+```python
+QUAD_VERT = """#version 330 core
+in vec2 in_pos; out vec2 v_uv;
+void main() { v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }
+"""
+quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
+prog = ctx.program(vertex_shader=QUAD_VERT, fragment_shader=FRAG) # FRAG: `in vec2 v_uv; out vec4 fragColor; ...`
+vao = ctx.vertex_array(prog, [(quad, "2f", "in_pos")])
+vao.render(mode=moderngl.TRIANGLE_STRIP) # 4 vertices
+```
+A fragment-only effect (Shadertoy style) in this language = one quad pass with `uniform float u_time; uniform vec2 u_resolution;`
+set from render(): `prog["u_time"].value = t`.
+
+## VBO / VAO with interleaved attributes, index buffer
+```python
+verts = np.array([...], dtype="f4") # x y z nx ny nz u v per vertex
+vbo = ctx.buffer(verts.tobytes())
+ibo = ctx.buffer(np.array([...], dtype="i4").tobytes())
+vao = ctx.vertex_array(prog, [(vbo, "3f 3f 2f", "in_pos", "in_normal", "in_uv")], index_buffer=ibo)
+vao.render(mode=moderngl.TRIANGLES)
+# attribute names MUST match the `in` names in the vertex shader; unused `in`s are optimised away → skip them
+# with "3f 3f 2x4" (x = padding) or check `prog.get("in_uv", None)`.
+```
+
+## Instancing (hundreds–thousands of objects in one draw)
+```python
+inst = np.concatenate([offsets, colors, scales[:, None]], axis=1).astype("f4") # per-instance rows
+ibo = ctx.buffer(inst.tobytes())
+vao = ctx.vertex_array(prog, [(vbo, "3f 3f", "in_pos", "in_normal"),
+ (ibo, "3f 3f 1f/i", "in_offset", "in_color", "in_scale")]) # "/i" = per instance
+vao.render(mode=moderngl.TRIANGLES, instances=len(inst))
+# vertex shader: `in vec3 in_offset; ... vec3 world = in_offset + in_scale * (R * in_pos);`
+# animate per-instance in the SHADER from u_time + a per-instance phase attribute → no per-frame buffer uploads
+```
+Updating instance data per frame (CPU particles): `ibo.write(new_rows.astype("f4").tobytes())` (keep row count constant; use `orphan()` for speed).
+
+## Uniforms and matrices (numpy → GLSL is column-major: transpose!)
+```python
+prog["u_color"].value = (1.0, 0.5, 0.2) # vec3
+prog["u_time"].value = float(t) # float
+prog["u_mvp"].write(mvp.T.astype("f4").tobytes()) # mat4: transpose a row-major numpy matrix
+prog["u_tex"].value = 0 # sampler → texture unit; then tex.use(location=0)
+if "u_optional" in prog: prog["u_optional"].value = 1.0 # uniforms unused by the shader are optimised away → KeyError
+```
+```python
+def perspective(fov_deg, aspect, near, far):
+ f = 1.0 / math.tan(math.radians(fov_deg) / 2); m = np.zeros((4, 4), dtype="f4")
+ m[0, 0], m[1, 1] = f / aspect, f
+ m[2, 2], m[2, 3], m[3, 2] = (far + near) / (near - far), 2 * far * near / (near - far), -1.0
+ return m
+def look_at(eye, target, up=(0, 1, 0)):
+ eye, target, up = (np.array(v, dtype="f4") for v in (eye, target, up))
+ f = target - eye; f /= np.linalg.norm(f); s = np.cross(f, up); s /= np.linalg.norm(s); u = np.cross(s, f)
+ m = np.identity(4, dtype="f4"); m[0, :3], m[1, :3], m[2, :3] = s, u, -f; m[:3, 3] = -m[:3, :3] @ eye
+ return m
+def rot_y(a): c, s = math.cos(a), math.sin(a); return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")
+mvp = proj @ view @ model # then prog["u_mvp"].write(mvp.T.astype("f4").tobytes())
+```
+
+## Textures (procedural data, noise, LUTs)
+```python
+rng = np.random.default_rng(0)
+noise = rng.random((256, 256, 4), dtype=np.float32)
+tex = ctx.texture((256, 256), 4, noise.astype("f4").tobytes(), dtype="f4") # or uint8 data with dtype default
+tex.filter = (moderngl.LINEAR, moderngl.LINEAR); tex.repeat_x = tex.repeat_y = True
+tex.use(location=0); prog["u_noise"].value = 0
+# 3D textures: ctx.texture3d((32,32,32), 1, data.tobytes(), dtype="f4")
+```
+
+## FBOs: offscreen scene, ping-pong feedback, MRT
+```python
+color = ctx.texture((w, h), 4, dtype="f2") # f2 = half float (HDR); "f4" = float32
+depth = ctx.depth_renderbuffer((w, h))
+scene_fbo = ctx.framebuffer(color_attachments=[color], depth_attachment=depth)
+scene_fbo.use(); ctx.viewport = (0, 0, w, h); scene_fbo.clear(0.0, 0.0, 0.0, 0.0, depth=1.0)
+...draw...
+# ping-pong (feedback / simulation): two FBOs, read A write B, then swap
+pp_tex = [ctx.texture((w, h), 4, dtype="f4") for _ in range(2)]; pp_fbo = [ctx.framebuffer(color_attachments=[t]) for t in pp_tex]
+read, write = state["pp"]; pp_fbo[write].use(); pp_tex[read].use(location=0); sim_vao.render(moderngl.TRIANGLE_STRIP); state["pp"] = (write, read)
+# MRT: ctx.framebuffer(color_attachments=[albedo, normal, position], depth_attachment=depth) with
+# `layout(location = 0) out vec4 out_albedo; layout(location = 1) out vec4 out_normal; ...` in the fragment shader
+```
+ALWAYS end render() with `fbo.use(); ctx.viewport = (0, 0, width, height)` and the final draw into the harness `fbo`.
+
+## Separable Gaussian blur (bloom)
+```glsl
+#version 330 core
+uniform sampler2D u_tex; uniform vec2 u_dir; in vec2 v_uv; out vec4 fragColor;
+void main() {
+ float w[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216);
+ vec3 acc = texture(u_tex, v_uv).rgb * w[0];
+ for (int i = 1; i < 5; i++) { acc += texture(u_tex, v_uv + u_dir * float(i)).rgb * w[i]; acc += texture(u_tex, v_uv - u_dir * float(i)).rgb * w[i]; }
+ fragColor = vec4(acc, 1.0);
+}
+```
+Run horizontally (`u_dir = (1/w, 0)`) into FBO A, vertically (`(0, 1/h)`) into FBO B, at half resolution; composite `scene + k * blur`, tonemap `c/(1+c)`, gamma `pow(c, 1/2.2)`.
+
+## Lighting in GLSL (Blinn-Phong + rim + fog)
+```glsl
+vec3 n = normalize(v_normal); vec3 l = normalize(vec3(0.5, 0.9, 0.4)); vec3 v = normalize(u_cam - v_world);
+float diff = max(dot(n, l), 0.0); float spec = pow(max(dot(n, normalize(l + v)), 0.0), 48.0);
+float rim = pow(1.0 - max(dot(n, v), 0.0), 3.0);
+vec3 col = albedo * (0.15 + 0.85 * diff) + 0.3 * spec + 0.3 * rim * albedo;
+col = mix(col, fogColor, 1.0 - exp(-0.03 * dist));
+```
+
+## Geometry generators (numpy)
+```python
+def grid_mesh(nx, nz, size): # flat plane for water / terrain (vertex shader displaces y)
+ xs = np.linspace(-size, size, nx, dtype="f4"); zs = np.linspace(-size, size, nz, dtype="f4")
+ X, Z = np.meshgrid(xs, zs); verts = np.stack([X, np.zeros_like(X), Z], axis=-1).reshape(-1, 3)
+ idx = []
+ for j in range(nz - 1):
+ for i in range(nx - 1):
+ a = j * nx + i; idx += [a, a + nx, a + 1, a + 1, a + nx, a + nx + 1]
+ return verts.astype("f4"), np.array(idx, dtype="i4")
+def sphere_mesh(rings, sectors, r): # pos3 + normal3 interleaved
+ data, idx = [], []
+ for j in range(rings + 1):
+ v = j / rings; phi = v * math.pi
+ for i in range(sectors + 1):
+ u = i / sectors; th = u * 2 * math.pi
+ n = (math.sin(phi) * math.cos(th), math.cos(phi), math.sin(phi) * math.sin(th))
+ data += [r * n[0], r * n[1], r * n[2], *n]
+ for j in range(rings):
+ for i in range(sectors):
+ a = j * (sectors + 1) + i; idx += [a, a + sectors + 1, a + 1, a + 1, a + sectors + 1, a + sectors + 2]
+ return np.array(data, dtype="f4"), np.array(idx, dtype="i4")
+```
+
+## GL state you may need
+```python
+ctx.enable(moderngl.DEPTH_TEST); ctx.disable(moderngl.DEPTH_TEST)
+ctx.enable(moderngl.BLEND); ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA # or ONE, ONE for additive glow
+ctx.enable(moderngl.CULL_FACE); ctx.front_face = "ccw"
+ctx.point_size = 4.0 # with mode=moderngl.POINTS (gl_PointSize in the vertex shader needs ctx.enable(moderngl.PROGRAM_POINT_SIZE))
+ctx.line_width = 1.0 # > 1 is unsupported on core profiles: draw quads for thick lines
+```
+
+## PITFALLS (each one cost a real run)
+* `KeyError: 'u_x'` — the uniform/attribute is unused in the GLSL and got optimised away; remove the assignment or guard with `in prog`.
+* Matrices: numpy is row-major, GLSL column-major → `write(m.T.astype("f4").tobytes())`; never `value = m.tolist()`.
+* Read-back rows are bottom-up (the harness flips them): draw with y up, do NOT flip in your shader.
+* Forgetting `fbo.use()` + viewport reset before the final pass → the harness frame stays black (cap 0.5).
+* `ctx.clear()` clears whatever FBO is bound; clear your own FBOs explicitly (`my_fbo.clear(...)`).
+* Depth: attach a depth renderbuffer to your offscreen FBOs or z-fighting / wrong occlusion; disable DEPTH_TEST for fullscreen passes.
+* `#version 330 core` at the very top of every shader string (no blank line before it); `out vec4 fragColor;` not gl_FragColor.
+* Attribute format strings: count+type per attribute (`"3f 3f 2f"`), `/i` for per-instance buffers; mismatched float counts silently shuffle data.
+* Big per-frame uploads (100k particles in numpy each frame) are slow; move animation into the vertex shader via `u_time`.
+* Deterministic: `np.random.default_rng(SEED)` in setup, never `random.random()` inside render without a seed.
+* Textures sampled with `texture()` need `.use(location=k)` every frame *and* `prog["u_tex"].value = k`.
+* Lines wider than 1 px and GL_QUADS do not exist in core profile; `ctx.wireframe = True` works for debugging only.
+* Half-float (`f2`) colour targets clip at ~65504 — tonemap before writing bright accumulations.
diff --git a/harness/codeverse/prompts/scene_threejs/contract.md b/harness/codeverse/prompts/scene_threejs/contract.md
index ef6ec268..ea0a3e3e 100644
--- a/harness/codeverse/prompts/scene_threejs/contract.md
+++ b/harness/codeverse/prompts/scene_threejs/contract.md
@@ -16,7 +16,11 @@ The harness serves the workspace root over http (`public/assets/` is mounted at
or off — write shaders that work either way) and `loaders = { gltf, texture, cube,
manager }` (GLTFLoader etc.). It awaits `createScene`, validates the return value, then
for each camera renders at t ∈ {0, 1.5} s (calling `update`) and takes probes (tris, draw
-calls, console/shader errors, camera-inside-geometry, black/blown frames, fps).
+calls, console/shader errors, camera-inside-geometry, black/blown frames, content coverage,
+fps). Frame gate (`scene_frames`, ERROR on authored cameras): mean luminance < 0.12 or
+> 35 % near-black pixels = too dark; > 20 % pure white = blown; establishing shot with < 20 %
+content pixels (rest sky/ground) = content too small. Dusk/night = coloured, never black
+(cookbook: "Dusk / night lighting recipe").
## createScene return value
* `scene`: `THREE.Scene` with `scene.fog` set and a background colour or sky dome.
diff --git a/harness/codeverse/prompts/scene_threejs/cookbook.md b/harness/codeverse/prompts/scene_threejs/cookbook.md
index c6571404..7a43f43f 100644
--- a/harness/codeverse/prompts/scene_threejs/cookbook.md
+++ b/harness/codeverse/prompts/scene_threejs/cookbook.md
@@ -87,6 +87,47 @@ Numbers: sun 2.2–3.2, hemisphere 0.4–0.7 (never both high — washed out); s
frustum just past the bounds; fog near ≈ half the bounds, far ≈ 1.5–2 × the diagonal;
128 × 128 ground segments for 100 m (≈ 0.8 m resolution).
+## Dusk / night lighting recipe (dark scenes are the #1 gate failure)
+
+"Dusk", "night", "moonlit", "lantern-lit" means COLOURED darkness, never black. The harness
+measures every camera's frame (mean luminance, % near-black pixels) and a frame with mean
+luminance < 0.12 or > 35 % near-black pixels is a gate ERROR (`scene_frames: dark_frame`),
+capping the score at 0.55. Numbers that pass (ACES tone mapping, exposure 1.0):
+
+```js
+function buildDuskEnv(THREE, scene) {
+ const SKY = 0x3a2a55, HORIZON = 0xd9703a; // purple zenith, orange horizon — NOT black
+ scene.background = new THREE.Color(0x52355a);
+ scene.fog = new THREE.Fog(0x52355a, 30, 140); // fog colour == sky colour at the horizon
+ // fill: the sky itself lights the shade. Keep ≥ 0.5 at dusk, ≥ 0.35 at night.
+ scene.add(new THREE.HemisphereLight(0x7a5aa0, 0x3a2e22, 0.7));
+ // key: low warm sun (dusk) 2.0–3.0, or a cool moon 0.8–1.5 (night); still casts shadows
+ const key = new THREE.DirectionalLight(0xffa060, 2.4);
+ key.position.set(-60, 18, 30); key.castShadow = true;
+ key.shadow.mapSize.set(2048, 2048); key.shadow.bias = -0.0005;
+ Object.assign(key.shadow.camera, { left: -55, right: 55, top: 55, bottom: -55, near: 5, far: 200 });
+ scene.add(key, key.target);
+ // practicals: every lantern / window / fire = emissive surface + a small PointLight
+ const glow = new THREE.MeshStandardMaterial({ color: 0xffc070, emissive: 0xffa040, emissiveIntensity: 3.0 });
+ const lantern = new THREE.Mesh(new THREE.SphereGeometry(0.15, 12, 8), glow); lantern.position.set(4, 1.8, 2);
+ const light = new THREE.PointLight(0xffa040, 1.5, 9, 2); light.position.copy(lantern.position);
+ scene.add(lantern, light); // ≤ 12 PointLights, none cast shadows
+ return { update(t, dt) {} };
+}
+```
+
+Rules of thumb: sun/moon + hemisphere together ≥ 2.5 at dusk (≥ 1.5 at night with ≥ 6
+practicals); hemisphere sky/ground colours carry the mood (purple, indigo, amber) — turning
+the key down is NOT how you make dusk, tinting it is; ground albedo ≥ 0.25 (a 0x0b0f08 lawn
+is black under any light); no black `scene.background` — the sky gradient's horizon band
+should be the brightest thing in the frame.
+
+**Exposure self-check (after each build):** run `scene_views` and read the frame table
+(`camera_checks` in the render's metrics.json) for every authored camera: `mean_lum` ≥ 0.15, `dark_frac` ≤ 0.25,
+`blown_frac` ≤ 0.10, `content_frac` ≥ 0.25 on the establishing shot. If the establishing
+frame is below 0.15, raise HemisphereLight by +0.3 and the key by +0.8 and re-render — do not
+ship a frame you cannot read.
+
## Water plane (use makeWaterMaterial from the GLSL cookbook)
```js
@@ -359,6 +400,8 @@ demoScene.add(orchardDemo, campfireDemo, ff);
sceneSelfcheck(THREE, demoScene, planCameras(THREE, demoScene));
```
-Then: `build` → `scene_probe` (draws/tris/fps/console) → `render_sheet` per camera →
-`shader_probe` if you wrote GLSL → fix the worst → repeat. Look at every camera's frame:
-no black, no white-out, nothing floating, the subject actually in frame.
+Then: `build` → `scene_probe` (draws/tris/fps/console) → `scene_views` (authored cameras +
+overview rig, with `camera_checks`) → `shader_probe` if you wrote GLSL → fix the worst →
+repeat. Look at every camera's frame AND its numbers: `mean_lum` ≥ 0.15 (no black frames),
+`blown_frac` ≤ 0.10 (no white-out), `content_frac` ≥ 0.25 on the establishing shot (the
+subject, not sky/ground, fills the frame), `camera_in_geometry` false, nothing floating.
diff --git a/harness/codeverse/prompts/system/harness_contract.md b/harness/codeverse/prompts/system/harness_contract.md
index 5bd9962f..e744cb49 100644
--- a/harness/codeverse/prompts/system/harness_contract.md
+++ b/harness/codeverse/prompts/system/harness_contract.md
@@ -1,6 +1,6 @@
# 3dcodeverse harness contract (read once, obey always)
-You are a **3D code author** working inside the `3dcodeverse` harness (CLI `c3v`).
+You are a **3D code author** working inside the `3dcodeverse` harness (CLI `3dcv`).
You write RAW executable code in one language (bpy / CadQuery / three.js / URDF+bpy /
multi-file three.js+GLSL). The harness — not you — builds, exports, measures, renders
and judges. Your code is the deliverable; every GLB / PNG / URDF export is derived from it.
diff --git a/harness/codeverse/prompts/system/tools_usage.md b/harness/codeverse/prompts/system/tools_usage.md
index 6aee2e37..504ceb73 100644
--- a/harness/codeverse/prompts/system/tools_usage.md
+++ b/harness/codeverse/prompts/system/tools_usage.md
@@ -1,4 +1,4 @@
-# Using the c3v spatial tools (look before you leap)
+# Using the 3dcv spatial tools (look before you leap)
The tools are the harness's instruments. They are cheap, deterministic and honest —
trust their numbers over your mental model. Observations come back as
diff --git a/harness/codeverse/prompts/texturing/image_prompt_style.md b/harness/codeverse/prompts/texturing/image_prompt_style.md
new file mode 100644
index 00000000..dd1bdfb4
--- /dev/null
+++ b/harness/codeverse/prompts/texturing/image_prompt_style.md
@@ -0,0 +1,30 @@
+# Image prompt style (texturing)
+
+Every texture prompt sent to the image model is composed by the harness as:
+
+ <subject from the material plan>, <family phrase>, seamless tileable texture,
+ perfectly repeating at the edges, top-down orthographic view, flat even diffuse
+ lighting, no shadows, no specular highlights, no vignette, no depth of field,
+ no text, no watermark, no border, fills the whole frame edge to edge, photoreal,
+ uniform scale, 1:1 square
+
+Family phrases (appended after the subject so the image model knows what physical
+surface it is drawing):
+
+| family | phrase |
+|----------|--------|
+| wood | natural wood surface, visible grain and subtle pores, uniform plank-free grain unless planks are named |
+| metal | metal surface albedo only, matte base colour, no reflections or environment |
+| fabric | woven textile close-up, visible thread weave, soft matte |
+| stone | stone surface, natural mineral variation, matte |
+| plastic | smooth plastic surface, subtle fine noise, uniform colour |
+| leather | leather surface, fine natural grain and pores, matte |
+| glass | (skipped by default — glass keeps its flat material) |
+| ceramic | glazed ceramic surface, subtle speckle, uniform colour |
+| painted | painted surface, subtle brush or roller micro-texture, uniform colour |
+| rubber | matte rubber surface, fine uniform grain |
+| other | matte natural surface material, fine detail (objects: skipped unless the planner names a subject; scenes: soil, grass, moss, sand) |
+
+Negative phrasing is kept inside the positive prompt (Gemini image models have no
+negative prompt field). The pattern MUST be scale-free: no objects, no horizon, no
+single feature (one knot, one logo) that would repeat visibly every tile.
diff --git a/harness/codeverse/prompts/texturing/material_plan.md b/harness/codeverse/prompts/texturing/material_plan.md
new file mode 100644
index 00000000..62d1a88c
--- /dev/null
+++ b/harness/codeverse/prompts/texturing/material_plan.md
@@ -0,0 +1,49 @@
+You are the MATERIAL PLANNER of a 3D pipeline. You see labelled renders of a finished
+3D model (flat colours, no textures yet) plus its part list. Your job: decide, per part,
+which SEAMLESS TILEABLE ALBEDO TEXTURE (a flat photo-like pattern, generated by a
+text-to-image model) should be mapped onto it, and with which PBR factors.
+
+Return ONLY JSON matching the schema. One entry per plan part (use the exact part
+names from the table; instances such as Leg_0/Leg_1 are ONE plan part "Leg").
+
+## Rules
+* `material_family`: one of wood | metal | fabric | stone | plastic | leather | glass |
+ ceramic | painted | rubber | other.
+* Parts made of the SAME material share the SAME `texture_id` (short snake_case, e.g.
+ `walnut_wood`, `brushed_steel`, `grey_linen`). Fewer distinct textures is better:
+ aim for 1-4 per object.
+* `subject`: 6-20 words describing ONLY the surface pattern for the image model, e.g.
+ "oiled walnut wood grain, straight figure, warm brown" or "brushed stainless steel,
+ fine horizontal grain" or "grey-blue woven linen upholstery, visible weave".
+ Do NOT mention the object, its shape, lighting, or 3D — the harness appends the
+ "seamless, tileable, top-down, flat lighting, no shadows, no text, photoreal" suffix.
+ Describe colour explicitly (the texture is the final colour; there is no tint unless
+ you set `tint_rgb`). Patterns must be statistically uniform (no centred motif, no
+ single knot or logo, no radial composition) so they repeat invisibly.
+* `projection`: how the flat texture wraps the part — `box` (slabs, frames, boxes;
+ default), `cylinder` (legs, rods, poles, bottles — around the long axis), `planar_y`
+ (flat horizontal tops/ground seen from above), `planar_z` (flat vertical panels
+ seen from the front), or `auto` (let the harness decide from the shape).
+* `tile_size_m`: the real-world size (m) one texture tile covers — wood planks 0.3-0.6,
+ fine wood grain 0.2-0.35, fabric/leather 0.15-0.3, brushed metal 0.2-0.4, stone
+ 0.4-0.8, painted/plastic 0.3-0.5. Small objects (< 0.3 m) use 0.05-0.15.
+* `roughness` 0-1 (matte fabric 0.9, oiled wood 0.5, satin metal 0.35, plastic 0.4),
+ `metallic` 0 or 1 (1 ONLY for real metals).
+* `skip: true` for parts that should keep their current flat material: glass, mirrors,
+ chrome / polished metal (a flat photo cannot fake a reflection), emissive parts,
+ tiny parts (< 3 cm), and anything the brief says must stay a solid colour. Give a
+ one-line `reason`.
+* Be faithful to the brief and the part materials in the table: a "walnut" chair gets
+ walnut, not oak; an "upholstered" seat gets fabric, the frame stays wood.
+
+## Brief
+{{ spec_prompt }}
+{% if style_notes %}
+## Plan style notes
+{{ style_notes }}
+{% endif %}
+## Parts ({{ n_parts }}) — name · role · material (from the plan) · extents w×d×h (m) · instances
+{{ parts_table }}
+
+The attached image(s) are the current renders (labelled views). Use them to see each
+part's shape (for `projection`) and current colour. Output the JSON now.
diff --git a/harness/codeverse/prompts/texturing/scene_pack.md b/harness/codeverse/prompts/texturing/scene_pack.md
new file mode 100644
index 00000000..b023f53f
--- /dev/null
+++ b/harness/codeverse/prompts/texturing/scene_pack.md
@@ -0,0 +1,34 @@
+You are the MATERIAL PLANNER of a 3D SCENE pipeline. Before any scene code is
+written you choose the small set of SEAMLESS TILEABLE ALBEDO TEXTURES (flat photo-like
+patterns generated by a text-to-image model) that the scene code will be able to load
+and repeat over ground, walls, roofs, paths, water beds, fabric, rock, wood, etc.
+
+Return ONLY JSON matching the schema: {{ n_min }}-{{ n_max }} textures. Each has:
+* `name`: short snake_case identifier used as the file name (e.g. `moss_ground`,
+ `granite_gravel`, `cedar_planks`, `slate_roof`, `red_lacquer`, `bamboo_poles`).
+* `material_family`: wood | metal | fabric | stone | plastic | leather | glass |
+ ceramic | painted | rubber | other (use `other` for soil, grass, moss, sand, water
+ bed, foliage).
+* `subject`: 6-20 words describing ONLY the surface pattern and colour, scale-free and
+ statistically uniform: no objects, no horizon, no single large feature, NO centred or
+ radial/concentric composition (raked gravel = straight parallel ridges, not rings). The harness appends the
+ "seamless tileable, top-down, flat lighting, no shadows, no text, photoreal" suffix.
+* `tile_size_m`: real-world size one tile covers when repeated — ground covers
+ 1.0-3.0 m, gravel/sand 0.5-1.0 m, stone walls 0.8-1.5 m, planks 0.5-1.0 m, roof
+ tiles 0.6-1.2 m, fabric 0.2-0.4 m, bark 0.3-0.6 m.
+* `role`: what in the scene uses it (ground | path | wall | roof | water_bed | prop |
+ foliage | fabric | trim), one word.
+* `roughness` 0-1 and `metallic` 0/1.
+
+Cover every large visible surface the plan implies (ground types per zone first, then
+built structures, then prop materials). Prefer textures several zones can share.
+
+## Scene plan
+Title: {{ title }}
+Setting: {{ setting }}
+Mood: {{ mood }}
+Environment: {{ environment }}
+Zones:
+{{ zones }}
+Assets:
+{{ assets }}
diff --git a/harness/codeverse/prompts/threejs/contract.md b/harness/codeverse/prompts/threejs/contract.md
index 838fef18..1adcb1dd 100644
--- a/harness/codeverse/prompts/threejs/contract.md
+++ b/harness/codeverse/prompts/threejs/contract.md
@@ -17,6 +17,9 @@ The harness loads `src/object.js` in node, calls `build(THREE)`, and exports
* Each part Group is returned **at its world pose** (position set on the Group or the
meshes — geometry in meters, root scale (1,1,1), never `root.scale.set(...)` to resize).
* Lowest point at y = 0, footprint centred on the Y axis. Real-world dimensions.
+ The harness exports the object **exactly where you put it** (no automatic drop to
+ the ground or re-centring): an off-ground / off-centre build only gets a build
+ warning plus a contract-gate finding, so place every part at its plan centre.
## Naming
* Part Group: `g.name = "<PartName>"` — PascalCase exactly as the plan (`SeatCushion`);
@@ -41,9 +44,15 @@ packages other than `three`, no `import ... from 'codeverse'` / `../runtime_js`.
`MeshPhysicalMaterial` only. Colours via `new THREE.Color(0xRRGGBB)`; vertex colours
allowed (`geometry.setAttribute('color', …)` + `vertexColors: true`).
* ≤ 600 k triangles (aim 20–150 k); ≤ 300 meshes (use `InstancedMesh` or merged
- geometries for repeats); module evaluates + builds in < 20 s.
+ geometries for repeats); module evaluates + builds in < 20 s. `InstancedMesh`
+ named `Posts` is exported as a group `Posts` of meshes `Posts_0 … Posts_{n-1}`
+ (instance matrices and colours baked), so gates and the census see every copy.
## Self-check (optional, keep it tiny, at the end of object.js)
+If `object.js` exports `selfcheck(THREE, root)`, the harness calls it on the group
+returned by `build(THREE)` right after validation, before export. A throw fails the
+build as `SelfCheckError` with your message and file:line, so assert only what you
+are sure about (the contract gate measures the GLB anyway).
```js
export function selfcheck(THREE, root) {
const box = new THREE.Box3().setFromObject(root);
diff --git a/harness/codeverse/prompts/threejs/cookbook.md b/harness/codeverse/prompts/threejs/cookbook.md
index 601652f0..389dfcc3 100644
--- a/harness/codeverse/prompts/threejs/cookbook.md
+++ b/harness/codeverse/prompts/threejs/cookbook.md
@@ -307,6 +307,9 @@ export function selfcheck(THREE, root, expectedNames = [], extentsHint = null) {
}
selfcheck(THREE, build(THREE), ['Seat', 'Legs', 'Leg1', 'Leg4'], [0.44, 0.45, 0.44]);
```
+The harness also calls an exported `selfcheck(THREE, root)` on the built group (defaults
+above make that call permissive); a throw fails the build as `SelfCheckError` with your
+message, so keep the assertions truthful.
Then use the tools: `build` → `render_sheet` → `check_connectivity` → `isolate` → `check_contract`.
diff --git a/harness/codeverse/prompts/tracks/generate_articulated.j2 b/harness/codeverse/prompts/tracks/generate_articulated.j2
index 64492062..0f1bc91c 100644
--- a/harness/codeverse/prompts/tracks/generate_articulated.j2
+++ b/harness/codeverse/prompts/tracks/generate_articulated.j2
@@ -9,6 +9,9 @@ between its limits and checks for penetrations, then renders rest + limit poses
{{ spec_prompt }}
Constraints:
{{ constraints }}
+{% if reference_note %}
+{{ reference_note }}
+{% endif %}
## The contract (hard rules)
{{ frame_doc }}
@@ -39,9 +42,11 @@ Joints (the URDF must realise EXACTLY these; pivots are WORLD points at rest):
## DO
- Build every link at its WORLD rest pose with the plan's bbox centre/extents (±0.01 m); each link is
ONE object (join sub-shapes into it) named exactly as the link.
-- Joint origins: for a joint with world pivot P and the parent's world origin O_parent, the URDF
- `<origin xyz>` is P − O_parent expressed in the parent frame; the child's visual `<origin>` is the
- child mesh offset relative to P. Keep the numbers consistent with the bbox centres in the table —
+- Joint origins: every link frame sits at its joint's world pivot (root at the world origin), so the
+ URDF `<joint><origin xyz>` = pivot_child − pivot_parent (plain subtraction of world points; root
+ parent pivot = 0 0 0). The harness exports meshes/<link>.glb in WORLD coordinates, therefore the
+ child's visual AND collision `<origin xyz>` = −P (the NEGATED world pivot; root link: `0 0 0`) —
+ never the mesh-centre offset. Keep the numbers consistent with the bbox centres in the table —
write them out explicitly as comments in the URDF before the joint.
- Use the axis vectors from the table verbatim; limits = lower/upper from the table; `effort`/
`velocity` any positive numbers.
diff --git a/harness/codeverse/prompts/tracks/generate_graphics.j2 b/harness/codeverse/prompts/tracks/generate_graphics.j2
new file mode 100644
index 00000000..8ff84c7c
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/generate_graphics.j2
@@ -0,0 +1,83 @@
+# Build `{{ title }}` in raw {{ language }}
+
+You write the COMPLETE code for one animated real-time effect from the plan below. A headless harness
+compiles/runs it with moderngl, renders frames at t = {{ judge_times }} at {{ resolution }}, measures them
+(luminance, colourfulness, detail, motion between frames, NaN pixels) and shows a labelled contact sheet
+to a judge. You never see the harness: make the code correct by construction and MAKE IT MOVE.
+
+## Request
+{{ spec_prompt }}
+Constraints:
+{{ constraints }}
+{% if reference_note %}
+{{ reference_note }}
+{% endif %}
+
+## The contract (hard rules — the build fails or the gate rejects when broken)
+{{ contract }}
+
+Files you must produce: {% for f in expected_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}.
+{% if cookbook_rel %}Copyable snippets live in `{{ cookbook_rel }}` (read it before writing if you can).{% endif %}
+{% if cookbook_excerpt %}
+Cookbook excerpt:
+{{ cookbook_excerpt }}
+{% endif %}
+
+## Plan
+{{ plan_summary }}
+Style: {{ style }}
+Resolution {{ resolution }}, loop {{ duration }} s. Harness uniforms in use: {{ uniforms }}.
+
+Passes / layers (implement EVERY row, in this order):
+{{ passes_table }}
+
+Key visuals a viewer must recognise:
+{% for v in key_visuals %}- {{ v }}
+{% endfor %}
+Motion: {{ motion }}
+
+## Acceptance checklist (the judge verifies each item; build so every item is visibly true)
+{{ acceptance }}
+
+## DO
+- Animate with time: every sampled frame (t = {{ judge_times }}) must differ visibly; continuous motion,
+ no hard cuts, no per-frame random seeds.
+- Aspect-correct coordinates: `p = (fragCoord - 0.5*u_resolution) / u_resolution.y` (circles stay round).
+- Layer the passes from the table: background → midground → foreground → grade (vignette, tonemap, gamma).
+- Use the style's palette literally (write the colour constants at the top); keep mean brightness in a
+ readable range (neither near-black nor blown-out); tonemap `c/(1+c)` then gamma.
+- Detail at several scales (fbm octaves, hash-placed elements, highlights) — the judge scores richness.
+- Guard the maths: `x / max(d, 1e-4)`, `sqrt(max(x, 0.0))`, `normalize` only non-zero vectors,
+ `clamp` acos/asin inputs — one NaN pixel caps the score at 0.
+- Constant loop bounds; keep per-pixel cost sane (≤ ~100 raymarch steps, ≤ 8 fbm octaves).
+
+## DON'T
+- No `#version` line, no `uniform`/`out` declarations of the harness names (shader); no window,
+ context creation, clock, file IO outside src/ (program).
+- No placeholders ("TODO", "simplified"); no static image when the plan says motion.
+- No textures other than the harness ones; no network; no imports outside the contract's allow-list.
+
+{% if skeleton_files %}
+## Current files (skeleton already in src/ — keep the structure, replace the placeholder look)
+{% for path, body in skeleton_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if previous_error %}
+## The previous attempt failed to build — fix the cause while rebuilding
+{{ previous_error }}
+{% endif %}
+
+{% if tool_cards and not single_shot %}
+## Tools available to you
+{{ tool_cards }}
+Workflow: edit → `gl_probe` (compile + first frame + stats; fix every error) → `gl_frames` (contact sheet
+of the judged times — LOOK at it and compare against the key visuals) → iterate until the frames match
+the plan. Ignore the mesh tools (measure, render_views, check_*): this track has no GLB.
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/generate_static.j2 b/harness/codeverse/prompts/tracks/generate_static.j2
index 06cb0e2f..49fe1440 100644
--- a/harness/codeverse/prompts/tracks/generate_static.j2
+++ b/harness/codeverse/prompts/tracks/generate_static.j2
@@ -8,6 +8,9 @@ see the harness: make the code correct by construction, with the plan's exact nu
{{ spec_prompt }}
Constraints:
{{ constraints }}
+{% if reference_note %}
+{{ reference_note }}
+{% endif %}
## The contract (hard rules — the build fails or the gate rejects when broken)
{{ frame_doc }}
diff --git a/harness/codeverse/prompts/tracks/plan_graphics.j2 b/harness/codeverse/prompts/tracks/plan_graphics.j2
new file mode 100644
index 00000000..4505f6f9
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/plan_graphics.j2
@@ -0,0 +1,44 @@
+You are the ART-DIRECTOR / TECHNICAL PLANNER for a real-time graphics harness. You turn ONE request for
+an animated effect into a machine-readable plan that a code-writing model will implement in
+`{{ language }}` without seeing you again. The effect is rendered headless by the harness at the
+plan's resolution and judged on frames sampled at t = 0, 1, 2.5, 4 and 6 s (plus a preview GIF).
+
+LANGUAGE CONTRACT THE BUILDER WILL FOLLOW (your plan must fit it — e.g. a fragment shader has no
+geometry; an OpenGL program may draw meshes, instances, multiple passes):
+{{ contract }}
+
+WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
+1. `title` — short name (`NeonRainWindow`).
+2. `summary` — two sentences: what the viewer sees, and what moves.
+3. `style` — palette in words (3-5 named colours with roles: base / accent / highlight), mood,
+ references ("cyberpunk poster", "Studio Ghibli sky"), rendering character (soft/filmic, crisp/flat, glow).
+4. `resolution` — [width, height]; default [1280, 720]; use [720, 1280] only for explicitly vertical requests.
+5. `duration_s` — loop length in seconds (6-12 s; the judge samples up to 6 s).
+6. `passes` — 2 to 5 passes in draw order. For a fragment shader these are LAYERS inside one
+ shader (background → midground → foreground → grade); for an OpenGL program they may be real
+ passes (geometry, FBO post-process). For EACH pass: `name` PascalCase, `kind`
+ (fullscreen | geometry | postprocess | feedback), `description` = the RECIPE in numbers:
+ technique (fbm octaves, sdf shapes, raymarch steps, particle counts, grid cells), sizes in
+ screen fractions, counts, speeds, colours from the style. Concrete beats adjectives.
+7. `uniforms` — which harness uniforms the effect needs (`u_time`, `u_resolution`, `u_prev` for
+ feedback trails, `u_noise` for a noise texture).
+8. `motion` — ONE paragraph: exactly what animates and how (direction, speed in screen-fractions
+ per second or Hz, easing), and what must stay still. Every request is animated unless it says
+ "static image": something must visibly differ between t=0 and t=1.
+9. `key_visuals` — 3 to 8 things a viewer MUST recognise (nouns: "rain drops with trails",
+ "blurred neon bokeh", "sun disc", "rolling fbm clouds").
+10. `acceptance` — 4 to 8 checklist items verifiable from the frames: one per user must-have,
+ one per key visual (`how: visual`), one for motion (`how: probe`, "frames change over time"),
+ one for palette/mood. Ids `a1`, `a2`, …; `priority: must` for things whose absence makes it the
+ wrong effect, `should` for polish.
+
+RULES
+- Plan for the language's strengths: shaders → procedural patterns (hash/noise/fbm/sdf/raymarch/
+ domain warp/palette), OpenGL programs → geometry, instancing, depth, multi-pass blur/bloom.
+- Numbers everywhere: counts, octaves, speeds, screen fractions, hex-ish colours (0.9, 0.2, 0.6).
+- Avoid textbook demos (plain plasma, rainbow spiral) unless asked; give the effect one idea that
+ makes it specific to the request.
+- No prose outside the JSON.
+
+WORKED EXAMPLE (shape only — do not copy its values):
+{{ example_json }}
diff --git a/harness/codeverse/prompts/tracks/refine_graphics.j2 b/harness/codeverse/prompts/tracks/refine_graphics.j2
new file mode 100644
index 00000000..8b6a8c42
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/refine_graphics.j2
@@ -0,0 +1,58 @@
+# Refine `{{ title }}` — round {{ round_index }}
+
+The effect already compiles and renders. The frames were measured and judged; below are the targeted
+changes for THIS round. Make exactly these changes, keep everything else as it is, and keep it building.
+
+## Changes to make (in priority order; `[gate/...]` items are hard failures — fix them first)
+{% for t in tasks %}
+{{ loop.index }}. {{ t }}
+{% endfor %}
+
+Targets: {{ targets | join(', ') }}
+Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+
+## What the judge saw
+{{ judge_summary }}
+
+## Frame metrics measured by the harness (t = {{ judge_times }})
+{{ frame_notes }}
+
+## Plan (the truth to converge to)
+{{ plan_summary }}
+Style: {{ style }}
+{{ passes_table }}
+Motion: {{ motion }}
+Key visuals:
+{% for v in key_visuals %}- {{ v }}
+{% endfor %}
+
+## Acceptance checklist (unchanged)
+{{ acceptance }}
+
+## Contract reminders
+- Harness uniforms only ({{ uniforms }}); no #version / uniform / out redeclarations in a shader; no window,
+ context or clock in a program.
+- Motion is judged by comparing frames at t = {{ judge_times }}: a "static" gate warning caps the score at 0.5.
+- NaN/Inf pixels cap the score at 0: guard divisions, sqrt/pow/log, normalize, acos/asin.
+- Keep brightness readable (mean luminance ~0.2-0.6), aspect-correct coordinates, tonemap + gamma last.
+- A "colour/light" change = palette constants / exposure / grade only; a "motion" change = the time terms only;
+ do not rewrite unrelated layers.
+{% if current_files %}
+
+## Current file contents (edit these; return each edited file COMPLETE)
+{% for path, body in current_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+Run `gl_probe` after editing (fix any error) and `gl_frames` once to LOOK at the result before finishing.
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/refine_object.j2 b/harness/codeverse/prompts/tracks/refine_object.j2
index 3c0f6e39..8083eff3 100644
--- a/harness/codeverse/prompts/tracks/refine_object.j2
+++ b/harness/codeverse/prompts/tracks/refine_object.j2
@@ -19,6 +19,11 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}
## What the judge saw
{{ judge_summary }}
+{% if reference_note %}
+
+## Reference images
+{{ reference_note }}
+{% endif %}
## Measured vs planned (exact numbers; the contract gate checks these)
{{ measurement_notes }}
diff --git a/harness/codeverse/prompts/urdf/contract.md b/harness/codeverse/prompts/urdf/contract.md
index a075e32b..f2756e12 100644
--- a/harness/codeverse/prompts/urdf/contract.md
+++ b/harness/codeverse/prompts/urdf/contract.md
@@ -3,59 +3,66 @@
## Files
```
src/model.py pure bpy (same rules as the blender contract): ONE mesh object per link,
- obj.name == link name, built in WORLD coordinates at the ZERO configuration.
-src/robot.urdf hand-written URDF: links + joints; every link's visual is
- <mesh filename="meshes/<link>.glb"/> with <origin xyz="0 0 0" rpy="0 0 0"/>.
+ obj.name == link name, built in WORLD coordinates at the REST pose (= URDF q=0).
+src/robot.urdf hand-written URDF: links + joints; every link has ONE <visual> and ONE identical
+ <collision>, geometry <mesh filename="meshes/<link>.glb"/>, origin = −(link frame).
```
-The harness runs `model.py` headless, exports `artifacts/meshes/<link>.glb` **in the
-link frame** (it translates your world mesh by −(link origin in world) — translation
-only, see the frame rule), lints the URDF, runs FK, sweeps every joint over its range
-for collisions, renders the rest/showcase pose and builds `object.glb` with one node
-per link. You never export.
+The harness runs `model.py` headless, exports `artifacts/meshes/<link>.glb` with the WORLD
+coordinates baked in (nothing is shifted for you), lints the URDF, checks that FK at q=0
+puts every mesh back where you authored it (1 mm — the build FAILS otherwise and prints the
+corrected `<origin>`), sweeps every joint over its range for collisions, renders q=0 plus
+every joint at its lower/upper limit, and builds `object.glb` with one node per link.
+You never export.
## Frame rule (the whole trick — follow it literally)
* Z up, −Y front, +X right, meters, radians. Object on z = 0, centred on Z.
-* **Zero configuration = what you build** = doors closed, drawers in, lids down, arms at
- home. The harness shows articulation by rendering at the plan's `rest` values
- (e.g. door 0.3 rad ajar) and by `joint_sweep` — do not bake an ajar pose into geometry.
+* **q = 0 = what you build = the plan's rest pose**: the plan's bbox centres/extents and
+ pivots describe this pose (usually doors closed, drawers in, lids down, arms at home —
+ the plan's `rest` is 0 then). The harness does not open anything for the showcase; the
+ judge sees q=0 and every joint at both limits.
* **Every joint `rpy="0 0 0"`.** All link frames stay axis-aligned with the world; a
link frame differs from the world frame only by a translation to its pivot.
-* `<joint><origin xyz>` = `pivot_child_world − pivot_parent_world` (plain subtraction),
- where `pivot_root_world = (0,0,0)` and a pivot is a point ON the joint axis (hinge line
- / slide axis / wheel axle). Fixed joints: the child's attachment point.
-* `<axis xyz>` is therefore the axis in WORLD coordinates (unit vector). Sign: positive
- q must move the child the way a user expects (door swings OPEN, drawer pulls OUT
- towards −Y front, lid lifts UP). If positive q closes it, negate the axis — never swap
- lower/upper.
-* Child visuals: `<origin xyz="0 0 0" rpy="0 0 0"/>` ALWAYS (the harness already placed
- the mesh in the link frame). No `scale`, no `package://`, no inline primitives.
-* Limits: `revolute`/`prismatic` MUST have `<limit lower upper effort velocity/>`
- with `lower < upper`, lower ≤ 0 ≤ upper (zero config inside the range);
- `continuous` has `<limit effort velocity/>` only; `fixed` none.
+* Root link frame = world origin `(0,0,0)`. Every other link frame = its joint's PIVOT: a
+ world point ON the joint axis (hinge line / slide axis / wheel axle); fixed joints: the
+ child's attachment point.
+* `<joint><origin xyz>` = `pivot_child − frame_parent` (plain subtraction; for a child of
+ the root that is just the pivot; for a handle on a door: `pivot_handle − pivot_door`).
+* `<visual>` AND `<collision>` `<origin xyz>` = `−pivot_link` (root: `0 0 0`), because the
+ mesh file holds world coordinates and the link frame sits at the pivot. This is the
+ line everyone gets wrong; the harness verifies it numerically and tells you the numbers.
+* `<axis xyz>` is the axis in WORLD coordinates (unit vector). Sign: positive q must move
+ the child the way a user expects (door swings OPEN, drawer pulls OUT towards −Y front,
+ lid lifts UP). If positive q closes it, negate the axis — never swap lower/upper.
+* Limits: `revolute`/`prismatic` MUST have `<limit lower upper effort velocity/>` with
+ `lower ≤ 0 ≤ upper` (q=0 inside the range). From the plan: `lower = plan.lower − rest`,
+ `upper = plan.upper − rest` — identical to the plan's numbers when `rest` is 0 (the
+ skeleton already wrote them). `continuous`: `<limit effort velocity/>` only; `fixed`: none.
* Single-root tree: exactly one link that is no joint's child (the base); every other
link is the child of exactly one joint; no cycles; ≤ 60 links. Moving parts that carry
hardware (handle on a door, knob on a drawer) attach with a `fixed` joint to the moving
link, not to the base.
-* Clearance: 1–3 mm between a moving part and its housing over the WHOLE range
- (drawer vs cabinet walls, door vs frame); no penetration at any q in [lower, upper].
-* Names: link names == Blender object names == plan part names (PascalCase). Joint names
- `<Parent>To<Child>` or the plan's joint names; all unique.
+* Clearance: 1–3 mm between a moving part and its housing over the WHOLE range (drawer vs
+ cabinet walls, door vs frame); no penetration at any q in [lower, upper]. Fixed
+ children touch their parent (gap ≤ 2 mm) or sink ≤ 2 mm into it.
+* Names: link name == Blender object name == `meshes/<link>.glb` stem, case-sensitive,
+ identical in both files. Keep the skeleton's names (snake_case of the plan parts:
+ `door`, `handle_left`); the plan's PascalCase spelling is accepted too. Never `Door.001`.
+ Joint names: the plan's joint names; all unique.
## Allowed / forbidden
Same as the blender contract for `model.py` (bpy, bmesh, mathutils, math, random).
URDF: no `<gazebo>`, `<transmission>`, `<sensor>`, xacro, `package://`, mesh scale,
-`mimic` (unless the plan has it). Inertial blocks are optional (harness fills defaults).
+inline primitives, `mimic` (unless the plan has it). Inertial blocks are optional.
-## COMPLETE minimal example (verified: bpy build + URDF parse + FK)
-A pedal bin: body + lid hinged at the back edge, knob fixed on the lid. Zero config =
-lid closed; the plan's `rest` (e.g. 0.5 rad) is what renders show.
+## COMPLETE minimal example (verified: harness build + FK check + joint sweep)
+A pedal bin: body + lid hinged at the back edge, knob fixed on the lid. q = 0 = lid closed.
`src/model.py`
```python
import bpy, bmesh
from mathutils import Vector
W, D, H, T = 0.25, 0.25, 0.35, 0.010 # bin outer size, wall/lid thickness (m)
-PIVOT = {"Body": Vector((0, 0, 0))}
+PIVOT = {"body": Vector((0, 0, 0))} # link frame (world) per link; root = origin
def make_box(name, size, center):
bm = bmesh.new(); bmesh.ops.create_cube(bm, size=1.0)
@@ -65,35 +72,43 @@ def make_box(name, size, center):
bpy.context.scene.collection.objects.link(o)
return o
-body = make_box("Body", (W, D, H), (0, 0, H / 2)) # root link, on the ground
-lid = make_box("Lid", (W, D, T), (0, 0, H + 0.001 + T / 2)) # 1 mm above the rim, closed
-knob = make_box("Knob", (0.03, 0.03, 0.02), (0, -D / 2 + 0.04, H + 0.001 + T + 0.008)) # 2 mm into lid
-PIVOT["Lid"] = Vector((0, D / 2, H + 0.001)) # hinge line = back top edge
-PIVOT["Knob"] = Vector((0, -D / 2 + 0.04, H + 0.001 + T)) # its attach point
-for child, parent in (("Lid", "Body"), ("Knob", "Lid")):
- d = PIVOT[child] - PIVOT[parent]
- print(child, f'<origin xyz="{d.x:.4f} {d.y:.4f} {d.z:.4f}" rpy="0 0 0"/>')
+body = make_box("body", (W, D, H), (0, 0, H / 2)) # root link, on the ground
+lid = make_box("lid", (W, D, T), (0, 0, H + 0.001 + T / 2)) # 1 mm above the rim, closed
+knob = make_box("knob", (0.03, 0.03, 0.02), (0, -D / 2 + 0.04, H + 0.001 + T + 0.0085)) # 1.5 mm into lid
+PIVOT["lid"] = Vector((0, D / 2, H + 0.001)) # hinge line = back top edge
+PIVOT["knob"] = Vector((0, -D / 2 + 0.04, H + 0.001 + T)) # its attachment point
+
+def xyz(v):
+ return f'{v.x:.4f} {v.y:.4f} {v.z:.4f}'
+for child, parent in (("lid", "body"), ("knob", "lid")):
+ print(child, "joint origin", xyz(PIVOT[child] - PIVOT[parent]), "| visual+collision origin", xyz(-PIVOT[child]))
```
`src/robot.urdf` — lid opens UP: +q about +X at the back edge would push the front edge
DOWN into the body, so the axis is −X (never fix a sign by swapping limits):
```xml
<?xml version="1.0"?>
-<robot name="PedalBin">
- <link name="Body"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Body.glb"/></geometry></visual></link>
- <link name="Lid"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Lid.glb"/></geometry></visual></link>
- <link name="Knob"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Knob.glb"/></geometry></visual></link>
- <joint name="BodyToLid" type="revolute">
- <parent link="Body"/><child link="Lid"/>
- <origin xyz="0 0.125 0.351" rpy="0 0 0"/>
+<robot name="pedal_bin">
+ <link name="body">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></collision>
+ </link>
+ <link name="lid"> <!-- frame at the hinge pivot (0 0.125 0.351) → origin = its negation -->
+ <visual><origin xyz="0 -0.125 -0.351" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></visual>
+ <collision><origin xyz="0 -0.125 -0.351" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></collision>
+ </link>
+ <link name="knob"> <!-- frame at its attachment point (0 -0.085 0.361) -->
+ <visual><origin xyz="0 0.085 -0.361" rpy="0 0 0"/><geometry><mesh filename="meshes/knob.glb"/></geometry></visual>
+ <collision><origin xyz="0 0.085 -0.361" rpy="0 0 0"/><geometry><mesh filename="meshes/knob.glb"/></geometry></collision>
+ </link>
+ <joint name="body_to_lid" type="revolute">
+ <parent link="body"/><child link="lid"/>
+ <origin xyz="0 0.125 0.351" rpy="0 0 0"/> <!-- pivot_lid - frame_body -->
<axis xyz="-1 0 0"/>
<limit lower="0" upper="1.5" effort="5" velocity="2"/>
</joint>
- <joint name="LidToKnob" type="fixed">
- <parent link="Lid"/><child link="Knob"/>
- <origin xyz="0 -0.21 0.01" rpy="0 0 0"/>
+ <joint name="lid_to_knob" type="fixed">
+ <parent link="lid"/><child link="knob"/>
+ <origin xyz="0 -0.21 0.01" rpy="0 0 0"/> <!-- pivot_knob - pivot_lid -->
</joint>
</robot>
```
diff --git a/harness/codeverse/prompts/urdf/cookbook.md b/harness/codeverse/prompts/urdf/cookbook.md
index a5903601..0ddb018c 100644
--- a/harness/codeverse/prompts/urdf/cookbook.md
+++ b/harness/codeverse/prompts/urdf/cookbook.md
@@ -7,14 +7,17 @@ Use `read_cookbook(section="<heading>")` for one chapter.
## The frame recipe (memorise this, it is the whole trick)
```text
-1. Build every link's mesh in WORLD coordinates at the ZERO configuration (closed/home).
-2. One Blender object per link, obj.name == link name == plan part name.
+1. Build every link's mesh in WORLD coordinates at the REST pose (= URDF q = 0: the pose
+ the plan's bboxes describe — closed / home unless the plan's `rest` says otherwise).
+2. One Blender object per link, obj.name == link name (the skeleton's snake_case names).
3. Pick a PIVOT for every non-root link: a point on its joint axis, in world coords
- (hinge line, slide axis, axle). Root pivot = (0, 0, 0).
-4. URDF: every joint has rpy="0 0 0"; origin xyz = pivot_child − pivot_parent;
- axis xyz = the joint axis in WORLD coords; every visual origin = "0 0 0".
-5. The harness exports meshes/<link>.glb already shifted by −pivot_link, so a link's
- visual mesh is simply its world mesh in a frame parented at its pivot.
+ (hinge line, slide axis, axle; fixed joint: the attachment point). Root pivot = (0, 0, 0).
+ The link frame sits AT the pivot, axis-aligned with the world.
+4. URDF: every joint has rpy="0 0 0"; joint origin xyz = pivot_child − pivot_parent;
+ axis xyz = the joint axis in WORLD coords.
+5. meshes/<link>.glb hold WORLD coordinates (the harness shifts nothing), so every link's
+ <visual> AND <collision> origin xyz = −pivot_link (root: 0 0 0). The build verifies
+ this (FK at q=0 must reproduce your geometry within 1 mm) and prints the fix if not.
```
Pivot arithmetic is plain vector subtraction — do it in Python and print it:
@@ -23,12 +26,16 @@ Pivot arithmetic is plain vector subtraction — do it in Python and print it:
import bpy, bmesh, math
from mathutils import Vector
-PIVOT = { # world-space pivots, filled while building
- "Base": Vector((0, 0, 0)),
+PIVOT = { # world-space pivots (= link frames), filled while building
+ "base": Vector((0, 0, 0)),
}
+def _xyz(v) -> str:
+ return f'{v.x:.4f} {v.y:.4f} {v.z:.4f}'
+
def urdf_origin(child: str, parent: str) -> str:
- d = PIVOT[child] - PIVOT[parent]
- return f'<origin xyz="{d.x:.4f} {d.y:.4f} {d.z:.4f}" rpy="0 0 0"/>'
+ """The two <origin> lines a link needs: joint origin and visual/collision origin."""
+ return (f'joint <origin xyz="{_xyz(PIVOT[child] - PIVOT[parent])}" rpy="0 0 0"/> '
+ f'visual+collision <origin xyz="{_xyz(-PIVOT[child])}" rpy="0 0 0"/>')
```
## Skeleton (`src/model.py` for articulated objects)
@@ -81,63 +88,77 @@ FRONT_Y = -D / 2 - DOOR_T / 2 - 0.001 # front panels sit 1 mm proud of the c
DRAWER_Z0, DRAWER_Z1 = 0.021, 0.156 # drawer box bottom/top (4 mm under the shelf)
SHELF_Z0, DOOR_Z0 = 0.160, 0.184 # shelf above the drawer; door bottom edge
-# --- Carcass (root): 6 panels joined into ONE link object; opening faces -Y (front)
+# --- carcass (root): 6 panels joined into ONE link object; opening faces -Y (front)
panels = [
- make_box("Carcass", (T, D, H), (-(W / 2 - T / 2), 0, H / 2)), # left side
- make_box("Carcass_R", (T, D, H), ((W / 2 - T / 2), 0, H / 2)), # right side
- make_box("Carcass_Top", (W - 2 * T, D, T), (0, 0, H - T / 2)),
- make_box("Carcass_Floor", (W - 2 * T, D, T), (0, 0, T / 2)),
- make_box("Carcass_Shelf", (W - 2 * T, D - T, T), (0, -T / 2, SHELF_Z0 + T / 2)),
- make_box("Carcass_Back", (W - 2 * T, T, H - 2 * T), (0, D / 2 - T / 2, H / 2)),
+ make_box("carcass", (T, D, H), (-(W / 2 - T / 2), 0, H / 2)), # left side
+ make_box("carcass_r", (T, D, H), ((W / 2 - T / 2), 0, H / 2)), # right side
+ make_box("carcass_top", (W - 2 * T, D, T), (0, 0, H - T / 2)),
+ make_box("carcass_floor", (W - 2 * T, D, T), (0, 0, T / 2)),
+ make_box("carcass_shelf", (W - 2 * T, D - T, T), (0, -T / 2, SHELF_Z0 + T / 2)),
+ make_box("carcass_back", (W - 2 * T, T, H - 2 * T), (0, D / 2 - T / 2, H / 2)),
]
-carcass = join_as("Carcass", panels); material(carcass, (0.72, 0.68, 0.62))
-PIVOT["Carcass"] = Vector((0, 0, 0))
+carcass = join_as("carcass", panels); material(carcass, (0.72, 0.68, 0.62))
+PIVOT["carcass"] = Vector((0, 0, 0))
-# --- Door: hinged on its LEFT edge, closed at q = 0; +q about -Z swings it open (to -Y)
+# --- door: hinged on its LEFT edge, closed at q = 0; +q about -Z swings it open (to -Y)
door_h = H - DOOR_Z0 - GAP
-door = make_box("Door", (W - 2 * GAP, DOOR_T, door_h), (0, FRONT_Y, DOOR_Z0 + door_h / 2))
+door = make_box("door", (W - 2 * GAP, DOOR_T, door_h), (0, FRONT_Y, DOOR_Z0 + door_h / 2))
material(door, (0.55, 0.35, 0.2))
-PIVOT["Door"] = Vector((-(W / 2 - GAP), FRONT_Y, 0)) # vertical hinge line (z arbitrary → 0)
+PIVOT["door"] = Vector((-(W / 2 - GAP), FRONT_Y, 0)) # vertical hinge line (z arbitrary → 0) = (-0.248, -0.21, 0)
-# --- DoorHandle: vertical bar on the door's free side, sunk 2 mm into the door (weld)
-handle = make_box("DoorHandle", (0.012, 0.034, 0.12), (W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.015, 0.45))
+# --- door_handle: vertical bar on the door's free side, sunk 1.5 mm into the door (weld)
+handle = make_box("door_handle", (0.012, 0.034, 0.12), (W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.0155, 0.45))
material(handle, (0.8, 0.78, 0.74), 0.3, 1.0)
-PIVOT["DoorHandle"] = Vector((W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.015, 0.45))
+PIVOT["door_handle"] = Vector((W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.0155, 0.45)) # = (0.2, -0.2345, 0.45)
-# --- Drawer: box + front panel joined; slides out towards -Y (front)
+# --- drawer: box + front panel joined; slides out towards -Y (front)
hb = DRAWER_Z1 - DRAWER_Z0
-drawer = join_as("Drawer", [
- make_box("Drawer", (W - 2 * T - 2 * GAP, 0.382, hb), (0, -0.011, DRAWER_Z0 + hb / 2)),
- make_box("Drawer_Front", (W - 2 * GAP, DOOR_T, DOOR_Z0 - 0.005), (0, FRONT_Y, (0.002 + DOOR_Z0 - 0.003) / 2)),
+drawer = join_as("drawer", [
+ make_box("drawer", (W - 2 * T - 2 * GAP, 0.382, hb), (0, -0.011, DRAWER_Z0 + hb / 2)),
+ make_box("drawer_front", (W - 2 * GAP, DOOR_T, DOOR_Z0 - 0.005), (0, FRONT_Y, (0.002 + DOOR_Z0 - 0.003) / 2)),
])
material(drawer, (0.55, 0.35, 0.2))
-PIVOT["Drawer"] = Vector((0, -0.011, DRAWER_Z0 + hb / 2)) # any point on the slide axis
+PIVOT["drawer"] = Vector((0, -0.011, DRAWER_Z0 + hb / 2)) # any point on the slide axis
-for child, parent in (("Door", "Carcass"), ("DoorHandle", "Door"), ("Drawer", "Carcass")):
+for child, parent in (("door", "carcass"), ("door_handle", "door"), ("drawer", "carcass")):
print(child, urdf_origin(child, parent))
```
+Every link: visual + collision origin = −pivot (the comment shows the pivot):
+
```xml
<?xml version="1.0"?>
-<robot name="Cabinet">
- <link name="Carcass"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Carcass.glb"/></geometry></visual></link>
- <link name="Door"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Door.glb"/></geometry></visual></link>
- <link name="DoorHandle"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/DoorHandle.glb"/></geometry></visual></link>
- <link name="Drawer"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Drawer.glb"/></geometry></visual></link>
+<robot name="cabinet">
+ <link name="carcass"> <!-- root: frame = world origin -->
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/carcass.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/carcass.glb"/></geometry></collision>
+ </link>
+ <link name="door"> <!-- pivot (-0.248 -0.21 0) -->
+ <visual><origin xyz="0.248 0.21 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></visual>
+ <collision><origin xyz="0.248 0.21 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision>
+ </link>
+ <link name="door_handle"> <!-- pivot (0.2 -0.2345 0.45) -->
+ <visual><origin xyz="-0.2 0.2345 -0.45" rpy="0 0 0"/><geometry><mesh filename="meshes/door_handle.glb"/></geometry></visual>
+ <collision><origin xyz="-0.2 0.2345 -0.45" rpy="0 0 0"/><geometry><mesh filename="meshes/door_handle.glb"/></geometry></collision>
+ </link>
+ <link name="drawer"> <!-- pivot (0 -0.011 0.0885) -->
+ <visual><origin xyz="0 0.011 -0.0885" rpy="0 0 0"/><geometry><mesh filename="meshes/drawer.glb"/></geometry></visual>
+ <collision><origin xyz="0 0.011 -0.0885" rpy="0 0 0"/><geometry><mesh filename="meshes/drawer.glb"/></geometry></collision>
+ </link>
<!-- hinge on the left front edge; +q about -Z swings the free edge to -Y (open) -->
- <joint name="CarcassToDoor" type="revolute">
- <parent link="Carcass"/><child link="Door"/>
- <origin xyz="-0.248 -0.210 0" rpy="0 0 0"/>
+ <joint name="carcass_to_door" type="revolute">
+ <parent link="carcass"/><child link="door"/>
+ <origin xyz="-0.248 -0.21 0" rpy="0 0 0"/> <!-- pivot_door - (0,0,0) -->
<axis xyz="0 0 -1"/>
<limit lower="0" upper="1.6" effort="10" velocity="1"/>
</joint>
- <joint name="DoorToDoorHandle" type="fixed">
- <parent link="Door"/><child link="DoorHandle"/>
- <origin xyz="0.448 -0.024 0.45" rpy="0 0 0"/>
+ <joint name="door_to_door_handle" type="fixed">
+ <parent link="door"/><child link="door_handle"/>
+ <origin xyz="0.448 -0.0245 0.45" rpy="0 0 0"/> <!-- pivot_handle - pivot_door -->
</joint>
<!-- +q pulls the drawer out towards the front (-Y) -->
- <joint name="CarcassToDrawer" type="prismatic">
- <parent link="Carcass"/><child link="Drawer"/>
+ <joint name="carcass_to_drawer" type="prismatic">
+ <parent link="carcass"/><child link="drawer"/>
<origin xyz="0 -0.011 0.0885" rpy="0 0 0"/>
<axis xyz="0 -1 0"/>
<limit lower="0" upper="0.30" effort="10" velocity="0.5"/>
@@ -155,23 +176,23 @@ BW, BD, BT = 0.33, 0.23, 0.018 # base footprint + thickness
LT, GAP = 0.006, 0.002 # lid thickness, hinge clearance
# --- Base link (root) ---------------------------------------------------------
-base = make_box("Base", (BW, BD, BT), (0, 0, BT / 2))
-keys = make_box("Base_Keys", (BW - 0.04, BD * 0.45, 0.002), (0, -0.02, BT + 0.001 - 0.0005)) # 0.5 mm sunk
-pad = make_box("Base_Pad", (0.10, 0.06, 0.001), (0, -BD / 2 + 0.045, BT + 0.0005 - 0.0003))
-base = join_as("Base", [base, keys, pad]); material(base, (0.15, 0.15, 0.17), 0.4, 0.6)
-PIVOT["Base"] = Vector((0, 0, 0))
+base = make_box("base", (BW, BD, BT), (0, 0, BT / 2))
+keys = make_box("base_keys", (BW - 0.04, BD * 0.45, 0.002), (0, -0.02, BT + 0.001 - 0.0005)) # 0.5 mm sunk
+pad = make_box("base_pad", (0.10, 0.06, 0.001), (0, -BD / 2 + 0.045, BT + 0.0005 - 0.0003))
+base = join_as("base", [base, keys, pad]); material(base, (0.15, 0.15, 0.17), 0.4, 0.6)
+PIVOT["base"] = Vector((0, 0, 0))
# --- Lid link: hinge axis along X, 8 mm in from the back edge, 6.5 mm above the base top.
# The hinge barrel belongs to the LID (it turns with it); closed (lying flat) at q = 0.
hinge_y, hinge_z = BD / 2 - 0.008, BT + 0.0065
LID_L = BD - 0.008 - GAP # plate runs from the axis to the front
-lid = make_box("Lid", (BW, LID_L, LT), (0, hinge_y - LID_L / 2, hinge_z))
-screen = make_box("Lid_Screen", (BW - 0.02, LID_L - 0.03, 0.0005), (0, hinge_y - LID_L / 2, hinge_z + LT / 2 - 0.0002))
-barrel = make_cyl("Lid_Hinge", 0.006, BW * 0.9, (0, hinge_y, hinge_z), axis='X', segments=24)
-lid = join_as("Lid", [lid, screen, barrel]); material(lid, (0.2, 0.2, 0.22), 0.3, 0.6)
-PIVOT["Lid"] = Vector((0, hinge_y, hinge_z))
+lid = make_box("lid", (BW, LID_L, LT), (0, hinge_y - LID_L / 2, hinge_z))
+screen = make_box("lid_screen", (BW - 0.02, LID_L - 0.03, 0.0005), (0, hinge_y - LID_L / 2, hinge_z + LT / 2 - 0.0002))
+barrel = make_cyl("lid_hinge", 0.006, BW * 0.9, (0, hinge_y, hinge_z), axis='X', segments=24)
+lid = join_as("lid", [lid, screen, barrel]); material(lid, (0.2, 0.2, 0.22), 0.3, 0.6)
+PIVOT["lid"] = Vector((0, hinge_y, hinge_z)) # = (0, 0.107, 0.0245)
-print("BaseToLid", urdf_origin("Lid", "Base")) # → <origin xyz="0.0000 0.1070 0.0245" rpy="0 0 0"/>
+print("base_to_lid", urdf_origin("lid", "base")) # → joint 0 0.107 0.0245 | visual+collision 0 -0.107 -0.0245
```
Axis sign check: a lid point at (0, −0.1, 0) relative to the hinge rotated by +q about
@@ -181,13 +202,17 @@ above the base top at q = 0 (keys are 1 mm below it): clearance, not contact.
```xml
<?xml version="1.0"?>
-<robot name="Laptop">
- <link name="Base"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Base.glb"/></geometry></visual></link>
- <link name="Lid"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Lid.glb"/></geometry></visual></link>
- <joint name="BaseToLid" type="revolute">
- <parent link="Base"/><child link="Lid"/>
+<robot name="laptop">
+ <link name="base">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></collision>
+ </link>
+ <link name="lid"> <!-- pivot (0 0.107 0.0245) -->
+ <visual><origin xyz="0 -0.107 -0.0245" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></visual>
+ <collision><origin xyz="0 -0.107 -0.0245" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></collision>
+ </link>
+ <joint name="base_to_lid" type="revolute">
+ <parent link="base"/><child link="lid"/>
<origin xyz="0 0.107 0.0245" rpy="0 0 0"/>
<axis xyz="-1 0 0"/>
<limit lower="0" upper="2.1" effort="5" velocity="2"/>
@@ -202,58 +227,70 @@ CW, CD, CH = 0.45, 0.35, 0.03 # deck
WR, WT = 0.10, 0.03 # wheel radius / width
POST_Y, POST_Z0, POST_H, POST_W, WALL = CD / 2 - 0.016, WR + CH, 0.60, 0.032, 0.003
-deck = make_box("Deck", (CW, CD, CH), (0, 0, WR + CH / 2)) # deck rides above the axle height
+deck = make_box("deck", (CW, CD, CH), (0, 0, WR + CH / 2)) # deck rides above the axle height
# the handle post is a HOLLOW square tube (4 walls) so the telescopic grip can slide inside it
-walls = [make_box(f"Deck_PostW{i}", s, c) for i, (s, c) in enumerate([
+walls = [make_box(f"deck_post_w{i}", s, c) for i, (s, c) in enumerate([
((POST_W, WALL, POST_H), (0, POST_Y - POST_W / 2 + WALL / 2, POST_Z0 + POST_H / 2)),
((POST_W, WALL, POST_H), (0, POST_Y + POST_W / 2 - WALL / 2, POST_Z0 + POST_H / 2)),
((WALL, POST_W - 2 * WALL, POST_H), (-POST_W / 2 + WALL / 2, POST_Y, POST_Z0 + POST_H / 2)),
((WALL, POST_W - 2 * WALL, POST_H), (POST_W / 2 - WALL / 2, POST_Y, POST_Z0 + POST_H / 2))])]
-deck = join_as("Deck", [deck, *walls]); material(deck, (0.5, 0.33, 0.18))
-PIVOT["Deck"] = Vector((0, 0, 0))
+deck = join_as("deck", [deck, *walls]); material(deck, (0.5, 0.33, 0.18))
+PIVOT["deck"] = Vector((0, 0, 0))
for i, sx in enumerate((-1, 1)):
- name = f"Wheel{i + 1}"
+ name = f"wheel_{i + 1}"
cx = sx * (CW / 2 + WT / 2 + 0.002) # 2 mm outside the deck side
w = make_cyl(name, WR, WT, (cx, -CD / 2 + 0.06, WR), axis='X')
- cap = make_cyl(name + "_Cap", 0.02, 0.012, (cx + sx * (WT / 2 + 0.003), -CD / 2 + 0.06, WR), axis='X')
+ cap = make_cyl(name + "_cap", 0.02, 0.012, (cx + sx * (WT / 2 + 0.003), -CD / 2 + 0.06, WR), axis='X')
w = join_as(name, [w, cap]); material(w, (0.05, 0.05, 0.05), 0.85) # cap overlaps the wheel 3 mm (same link)
PIVOT[name] = Vector((cx, -CD / 2 + 0.06, WR)) # on the axle
# axle stubs belong to the Deck; they stop 1 mm short of each wheel's inner face (no penetration, "touching")
-axle = make_cyl("Deck_Axle", 0.008, CW + 0.002, (0, -CD / 2 + 0.06, WR), axis='X', segments=16)
-deck = join_as("Deck", [deck, axle])
+axle = make_cyl("deck_axle", 0.008, CW + 0.002, (0, -CD / 2 + 0.06, WR), axis='X', segments=16)
+deck = join_as("deck", [deck, axle])
-# telescopic handle slides UP (+Z) inside the post: zero config = fully retracted.
+# telescopic handle slides UP (+Z) inside the post: q = 0 = fully retracted.
# grip 24 mm square inside the 26 mm bore (1 mm clearance), bottom 70 mm above the deck, top 20 mm above the post
-grip = make_box("Handle", (0.024, 0.024, 0.55), (0, POST_Y, POST_Z0 + 0.07 + 0.275))
-bar = make_box("Handle_Bar", (0.30, 0.024, 0.024), (0, POST_Y, POST_Z0 + 0.07 + 0.55 + 0.012 - 0.004)) # 4 mm weld
-handle = join_as("Handle", [grip, bar]); material(handle, (0.7, 0.7, 0.72), 0.3, 1.0)
-PIVOT["Handle"] = Vector((0, POST_Y, POST_Z0 + POST_H / 2)) # any point on the slide axis
+grip = make_box("handle", (0.024, 0.024, 0.55), (0, POST_Y, POST_Z0 + 0.07 + 0.275))
+bar = make_box("handle_bar", (0.30, 0.024, 0.024), (0, POST_Y, POST_Z0 + 0.07 + 0.55 + 0.012 - 0.004)) # 4 mm weld
+handle = join_as("handle", [grip, bar]); material(handle, (0.7, 0.7, 0.72), 0.3, 1.0)
+PIVOT["handle"] = Vector((0, POST_Y, POST_Z0 + POST_H / 2)) # any point on the slide axis = (0, 0.159, 0.43)
-for child, parent in (("Wheel1", "Deck"), ("Wheel2", "Deck"), ("Handle", "Deck")):
+for child, parent in (("wheel_1", "deck"), ("wheel_2", "deck"), ("handle", "deck")):
print(child, urdf_origin(child, parent))
```
```xml
<?xml version="1.0"?>
-<robot name="HandCart">
- <link name="Deck"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Deck.glb"/></geometry></visual></link>
- <link name="Wheel1"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Wheel1.glb"/></geometry></visual></link>
- <link name="Wheel2"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Wheel2.glb"/></geometry></visual></link>
- <link name="Handle"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Handle.glb"/></geometry></visual></link>
- <joint name="DeckToWheel1" type="continuous">
- <parent link="Deck"/><child link="Wheel1"/>
+<robot name="hand_cart">
+ <link name="deck">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/deck.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/deck.glb"/></geometry></collision>
+ </link>
+ <link name="wheel_1"> <!-- pivot (-0.242 -0.115 0.1) -->
+ <visual><origin xyz="0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_1.glb"/></geometry></visual>
+ <collision><origin xyz="0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_1.glb"/></geometry></collision>
+ </link>
+ <link name="wheel_2"> <!-- pivot (0.242 -0.115 0.1) -->
+ <visual><origin xyz="-0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_2.glb"/></geometry></visual>
+ <collision><origin xyz="-0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_2.glb"/></geometry></collision>
+ </link>
+ <link name="handle"> <!-- pivot (0 0.159 0.43) -->
+ <visual><origin xyz="0 -0.159 -0.43" rpy="0 0 0"/><geometry><mesh filename="meshes/handle.glb"/></geometry></visual>
+ <collision><origin xyz="0 -0.159 -0.43" rpy="0 0 0"/><geometry><mesh filename="meshes/handle.glb"/></geometry></collision>
+ </link>
+ <joint name="deck_to_wheel_1" type="continuous">
+ <parent link="deck"/><child link="wheel_1"/>
<origin xyz="-0.242 -0.115 0.1" rpy="0 0 0"/><axis xyz="1 0 0"/>
<limit effort="1" velocity="20"/>
</joint>
- <joint name="DeckToWheel2" type="continuous">
- <parent link="Deck"/><child link="Wheel2"/>
+ <joint name="deck_to_wheel_2" type="continuous">
+ <parent link="deck"/><child link="wheel_2"/>
<origin xyz="0.242 -0.115 0.1" rpy="0 0 0"/><axis xyz="1 0 0"/>
<limit effort="1" velocity="20"/>
</joint>
- <joint name="DeckToHandle" type="prismatic">
- <parent link="Deck"/><child link="Handle"/>
+ <joint name="deck_to_handle" type="prismatic">
+ <parent link="deck"/><child link="handle"/>
<origin xyz="0 0.159 0.43" rpy="0 0 0"/><axis xyz="0 0 1"/>
<limit lower="0" upper="0.35" effort="10" velocity="0.5"/>
</joint>
@@ -261,7 +298,7 @@ for child, parent in (("Wheel1", "Deck"), ("Wheel2", "Deck"), ("Handle", "Deck")
```
Why: wheels are cylinders along X (`axis='X'`), their pivot is the axle point; the
-telescopic handle's zero config is retracted (inside the post), q pulls it up.
+telescopic handle's q = 0 is retracted (inside the post), +q pulls it up.
## Joint types, axes, limits (what to write)
@@ -292,18 +329,20 @@ Plausible ranges (SI):
| robot arm joint | revolute | −2.9 | 2.9 rad | |
| gripper finger | prismatic | 0 | 0.04 m | |
-The harness renders the showcase pose at the plan's `rest` (e.g. door 0.3 rad, drawer
-0.12 m) so the articulation is visible — you still build q = 0.
+The harness renders q = 0 plus every joint at its lower and upper limit (the judge sees
+all three), so articulation is always visible — never bake an ajar pose into geometry to
+"show" it. URDF limits from the plan: `lower − rest` … `upper − rest` (the plan's values
+verbatim when `rest` = 0, the usual case; the skeleton already has them).
## Clearances, rest pose, hardware
* Moving part vs housing: 1–3 mm all round over the WHOLE range (drawer box inside the
cabinet: 2 mm each side, 4 mm above; door leaf vs frame: 2 mm). Test mentally at
`upper`: does the door corner sweep through the side panel? Put the hinge ON the edge.
-* Zero config must not self-intersect: a closed door touches the carcass face
- (flush, 0–1 mm), never sinks into it.
-* Handles / knobs / pulls: `fixed` joint to the MOVING link, welded 2 mm into it, pivot =
- handle centre. Hinge barrels and drawer runners belong to the housing link (or to the
+* q = 0 must not self-intersect: a closed door touches the carcass face (flush, 0–1 mm),
+ never sinks into it.
+* Handles / knobs / pulls: `fixed` joint to the MOVING link, touching it or sunk ≤ 2 mm
+ into it, pivot = the attachment point (handle centre is fine). Hinge barrels and drawer runners belong to the housing link (or to the
moving link) — they are geometry, not joints.
* One mechanism per joint. Doubles (two doors, four wheels) = separate links with their
own pivots; identical meshes are fine.
@@ -314,20 +353,20 @@ The harness renders the showcase pose at the plan's `rest` (e.g. door 0.3 rad, d
```xml
<?xml version="1.0"?>
-<robot name="ObjectName">
- <!-- one <link> per Blender object, names identical -->
- <link name="Base">
- <visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Base.glb"/></geometry></visual>
- <!-- optional but welcome: <inertial><mass value="5"/><inertia ixx="0.1" iyy="0.1" izz="0.1" ixy="0" ixz="0" iyz="0"/></inertial> -->
+<robot name="object_name">
+ <!-- one <link> per Blender object, names identical; visual + collision origin = -pivot -->
+ <link name="base"> <!-- root: frame = world origin -->
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></collision>
+ <!-- optional: <inertial><mass value="5"/><inertia ixx="0.1" iyy="0.1" izz="0.1" ixy="0" ixz="0" iyz="0"/></inertial> -->
</link>
- <link name="Child">
- <visual><origin xyz="0 0 0" rpy="0 0 0"/>
- <geometry><mesh filename="meshes/Child.glb"/></geometry></visual>
+ <link name="child"> <!-- frame at pivot (PX PY PZ) -->
+ <visual><origin xyz="-PX -PY -PZ" rpy="0 0 0"/><geometry><mesh filename="meshes/child.glb"/></geometry></visual>
+ <collision><origin xyz="-PX -PY -PZ" rpy="0 0 0"/><geometry><mesh filename="meshes/child.glb"/></geometry></collision>
</link>
- <joint name="BaseToChild" type="revolute">
- <parent link="Base"/><child link="Child"/>
- <origin xyz="PX PY PZ" rpy="0 0 0"/> <!-- pivot_child - pivot_parent -->
+ <joint name="base_to_child" type="revolute">
+ <parent link="base"/><child link="child"/>
+ <origin xyz="PX PY PZ" rpy="0 0 0"/> <!-- pivot_child - pivot_parent (root pivot = 0 0 0) -->
<axis xyz="0 0 1"/> <!-- unit, WORLD direction, +q = open -->
<limit lower="0" upper="1.6" effort="10" velocity="1"/>
</joint>
@@ -341,8 +380,10 @@ The harness renders the showcase pose at the plan's `rest` (e.g. door 0.3 rad, d
2. **Child jumps when q changes / orbits around the wrong point** → pivot not on the
hinge line: the pivot must be a point ON the axis (edge of the door, the axle), not
the part's centre.
-3. **Lid/door geometry shifted after export** → you wrote a non-zero visual `<origin>` or
- `rpy` on a joint. Everything is `0 0 0`; the harness does the shifting.
+3. **Build fails `FkInconsistent` / "URDF frames do not reproduce the authored geometry"**
+ → a link's visual/collision `<origin>` is not `−pivot` (most often left at `0 0 0`), or a
+ joint has `rpy ≠ 0`. Meshes are world coordinates; the link frame sits at the pivot, so
+ the origin must undo it. Copy the corrected numbers from the message into BOTH tags.
4. **"link X has two parent joints" / "not connected to root"** → every non-root link is
the child of exactly one joint; handles attach to the door, not to the base AND door.
5. **Penetration at upper limit** (`joint_sweep` says `Drawer` hits `Base` at q = 0.4) →
@@ -350,17 +391,21 @@ The harness renders the showcase pose at the plan's `rest` (e.g. door 0.3 rad, d
6. **Parts float** (`check_connectivity`): hinge barrels, runners, knobs not overlapping.
Weld 2 mm.
7. **`continuous` with `<limit lower upper>`** or `revolute` without limits → lint error.
-8. **Blender object names ≠ link names** (`Door.001`, `door`) → mesh not found. Exact
- PascalCase, unique, no suffix; join sub-pieces with `join_as`.
-9. **Object not on the ground** → wheels' bottom / feet at z = 0 in the zero config.
+8. **Blender object names ≠ link names** (`door.001`, `Door` vs `door`) → mesh not found.
+ Identical spelling in both files, unique, no `.001` suffix; join sub-pieces with `join_as`.
+9. **Object not on the ground** → wheels' bottom / feet at z = 0 at q = 0.
10. **Mesh scale in URDF** (`scale="0.001 …"`) → forbidden; author in metres.
11. **Non-unit axis** (`0 0 2`) → lint error; also avoid `0.7 0.7 0` unless intended.
-12. **Zero config is the open pose** → renders at rest look closed/odd and collision at
- `lower` fails; build closed, let the harness open it.
-13. **Articulation invisible in renders** → plan `rest` 0 on every joint; ask for a
- non-zero showcase (door 0.3 rad, drawer 0.12 m) — that is the plan's job, not geometry's.
-14. **Handles built in world but parented to the wrong link** → their pivot must be
- subtracted from the DOOR pivot (`urdf_origin("Handle", "Door")`), not from the base.
+12. **q = 0 is the open pose** (but the plan says rest 0 = closed) → the rest render looks
+ odd and the sweep at `lower` collides; build the pose the plan's bboxes describe and let
+ the limit poses show the motion.
+13. **Limits copied verbatim although the plan's `rest` ≠ 0** → the joint over-opens by
+ `rest` and never closes. Write `lower − rest` … `upper − rest` (the skeleton did).
+14. **Handles built in world but parented to the wrong link** → their joint origin must be
+ subtracted from the DOOR pivot (`urdf_origin("door_handle", "door")`), not from the base;
+ their visual/collision origin is still `−pivot_handle`.
+15. **`<collision>` missing or ≠ `<visual>`** → lint warning; give every link one identical
+ collision block (same mesh, same origin) — the sweep collides those.
## Self-check (before you call it done)
@@ -378,10 +423,11 @@ def urdf_selfcheck(expected_links):
assert abs(zmin) < 0.002, f"lowest point z={zmin:.4f}"
print("[selfcheck] links", names, "pivots ok")
-urdf_selfcheck(["Carcass", "Door", "DoorHandle", "Drawer", "Base", "Lid",
- "Deck", "Wheel1", "Wheel2", "Handle"])
+urdf_selfcheck(["carcass", "door", "door_handle", "drawer", "base", "lid",
+ "deck", "wheel_1", "wheel_2", "handle"])
```
-Then: `build` → `render_sheet` → `check_connectivity` → `joint_sweep` on EVERY joint
-(look at q = lower / mid / upper renders: does the right part move, the right way, without
-penetration?) → `check_contract`.
+Then: `build` (it runs the FK check and the collision sweep and tells you the numbers) →
+`render_sheet` → `check_connectivity` → `joint_sweep` on EVERY joint (look at q = lower /
+mid / upper renders: does the right part move, the right way, without penetration?) →
+`check_contract`.
diff --git a/harness/codeverse/spatial/connectivity.py b/harness/codeverse/spatial/connectivity.py
index 6d75bcff..63d25d89 100644
--- a/harness/codeverse/spatial/connectivity.py
+++ b/harness/codeverse/spatial/connectivity.py
@@ -17,7 +17,10 @@ Mechanism
through each other).
6. Tiny disconnected islands inside a single part → WARN (stray geometry).
-All thresholds are module constants (meters) and keyword-overridable.
+All thresholds are module constants (meters) and keyword-overridable. Pass the
+authoring ``language`` so translation hints are written in the frame the agent
+codes in (Blender/CadQuery/URDF are Z-up; the GLB is Y-up) — a hint in the wrong
+frame moves a part forward instead of down.
"""
from __future__ import annotations
@@ -31,7 +34,8 @@ import numpy as np
import trimesh
from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.conventions import CONTACT_GAP_M
+from codeverse.conventions import CONTACT_GAP_M, Frame
+from codeverse.spatial.contract import frame_label, glb_vec_to_plan, language_frame
from codeverse.spatial.measure import GlbLoadError, load_scene, part_meshes
GATE = "connectivity"
@@ -150,7 +154,7 @@ def _components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]
def _fmt_vec(v: tuple[float, float, float]) -> str:
- return "(" + ", ".join(f"{x:+.4f}" for x in v) + ")"
+ return "(" + ", ".join(f"{round(x, 4) + 0.0:+.4f}" for x in v) + ")" # + 0.0: no '-0.0000'
def _island_findings(name: str, mesh: trimesh.Trimesh) -> list[GateFinding]:
@@ -180,9 +184,12 @@ def check_connectivity(
min_part_size_m: float = MIN_PART_SIZE_M,
penetration_warn_m: float = PENETRATION_WARN_M,
penetration_error_m: float = PENETRATION_ERROR_M,
+ language: str = "",
) -> GateReport:
- """Run the connectivity gate on ``glb`` (see module docstring)."""
+ """Run the connectivity gate on ``glb`` (see module docstring). ``language`` selects
+ the frame of the translation hints (default: the GLB frame, labelled as such)."""
t0 = time.time()
+ up = "z" if language_frame(language) is Frame.Z_UP_NEG_Y_FRONT else "y"
findings: list[GateFinding] = []
try:
parts = {k: v for k, v in part_meshes(load_scene(glb)).items() if v is not None and len(v.faces)}
@@ -232,8 +239,8 @@ def check_connectivity(
support |= c
else:
support = max(comps, key=lambda c: sum(len(parts[n].faces) for n in c)) if comps else set()
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, message="no part touches the ground (y=0)",
- fix_hint="move the whole object down so its lowest point sits at y=0"))
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, message=f"no part touches the ground ({up}=0)",
+ fix_hint=f"move the whole object down so its lowest point sits on the ground ({up}=0, {frame_label(language)})"))
for n in big:
if n in support:
continue
@@ -243,15 +250,17 @@ def check_connectivity(
message=f"part '{n}' is floating: touches nothing", fix_hint=f"attach '{n}' to a neighbouring part"))
continue
other = near.b if near.a == n else near.a
- vec = near.gap_vector if near.a == n else tuple(-x for x in near.gap_vector)
+ vec_glb = near.gap_vector if near.a == n else tuple(-x for x in near.gap_vector)
p_self = near.point_a if near.a == n else near.point_b
p_other = near.point_b if near.a == n else near.point_a
+ vec = tuple(float(x) for x in glb_vec_to_plan(vec_glb, language))
findings.append(GateFinding(
gate=GATE, severity=Severity.ERROR, target=n,
message=f"part '{n}' is floating: nearest supported part is '{other}' at {near.distance * 1000:.1f} mm",
- fix_hint=f"translate '{n}' by {_fmt_vec(vec)} m (or extend it by {near.distance * 1000:.1f} mm towards '{other}') so the surfaces touch",
- data={"nearest": other, "gap_m": near.distance, "gap_vector_m": list(vec),
- "closest_point_self": list(p_self), "closest_point_other": list(p_other)},
+ fix_hint=f"translate '{n}' by {_fmt_vec(vec)} m ({frame_label(language)}) — or extend it by "
+ f"{near.distance * 1000:.1f} mm towards '{other}' — so the surfaces touch",
+ data={"nearest": other, "gap_m": near.distance, "gap_vector_m": list(vec), "frame": language_frame(language).value,
+ "gap_vector_glb_m": list(vec_glb), "closest_point_self": list(p_self), "closest_point_other": list(p_other)},
))
# ---- stray islands inside parts
for n in big:
diff --git a/harness/codeverse/spatial/contract.py b/harness/codeverse/spatial/contract.py
index c050b175..ed645fd1 100644
--- a/harness/codeverse/spatial/contract.py
+++ b/harness/codeverse/spatial/contract.py
@@ -3,7 +3,10 @@
Plans are authored in the language's *native* frame (see ``conventions``):
blender / cadquery / urdf are Z-up with -Y front, three.js is Y-up. The GLB is
always Y-up, so plan boxes are converted with the glTF mapping
-``(x, y, z) → (x, z, -y)`` before comparison.
+``(x, y, z) → (x, z, -y)`` before comparison — and every number in a fix hint
+(sizes, deltas, centres, translation vectors) is converted *back* into the
+authoring frame and labelled, because hints are pasted verbatim into refine
+prompts that speak the language's frame.
Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
* plan part missing in the GLB → ERROR
@@ -42,16 +45,37 @@ _AXES = ("x", "y", "z")
# --------------------------------------------------------------------------- frames
+def language_frame(language: str) -> Frame:
+ """Authoring frame of ``language`` (unknown / empty → the GLB frame itself)."""
+ return LANGUAGE_FRAME.get(str(language), Frame.Y_UP_POS_Z_FRONT)
+
+
+def frame_label(language: str) -> str:
+ """Short frame tag for fix hints, e.g. ``"blender frame: Z-up, -Y front"``."""
+ if language_frame(language) is Frame.Z_UP_NEG_Y_FRONT:
+ return f"{language} frame: Z-up, -Y front"
+ return f"{language} frame: Y-up, +Z front" if language else "GLB frame: Y-up, +Z front"
+
+
def plan_bbox_to_glb(bbox: BBox, language: str) -> BBox:
"""Convert a plan-frame box to the canonical GLB frame (Y-up, +Z front)."""
- frame = LANGUAGE_FRAME.get(str(language), Frame.Y_UP_POS_Z_FRONT)
- if frame is Frame.Y_UP_POS_Z_FRONT:
+ if language_frame(language) is Frame.Y_UP_POS_Z_FRONT:
return bbox
cx, cy, cz = bbox.center
ex, ey, ez = bbox.extents
return BBox(center=(cx, cz, -cy), extents=(ex, ez, ey))
+def glb_vec_to_plan(v, language: str, *, extents: bool = False) -> np.ndarray:
+ """Inverse of the glTF mapping for a GLB-frame vector: Z-up languages get
+ ``(x, y, z) → (x, -z, y)``; ``extents`` (per-axis sizes / size deltas) are only
+ permuted, never sign-flipped. Hints must be written in the frame the agent codes in."""
+ v = np.asarray(v, dtype=float)
+ if language_frame(language) is Frame.Y_UP_POS_Z_FRONT:
+ return v
+ return np.array([v[0], v[2] if extents else -v[2], v[1]])
+
+
# --------------------------------------------------------------------------- matching
def _instance_re(snake: str) -> re.Pattern[str]:
return re.compile(rf"^{re.escape(snake)}(?:[_.-]?\d{{1,3}})?$")
@@ -98,8 +122,15 @@ def _fmt_ext(v) -> str:
return "×".join(f"{float(x) * 100:.1f}" for x in v)
-def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, check_center: bool = True) -> list[GateFinding]:
- """WARN/ERROR findings for one box comparison (empty when within tolerance)."""
+def _fmt_vec(v) -> str:
+ return "(" + ", ".join(f"{round(float(x), 3) + 0.0:+.3f}" for x in v) + ")" # + 0.0: no '-0.000'
+
+
+def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, language: str,
+ check_center: bool = True) -> list[GateFinding]:
+ """WARN/ERROR findings for one box comparison (empty when within tolerance).
+ ``d``/``plan`` are in the GLB frame; every number in the hint (and ``data``) is
+ written back in ``language``'s authoring frame so the agent can paste it."""
out: list[GateFinding] = []
ext_bad = np.abs(d.extents) > d.tol
ctr_bad = check_center and np.any(np.abs(d.center) > d.tol)
@@ -107,17 +138,22 @@ def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, check_cen
return out
ratio = d.worst_ratio if check_center else float(np.max(np.abs(d.extents) / d.tol))
sev = Severity.ERROR if ratio > ERROR_FACTOR else Severity.WARN
+ p_ext = glb_vec_to_plan(plan.extents, language, extents=True)
+ d_ext = glb_vec_to_plan(d.extents, language, extents=True)
+ d_ctr = glb_vec_to_plan(d.center, language)
+ p_ctr = glb_vec_to_plan(plan.center, language)
bits = []
if ext_bad.any():
- bits.append(f"size {_fmt_ext(np.asarray(plan.extents) + d.extents)} vs planned {_fmt_ext(plan.extents)} cm (Δ {_fmt_delta(d.extents)})")
+ bits.append(f"size {_fmt_ext(p_ext + d_ext)} vs planned {_fmt_ext(p_ext)} cm (Δ {_fmt_delta(d_ext)})")
if ctr_bad:
- bits.append(f"centre off by ({_fmt_delta(d.center)})")
+ bits.append(f"centre off by ({_fmt_delta(d_ctr)})")
hint = f"{what}: " + ("; ".join(bits))
out.append(GateFinding(
gate=GATE, severity=sev, target=target,
message=f"{what} bbox deviates from the plan (worst {ratio:.1f}× tolerance)",
- fix_hint=hint + f"; planned centre ({', '.join(f'{c:.3f}' for c in plan.center)}) m in the GLB frame (Y-up)",
- data={"delta_center_m": d.center.tolist(), "delta_extents_m": d.extents.tolist(), "tol_m": d.tol.tolist()},
+ fix_hint=hint + f"; planned centre ({', '.join(f'{c:.3f}' for c in p_ctr)}) m ({frame_label(language)})",
+ data={"delta_center_m": d_ctr.tolist(), "delta_extents_m": d_ext.tolist(),
+ "tol_m": glb_vec_to_plan(d.tol, language, extents=True).tolist(), "frame": language_frame(language).value},
))
return out
@@ -148,7 +184,7 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
))
if len(rows) == 1 and pp.instances == 1:
d = _box_delta(np.asarray(rows[0].bbox_min), np.asarray(rows[0].bbox_max), box, tol_m)
- findings.extend(_box_findings(target, d, box, what=f"part '{pp.name}'"))
+ findings.extend(_box_findings(target, d, box, what=f"part '{pp.name}'", language=language))
else:
# instances: each copy should have the planned extents; the centre is unknowable
per = [_box_delta(np.asarray(r.bbox_min), np.asarray(r.bbox_max), box, tol_m) for r in rows]
@@ -156,13 +192,13 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
worst_each = max(per, key=lambda d: float(np.max(np.abs(d.extents) / d.tol)))
# accept whichever reading (per-instance or union) fits the plan better
if float(np.max(np.abs(union.extents) / union.tol)) < float(np.max(np.abs(worst_each.extents) / worst_each.tol)):
- findings.extend(_box_findings(target, union, box, what=f"'{pp.name}' (all instances)", check_center=False))
+ findings.extend(_box_findings(target, union, box, what=f"'{pp.name}' (all instances)", language=language, check_center=False))
else:
- findings.extend(_box_findings(target, worst_each, box, what=f"'{pp.name}' (each instance)", check_center=False))
+ findings.extend(_box_findings(target, worst_each, box, what=f"'{pp.name}' (each instance)", language=language, check_center=False))
# overall bbox
ob = plan_bbox_to_glb(plan.overall_bbox, language)
d = _box_delta(np.asarray(m.bbox_min), np.asarray(m.bbox_max), ob, tol_m)
- findings.extend(_box_findings("overall", d, ob, what="overall"))
+ findings.extend(_box_findings("overall", d, ob, what="overall", language=language))
# ground + footprint
if abs(m.ground_gap_m) > tol_m:
where = "above" if m.ground_gap_m > 0 else "below"
@@ -176,8 +212,9 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
findings.append(GateFinding(
gate=GATE, severity=Severity.WARN, target="overall",
message=f"footprint centre is {m.footprint_offset_m * 100:.1f} cm off the up axis",
- fix_hint=f"translate everything by ({-m.center[0]:+.3f}, 0, {-m.center[2]:+.3f}) m (GLB frame) to centre the footprint",
- data={"footprint_offset_m": m.footprint_offset_m},
+ fix_hint=f"translate everything by {_fmt_vec(glb_vec_to_plan((-m.center[0], 0.0, -m.center[2]), language))} m "
+ f"({frame_label(language)}) to centre the footprint",
+ data={"footprint_offset_m": m.footprint_offset_m, "frame": language_frame(language).value},
))
for r in extra:
findings.append(GateFinding(gate=GATE, severity=Severity.INFO, target=r.name,
@@ -197,10 +234,12 @@ def _check_scene_plan(m: Measurement, plan: ScenePlan, language: str, tol_m: flo
lo, hi = np.asarray(b.min), np.asarray(b.max)
over = np.maximum(lo - np.asarray(m.bbox_min), 0) + np.maximum(np.asarray(m.bbox_max) - hi, 0)
if float(np.max(over)) > max(tol_m, REL_TOL * float(np.max(b.extents))):
+ over_plan = glb_vec_to_plan(over, language, extents=True)
findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target="bounds",
- message=f"scene geometry exceeds the planned bounds by {_fmt_delta(over)}",
- fix_hint=f"keep everything inside centre {b.center}, extents {b.extents} m (GLB frame)",
- data={"overshoot_m": over.tolist()}))
+ message=f"scene geometry exceeds the planned bounds by {_fmt_delta(over_plan)}",
+ fix_hint=f"keep everything inside centre {plan.bounds.center}, extents {plan.bounds.extents} m "
+ f"({frame_label(language)})",
+ data={"overshoot_m": over_plan.tolist(), "frame": language_frame(language).value}))
return findings
diff --git a/harness/codeverse/spatial/frame_metrics.py b/harness/codeverse/spatial/frame_metrics.py
new file mode 100644
index 00000000..2f57f54f
--- /dev/null
+++ b/harness/codeverse/spatial/frame_metrics.py
@@ -0,0 +1,218 @@
+"""Frame-quality gate for scene renders: ``scene_frames``.
+
+Reads the deterministic ``camera_checks`` that ``render_scene`` leaves in
+``metrics.json`` (per camera: mean luminance, dark/blown/modal fractions,
+content/ground/sky coverage, nearest geometry, eye height) and turns them into
+``GateFinding``s with copyable fix hints, so a too-dark dusk, a blown sky, a
+camera buried in a wall or an establishing shot that shows a tiny island of
+content become gate findings (→ judge caps + refine instructions) instead of
+silently lowering a VLM score.
+
+* ``frame_findings(metrics)`` → GateReport
+* ``frame_gate_from_renders(rs_or_path)`` → GateReport (RenderSet / out dir / metrics.json)
+* ``frame_summary_text(metrics)`` → per-camera table for tool observations / prompts
+
+Authored cameras get ERRORs; harness orbit views only WARN (the agent does not
+place them) except for the content-sparse overview, which is informational.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, RenderSet, Severity
+
+FRAME_GATE = "scene_frames"
+
+# thresholds (fractions of the frame / of full white)
+DARK_MEAN_LUM = 0.12
+DARK_FRAC = 0.35
+BLOWN_FRAC = 0.20
+FLAT_MODAL_FRAC = 0.85
+FLAT_MODAL_ERROR = 0.92
+NEAR_HIT_M = 0.5
+CONTENT_MIN_ESTABLISHING = 0.20
+CONTENT_MIN_AUTHORED = 0.10
+CONTENT_MIN_OVERVIEW = 0.05
+EYE_MIN_ABOVE_GROUND_M = 0.3
+EYE_MAX_ABOVE_GROUND_M = 80.0
+
+_DARK_HINT = (
+ "raise the key + fill: DirectionalLight intensity 2–4, HemisphereLight 0.5–1.0 (sky colour / ground colour), "
+ "add emissive lights where the brief has them (lantern glow: MeshStandardMaterial emissive + emissiveIntensity 2–6, "
+ "a PointLight 0.5–2 per lantern); scene.fog colour must match the sky colour; dusk/night is orange/purple/deep blue, "
+ "NOT black — keep mean luminance ≥ 0.15 (check with scene_views: camera_checks.mean_lum)"
+)
+_BLOWN_HINT = (
+ "lower exposure: DirectionalLight ≤ 3, HemisphereLight ≤ 1.0, no MeshBasicMaterial white planes; "
+ "sky colour below 0.9 white; emissiveIntensity ≤ 4 on large surfaces"
+)
+_FLAT_HINT = (
+ "one colour dominates the frame: aim the camera at content (lookAt the zone centre), add contrast with a shadow-casting "
+ "DirectionalLight, vary materials, and make sure the sky gradient / fog is not a single flat tint"
+)
+_NEAR_HINT = "move the camera ≥ 0.5 m away from every surface (raise it above ground/terrain, pull it out of walls and trees) and keep lookAt on the content"
+_SMALL_HINT = (
+ "the shot shows mostly sky/ground: move the camera closer to the content (distance ≈ 1.2 × the content's widest span), "
+ "lower it toward eye level, point lookAt at the content centre, or fill the bounds with more zones/assets"
+)
+
+
+def _view_kind(chk: dict[str, Any]) -> str:
+ return str(chk.get("kind") or "authored")
+
+
+def _f(sev: Severity, target: str, msg: str, hint: str, **data: Any) -> GateFinding:
+ return GateFinding(gate=FRAME_GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
+
+
+def _num(chk: dict[str, Any], key: str) -> float | None:
+ v = chk.get(key)
+ return float(v) if isinstance(v, (int, float)) else None
+
+
+def _exposure_findings(chk: dict[str, Any], *, authored: bool) -> list[GateFinding]:
+ name = str(chk.get("name", "?"))
+ sev = Severity.ERROR if authored else Severity.WARN
+ out: list[GateFinding] = []
+ mean, dark, blown, modal = (_num(chk, k) for k in ("mean_lum", "dark_frac", "blown_frac", "modal_frac"))
+ is_dark = (mean is not None and mean < DARK_MEAN_LUM) or (dark is not None and dark > DARK_FRAC)
+ if is_dark:
+ out.append(_f(sev, name, f"frame too dark: mean luminance {mean:.2f}, {dark or 0:.0%} of pixels near black" if mean is not None
+ else f"frame too dark: {dark:.0%} of pixels near black", _DARK_HINT,
+ kind="dark_frame", view=name, mean_lum=mean, dark_frac=dark))
+ if blown is not None and blown > BLOWN_FRAC:
+ out.append(_f(sev, name, f"frame blown out: {blown:.0%} of pixels pure white", _BLOWN_HINT,
+ kind="blown_frame", view=name, blown_frac=blown))
+ if modal is not None and modal > FLAT_MODAL_FRAC and not is_dark:
+ flat_sev = sev if modal > FLAT_MODAL_ERROR else Severity.WARN
+ out.append(_f(flat_sev, name, f"flat frame: one luminance band holds {modal:.0%} of the pixels", _FLAT_HINT,
+ kind="flat_frame", view=name, modal_frac=modal, mean_lum=mean))
+ return out
+
+
+def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float | None) -> list[GateFinding]:
+ name = str(chk.get("name", "?"))
+ sev = Severity.ERROR if authored else Severity.WARN
+ out: list[GateFinding] = []
+ near = _num(chk, "nearest_hit_m")
+ inside = list(chk.get("inside_mesh_bbox") or [])
+ if chk.get("camera_in_geometry") or (near is not None and near < NEAR_HIT_M):
+ where = f"inside {inside[:3]}" if inside else f"nearest surface {near:.2f} m ({chk.get('nearest_hit_name', '')})"
+ out.append(_f(sev, name, f"camera inside / touching geometry: {where}", _NEAR_HINT,
+ kind="camera_in_geometry", view=name, nearest_hit_m=near, inside=inside[:5]))
+ eye = _num(chk, "eye_height_m")
+ if authored and eye is not None and ground_y is not None:
+ above = eye - ground_y
+ if above < -0.2:
+ out.append(_f(Severity.ERROR, name, f"camera is {-above:.1f} m BELOW the ground level ({ground_y:.2f} m)",
+ "set position[1] = heightAt(x, z) + 1.6 (eye level) — never below the terrain",
+ kind="camera_underground", view=name, eye_height_m=eye, ground_y=ground_y))
+ elif above < EYE_MIN_ABOVE_GROUND_M:
+ out.append(_f(Severity.WARN, name, f"camera eye only {above:.2f} m above ground — ant's-eye view",
+ "human shots: position[1] = heightAt(x, z) + 1.6; establishing: 6–20 m above ground looking down 15–30°",
+ kind="camera_low", view=name, eye_height_m=eye, ground_y=ground_y))
+ elif above > EYE_MAX_ABOVE_GROUND_M:
+ out.append(_f(Severity.WARN, name, f"camera {above:.0f} m above ground — satellite view, not a shot",
+ "bring the camera down: establishing 6–20 m above ground at ~1.2 × the content span",
+ kind="camera_high", view=name, eye_height_m=eye, ground_y=ground_y))
+ return out
+
+
+def _coverage_finding(chk: dict[str, Any], *, role: str) -> GateFinding | None:
+ """role: 'establishing' | 'authored' | 'overview' | 'eye'."""
+ content = _num(chk, "content_frac")
+ if content is None or role == "eye":
+ return None
+ name = str(chk.get("name", "?"))
+ sky, ground = _num(chk, "sky_frac"), _num(chk, "ground_frac")
+ detail = f"content {content:.0%} of the frame (sky {sky or 0:.0%}, ground {ground or 0:.0%})"
+ if role == "establishing" and content < CONTENT_MIN_ESTABLISHING:
+ return _f(Severity.ERROR, name, f"establishing shot shows too little content: {detail}", _SMALL_HINT,
+ kind="content_small", view=name, content_frac=content, sky_frac=sky, ground_frac=ground, role=role)
+ if role == "authored" and content < CONTENT_MIN_AUTHORED:
+ return _f(Severity.WARN, name, f"shot shows little content: {detail}", _SMALL_HINT,
+ kind="content_small", view=name, content_frac=content, sky_frac=sky, ground_frac=ground, role=role)
+ if role == "overview" and content < CONTENT_MIN_OVERVIEW:
+ return _f(Severity.WARN, name, f"overview rig sees sparse content: {detail}",
+ "the plan bounds are mostly empty ground: add the planned zones/assets, or densify (instanced scatter, props) "
+ "so the content fills the bounds", kind="content_small", view=name, content_frac=content, role=role)
+ return None
+
+
+def frame_findings(metrics: dict[str, Any]) -> GateReport:
+ """``scene_frames`` gate from a ``metrics.json`` payload (``camera_checks`` + ``census``)."""
+ checks: list[dict[str, Any]] = [c for c in metrics.get("camera_checks") or [] if isinstance(c, dict)]
+ ground_y = (metrics.get("census") or {}).get("ground_y")
+ ground_y = float(ground_y) if isinstance(ground_y, (int, float)) else None
+ findings: list[GateFinding] = []
+ first_authored = next((c for c in checks if _view_kind(c) == "authored"), None)
+ for chk in checks:
+ authored = _view_kind(chk) == "authored"
+ findings += _exposure_findings(chk, authored=authored)
+ findings += _geometry_findings(chk, authored=authored, ground_y=ground_y)
+ if authored:
+ role = "establishing" if chk is first_authored else "authored"
+ else:
+ role = "overview" if str(chk.get("name", "")).startswith("overview") else "eye"
+ cov = _coverage_finding(chk, role=role)
+ if cov is not None:
+ findings.append(cov)
+ if checks and not findings:
+ n = len(checks)
+ findings.append(_f(Severity.INFO, "overall", f"{n} camera frame(s) checked: exposure, geometry and coverage within limits", "",
+ kind="frames_ok", n_views=n))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=FRAME_GATE, passed=passed, findings=findings)
+
+
+def frame_gate_from_renders(source: RenderSet | Path | str) -> GateReport:
+ """``scene_frames`` gate from a RenderSet (locates its metrics.json), a render
+ directory or a metrics.json path. Missing metrics → an empty passing report."""
+ from codeverse.spatial.render_scene import metrics_path_for
+
+ if isinstance(source, RenderSet):
+ path = metrics_path_for(source)
+ else:
+ p = Path(source)
+ path = p if p.is_file() else (p / "metrics.json" if (p / "metrics.json").is_file() else None)
+ if path is None:
+ return GateReport(gate=FRAME_GATE, passed=True, findings=[])
+ try:
+ metrics = json.loads(path.read_text())
+ except (OSError, ValueError):
+ return GateReport(gate=FRAME_GATE, passed=True, findings=[])
+ return frame_findings(metrics)
+
+
+def frame_summary_text(metrics: dict[str, Any], *, max_rows: int = 12) -> str:
+ """Compact per-camera table for tool observations / prompts:
+ ``name: lum 0.07 dark 41% blown 0% content 48% (sky 25% ground 27%) eye 5.2 m — TOO DARK``."""
+ rows: list[str] = []
+ report = frame_findings(metrics)
+ flagged: dict[str, list[str]] = {}
+ for f in report.findings:
+ if f.severity != Severity.INFO and f.target:
+ flagged.setdefault(f.target, []).append(str(f.data.get("kind", "")).replace("_", " ").upper())
+ for chk in (metrics.get("camera_checks") or [])[:max_rows]:
+ if not isinstance(chk, dict):
+ continue
+ name = str(chk.get("name", "?"))
+ bits = [f"{name} [{_view_kind(chk)}]:"]
+ for key, label, pct in (("mean_lum", "lum", False), ("dark_frac", "dark", True), ("blown_frac", "blown", True),
+ ("content_frac", "content", True), ("sky_frac", "sky", True), ("ground_frac", "ground", True)):
+ v = _num(chk, key)
+ if v is not None:
+ bits.append(f"{label} {v:.0%}" if pct else f"{label} {v:.2f}")
+ eye, near = _num(chk, "eye_height_m"), _num(chk, "nearest_hit_m")
+ if eye is not None:
+ bits.append(f"eye {eye:.1f} m")
+ if near is not None:
+ bits.append(f"nearest {near:.1f} m")
+ if name in flagged:
+ bits.append("— " + ", ".join(flagged[name]))
+ rows.append(" ".join(bits))
+ head = f"frame checks ({'ok' if report.passed else 'FAILED'}; mean_lum ≥ 0.15, dark ≤ 35 %, blown ≤ 20 %, establishing content ≥ 20 %):"
+ return "\n".join([head, *rows]) if rows else "frame checks: no camera_checks in metrics"
diff --git a/harness/codeverse/spatial/frame_stats.py b/harness/codeverse/spatial/frame_stats.py
new file mode 100644
index 00000000..e6a744a2
--- /dev/null
+++ b/harness/codeverse/spatial/frame_stats.py
@@ -0,0 +1,182 @@
+"""Visual + temporal metrics for a rendered frame sequence (numpy + PIL only).
+
+Per frame: mean luminance, luminance std, % near-black, % blown-out pixels,
+colourfulness (Hasler–Süsstrunk), edge density (gradient magnitude above a
+threshold). Temporal: mean absolute difference between consecutive frames
+(0 → static), duplicate frames, flicker (very large diffs), plus NaN/Inf counts
+reported by the GL runner (float readback). ``frame_gate`` turns the sequence
+into the ``gl_frames`` GateReport the graphics track + rubric caps consume
+(``data["kind"]`` ∈ nan · black · blown · static · flicker · duplicate · low_detail).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+
+GATE = "gl_frames"
+BLACK_LUM = 0.03
+BLOWN_LUM = 0.98
+STATIC_DIFF = 0.002
+FLICKER_DIFF = 0.35
+DUPLICATE_DIFF = 1e-4
+LOW_DETAIL_EDGE = 0.002
+ANALYSIS_MAX_W = 512
+
+
+class FrameStat(BaseModel):
+ time: float
+ path: str
+ mean_lum: float
+ std_lum: float
+ pct_black: float
+ pct_blown: float
+ colourfulness: float
+ edge_density: float
+ nan: int = 0
+ inf: int = 0
+
+
+class SequenceStats(BaseModel):
+ frames: list[FrameStat] = Field(default_factory=list)
+ diffs: list[float] = Field(default_factory=list, description="mean |Δ| between consecutive frames (0..1)")
+ mean_diff: float = 0.0
+ max_diff: float = 0.0
+ n_duplicates: int = 0
+ static: bool = False
+ flicker: bool = False
+ any_nan: bool = False
+ mean_lum: float = 0.0
+ mean_colourfulness: float = 0.0
+ mean_edge_density: float = 0.0
+ all_black: bool = False
+ all_blown: bool = False
+
+ def summary_lines(self) -> list[str]:
+ out = [f"frames={len(self.frames)} mean_lum={self.mean_lum:.3f} colourfulness={self.mean_colourfulness:.3f} "
+ f"edge_density={self.mean_edge_density:.4f} motion(mean|Δ|)={self.mean_diff:.4f} max|Δ|={self.max_diff:.4f} "
+ f"duplicates={self.n_duplicates}" + (" NaN/Inf!" if self.any_nan else "")]
+ for f in self.frames:
+ out.append(f" t={f.time:g}s lum={f.mean_lum:.3f}±{f.std_lum:.3f} black={f.pct_black:.0%} blown={f.pct_blown:.0%} "
+ f"colour={f.colourfulness:.3f} edges={f.edge_density:.4f}" + (f" nan={f.nan} inf={f.inf}" if f.nan or f.inf else ""))
+ return out
+
+
+# --------------------------------------------------------------------------- per frame
+def load_rgb(path: str | Path, max_w: int = ANALYSIS_MAX_W) -> np.ndarray:
+ im = Image.open(path).convert("RGB")
+ if im.width > max_w:
+ im = im.resize((max_w, max(1, round(im.height * max_w / im.width))), Image.BILINEAR)
+ return np.asarray(im, dtype=np.float32) / 255.0
+
+
+def luminance(rgb: np.ndarray) -> np.ndarray:
+ return rgb[..., 0] * 0.2126 + rgb[..., 1] * 0.7152 + rgb[..., 2] * 0.0722
+
+
+def colourfulness(rgb: np.ndarray) -> float:
+ """Hasler & Süsstrunk (2003) metric on 0..1 floats (≈0 grey, ~0.3+ vivid)."""
+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
+ rg = r - g
+ yb = 0.5 * (r + g) - b
+ std = float(np.hypot(rg.std(), yb.std()))
+ mean = float(np.hypot(rg.mean(), yb.mean()))
+ return std + 0.3 * mean
+
+
+def edge_density(lum: np.ndarray, threshold: float = 0.02) -> float:
+ gy, gx = np.gradient(lum)
+ mag = np.hypot(gx, gy)
+ return float((mag > threshold).mean())
+
+
+def frame_stat(path: str | Path, *, time: float, nan: int = 0, inf: int = 0, rgb: np.ndarray | None = None) -> FrameStat:
+ rgb = load_rgb(path) if rgb is None else rgb
+ lum = luminance(rgb)
+ return FrameStat(time=time, path=str(path), mean_lum=float(lum.mean()), std_lum=float(lum.std()),
+ pct_black=float((lum < BLACK_LUM).mean()), pct_blown=float((lum > BLOWN_LUM).mean()),
+ colourfulness=colourfulness(rgb), edge_density=edge_density(lum), nan=nan, inf=inf)
+
+
+# --------------------------------------------------------------------------- sequence
+def sequence_stats(frames: Sequence[tuple[float, str | Path]], *, nan_counts: Sequence[tuple[int, int]] | None = None) -> SequenceStats:
+ """``frames`` = [(time, png_path)] sorted by time; ``nan_counts`` aligned [(nan, inf)]."""
+ ordered = sorted(enumerate(frames), key=lambda it: it[1][0])
+ stats: list[FrameStat] = []
+ arrays: list[np.ndarray] = []
+ for orig_i, (t, p) in ordered:
+ rgb = load_rgb(p)
+ nan, inf = (nan_counts[orig_i] if nan_counts and orig_i < len(nan_counts) else (0, 0))
+ stats.append(frame_stat(p, time=t, nan=nan, inf=inf, rgb=rgb))
+ arrays.append(rgb)
+ diffs: list[float] = []
+ for a, b in zip(arrays, arrays[1:], strict=False):
+ if a.shape != b.shape:
+ diffs.append(1.0)
+ continue
+ diffs.append(float(np.abs(a - b).mean()))
+ seq = SequenceStats(frames=stats, diffs=diffs)
+ if stats:
+ seq.mean_lum = float(np.mean([f.mean_lum for f in stats]))
+ seq.mean_colourfulness = float(np.mean([f.colourfulness for f in stats]))
+ seq.mean_edge_density = float(np.mean([f.edge_density for f in stats]))
+ seq.all_black = all(f.pct_black > 0.97 for f in stats)
+ seq.all_blown = all(f.pct_blown > 0.97 for f in stats)
+ seq.any_nan = any(f.nan or f.inf for f in stats)
+ if diffs:
+ seq.mean_diff = float(np.mean(diffs))
+ seq.max_diff = float(np.max(diffs))
+ seq.n_duplicates = sum(1 for d in diffs if d < DUPLICATE_DIFF)
+ seq.static = seq.mean_diff < STATIC_DIFF
+ seq.flicker = seq.max_diff > FLICKER_DIFF and len(diffs) >= 2
+ return seq
+
+
+# --------------------------------------------------------------------------- gate
+def frame_gate(seq: SequenceStats, *, motion_expected: bool = True, gate: str = GATE) -> GateReport:
+ """Deterministic findings the judge/refiner/caps consume (``data["kind"]`` set)."""
+ f: list[GateFinding] = []
+
+ def add(sev: Severity, kind: str, msg: str, hint: str, target: str = "overall", **data: object) -> None:
+ f.append(GateFinding(gate=gate, severity=sev, target=target, message=msg, fix_hint=hint, data={"kind": kind, **data}))
+
+ if not seq.frames:
+ add(Severity.ERROR, "no_frames", "no frames were rendered", "the program must produce at least one frame")
+ return GateReport(gate=gate, passed=False, findings=f)
+ if seq.any_nan:
+ bad = [fr for fr in seq.frames if fr.nan or fr.inf]
+ add(Severity.ERROR, "nan", f"NaN/Inf pixels in {len(bad)} frame(s) (first at t={bad[0].time:g}s: nan={bad[0].nan} inf={bad[0].inf})",
+ "guard divisions (x / max(d, 1e-4)), sqrt/pow/log of negatives (max(x, 0.0)), normalize(vec) of zero vectors, "
+ "and acos/asin arguments (clamp(x, -1.0, 1.0)); never let a colour be NaN",
+ n_frames=len(bad))
+ if seq.all_black:
+ add(Severity.ERROR, "black", f"frames are essentially black (mean luminance {seq.mean_lum:.3f})",
+ "something must be visible: check the final fragColor assignment, the raymarch hit test, camera direction and "
+ "that colours are not multiplied to zero; aim for mean luminance 0.2-0.6")
+ elif seq.all_blown:
+ add(Severity.ERROR, "blown", f"frames are blown out white (mean luminance {seq.mean_lum:.3f})",
+ "tone-map and clamp: col = col / (1.0 + col); keep accumulated glow sums bounded")
+ if seq.static and motion_expected:
+ add(Severity.WARN, "static", f"frames do not change over time (mean |Δ| {seq.mean_diff:.4f}); the shader looks static",
+ "use u_time for motion: scroll uv, rotate, animate noise offsets, move lights — the judge compares frames at t=0..6s")
+ elif seq.n_duplicates and motion_expected:
+ add(Severity.INFO, "duplicate", f"{seq.n_duplicates} consecutive frame pair(s) are identical",
+ "make sure every sampled time differs visibly (continuous motion rather than rare jumps)")
+ if seq.flicker:
+ add(Severity.WARN, "flicker", f"very large frame-to-frame change (max |Δ| {seq.max_diff:.3f}); flicker or hard cuts",
+ "avoid discontinuous functions of u_time (fract/mod jumps, random per-frame seeds); motion should be continuous")
+ if seq.mean_edge_density < LOW_DETAIL_EDGE and not seq.all_black and not seq.all_blown:
+ add(Severity.WARN, "low_detail", f"very low visual detail (edge density {seq.mean_edge_density:.4f}); the image is a near-flat gradient",
+ "add structure: fbm layers, shapes (sdf), stars/particles, lines — the rubric rewards visual richness")
+ passed = not any(x.severity == Severity.ERROR for x in f)
+ return GateReport(gate=gate, passed=passed, findings=f)
+
+
+def stats_table(seq: SequenceStats) -> str:
+ return "\n".join(seq.summary_lines())
diff --git a/harness/codeverse/spatial/gl_render.py b/harness/codeverse/spatial/gl_render.py
new file mode 100644
index 00000000..8b4db1a2
--- /dev/null
+++ b/harness/codeverse/spatial/gl_render.py
@@ -0,0 +1,245 @@
+"""GlHost: headless moderngl rendering of fragment shaders / raw OpenGL programs.
+
+moderngl contexts are not fork-safe and the harness is multi-threaded, so every
+render happens in a fresh ``python3`` subprocess running the standalone
+``languages/opengl_python/wrappers/run_gl.py``. The host tries the GPU driver
+environment first (Mesa d3d12 on WSL2) and falls back to llvmpipe when the
+context cannot be created; the decision is cached per process.
+
+Public API::
+
+ host = GlHost() # gpu="auto" | "on" | "off"
+ res = host.render_fragment_shader(frag_src, out_dir, width=1280, height=720, times=(0, 1, 2.5),
+ buffer_a_src=None, feedback=False, extra_times=())
+ res = host.run_program(program_path, out_dir, width=..., height=..., times=...)
+ res.ok · res.frames[GlFrame] · res.judge_frames · res.stage · res.error_message · res.renderer
+
+Artifacts derived from a result: :func:`write_contact_sheet`, :func:`write_gif`.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.languages._common import run_subprocess
+
+RUNNER = Path(__file__).resolve().parent.parent / "languages" / "opengl_python" / "wrappers" / "run_gl.py"
+
+#: Mesa d3d12 driver env (GPU on WSL2). Falls back to llvmpipe when unusable.
+GPU_ENV: dict[str, str] = {
+ "GALLIUM_DRIVER": "d3d12",
+ "MESA_LOADER_DRIVER_OVERRIDE": "d3d12",
+ "MESA_D3D12_DEFAULT_ADAPTER_NAME": "NVIDIA",
+}
+CPU_ENV: dict[str, str] = {"LIBGL_ALWAYS_SOFTWARE": "1", "GALLIUM_DRIVER": "llvmpipe"}
+_ENV_PASS = ("PATH", "HOME", "LANG", "LC_ALL", "PYTHONHASHSEED", "LD_LIBRARY_PATH", "XDG_RUNTIME_DIR", "TMPDIR")
+
+DEFAULT_TIMES: tuple[float, ...] = (0.0, 1.0, 2.5, 4.0, 6.0)
+EXIT_CONTEXT = 3
+RESULT_NAME = "gl_result.json"
+JOB_NAME = "gl_job.json"
+
+_gpu_state: dict[str, bool | None] = {"ok": None}
+
+
+class GlFrame(BaseModel):
+ index: int
+ time: float
+ path: str
+ judge: bool = True
+ nan: int = 0
+ inf: int = 0
+ mean: float = 0.0
+
+
+class GlResult(BaseModel):
+ ok: bool
+ mode: str
+ stage: str = ""
+ error_type: str = ""
+ error_message: str = ""
+ traceback: str = ""
+ stdout_tail: str = ""
+ stderr_tail: str = ""
+ renderer: str = ""
+ gpu: bool = False
+ feedback: bool = False
+ frames: list[GlFrame] = Field(default_factory=list)
+ duration_ms: int = 0
+ timed_out: bool = False
+
+ @property
+ def judge_frames(self) -> list[GlFrame]:
+ return [f for f in self.frames if f.judge]
+
+ @property
+ def has_nan(self) -> bool:
+ return any(f.nan or f.inf for f in self.frames)
+
+
+class GlHostError(RuntimeError):
+ """Harness-side failure (runner missing, no GL at all) — not an agent error."""
+
+
+def _base_env(extra: dict[str, str]) -> dict[str, str]:
+ env = {k: os.environ[k] for k in _ENV_PASS if k in os.environ}
+ env["PYTHONUNBUFFERED"] = "1"
+ env.update(extra)
+ return env
+
+
+def gpu_preference(gpu: str) -> list[bool]:
+ """Order of attempts: [True, False] (GPU then CPU) for auto, etc."""
+ if gpu == "on":
+ return [True]
+ if gpu == "off":
+ return [False]
+ if _gpu_state["ok"] is False:
+ return [False]
+ return [True, False]
+
+
+class GlHost:
+ def __init__(self, *, gpu: str = "auto", python: str | None = None, timeout_s: float = 240.0, fps: int = 30,
+ max_steps: int = 240):
+ if not RUNNER.is_file():
+ raise GlHostError(f"GL runner missing: {RUNNER}")
+ self.gpu = gpu
+ self.python = python or sys.executable
+ self.timeout_s = timeout_s
+ self.fps = fps
+ self.max_steps = max_steps
+
+ # ------------------------------------------------------------------ public
+ def render_fragment_shader(self, frag_src: str, out_dir: Path, *, width: int = 1280, height: int = 720,
+ times: Sequence[float] = DEFAULT_TIMES, buffer_a_src: str | None = None,
+ feedback: bool = False, extra_times: Sequence[float] = ()) -> GlResult:
+ job = {"mode": "shader", "frag_src": frag_src, "buffer_a_src": buffer_a_src, "feedback": bool(feedback),
+ "width": int(width), "height": int(height), "times": [float(t) for t in times],
+ "extra_times": [float(t) for t in extra_times]}
+ return self._run(job, out_dir)
+
+ def run_program(self, program_path: Path, out_dir: Path, *, width: int = 1280, height: int = 720,
+ times: Sequence[float] = DEFAULT_TIMES, extra_times: Sequence[float] = (),
+ cwd: Path | None = None) -> GlResult:
+ program_path = Path(program_path).resolve()
+ job = {"mode": "program", "program_path": str(program_path), "program_cwd": str(cwd or program_path.parent),
+ "width": int(width), "height": int(height), "times": [float(t) for t in times],
+ "extra_times": [float(t) for t in extra_times]}
+ return self._run(job, out_dir)
+
+ # ------------------------------------------------------------------ internals
+ def _run(self, job: dict[str, Any], out_dir: Path) -> GlResult:
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / RESULT_NAME).unlink(missing_ok=True)
+ for p in (out_dir / "frames").glob("*.png"):
+ p.unlink()
+ job.update({"out_dir": str(out_dir), "fps": self.fps, "max_steps": self.max_steps, "backend": "egl"})
+ job_path = out_dir / JOB_NAME
+ job_path.write_text(json.dumps(job))
+ last: GlResult | None = None
+ for use_gpu in gpu_preference(self.gpu):
+ res = self._run_once(job_path, out_dir, use_gpu=use_gpu, mode=str(job["mode"]))
+ if res.stage == "context" and not res.ok:
+ if use_gpu:
+ _gpu_state["ok"] = False
+ last = res
+ continue
+ if use_gpu and _gpu_state["ok"] is None:
+ _gpu_state["ok"] = True
+ return res
+ assert last is not None
+ raise GlHostError(f"no usable OpenGL context: {last.error_type}: {last.error_message[:300]}")
+
+ def _run_once(self, job_path: Path, out_dir: Path, *, use_gpu: bool, mode: str) -> GlResult:
+ env = _base_env(GPU_ENV if use_gpu else CPU_ENV)
+ t0 = time.time()
+ proc = run_subprocess([self.python, str(RUNNER), "--job", str(job_path)], cwd=out_dir, timeout_s=self.timeout_s, env=env)
+ result_path = out_dir / RESULT_NAME
+ base = dict(mode=mode, gpu=use_gpu, stdout_tail=proc.stdout[-3000:], stderr_tail=proc.stderr[-3000:],
+ duration_ms=proc.duration_ms or int((time.time() - t0) * 1000))
+ if proc.timed_out:
+ return GlResult(ok=False, stage="render", error_type="RenderTimeout", timed_out=True,
+ error_message=f"rendering exceeded {self.timeout_s:.0f}s — reduce loop counts / raymarch steps / resolution",
+ **base)
+ if not result_path.is_file():
+ if proc.returncode == EXIT_CONTEXT:
+ return GlResult(ok=False, stage="context", error_type="ContextError", error_message=proc.stderr[-800:], **base)
+ return GlResult(ok=False, stage="crash", error_type="RunnerCrash",
+ error_message=f"GL runner exited {proc.returncode} without a result (segfault / OOM?)", **base)
+ data = json.loads(result_path.read_text())
+ frames = [GlFrame.model_validate(f) for f in data.get("frames", [])]
+ res = GlResult(ok=bool(data.get("ok")), stage=str(data.get("stage", "")), error_type=str(data.get("error_type", "")),
+ error_message=str(data.get("error_message", "")), traceback=str(data.get("traceback", "")),
+ renderer=str(data.get("renderer", "")), feedback=bool(data.get("feedback", False)), frames=frames, **base)
+ if data.get("stdout"):
+ res.stdout_tail = (str(data["stdout"]) + "\n" + res.stdout_tail)[-3000:]
+ return res
+
+
+# --------------------------------------------------------------------------- derived artifacts
+def write_contact_sheet(frames: Sequence[GlFrame], out: Path, *, cols: int = 3, tile_w: int = 480) -> Path:
+ """Labelled grid of frames keeping their aspect ratio (``t=<s>`` under each tile)."""
+ import math
+
+ from PIL import Image, ImageDraw
+
+ from codeverse.spatial.sheet import LABEL_BG, LABEL_FG, LABEL_H, PAD, _font
+
+ frames = list(frames)
+ if not frames:
+ raise ValueError("write_contact_sheet: no frames")
+ first = Image.open(frames[0].path)
+ tile_h = max(1, round(tile_w * first.height / first.width))
+ cols = max(1, min(cols, len(frames)))
+ rows = math.ceil(len(frames) / cols)
+ cell_h = tile_h + LABEL_H
+ sheet = Image.new("RGB", (cols * (tile_w + PAD) + PAD, rows * (cell_h + PAD) + PAD), (250, 250, 250))
+ draw = ImageDraw.Draw(sheet)
+ font = _font(15)
+ for i, f in enumerate(frames):
+ x = PAD + (i % cols) * (tile_w + PAD)
+ y = PAD + (i // cols) * (cell_h + PAD)
+ im = Image.open(f.path).convert("RGB").resize((tile_w, tile_h), Image.LANCZOS)
+ sheet.paste(im, (x, y))
+ draw.rectangle([x, y + tile_h, x + tile_w, y + tile_h + LABEL_H], fill=LABEL_BG)
+ label = f"t={f.time:g}s"
+ tw = draw.textlength(label, font=font)
+ draw.text((x + (tile_w - tw) / 2, y + tile_h + 6), label, fill=LABEL_FG, font=font)
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ sheet.save(out)
+ return out
+
+
+def write_gif(frames: Sequence[GlFrame], out: Path, *, width: int = 480, fps: int = 6) -> Path | None:
+ """Animated GIF preview from ALL frames (judge + extra), resized to ``width``."""
+ from PIL import Image
+
+ ordered = sorted(frames, key=lambda f: f.time)
+ if len(ordered) < 2:
+ return None
+ ims = []
+ for f in ordered:
+ im = Image.open(f.path).convert("RGB")
+ h = max(1, round(im.height * width / im.width))
+ ims.append(im.resize((width, h), Image.BILINEAR).convert("P", palette=Image.ADAPTIVE, colors=128))
+ out.parent.mkdir(parents=True, exist_ok=True)
+ ims[0].save(out, save_all=True, append_images=ims[1:], duration=int(1000 / fps), loop=0, optimize=False)
+ return out
+
+
+def gif_times(duration_s: float, n: int = 12) -> list[float]:
+ """Evenly spaced preview times across one loop (excluding the end)."""
+ n = max(2, n)
+ d = max(0.5, float(duration_s))
+ return [round(i * d / n, 3) for i in range(n)]
diff --git a/harness/codeverse/spatial/joints_collide.py b/harness/codeverse/spatial/joints_collide.py
new file mode 100644
index 00000000..009dde53
--- /dev/null
+++ b/harness/codeverse/spatial/joints_collide.py
@@ -0,0 +1,181 @@
+"""Per-link collision bodies for the pose sweep (:mod:`joints_sweep`).
+
+FCL (``python-fcl``, a hard dependency) answers the boolean surface-collide and
+the exact separation distance on BVH models. Penetration *depth* is measured
+deterministically on the link's **watertight islands**: a surface sample of
+body A counts as inside body B when a fixed-direction parity ray test (forward
+and backward rays agree) places it inside one of B's islands, and its depth is
+the unsigned distance to that island's surface. This is independent of the
+mesh winding (agent meshes routinely come out inverted) and does not depend on
+``Trimesh.contains`` / signed normals on the merged link mesh, which is usually
+non-watertight (touching panels share vertices) and was re-cast with *random*
+rays. Islands that are not watertight are tested the same way but flagged
+``approx``. When FCL is missing the same deterministic inside test doubles as
+the collision predicate (``backend == "trimesh"``).
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import trimesh
+from trimesh.ray import ray_util
+
+try: # declared in pyproject; guarded so a broken wheel degrades to the trimesh path
+ import fcl as _fcl
+except Exception: # pragma: no cover - depends on the environment
+ _fcl = None
+
+_MAX_SAMPLE_POINTS = 1500
+#: fixed, non-axis-aligned ray direction for parity tests (never re-cast at random)
+_RAY_DIR = np.array([0.4395064455, 0.617598629942, 0.652231566745])
+
+
+def backend_name() -> str:
+ return "fcl" if _fcl is not None else "trimesh"
+
+
+def _sample_points(mesh: trimesh.Trimesh) -> np.ndarray:
+ pts = np.asarray(mesh.vertices)
+ if len(pts) > _MAX_SAMPLE_POINTS:
+ idx = np.linspace(0, len(pts) - 1, _MAX_SAMPLE_POINTS).astype(int)
+ pts = pts[idx]
+ n_surf = max(64, _MAX_SAMPLE_POINTS - len(pts))
+ surf, _ = trimesh.sample.sample_surface(mesh, n_surf, seed=0)
+ return np.vstack([pts, surf])
+
+
+def oriented_islands(mesh: trimesh.Trimesh) -> list[trimesh.Trimesh]:
+ """Connected components of ``mesh``; watertight ones get outward-facing normals
+ (inverted winding → ``invert()``), so volumes/booleans are meaningful."""
+ try:
+ islands = list(mesh.split(only_watertight=False))
+ except Exception:
+ islands = []
+ if not islands:
+ islands = [mesh.copy()]
+ for isl in islands:
+ if isl.is_watertight and float(isl.volume) < 0.0:
+ isl.invert()
+ return islands
+
+
+def _inside(island: trimesh.Trimesh, points: np.ndarray) -> np.ndarray:
+ """Deterministic parity containment (fixed ray direction, both directions must agree)."""
+ if len(points) == 0:
+ return np.zeros(0, dtype=bool)
+ return np.asarray(ray_util.contains_points(island.ray, points, check_direction=_RAY_DIR), dtype=bool)
+
+
+class LinkBody:
+ """Per-link collision state reused across poses (geometry in the LINK frame)."""
+
+ def __init__(self, name: str, mesh: trimesh.Trimesh):
+ self.name = name
+ self.mesh = mesh
+ self.local_points = _sample_points(mesh)
+ self.islands = oriented_islands(mesh)
+ self.watertight = all(bool(i.is_watertight) for i in self.islands)
+ self._island_pq = [trimesh.proximity.ProximityQuery(i) for i in self.islands]
+ self._pq = trimesh.proximity.ProximityQuery(mesh) # unsigned distances, LOCAL frame
+ self.obj = None
+ if _fcl is not None:
+ model = _fcl.BVHModel()
+ model.beginModel(len(mesh.vertices), len(mesh.faces))
+ model.addSubModel(np.asarray(mesh.vertices, dtype=float), np.asarray(mesh.faces, dtype=np.int64))
+ model.endModel()
+ self.obj = _fcl.CollisionObject(model, _fcl.Transform())
+ self.T = np.eye(4)
+ self.T_inv = np.eye(4)
+
+ def set_pose(self, T: np.ndarray) -> None:
+ self.T = T
+ self.T_inv = np.linalg.inv(T)
+ if self.obj is not None:
+ self.obj.setTransform(_fcl.Transform(np.ascontiguousarray(T[:3, :3]), np.ascontiguousarray(T[:3, 3])))
+
+ @property
+ def posed(self) -> trimesh.Trimesh:
+ m = trimesh.util.concatenate(self.islands) if len(self.islands) > 1 else self.islands[0].copy()
+ m.apply_transform(self.T)
+ return m
+
+ @property
+ def points(self) -> np.ndarray:
+ return trimesh.transform_points(self.local_points, self.T)
+
+ @property
+ def aabb(self) -> np.ndarray:
+ corners = trimesh.bounds.corners(self.mesh.bounds)
+ pts = trimesh.transform_points(corners, self.T)
+ return np.vstack([pts.min(axis=0), pts.max(axis=0)])
+
+ def surface_distance(self, points_world: np.ndarray) -> np.ndarray:
+ """Unsigned distance of world points to this body's surface."""
+ return self._pq.on_surface(trimesh.transform_points(points_world, self.T_inv))[1]
+
+ def depth_of(self, points_world: np.ndarray) -> float:
+ """Max distance-to-surface of the ``points_world`` that lie inside one of this body's islands."""
+ local = trimesh.transform_points(points_world, self.T_inv)
+ depth = 0.0
+ for island, pq in zip(self.islands, self._island_pq, strict=True):
+ inside = _inside(island, local)
+ if inside.any():
+ depth = max(depth, float(pq.on_surface(local[inside])[1].max()))
+ return depth
+
+ def any_inside(self, points_world: np.ndarray) -> bool:
+ local = trimesh.transform_points(points_world, self.T_inv)
+ return any(bool(_inside(i, local).any()) for i in self.islands)
+
+
+def aabb_gap(a: np.ndarray, b: np.ndarray) -> float:
+ """Largest per-axis separation of two AABBs (≤ 0 when they intersect)."""
+ gaps = np.maximum(a[0] - b[1], b[0] - a[1])
+ return float(gaps.max())
+
+
+def collide(a: LinkBody, b: LinkBody) -> bool:
+ """Surfaces intersect (FCL) — or, without FCL, a surface sample of one lies inside the other."""
+ if a.obj is not None and b.obj is not None:
+ req = _fcl.CollisionRequest(num_max_contacts=1, enable_contact=False)
+ res = _fcl.CollisionResult()
+ return int(_fcl.collide(a.obj, b.obj, req, res)) > 0
+ return contained(a, b, n=None)
+
+
+def contained(a: LinkBody, b: LinkBody, n: int | None = 24) -> bool:
+ """True when surface samples of one body lie inside the other (FCL's surface-only
+ collide misses a part fully swallowed by another). ``n`` samples per side (None = all)."""
+ if n is None:
+ pa, pb = a.points, b.points
+ else:
+ pa = a.points[:: max(1, len(a.points) // n)][:n]
+ pb = b.points[:: max(1, len(b.points) // n)][:n]
+ return b.any_inside(pa) or a.any_inside(pb)
+
+
+def distance(a: LinkBody, b: LinkBody) -> float:
+ """Minimum surface separation (0 when touching/overlapping)."""
+ if a.obj is not None and b.obj is not None:
+ req = _fcl.DistanceRequest()
+ res = _fcl.DistanceResult()
+ return max(0.0, float(_fcl.distance(a.obj, b.obj, req, res)))
+ d = min(float(b.surface_distance(a.points).min()), float(a.surface_distance(b.points).min()))
+ return max(0.0, d)
+
+
+def penetration(a: LinkBody, b: LinkBody) -> tuple[float, bool]:
+ """Max penetration depth (m) of A's surface into B or B's into A; ``approx``
+ when an island is not watertight (the inside test is then heuristic)."""
+ depth = max(b.depth_of(a.points), a.depth_of(b.points))
+ return depth, not (a.watertight and b.watertight)
+
+
+def intersection_volume(a: LinkBody, b: LinkBody) -> float | None:
+ if not (a.watertight and b.watertight):
+ return None
+ try:
+ inter = trimesh.boolean.intersection([a.posed, b.posed], engine="manifold")
+ return float(abs(inter.volume)) if isinstance(inter, trimesh.Trimesh) and not inter.is_empty else 0.0
+ except Exception:
+ return None
diff --git a/harness/codeverse/spatial/joints_export.py b/harness/codeverse/spatial/joints_export.py
index 2b013cb5..9b17d74f 100644
--- a/harness/codeverse/spatial/joints_export.py
+++ b/harness/codeverse/spatial/joints_export.py
@@ -32,6 +32,8 @@ ARTICULATION_SHEET_NAME = "articulation_sheet.png"
#: URDF (Z-up, -Y front) → glTF (Y-up, +Z front): (x, y, z) → (x, z, -y)
ZUP_TO_YUP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], dtype=float)
YUP_TO_ZUP = ZUP_TO_YUP.T.copy()
+#: scene-graph base frame of the exported GLB (not a glTF node; must not collide with a link name)
+SCENE_BASE_FRAME = "__scene__"
Renderer = Callable[..., RenderSet]
@@ -45,12 +47,23 @@ def joint_extras(j: Joint) -> dict[str, Any]:
}
+def robot_node_name(robot: Robot) -> str:
+ """Name of the ``<robot>`` root node (carries the Z-up → Y-up rotation). Scene-graph
+ node names must be unique, so a robot named like one of its links (``<robot
+ name="body">`` with a link ``body``) gets a ``__root`` suffix instead of silently
+ aliasing the link node — which would drop the rotation and the link's placement."""
+ name = robot.name or "robot"
+ while name in robot.links or name == SCENE_BASE_FRAME:
+ name += "__root"
+ return name
+
+
def robot_scene(robot: Robot, pose: dict[str, float] | None = None, *, joint_extras_on: bool = True) -> trimesh.Scene:
"""Build the trimesh.Scene (hierarchical, Y-up) for ``robot`` at ``pose``."""
pose = pose or {}
T = fk(robot, pose) # validates joint names
- scene = trimesh.Scene()
- robot_node = robot.name or "robot"
+ scene = trimesh.Scene(base_frame=SCENE_BASE_FRAME) # never a link name (a link 'world' would close a cycle)
+ robot_node = robot_node_name(robot)
meta = {"links": robot.link_order(), "frame": "y_up_pos_z_front", "pose": dict(pose), "units": "meters"}
if joint_extras_on:
meta["joints"] = [joint_extras(j) for j in robot.joints.values()]
diff --git a/harness/codeverse/spatial/joints_model.py b/harness/codeverse/spatial/joints_model.py
index 93a8274a..bd1d32d2 100644
--- a/harness/codeverse/spatial/joints_model.py
+++ b/harness/codeverse/spatial/joints_model.py
@@ -26,6 +26,10 @@ import trimesh
MOVABLE_TYPES = ("revolute", "prismatic", "continuous")
JOINT_TYPES = MOVABLE_TYPES + ("fixed",)
+#: link names that cannot become GLB nodes: glTF readers (trimesh) use ``world`` as the
+#: scene-graph base frame and stomp on a node of that name (the export then loses its
+#: frame / cycles). ``load_urdf`` rejects them; ``lint`` reports them first.
+RESERVED_LINK_NAMES = frozenset({"world"})
class UrdfError(ValueError):
@@ -325,6 +329,8 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo
link = _link_from_xml(el, urdf_path.parent, meshes, load_meshes=load_meshes)
if link.name in links:
raise UrdfError(f"duplicate link name {link.name!r}")
+ if link.name in RESERVED_LINK_NAMES:
+ raise UrdfError(f"link name {link.name!r} is reserved by the GLB scene graph; rename it (e.g. 'base')")
links[link.name] = link
joints = {}
for el in root_el.findall("joint"):
diff --git a/harness/codeverse/spatial/joints_sweep.py b/harness/codeverse/spatial/joints_sweep.py
index b31ef262..87890ef6 100644
--- a/harness/codeverse/spatial/joints_sweep.py
+++ b/harness/codeverse/spatial/joints_sweep.py
@@ -1,8 +1,7 @@
"""Pose sweep QC on a :class:`Robot`: overlaps, contacts, floating links, motion
-direction. FCL (``python-fcl``) does the boolean collide / distance queries on
-BVH models; penetration depth is measured with trimesh signed distances of
-surface samples (FCL's mesh-mesh contact depths are per-triangle artefacts).
-Falls back to trimesh proximity when FCL is unavailable.
+direction. Collision bodies live in :mod:`joints_collide` (FCL for the boolean
+collide / distance queries; deterministic per-island containment for the
+penetration depth — FCL's mesh-mesh contact depths are per-triangle artefacts).
"""
from __future__ import annotations
@@ -16,16 +15,10 @@ from pydantic import BaseModel, Field
from codeverse.contracts.artifacts import GateFinding, Severity
from codeverse.conventions import CONTACT_GAP_M
+from codeverse.spatial import joints_collide as collide
from codeverse.spatial.joints_model import Robot, UrdfError, fk
from codeverse.spatial.joints_poses import pose_label
-try: # optional accelerator
- import fcl as _fcl
-except Exception: # pragma: no cover - depends on the environment
- _fcl = None
-
-_MAX_SAMPLE_POINTS = 1500
-
# ------------------------------------------------------------------ report types
class Overlap(BaseModel):
@@ -34,6 +27,8 @@ class Overlap(BaseModel):
depth_m: float = Field(description="max distance of a penetrating surface point from the other surface")
volume_m3: float | None = None
approx: bool = Field(default=False, description="depth estimated on non-watertight meshes")
+ rigid: bool = Field(default=False, description="only fixed joints between the links: the overlap is structural "
+ "(a weld), identical in every pose — judged with the rest policy")
class FloatingLink(BaseModel):
@@ -84,128 +79,6 @@ class MotionCheck(BaseModel):
message: str
-# ------------------------------------------------------------------ collision backends
-def _sample_points(mesh: trimesh.Trimesh) -> np.ndarray:
- pts = np.asarray(mesh.vertices)
- if len(pts) > _MAX_SAMPLE_POINTS:
- idx = np.linspace(0, len(pts) - 1, _MAX_SAMPLE_POINTS).astype(int)
- pts = pts[idx]
- n_surf = max(64, _MAX_SAMPLE_POINTS - len(pts))
- surf, _ = trimesh.sample.sample_surface(mesh, n_surf, seed=0)
- return np.vstack([pts, surf])
-
-
-class _LinkBody:
- """Per-link collision state reused across poses."""
-
- def __init__(self, name: str, mesh: trimesh.Trimesh):
- self.name = name
- self.mesh = mesh
- self.local_points = _sample_points(mesh)
- self.watertight = bool(mesh.is_watertight)
- self.obj = None
- if _fcl is not None:
- model = _fcl.BVHModel()
- model.beginModel(len(mesh.vertices), len(mesh.faces))
- model.addSubModel(np.asarray(mesh.vertices, dtype=float), np.asarray(mesh.faces, dtype=np.int64))
- model.endModel()
- self.obj = _fcl.CollisionObject(model, _fcl.Transform())
- self.T = np.eye(4)
- self.T_inv = np.eye(4)
- self._pq = trimesh.proximity.ProximityQuery(mesh) # built once, queried in the LOCAL frame
-
- def set_pose(self, T: np.ndarray) -> None:
- self.T = T
- self.T_inv = np.linalg.inv(T)
- if self.obj is not None:
- self.obj.setTransform(_fcl.Transform(np.ascontiguousarray(T[:3, :3]), np.ascontiguousarray(T[:3, 3])))
-
- @property
- def posed(self) -> trimesh.Trimesh:
- m = self.mesh.copy()
- m.apply_transform(self.T)
- return m
-
- def signed_distance(self, points_world: np.ndarray) -> np.ndarray:
- """trimesh convention: > 0 inside this body."""
- return self._pq.signed_distance(trimesh.transform_points(points_world, self.T_inv))
-
- def contains(self, points_world: np.ndarray) -> np.ndarray:
- return self.mesh.contains(trimesh.transform_points(points_world, self.T_inv))
-
- @property
- def points(self) -> np.ndarray:
- return trimesh.transform_points(self.local_points, self.T)
-
- @property
- def aabb(self) -> np.ndarray:
- corners = trimesh.bounds.corners(self.mesh.bounds)
- pts = trimesh.transform_points(corners, self.T)
- return np.vstack([pts.min(axis=0), pts.max(axis=0)])
-
-
-def _aabb_gap(a: np.ndarray, b: np.ndarray) -> float:
- """Largest per-axis separation of two AABBs (≤ 0 when they intersect)."""
- gaps = np.maximum(a[0] - b[1], b[0] - a[1])
- return float(gaps.max())
-
-
-def _collide(a: _LinkBody, b: _LinkBody) -> bool:
- if a.obj is not None and b.obj is not None:
- req = _fcl.CollisionRequest(num_max_contacts=1, enable_contact=False)
- res = _fcl.CollisionResult()
- return int(_fcl.collide(a.obj, b.obj, req, res)) > 0
- # trimesh fallback: any surface sample of one inside the other, or AABB overlap + near-zero distance
- return _penetration(a, b)[0] > 0.0
-
-
-def _contained(a: _LinkBody, b: _LinkBody, n: int = 24) -> bool:
- """True when a few surface samples of one body lie inside the other (FCL's
- surface-only collide misses a part fully swallowed by another)."""
- pa = a.points[:: max(1, len(a.points) // n)][:n]
- pb = b.points[:: max(1, len(b.points) // n)][:n]
- return bool(b.contains(pa).any() or a.contains(pb).any())
-
-
-def _distance(a: _LinkBody, b: _LinkBody) -> float:
- if a.obj is not None and b.obj is not None:
- req = _fcl.DistanceRequest()
- res = _fcl.DistanceResult()
- return max(0.0, float(_fcl.distance(a.obj, b.obj, req, res)))
- d_ab = b.signed_distance(a.points)
- d_ba = a.signed_distance(b.points)
- return max(0.0, float(min(-d_ab.max(), -d_ba.max())))
-
-
-def _depth_into(points_world: np.ndarray, other: _LinkBody, cap: int = 400) -> float:
- """Max distance-to-surface of the ``points_world`` that lie INSIDE ``other``.
- contains() first (cheap) so exact distances run only on the contained few."""
- inside = other.contains(points_world)
- if not inside.any():
- return 0.0
- pts = points_world[inside]
- if len(pts) > cap:
- pts = pts[np.linspace(0, len(pts) - 1, cap).astype(int)]
- return max(0.0, float(other.signed_distance(pts).max()))
-
-
-def _penetration(a: _LinkBody, b: _LinkBody) -> tuple[float, bool]:
- """Max penetration depth (m) of A's surface into B or B's into A; ``approx``
- when a mesh is not watertight (inside test is then heuristic)."""
- depth = max(_depth_into(a.points, b), _depth_into(b.points, a))
- return depth, not (a.watertight and b.watertight)
-
-
-def _intersection_volume(a: _LinkBody, b: _LinkBody) -> float | None:
- if not (a.watertight and b.watertight):
- return None
- try:
- inter = trimesh.boolean.intersection([a.posed, b.posed], engine="manifold")
- return float(abs(inter.volume)) if isinstance(inter, trimesh.Trimesh) and not inter.is_empty else 0.0
- except Exception:
- return None
-
-
# ------------------------------------------------------------------ sweep
def _components(links: list[str], edges: set[tuple[str, str]]) -> dict[str, int]:
parent = {n: n for n in links}
@@ -244,12 +117,17 @@ def sweep_collisions(
names = robot.meshed_links()
if not names:
raise UrdfError("sweep_collisions: robot has no link meshes")
- bodies = {n: _LinkBody(n, robot.links[n].mesh) for n in names} # type: ignore[arg-type]
+ bodies = {n: collide.LinkBody(n, robot.links[n].mesh) for n in names} # type: ignore[arg-type]
allowed = {tuple(sorted(p)) for p in allow_pairs}
per_pose: list[PoseReport] = []
- islands = {n: max(1, len(robot.links[n].mesh.split(only_watertight=False))) for n in names} # type: ignore[union-attr]
-
- for q in poses:
+ islands = {n: len(bodies[n].islands) for n in names}
+ # links joined only by fixed joints never move relative to each other: their overlap is
+ # structural and is measured once (at rest when the sweep has a rest pose, else first pose)
+ rigid_group = _components(list(robot.links), {(j.parent, j.child) for j in robot.joints.values() if j.type == "fixed"})
+ labels = [pose_label(robot, q) for q in poses]
+ rigid_pose = labels.index("rest") if "rest" in labels else 0
+
+ for idx, q in enumerate(poses):
T = fk(robot, q)
for n, body in bodies.items():
body.set_pose(T[n])
@@ -259,20 +137,24 @@ def sweep_collisions(
for i, a in enumerate(names):
for b in names[i + 1 :]:
ba, bb = bodies[a], bodies[b]
- gap_aabb = _aabb_gap(ba.aabb, bb.aabb)
+ gap_aabb = collide.aabb_gap(ba.aabb, bb.aabb)
if gap_aabb > max(contact_gap_m, hinge_clearance_m * 3):
nearest[a][b] = nearest[b][a] = gap_aabb # lower bound is enough this far apart
continue
- if _collide(ba, bb) or (gap_aabb <= 0.0 and _contained(ba, bb)):
- depth, approx = _penetration(ba, bb)
+ rigid = rigid_group[a] == rigid_group[b]
+ if collide.collide(ba, bb) or (gap_aabb <= 0.0 and collide.contained(ba, bb)):
dist = 0.0
- if depth > tol_m and tuple(sorted((a, b))) not in allowed:
- overlaps.append(
- Overlap(a=a, b=b, depth_m=round(depth, 6), approx=approx,
- volume_m3=_intersection_volume(ba, bb) if volumes else None)
- )
+ if rigid and idx != rigid_pose:
+ pass # structural overlap, already measured in pose ``rigid_pose``
+ elif tuple(sorted((a, b))) not in allowed:
+ depth, approx = collide.penetration(ba, bb)
+ if round(depth, 4) > tol_m: # 0.1 mm: float32 mesh coordinates carry no finer meaning
+ overlaps.append(
+ Overlap(a=a, b=b, depth_m=round(depth, 6), approx=approx, rigid=rigid,
+ volume_m3=collide.intersection_volume(ba, bb) if volumes else None)
+ )
else:
- dist = _distance(ba, bb)
+ dist = collide.distance(ba, bb)
nearest[a][b] = nearest[b][a] = dist
if dist <= contact_gap_m:
touching.add((a, b))
@@ -286,7 +168,7 @@ def sweep_collisions(
if j.type == "fixed":
thr = contact_gap_m
elif j.type == "prismatic":
- if _aabb_gap(bodies[n].aabb, bodies[j.parent].aabb) <= 0.0:
+ if collide.aabb_gap(bodies[n].aabb, bodies[j.parent].aabb) <= 0.0:
continue # inserted into the parent's envelope (drawer in cavity)
thr = hinge_clearance_m
else: # revolute / continuous / planar / floating
@@ -294,7 +176,7 @@ def sweep_collisions(
if d > thr:
floating.append(FloatingLink(link=n, nearest=j.parent, joint_type=j.type,
gap_m=round(d, 6) if math.isfinite(d) else math.inf))
- per_pose.append(PoseReport(label=pose_label(robot, q), q=dict(q), overlaps=overlaps, floating=floating,
+ per_pose.append(PoseReport(label=labels[idx], q=dict(q), overlaps=overlaps, floating=floating,
n_contacts=len(touching)))
summary = _summarise(per_pose, len(names), islands)
@@ -302,14 +184,13 @@ def sweep_collisions(
def _summarise(per_pose: list[PoseReport], n_links: int, islands: dict[str, int]) -> SweepSummary:
- s = SweepSummary(n_poses=len(per_pose), n_links=n_links, link_islands=islands,
- backend="fcl" if _fcl is not None else "trimesh")
+ s = SweepSummary(n_poses=len(per_pose), n_links=n_links, link_islands=islands, backend=collide.backend_name())
floating_any: set[str] = set()
for pr in per_pose:
for o in pr.overlaps:
if o.depth_m > s.max_penetration_m:
s.max_penetration_m, s.worst_pose, s.worst_pair = o.depth_m, pr.label, (o.a, o.b)
- if pr.label == "rest":
+ if pr.label == "rest" or o.rigid: # structural overlaps count as rest penetration
s.rest_max_penetration_m = max(s.rest_max_penetration_m, o.depth_m)
if pr.overlaps:
s.overlapping_poses.append(pr.label)
@@ -328,13 +209,14 @@ def sweep_findings(report: SweepReport, *, rest_max_m: float = 0.005, hinge_clea
out: list[GateFinding] = []
for pr in report.per_pose:
for o in pr.overlaps:
- at_rest = pr.label == "rest"
+ at_rest = pr.label == "rest" or o.rigid # a weld between rigidly joined links is a rest-pose property
sev = Severity.ERROR if (not at_rest or o.depth_m > rest_max_m) else Severity.WARN
out.append(GateFinding(
gate=gate, severity=sev, target=f"{o.a}|{o.b}",
message=f"links '{o.a}' and '{o.b}' overlap by {o.depth_m*1000:.1f} mm at pose {pr.label}"
+ (f" (pose q={pr.q})" if pr.q else "") + (" [approx: non-watertight mesh]" if o.approx else ""),
- fix_hint=(f"At q=0 the meshes in model.py interpenetrate: shrink/move one of '{o.a}', '{o.b}' so they touch (≤ {report.tol_m*1000:.0f} mm) instead of overlapping."
+ fix_hint=(f"The meshes in model.py interpenetrate{'' if pr.label == 'rest' else ' (rigidly joined links: same in every pose)'}: "
+ f"shrink/move one of '{o.a}', '{o.b}' so they touch (≤ {report.tol_m*1000:.0f} mm) instead of overlapping."
if at_rest else
f"Moving joint(s) {sorted(pr.q)} drives '{o.a}' into '{o.b}'. Either move the pivot/axis in robot.urdf so the part swings/slides clear, shrink the limits, or carve the clearance in model.py."),
data={"kind": "penetration", "pose": pr.q, "depth_m": o.depth_m, "volume_m3": o.volume_m3},
diff --git a/harness/codeverse/spatial/mcp_server.py b/harness/codeverse/spatial/mcp_server.py
index 6ccae541..3b7f942e 100644
--- a/harness/codeverse/spatial/mcp_server.py
+++ b/harness/codeverse/spatial/mcp_server.py
@@ -29,7 +29,7 @@ from codeverse.workspace import Workspace
MAX_IMAGES = 4
MAX_IMAGE_SIDE = 1024
MAX_NUMBERS_CHARS = 1200
-SERVER_NAME = "c3v"
+SERVER_NAME = "3dcv"
def build_context(workspace: Path, *, track: str = "", language: str = "", round_index: int = 0) -> ToolContext:
diff --git a/harness/codeverse/spatial/measure.py b/harness/codeverse/spatial/measure.py
index 236ee9ed..40a38352 100644
--- a/harness/codeverse/spatial/measure.py
+++ b/harness/codeverse/spatial/measure.py
@@ -52,11 +52,15 @@ def load_scene(glb: Path | str) -> trimesh.Scene:
def _subtree_nodes(scene: trimesh.Scene, root: str) -> list[str]:
- """All nodes under ``root`` (inclusive), depth first."""
+ """All nodes under ``root`` (inclusive), depth first; cycle-safe (a malformed
+ graph, e.g. a node named like the base frame, must not hang the gate)."""
children = scene.graph.transforms.children
- out, stack = [], [root]
+ out, stack, seen = [], [root], set()
while stack:
n = stack.pop()
+ if n in seen:
+ continue
+ seen.add(n)
out.append(n)
stack.extend(children.get(n, ()))
return out
diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.py
index 65d90c22..d9e5fbc1 100644
--- a/harness/codeverse/spatial/node.py
+++ b/harness/codeverse/spatial/node.py
@@ -130,7 +130,7 @@ def run_node(
env = dict(os.environ)
env["NODE_PATH"] = str(node_modules_dir())
- env.setdefault("C3V_CACHE_DIR", str(settings.cache_dir))
+ env.setdefault("CV3D_CACHE_DIR", str(settings.cache_dir))
env.setdefault("NODE_OPTIONS", "")
env["NODE_NO_WARNINGS"] = "1"
if env_extra:
diff --git a/harness/codeverse/spatial/probes.py b/harness/codeverse/spatial/probes.py
index b6ac0260..2b02baf8 100644
--- a/harness/codeverse/spatial/probes.py
+++ b/harness/codeverse/spatial/probes.py
@@ -42,11 +42,16 @@ _BOOT_HINTS = {
class SceneProbeResult(BaseModel):
"""``probe_scene`` result: unpacks as ``gate, census = probe_scene(ws)`` and also
- dumps to a dict with ``errors`` so generic tool adapters can read it."""
+ dumps to a dict generic tool adapters can read. Tool semantics: ``ok`` /
+ ``errors`` describe whether the PROBE TOOL ran (``is_error`` in MCP terms) —
+ a gate that fails on agent-fixable findings keeps ``ok=True`` with the
+ finding lines under ``findings``; ``errors`` holds only harness/driver
+ failures. Gate truth stays on ``gate.passed``."""
gate: GateReport
census: dict[str, Any] = Field(default_factory=dict)
- errors: list[str] = Field(default_factory=list)
+ errors: list[str] = Field(default_factory=list, description="harness/driver failures only (tool could not run)")
+ findings: list[str] = Field(default_factory=list, description="agent-fixable gate findings, one line each")
ok: bool = False
def __iter__(self): # type: ignore[override]
@@ -54,9 +59,11 @@ class SceneProbeResult(BaseModel):
yield self.census
-def _result(gate: GateReport, census: dict[str, Any]) -> SceneProbeResult:
- return SceneProbeResult(gate=gate, census=census, ok=gate.passed,
- errors=[f"{f.target or ''}: {f.message}" for f in gate.errors])
+def _result(gate: GateReport, census: dict[str, Any], *, driver_failure: str = "") -> SceneProbeResult:
+ lines = [f"[{f.severity.value}] {f.target or ''}: {f.message}" for f in gate.findings
+ if f.severity != Severity.INFO and not f.data.get("harness_failure")]
+ return SceneProbeResult(gate=gate, census=census, ok=not driver_failure,
+ errors=[driver_failure] if driver_failure else [], findings=lines)
def _f(gate: str, sev: Severity, msg: str, *, target: str | None = None, hint: str = "", **data: Any) -> GateFinding:
@@ -77,8 +84,9 @@ def probe_scene(ws: Workspace, *, timeout_s: float = 60.0, write_census: bool =
)
except SceneRenderError as e:
findings.append(_f(gate, Severity.ERROR, f"scene probe could not run: {e}", target="src/scene.js",
- hint="this is a harness/driver failure, not your code; retry or report"))
- return _result(GateReport(gate=gate, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000)), census)
+ hint="this is a harness/driver failure, not your code; retry or report", harness_failure=True))
+ return _result(GateReport(gate=gate, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000)), census,
+ driver_failure=f"scene probe could not run: {e}"[:800])
s = res.summary
boot = s.get("boot") or {}
if not boot.get("ok"):
@@ -100,6 +108,8 @@ def probe_scene(ws: Workspace, *, timeout_s: float = 60.0, write_census: bool =
for e in s.get("console_errors", []):
if e.startswith("boot["):
continue
+ if e.startswith("update(t=") and s.get("update_ok") is False:
+ continue # already reported as the update(t, dt) finding above
findings.append(_f(gate, Severity.ERROR, f"console: {e}"[:1000], target="src/scene.js",
hint="the browser console must stay clean: fix the quoted error"))
for w in s.get("console_warnings", []):
@@ -167,7 +177,7 @@ def check_shaders(ws: Workspace, *, module: str | None = None, timeout_s: float
res = run_scene_script("check_shaders.mjs", args, timeout_s=timeout_s + 20)
except SceneRenderError as e:
findings.append(_f(gate, Severity.ERROR, f"shader preflight could not run: {e}", target="src/scene.js",
- hint="harness/driver failure; retry or report"))
+ hint="harness/driver failure; retry or report", harness_failure=True))
return GateReport(gate=gate, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000))
rep = res.summary
for e in rep.get("errors", []):
diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.py
index 239328a8..36c25df3 100644
--- a/harness/codeverse/spatial/render_scene.py
+++ b/harness/codeverse/spatial/render_scene.py
@@ -1,10 +1,14 @@
"""Render a ``scene_threejs`` workspace through the node host (headless GPU Chrome).
``render_scene(ws, out_dir, ...)`` drives ``runtime_js/render_scene.mjs``:
-authored cameras + an overview orbit rig (``conventions.SCENE_VIEWS``) at one
-or more animation times, deterministic instruments (console/shader errors,
-fps, census, camera checks) and a labelled contact sheet. Returns a
-``RenderSet``; the full instrument payload is left at ``out_dir/metrics.json``.
+authored cameras + an overview orbit rig (``conventions.SCENE_VIEWS``, fitted
+to the scene CONTENT, guarded by the plan bounds) at one or more animation
+times, deterministic instruments (console/shader errors, fps, census, camera
+checks incl. luminance + content coverage) and a labelled contact sheet built
+from the JUDGE subset of views. Returns a ``RenderSet`` with every view; the
+full instrument payload is left at ``out_dir/metrics.json`` (``metrics_path_for``
+finds it again from a RenderSet) and ``views.json`` marks ``judge: true`` on the
+views ``select_judge_views`` keeps.
"""
from __future__ import annotations
@@ -22,10 +26,13 @@ from typing import Any
from codeverse.config import get_settings
from codeverse.contracts.artifacts import RenderSet, RenderView
-from codeverse.contracts.plan import CameraPlan
+from codeverse.contracts.plan import BBox, CameraPlan
from codeverse.conventions import SCENE_VIEWS, ViewPreset
from codeverse.workspace import Workspace
+#: views the judge sees (contact sheet + individual images are built from these)
+JUDGE_MAX_VIEWS = 10
+
class SceneRenderError(RuntimeError):
"""The node driver could not run (missing node/deps, timeout, crash)."""
@@ -60,8 +67,8 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
raise SceneRenderError(f"missing node driver {path}")
env_extra: dict[str, str] = {}
gpu = get_settings().render.gpu
- if gpu and "C3V_RENDER_GPU" not in os.environ:
- env_extra["C3V_RENDER_GPU"] = gpu
+ if gpu and "CV3D_RENDER_GPU" not in os.environ:
+ env_extra["CV3D_RENDER_GPU"] = gpu
try:
from codeverse.spatial.node import NodeError, run_node
except ImportError: # pragma: no cover - C1 not present
@@ -124,6 +131,22 @@ def _views_json(views: Sequence[ViewPreset]) -> str:
return json.dumps([{"name": v.name, "azimuth": v.azimuth_deg, "elevation": v.elevation_deg} for v in views])
+def _bounds_json(bounds: BBox) -> str:
+ return json.dumps({"min": list(bounds.min), "max": list(bounds.max)})
+
+
+def plan_bounds(ws: Workspace) -> BBox | None:
+ """Scene bounds from the workspace's ``plan.json`` (None when absent/invalid)."""
+ p = ws.plan_path
+ if not p.is_file():
+ return None
+ try:
+ raw = json.loads(p.read_text()).get("bounds")
+ return BBox.model_validate(raw) if raw else None
+ except (OSError, ValueError):
+ return None
+
+
def _contact_sheet(images: list[tuple[str, Path]], out: Path, cols: int, tile: int) -> Path | None:
"""Use ``codeverse.spatial.sheet.contact_sheet`` when present, else a local PIL grid."""
if not images:
@@ -173,16 +196,23 @@ def render_scene(
fps_seconds: float = 2.0,
counterfactual: bool = False,
timeout_s: float | None = None,
+ bounds: BBox | None = None,
+ sheet_max_views: int = JUDGE_MAX_VIEWS,
) -> RenderSet:
"""Render authored (+ orbit) views at ``times``; returns a RenderSet.
- ``cameras=None`` uses the cameras authored in ``createScene()``. A scene
- that fails to boot yields an empty RenderSet whose ``console_errors`` say
- why (the build gate normally catches that earlier); a driver failure raises
- ``SceneRenderError``.
+ ``cameras=None`` uses the cameras authored in ``createScene()``. ``bounds``
+ (default: the workspace plan's bounds) guards the orbit framing against
+ scatter that sprawls past the plan. The contact sheet holds at most
+ ``sheet_max_views`` tiles (the ``select_judge_views`` subset; 0 = all). A
+ scene that fails to boot yields an empty RenderSet whose ``console_errors``
+ say why (the build gate normally catches that earlier); a driver failure
+ raises ``SceneRenderError``.
"""
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
+ for stale in ("metrics.json", "views.json"):
+ (out_dir / stale).unlink(missing_ok=True) # never read a previous run's instruments
settings = get_settings()
args: list[str] = [
"--ws", str(ws.root), "--out", str(out_dir),
@@ -194,9 +224,22 @@ def render_scene(
]
if counterfactual:
args.append("--counterfactual")
+ bounds = bounds or plan_bounds(ws)
+ if bounds is not None:
+ args += ["--bounds", _bounds_json(bounds)]
tmo = timeout_s or settings.limits.render_timeout_s
args += ["--timeout-ms", str(int(tmo * 1000))]
- res = run_scene_script("render_scene.mjs", args, timeout_s=tmo + 30)
+ driver_error = ""
+ try:
+ res = run_scene_script("render_scene.mjs", args, timeout_s=tmo + 30)
+ except SceneRenderError as e:
+ # The driver died mid-run but this invocation already wrote instruments:
+ # a scene-side failure the round loop must see as a gate finding, not a
+ # harness crash. No metrics at all = a genuine driver problem: re-raise.
+ if not (out_dir / "metrics.json").is_file():
+ raise
+ driver_error = str(e).splitlines()[0][:500]
+ res = NodeResult(returncode=2, stdout="", stderr="", summary={"error": driver_error}, duration_ms=0)
metrics = _read_json(out_dir / "metrics.json")
views: list[RenderView] = []
for v in metrics.get("views", []):
@@ -205,22 +248,63 @@ def render_scene(
camera_position=tuple(v["position"]), look_at=tuple(v["lookAt"]), fov=v.get("fov"),
time_s=v.get("time_s"),
))
- sheet_path = None
- if sheet and views:
- labelled = [(f"{v.name} t={v.time_s:g}", Path(v.path)) for v in views if "_nocustom" not in v.name]
- sheet_path = _contact_sheet(labelled, out_dir / "sheet.png", settings.render.sheet_cols, settings.render.sheet_tile)
fps = (metrics.get("fps") or {}).get("fps")
errors = list(metrics.get("console_errors", []))
for e in metrics.get("shader_errors", []):
errors.append(f"shader[{e.get('stage')}]: {e.get('message')} — {e.get('source_line', '')}".strip())
+ if driver_error and driver_error not in errors:
+ errors.append(driver_error)
if not metrics and res.summary.get("error"):
errors.append(str(res.summary["error"]))
- return RenderSet(
- views=views, contact_sheet=str(sheet_path) if sheet_path else None,
- renderer=str(metrics.get("renderer") or res.summary.get("renderer") or ""),
- duration_ms=res.duration_ms, console_errors=errors,
- fps=float(fps) if fps is not None else None,
+ rs = RenderSet(
+ views=views, renderer=str(metrics.get("renderer") or res.summary.get("renderer") or ""),
+ duration_ms=res.duration_ms, console_errors=errors, fps=float(fps) if fps is not None else None,
)
+ judge_names = {(v.name, v.time_s) for v in select_judge_views(rs, max_n=sheet_max_views or len(views), orbit_names=[v.name for v in orbit_views]).views}
+ _mark_judge_views(out_dir / "views.json", judge_names)
+ if sheet and views:
+ labelled = [(f"{v.name} t={v.time_s:g}", Path(v.path)) for v in views if (v.name, v.time_s) in judge_names]
+ sheet_path = _contact_sheet(labelled, out_dir / "sheet.png", settings.render.sheet_cols, settings.render.sheet_tile)
+ rs.contact_sheet = str(sheet_path) if sheet_path else None
+ return rs
+
+
+def select_judge_views(rs: RenderSet, max_n: int = JUDGE_MAX_VIEWS, *, orbit_names: Sequence[str] | None = None) -> RenderSet:
+ """Copy of ``rs`` with the views a judge should see (≤ ``max_n``), in priority order:
+ authored cameras at the first time · the first two overview orbit views at that time
+ · the first two authored cameras at the last time · remaining orbit / authored /
+ other views. Counterfactual ``*_nocustom`` views are never chosen. Tracks call
+ this before judging; the full set stays on disk."""
+ orbit = set(orbit_names if orbit_names is not None else [v.name for v in SCENE_VIEWS])
+ views = [v for v in rs.views if "_nocustom" not in v.name]
+ if not views or max_n <= 0:
+ return rs.model_copy(update={"views": views[:max(max_n, 0)]})
+ times = sorted({v.time_s if v.time_s is not None else 0.0 for v in views})
+ t0, t_last = times[0], times[-1]
+ authored = [v for v in views if v.name not in orbit]
+ overview = [v for v in views if v.name in orbit and v.name.startswith("overview")]
+ at = lambda vs, t: [v for v in vs if (v.time_s if v.time_s is not None else 0.0) == t] # noqa: E731
+ first_two = [v.name for v in at(authored, t0)[:2]]
+ ordered: list[RenderView] = [*at(authored, t0), *at(overview, t0)[:2]]
+ if t_last != t0:
+ ordered += [v for v in at(authored, t_last) if v.name in first_two]
+ ordered += [v for v in views if v not in ordered]
+ chosen = ordered[:max_n]
+ keep = {id(v) for v in chosen}
+ return rs.model_copy(update={"views": [v for v in views if id(v) in keep]}) # disk order, judge subset
+
+
+def _mark_judge_views(views_json: Path, judge: set[tuple[str, float | None]]) -> None:
+ """Stamp ``judge: true|false`` on each entry of the driver's views.json."""
+ if not views_json.is_file():
+ return
+ try:
+ entries = json.loads(views_json.read_text())
+ except (OSError, ValueError):
+ return
+ for e in entries:
+ e["judge"] = (e.get("name"), e.get("time_s")) in judge
+ views_json.write_text(json.dumps(entries, indent=1))
def _read_json(p: Path) -> dict[str, Any]:
@@ -232,3 +316,51 @@ def _read_json(p: Path) -> dict[str, Any]:
def read_metrics(out_dir: Path) -> dict[str, Any]:
"""Full instrument payload written by the driver (census, camera_checks, ...)."""
return _read_json(Path(out_dir) / "metrics.json")
+
+
+def frame_table(source: RenderSet | dict[str, Any] | Path | str) -> str:
+ """Compact per-view frame table for tools / judge context, one line per camera:
+
+ view mean_lum dark% blown% content% cam_in_geom
+ overview [authored] 0.34 5% 0% 48% no
+
+ ``source`` may be a scene RenderSet (its metrics.json is located), a
+ metrics payload dict, a render directory or a metrics.json path. Views
+ without ``camera_checks`` yield an explanatory one-liner instead.
+ """
+ if isinstance(source, RenderSet):
+ p = metrics_path_for(source)
+ metrics = _read_json(p) if p else {}
+ elif isinstance(source, dict):
+ metrics = source
+ else:
+ p = Path(source)
+ metrics = _read_json(p if p.suffix == ".json" else p / "metrics.json")
+ checks = [c for c in metrics.get("camera_checks") or [] if isinstance(c, dict)]
+ if not checks:
+ return "frame table: no camera_checks available (scene not rendered or metrics.json missing)"
+
+ def pct(v: Any) -> str:
+ return f"{float(v):.0%}" if isinstance(v, (int, float)) else "-"
+
+ def num(v: Any) -> str:
+ return f"{float(v):.2f}" if isinstance(v, (int, float)) else "-"
+
+ rows = [("view", "mean_lum", "dark%", "blown%", "content%", "cam_in_geom")]
+ for c in checks:
+ name = f"{c.get('name', '?')} [{c.get('kind', 'authored')}]"
+ in_geom = c.get("camera_in_geometry")
+ rows.append((name[:40], num(c.get("mean_lum")), pct(c.get("dark_frac")), pct(c.get("blown_frac")),
+ pct(c.get("content_frac")), "-" if in_geom is None else ("YES" if in_geom else "no")))
+ widths = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))]
+ return "\n".join(r[0].ljust(widths[0]) + " " + " ".join(r[i].rjust(widths[i]) for i in range(1, len(r))) for r in rows)
+
+
+def metrics_path_for(rs: RenderSet) -> Path | None:
+ """``metrics.json`` next to a RenderSet's sheet / views (None when not a scene render)."""
+ for cand in (rs.contact_sheet, *(v.path for v in rs.views)):
+ if cand:
+ p = Path(cand).parent / "metrics.json"
+ if p.is_file():
+ return p
+ return None
diff --git a/harness/codeverse/spatial/sheet.py b/harness/codeverse/spatial/sheet.py
index 9284a767..3d217dbd 100644
--- a/harness/codeverse/spatial/sheet.py
+++ b/harness/codeverse/spatial/sheet.py
@@ -82,3 +82,53 @@ def contact_sheet(
out.parent.mkdir(parents=True, exist_ok=True)
sheet.save(out, format="PNG", optimize=False)
return out
+
+
+# --------------------------------------------------------------------------- montage helpers (judge inputs)
+MONTAGE_MAX_TILES = 4
+
+
+def montage_2x2(
+ images: Sequence[tuple[str, str | Path]],
+ out: Path | str,
+ tile: int = 512,
+) -> Path:
+ """A labelled ≤ 2×2 grid (1–4 tiles) — the judge-facing montage format.
+
+ VLM judges get position-biased and saturate with many tiles, so judge
+ images carry at most four views each. Raises ``ValueError`` above 4.
+ """
+ if not 1 <= len(images) <= MONTAGE_MAX_TILES:
+ raise ValueError(f"montage_2x2: need 1..{MONTAGE_MAX_TILES} tiles, got {len(images)}")
+ cols = 1 if len(images) == 1 else 2
+ return contact_sheet(images, out, cols=cols, tile=tile, label=True)
+
+
+def crop_region(
+ src: Path | str,
+ out: Path | str,
+ box_frac: tuple[float, float, float, float],
+ *,
+ min_px: int = 512,
+) -> Path:
+ """Crop ``src`` to the fractional box ``(left, top, right, bottom)`` (0..1) and
+ upscale so the long side is ≥ ``min_px`` (a "detail crop" for judges).
+
+ Returns ``out``. Raises ``ValueError`` for an empty box, ``OSError`` for an
+ unreadable image.
+ """
+ x0, y0, x1, y1 = (max(0.0, min(1.0, float(v))) for v in box_frac)
+ if x1 <= x0 or y1 <= y0:
+ raise ValueError(f"crop_region: empty box {box_frac}")
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ with Image.open(src) as im:
+ im = im.convert("RGB")
+ w, h = im.size
+ region = im.crop((round(x0 * w), round(y0 * h), max(round(x0 * w) + 1, round(x1 * w)), max(round(y0 * h) + 1, round(y1 * h))))
+ rw, rh = region.size
+ scale = max(1.0, min_px / max(rw, rh))
+ if scale > 1.0:
+ region = region.resize((max(1, round(rw * scale)), max(1, round(rh * scale))), Image.LANCZOS)
+ region.save(out, format="PNG", optimize=False)
+ return out
diff --git a/harness/codeverse/spatial/tool_common.py b/harness/codeverse/spatial/tool_common.py
index 78b34798..1d99d713 100644
--- a/harness/codeverse/spatial/tool_common.py
+++ b/harness/codeverse/spatial/tool_common.py
@@ -18,7 +18,7 @@ from typing import Any
from pydantic import ValidationError
from codeverse.contracts.artifacts import RenderSet
-from codeverse.contracts.plan import ArticulatedPlan, Plan, ScenePlan, StaticPlan
+from codeverse.contracts.plan import ArticulatedPlan, GraphicsPlan, Plan, ScenePlan, StaticPlan
from codeverse.conventions import OBJECT_VIEWS, ViewPreset
from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError
@@ -99,11 +99,13 @@ def load_plan(path: Path) -> Plan:
if not path.is_file():
raise ToolUsageError("plan.json not found in the workspace")
data = json.loads(path.read_text())
- model: type[StaticPlan] | type[ArticulatedPlan] | type[ScenePlan]
+ model: type[StaticPlan] | type[ArticulatedPlan] | type[ScenePlan] | type[GraphicsPlan]
if "zones" in data:
model = ScenePlan
elif "joints" in data:
model = ArticulatedPlan
+ elif "passes" in data:
+ model = GraphicsPlan
else:
model = StaticPlan
try:
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
index be870b97..7dee5999 100644
--- a/harness/codeverse/spatial/tools.py
+++ b/harness/codeverse/spatial/tools.py
@@ -75,6 +75,51 @@ def _measure_after_build(ctx: ToolContext, br: BuildResult) -> tuple[Measurement
return m, measure_summary_table(m)
+#: languages whose build has no GLB deliverable — build ok is reported through
+#: the language's own artifacts instead of 'no GLB path'
+_SCENE_LANGS = ("scene_threejs",)
+_GL_LANGS = ("glsl_shader", "opengl_python")
+
+
+def _no_glb_summary(ctx: ToolContext, br: BuildResult, language: str) -> tuple[bool, list[str], dict[str, Any]]:
+ """(ok, lines, numbers) for a successful build without a GLB (scene / graphics)."""
+ ws = ctx.workspace
+ census = dict(br.census) if isinstance(br.census, dict) else {}
+ if language in _GL_LANGS:
+ lines, numbers = [], {}
+ try:
+ read_metrics = lazy("codeverse.languages.glsl_shader.gl_build", "read_metrics")
+ m = read_metrics(ws)
+ except ToolUnavailable:
+ m = None
+ if m is not None:
+ stats, gate = m
+ lines.extend(stats.summary_lines())
+ for f in gate.findings:
+ if f.severity == Severity.INFO:
+ continue
+ lines.append(f"- {f.severity.value.upper()} [{f.data.get('kind', '')}] {sanitize_text(f.message, ws.root)}")
+ numbers.update({"n_frames": len(stats.frames), "static": stats.static, "any_nan": stats.any_nan,
+ "gate_errors": len(gate.errors)})
+ ok = not gate.errors
+ else:
+ lines.append("(no frame metrics)")
+ ok = True
+ for key in ("frames", "sheet", "gif"):
+ p = br.extra_paths.get(key)
+ if p:
+ lines.append(f"{key}: {rel_path(p, ws.root)}")
+ return ok, lines, numbers
+ # scene_threejs: probe census (+ shader preflight) is the deliverable
+ keep = {k: v for k, v in census.items() if isinstance(v, (int, float, str, bool)) and k != "build_report"}
+ lines = ["scene probe census: " + (", ".join(f"{k}={v}" for k, v in sorted(keep.items())[:20]) or "(empty)")]
+ for key in ("scene_probe", "shader_preflight"):
+ p = br.extra_paths.get(key)
+ if p:
+ lines.append(f"{key}: {rel_path(p, ws.root)}")
+ return True, lines, {"census": keep}
+
+
@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow")
def build(ctx: ToolContext, args: NoArgs) -> Observation:
ws = ctx.workspace
@@ -108,11 +153,19 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
numbers.update({"error_type": br.error_type, "error_file": rel_path(br.error_file, ws.root), "error_line": br.error_line})
return Observation(ok=False, text=truncate("\n".join(lines), 3000), numbers=numbers,
duration_ms=int((time.time() - t0) * 1000))
- m, table = _measure_after_build(ctx, br)
- lines = [f"BUILD OK ({br.duration_ms} ms) → {rel_path(br.glb_path, ws.root)}"]
- if br.extra_paths:
- lines.append("extras: " + ", ".join(f"{k}={rel_path(v, ws.root)}" for k, v in br.extra_paths.items()))
- lines.append(table)
+ if not br.glb_path and language in _SCENE_LANGS + _GL_LANGS:
+ # languages without a GLB deliverable: report the language's own artifacts
+ ok, extra_lines, extra_numbers = _no_glb_summary(ctx, br, language)
+ lines = [f"BUILD OK ({br.duration_ms} ms)"] + extra_lines
+ numbers.update(extra_numbers)
+ m = None
+ else:
+ m, table = _measure_after_build(ctx, br)
+ ok = m is not None
+ lines = [f"BUILD OK ({br.duration_ms} ms) → {rel_path(br.glb_path, ws.root)}"]
+ if br.extra_paths:
+ lines.append("extras: " + ", ".join(f"{k}={rel_path(v, ws.root)}" for k, v in br.extra_paths.items()))
+ lines.append(table)
if m is not None:
numbers.update({"extents_m": list(m.extents), "tri_count": m.tri_count, "n_parts": len(m.parts),
"n_islands": m.n_islands, "ground_gap_m": m.ground_gap_m,
@@ -124,7 +177,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
census_warn = br.census.get("warnings") if isinstance(br.census, dict) else None
if census_warn:
lines.append("build warnings:\n" + "\n".join(f"- {sanitize_text(str(w), ws.root)}" for w in list(census_warn)[:10]))
- return Observation(ok=m is not None, text=truncate("\n".join(lines), 3000), numbers=numbers,
+ return Observation(ok=ok, text=truncate("\n".join(lines), 3000), numbers=numbers,
duration_ms=int((time.time() - t0) * 1000))
@@ -158,7 +211,7 @@ def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
@tool("check_connectivity", NoArgs, "Contact graph of all parts: floating parts (with the exact gap vector to close), interpenetration, stray islands.")
def check_connectivity(ctx: ToolContext, args: NoArgs) -> Observation:
glb = glb_path(ctx)
- report = _check_connectivity(glb)
+ report = _check_connectivity(glb, language=language_of(ctx))
ctx.workspace.write_json(ctx.workspace.gates_dir(ctx.round_index) / "connectivity_tool.json", report)
return gate_observation(report)
@@ -201,6 +254,7 @@ def cross_section(ctx: ToolContext, args: CrossSectionArgs) -> Observation:
# register the remaining tool modules (order matters only for the prompt card listing)
import codeverse.spatial.cookbook_tool # noqa: E402,F401
+import codeverse.spatial.tools_graphics # noqa: E402,F401
import codeverse.spatial.tools_render # noqa: E402,F401
import codeverse.spatial.tools_scene # noqa: E402,F401
-
+import codeverse.spatial.tools_texture # noqa: E402,F401
diff --git a/harness/codeverse/spatial/tools_graphics.py b/harness/codeverse/spatial/tools_graphics.py
new file mode 100644
index 00000000..b44b14ec
--- /dev/null
+++ b/harness/codeverse/spatial/tools_graphics.py
@@ -0,0 +1,155 @@
+"""Graphics-track tools: ``gl_probe`` (compile + first frame + stats) and ``gl_frames``
+(render the judged times → contact sheet + frame metrics). Both run the language
+runtime's build (lint → moderngl subprocess) so the agent sees exactly what the
+harness will see; languages = glsl_shader · opengl_python.
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import BuildResult, GateReport, Severity
+from codeverse.contracts.common import Language
+from codeverse.spatial.observe import rel_path, sanitize_text, tail_lines, truncate
+from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
+from codeverse.spatial.tool_common import ToolUnavailable, language_of, lazy, unavailable_obs
+
+GRAPHICS_LANGS = (Language.GLSL_SHADER.value, Language.OPENGL_PYTHON.value)
+MAX_FRAMES = 8
+
+
+class GlProbeArgs(BaseModel):
+ """Compile the shader / import the program and render ONE frame at ``t``."""
+
+ t: float = Field(default=1.0, ge=0.0, le=120.0, description="time (s) of the single probe frame")
+
+
+class GlFramesArgs(BaseModel):
+ times: list[float] = Field(default=[0.0, 1.0, 2.5, 4.0, 6.0], description="times (s) to render, 1..8 values")
+ width: int = Field(default=0, ge=0, le=1920, description="override width (0 = plan resolution)")
+ height: int = Field(default=0, ge=0, le=1080, description="override height (0 = plan resolution)")
+
+
+def _runtime(ctx: ToolContext):
+ lang = language_of(ctx)
+ if lang not in GRAPHICS_LANGS:
+ raise ToolUsageError(f"gl tools only apply to {GRAPHICS_LANGS}; workspace language is {lang!r}")
+ get_runtime = lazy("codeverse.languages", "get_runtime")
+ return get_runtime(lang)
+
+
+def _lint_block(report: GateReport, root: Path) -> tuple[list[str], list[str]]:
+ errs, warns = [], []
+ for f in report.findings:
+ if f.severity == Severity.INFO:
+ continue
+ line = f"- {sanitize_text(f.message, root)}" + (f"\n fix: {sanitize_text(f.fix_hint, root)}" if f.fix_hint else "")
+ (errs if f.severity == Severity.ERROR else warns).append(line)
+ return errs, warns
+
+
+def _failure_text(br: BuildResult, root: Path, lint_warns: list[str]) -> str:
+ shown = br.error_file if not Path(br.error_file).is_absolute() else rel_path(br.error_file, root)
+ where = f" at {shown}:{br.error_line}" if br.error_file else ""
+ lines = [f"BUILD FAILED: {br.error_type or 'Error'}{where}", sanitize_text(br.error_message, root)]
+ tail = tail_lines(sanitize_text(br.stderr_tail, root), 25)
+ if tail and tail not in br.error_message:
+ lines.append("log tail:\n" + tail)
+ if lint_warns:
+ lines.append("lint hints:\n" + "\n".join(lint_warns[:8]))
+ return "\n".join(lines)
+
+
+def _run_build(ctx: ToolContext, *, times: list[float], preview: bool, width: int = 0, height: int = 0) -> tuple[Observation | None, BuildResult | None, list[str]]:
+ """Lint → build; returns (error observation | None, build, lint warnings)."""
+ ws = ctx.workspace
+ try:
+ rt = _runtime(ctx)
+ except ToolUnavailable as e:
+ return unavailable_obs("gl_frames", e), None, []
+ lint: GateReport = rt.lint(ws)
+ errs, warns = _lint_block(lint, ws.root)
+ if errs:
+ text = "LINT FAILED — fix these before rendering:\n" + "\n".join(errs)
+ if warns:
+ text += "\nwarnings:\n" + "\n".join(warns[:8])
+ return Observation(ok=False, text=truncate(text), numbers={"stage": "lint", "lint_errors": len(errs)}), None, warns
+ kw = {"times": times, "preview": preview}
+ if width and height:
+ kw.update(width=width, height=height)
+ br: BuildResult = rt.build(ws, **kw)
+ ws.write_json(ws.artifacts / "build_last.json", br)
+ if not br.ok:
+ return Observation(ok=False, text=truncate(_failure_text(br, ws.root, warns), 3000),
+ numbers={"stage": "build", "error_type": br.error_type, "error_file": br.error_file,
+ "error_line": br.error_line}), br, warns
+ return None, br, warns
+
+
+def _stats_text(ctx: ToolContext) -> tuple[str, dict]:
+ read_metrics = lazy("codeverse.languages.glsl_shader.gl_build", "read_metrics")
+ m = read_metrics(ctx.workspace)
+ if m is None:
+ return "(no frame metrics)", {}
+ stats, gate = m
+ lines = stats.summary_lines()
+ for f in gate.findings:
+ if f.severity == Severity.INFO:
+ continue
+ lines.append(f"- {f.severity.value.upper()} [{f.data.get('kind', '')}] {f.message}" + (f"\n fix: {f.fix_hint}" if f.fix_hint else ""))
+ numbers = {"mean_lum": stats.mean_lum, "colourfulness": stats.mean_colourfulness, "edge_density": stats.mean_edge_density,
+ "mean_diff": stats.mean_diff, "static": stats.static, "any_nan": stats.any_nan, "gate_passed": gate.passed,
+ "gate_errors": len(gate.errors), "n_frames": len(stats.frames)}
+ return "\n".join(lines), numbers
+
+
+@tool("gl_probe", GlProbeArgs, "Compile the shader / import the program and render ONE frame (default t=1 s): errors with src line numbers, or the frame + its stats. Call after every edit.",
+ languages=GRAPHICS_LANGS, cost_hint="slow")
+def gl_probe(ctx: ToolContext, args: GlProbeArgs) -> Observation:
+ t0 = time.time()
+ err, br, warns = _run_build(ctx, times=[args.t], preview=False)
+ if err is not None:
+ err.duration_ms = int((time.time() - t0) * 1000)
+ return err
+ assert br is not None
+ text, numbers = _stats_text(ctx)
+ frames = sorted(Path(br.extra_paths["frames"]).glob("f*_t*.png")) if br.extra_paths.get("frames") else []
+ lines = [f"PROBE OK ({br.duration_ms} ms, {br.census.get('renderer', 'GL')}) — frame at t={args.t:g}s", text]
+ if warns:
+ lines.append("lint warnings:\n" + "\n".join(warns[:8]))
+ numbers.update({"stage": "probe", "t": args.t, "duration_ms": br.duration_ms})
+ return Observation(ok=numbers.get("gate_errors", 0) == 0, text=truncate("\n".join(lines), 3000), numbers=numbers,
+ images=[str(p) for p in frames[:1]], duration_ms=int((time.time() - t0) * 1000))
+
+
+@tool("gl_frames", GlFramesArgs, "Render frames at the judged times (0,1,2.5,4,6 s by default) → labelled contact sheet + per-frame metrics (luminance, colour, detail, motion, NaN) + the gl_frames gate. LOOK at the sheet.",
+ languages=GRAPHICS_LANGS, cost_hint="slow")
+def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:
+ if not args.times or len(args.times) > MAX_FRAMES:
+ raise ToolUsageError(f"times must hold 1..{MAX_FRAMES} values", "gl_frames(times=[0, 1, 2.5, 4, 6])")
+ t0 = time.time()
+ err, br, warns = _run_build(ctx, times=sorted(set(float(t) for t in args.times)), preview=False, width=args.width, height=args.height)
+ if err is not None:
+ err.duration_ms = int((time.time() - t0) * 1000)
+ return err
+ assert br is not None
+ text, numbers = _stats_text(ctx)
+ out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_gl_{int(time.time()) % 100000}"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ images: list[str] = []
+ sheet = br.extra_paths.get("sheet")
+ if sheet and Path(sheet).is_file():
+ import shutil
+
+ dst = out_dir / "sheet.png"
+ shutil.copy2(sheet, dst)
+ images.append(str(dst))
+ lines = [f"FRAMES OK ({br.duration_ms} ms, {br.census.get('renderer', 'GL')}) — sheet tiles labelled t=<s>; compare them for motion", text]
+ if warns:
+ lines.append("lint warnings:\n" + "\n".join(warns[:8]))
+ numbers.update({"stage": "frames", "times": args.times, "duration_ms": br.duration_ms, "sheet": rel_path(images[0], ctx.workspace.root) if images else ""})
+ return Observation(ok=numbers.get("gate_errors", 0) == 0, text=truncate("\n".join(lines), 3000), numbers=numbers, images=images,
+ duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/spatial/tools_texture.py b/harness/codeverse/spatial/tools_texture.py
new file mode 100644
index 00000000..9fda4747
--- /dev/null
+++ b/harness/codeverse/spatial/tools_texture.py
@@ -0,0 +1,108 @@
+"""Texturing tools: ``texture_pass`` (plan → generate → apply → gate on the built
+GLB) and ``texture_preview`` (a labelled sheet of the current textured GLB /
+generated textures). Registered for the object tracks, every language.
+
+The tools read ``spec.json`` / ``plan.json`` from the workspace; the image model
+and judge come from the spec's backends (planner for the material plan, judge for
+the ship gate) unless ``ctx.extra`` injects ``image_model`` / ``judge`` (tests).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Track
+from codeverse.contracts.plan import StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.spatial.observe import rel_path
+from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
+from codeverse.spatial.tool_common import (
+ ToolUnavailable,
+ glb_path,
+ lazy,
+ load_plan,
+ spec_dict,
+ unavailable_obs,
+)
+
+_OBJECT_TRACKS = (Track.STATIC_OBJECT.value, Track.ARTICULATED_OBJECT.value)
+
+
+class TexturePassArgs(BaseModel):
+ judge: bool = Field(default=True, description="run the before/after VLM ship gate (False = ship on seam gate only)")
+ model: str = Field(default="", description="planner chat model id for the material plan (default: spec planner)")
+ size: int = Field(default=1024, ge=256, le=2048, description="texture size in px")
+
+
+def _spec_plan(ctx: ToolContext) -> tuple[Spec, StaticPlan]:
+ try:
+ spec = Spec.model_validate(spec_dict(ctx))
+ except Exception as e: # pydantic ValidationError
+ raise ToolUsageError(f"spec.json missing or invalid: {e}") from e
+ plan = load_plan(ctx.workspace.plan_path)
+ if not isinstance(plan, StaticPlan):
+ raise ToolUsageError("texture_pass needs an object plan (StaticPlan / ArticulatedPlan)")
+ return spec, plan
+
+
+@tool("texture_pass", TexturePassArgs,
+ "Text-to-image texturing of the built GLB: material plan (VLM) → tileable textures (image model) → "
+ "analytic UVs + PBR materials → artifacts/object_textured.glb, shipped only if the judge score does not drop.",
+ tracks=_OBJECT_TRACKS, cost_hint="slow")
+def texture_pass_tool(ctx: ToolContext, args: TexturePassArgs) -> Observation:
+ glb = glb_path(ctx)
+ spec, plan = _spec_plan(ctx)
+ try:
+ texture_pass = lazy("codeverse.texturing.run", "texture_pass")
+ except ToolUnavailable as e:
+ return unavailable_obs("texture_pass", e)
+ judge = ctx.extra.get("judge", args.judge)
+ rep = texture_pass(ctx.workspace, spec, plan, model_id=args.model or spec.backends.planner,
+ image_model=ctx.extra.get("image_model"), judge=judge, glb_in=glb, size=args.size,
+ plan_model=ctx.extra.get("plan_model"), render=ctx.extra.get("render"),
+ cache_dir=ctx.extra.get("cache_dir"))
+ s = rep.summary()
+ root = ctx.workspace.root
+ lines = [
+ f"texture pass: {'SHIPPED' if rep.shipped else 'not shipped'} — {s['reason'] or 'ok'}",
+ f"textures: {s['n_textures']} generated ({', '.join(rep.plan.texture_ids()) or '-'}); seam failed: {s['seam_failed'] or 'none'}",
+ f"parts textured: {s['parts_textured']} / skipped: {len(rep.apply.parts_skipped) if rep.apply else 0}",
+ ]
+ if rep.gate is not None and rep.gate.overall_before is not None:
+ lines.append(f"judge before {rep.gate.overall_before:.3f} → after {rep.gate.overall_after:.3f} "
+ f"(Δ {rep.gate.delta:+.3f}; {rep.gate.materials_criterion} Δ {rep.gate.materials_delta:+.3f})")
+ if rep.glb_out:
+ lines.append(f"textured GLB: {rel_path(rep.glb_out, root)}")
+ lines.append(f"cost ${rep.usage.cost_usd:.4f}, {rep.duration_s:.0f}s")
+ images = []
+ if rep.gate is not None and rep.gate.renders_after and rep.gate.renders_after.contact_sheet:
+ images.append(rep.gate.renders_after.contact_sheet)
+ return Observation(ok=True, text="\n".join(lines), numbers=s, images=images)
+
+
+class TexturePreviewArgs(BaseModel):
+ views: list[str] = Field(default=["front_right_34", "back_left_34", "front", "top"], description="view names")
+
+
+@tool("texture_preview", TexturePreviewArgs,
+ "Render artifacts/object_textured.glb (after texture_pass) as a labelled contact sheet + list the generated textures.",
+ tracks=_OBJECT_TRACKS, cost_hint="slow")
+def texture_preview(ctx: ToolContext, args: TexturePreviewArgs) -> Observation:
+ from codeverse.spatial.tool_common import cached_render_glb, resolve_views
+
+ ws = ctx.workspace
+ glb = ws.artifacts / "object_textured.glb"
+ if not glb.is_file():
+ raise ToolUsageError("artifacts/object_textured.glb does not exist — run texture_pass first", "texture_pass()")
+ presets = resolve_views(args.views)
+ try:
+ rs = cached_render_glb(ctx, glb, views=presets, mode="shaded", size=512, sheet=True)
+ except ToolUnavailable as e:
+ return unavailable_obs("texture_preview", e)
+ tex_dir = ws.artifacts / "textures"
+ pngs = sorted(p.name for p in tex_dir.glob("*.png")) if tex_dir.is_dir() else []
+ text = f"textured GLB rendered ({len(rs.views)} views). textures: {', '.join(pngs) or 'none'}"
+ images = [rs.contact_sheet] if rs.contact_sheet else [v.path for v in rs.views]
+ return Observation(ok=True, text=text, numbers={"n_textures": len(pngs)}, images=[str(Path(i)) for i in images])
diff --git a/harness/codeverse/texturing/__init__.py b/harness/codeverse/texturing/__init__.py
new file mode 100644
index 00000000..22c50872
--- /dev/null
+++ b/harness/codeverse/texturing/__init__.py
@@ -0,0 +1,18 @@
+"""Text-to-image texturing: a language-agnostic pass on the canonical GLB
+(objects) and a scene texture pack (scenes). See ``run.texture_pass`` and
+``scene_pack.scene_texture_pack``."""
+
+from codeverse.texturing.apply import ApplyReport, apply_textures
+from codeverse.texturing.gate import GateResult, SeamGateResult, judge_gate, seam_gate
+from codeverse.texturing.generate import FakeImageModel, TextureAsset, TextureSet, generate_textures
+from codeverse.texturing.plan import TexturePart, TexturePlan, default_plan, material_plan
+from codeverse.texturing.run import TextureReport, texture_pass
+from codeverse.texturing.scene_pack import ScenePack, scene_texture_pack, texture_pack_prompt
+from codeverse.texturing.tile import make_tileable, seam_score
+
+__all__ = [
+ "ApplyReport", "apply_textures", "GateResult", "SeamGateResult", "judge_gate", "seam_gate",
+ "FakeImageModel", "TextureAsset", "TextureSet", "generate_textures", "TexturePart", "TexturePlan",
+ "default_plan", "material_plan", "TextureReport", "texture_pass", "ScenePack", "scene_texture_pack",
+ "texture_pack_prompt", "make_tileable", "seam_score",
+]
diff --git a/harness/codeverse/texturing/apply.py b/harness/codeverse/texturing/apply.py
new file mode 100644
index 00000000..7dbc5bd2
--- /dev/null
+++ b/harness/codeverse/texturing/apply.py
@@ -0,0 +1,197 @@
+"""Apply a ``TexturePlan`` + generated images to the canonical GLB → a textured GLB.
+
+How textures are embedded (trimesh 4.x): every textured geometry gets
+``trimesh.visual.TextureVisuals(uv=<per-vertex UV>, material=PBRMaterial(
+baseColorTexture=<PIL image>, baseColorFactor=tint|white, metallicFactor,
+roughnessFactor))``; ``Scene.export(path)`` (glTF exporter) writes TEXCOORD_0,
+one glTF ``image``/``texture``/``material`` per distinct ``PBRMaterial`` object
+(materials are shared across parts with the same texture id + factors, so the
+GLB carries each PNG once) and keeps node names + transforms. Geometry
+positions are never altered (only seam-split vertices are duplicated); parts
+marked ``skip`` keep their original visuals (flat colours / vertex colours).
+
+Verification: the exported file is reloaded with trimesh and the node-name set
+and per-part textured state are checked before the function returns.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from pathlib import Path
+
+import numpy as np
+import trimesh
+from PIL import Image
+from pydantic import BaseModel, Field
+
+from codeverse.conventions import to_snake
+from codeverse.spatial.measure import GlbLoadError, instance_groups, load_scene
+from codeverse.texturing.plan import TexturePart, TexturePlan
+from codeverse.texturing.uv import unwrap
+
+log = logging.getLogger(__name__)
+
+
+class ApplyReport(BaseModel):
+ glb_out: str
+ parts_textured: list[str] = Field(default_factory=list)
+ parts_skipped: list[str] = Field(default_factory=list)
+ parts_unmatched: list[str] = Field(default_factory=list, description="scene nodes with no plan part")
+ projections: dict[str, str] = Field(default_factory=dict, description="node → projection used")
+ n_materials: int = 0
+ n_split_vertices: int = 0
+ warnings: list[str] = Field(default_factory=list)
+ duration_ms: int = 0
+
+
+def node_part_lookup(node_names: list[str], plan_parts: dict[str, TexturePart]) -> dict[str, TexturePart | None]:
+ """Map scene node names to plan parts: exact (snake) → instance base (``Leg_0`` →
+ ``Leg``) → link piece (``Link__2`` → ``Link``)."""
+ groups = instance_groups(list(node_names))
+ base_of: dict[str, str] = {}
+ for base, members in groups.items():
+ for m in members:
+ base_of[m] = base
+ out: dict[str, TexturePart | None] = {}
+ for n in node_names:
+ cands = [to_snake(n), to_snake(base_of.get(n, n)), to_snake(n.split("__", 1)[0])]
+ hit = next((plan_parts[c] for c in cands if c in plan_parts), None)
+ out[n] = hit
+ return out
+
+
+def _material(part: TexturePart, image: Image.Image) -> trimesh.visual.material.PBRMaterial:
+ tint = part.tint_rgb or (1.0, 1.0, 1.0)
+ factor = [int(round(255 * float(c))) for c in tint] + [255]
+ return trimesh.visual.material.PBRMaterial(
+ name=part.texture_id,
+ baseColorTexture=image,
+ baseColorFactor=factor,
+ metallicFactor=float(part.metallic),
+ roughnessFactor=float(part.roughness),
+ doubleSided=False,
+ )
+
+
+def _node_transform(scene: trimesh.Scene, node: str) -> np.ndarray:
+ T, _ = scene.graph.get(node)
+ return np.asarray(T, dtype=np.float64)
+
+
+def apply_textures(
+ glb_in: Path | str,
+ texture_plan: TexturePlan,
+ textures: dict[str, Path | str],
+ glb_out: Path | str,
+ *,
+ verify: bool = True,
+) -> ApplyReport:
+ """Write ``glb_out`` = ``glb_in`` with textured PBR materials on the planned parts.
+ ``textures`` maps texture_id → PNG path (missing ids leave those parts untextured)."""
+ t0 = time.time()
+ glb_in, glb_out = Path(glb_in), Path(glb_out)
+ scene = load_scene(glb_in)
+ rep = ApplyReport(glb_out=str(glb_out))
+ parts = texture_plan.by_part()
+ nodes = list(scene.graph.nodes_geometry)
+ lookup = node_part_lookup(nodes, parts)
+ images: dict[str, Image.Image] = {}
+ for tid, p in textures.items():
+ p = Path(p)
+ if p.is_file():
+ images[tid] = Image.open(p).convert("RGB")
+ else:
+ rep.warnings.append(f"texture file missing for {tid}: {p.name}")
+ materials: dict[tuple[str, float, float, tuple[float, ...] | None], trimesh.visual.material.PBRMaterial] = {}
+ geom_proj: dict[str, str] = {}
+ for node in nodes:
+ part = lookup.get(node)
+ if part is None:
+ rep.parts_unmatched.append(node)
+ continue
+ if part.skip:
+ rep.parts_skipped.append(node)
+ continue
+ img = images.get(part.texture_id)
+ if img is None:
+ rep.parts_skipped.append(node)
+ rep.warnings.append(f"{node}: no image for texture {part.texture_id}")
+ continue
+ _, geom_name = scene.graph.get(node)
+ if geom_name is None:
+ continue
+ if geom_name in geom_proj: # instance sharing an already-unwrapped geometry
+ rep.parts_textured.append(node)
+ rep.projections[node] = geom_proj[geom_name]
+ continue
+ geom = scene.geometry.get(geom_name)
+ if not isinstance(geom, trimesh.Trimesh) or len(geom.faces) == 0:
+ rep.parts_unmatched.append(node)
+ continue
+ try:
+ uw = unwrap(geom.vertices, geom.faces, _node_transform(scene, node), projection=part.projection,
+ tile_size_m=part.tile_size_m, normals_local=np.asarray(geom.vertex_normals))
+ except ValueError as e:
+ rep.warnings.append(f"{node}: unwrap failed: {e}")
+ rep.parts_skipped.append(node)
+ continue
+ mkey = (part.texture_id, float(part.roughness), float(part.metallic), part.tint_rgb)
+ mat = materials.get(mkey)
+ if mat is None:
+ mat = materials[mkey] = _material(part, img)
+ mesh = trimesh.Trimesh(vertices=uw.vertices, faces=uw.faces, vertex_normals=uw.normals, process=False)
+ mesh.visual = trimesh.visual.TextureVisuals(uv=uw.uv, material=mat)
+ mesh.metadata = dict(geom.metadata or {})
+ scene.geometry[geom_name] = mesh
+ geom_proj[geom_name] = uw.projection
+ rep.parts_textured.append(node)
+ rep.projections[node] = uw.projection
+ rep.n_split_vertices += uw.n_split
+ rep.n_materials = len(materials)
+ glb_out.parent.mkdir(parents=True, exist_ok=True)
+ scene.export(glb_out)
+ if verify:
+ rep.warnings.extend(verify_textured_glb(glb_in, glb_out, expected_textured=len(rep.parts_textured)))
+ rep.duration_ms = int((time.time() - t0) * 1000)
+ return rep
+
+
+def verify_textured_glb(glb_in: Path, glb_out: Path, *, expected_textured: int) -> list[str]:
+ """Reload and compare: same node-name set, textures present. Returns warnings
+ (empty = ok); raises ``GlbLoadError`` when the output does not load at all."""
+ warnings: list[str] = []
+ try:
+ a = load_scene(glb_in)
+ b = load_scene(glb_out)
+ except GlbLoadError as e:
+ raise GlbLoadError(f"textured GLB verification failed: {e}") from e
+ na, nb = set(a.graph.nodes_geometry), set(b.graph.nodes_geometry)
+ if na != nb:
+ warnings.append(f"node set changed: missing={sorted(na - nb)[:5]} extra={sorted(nb - na)[:5]}")
+ n_tex = sum(
+ 1 for g in b.geometry.values()
+ if isinstance(g.visual, trimesh.visual.TextureVisuals) and getattr(g.visual.material, "baseColorTexture", None) is not None
+ )
+ if expected_textured and n_tex == 0:
+ warnings.append("no textured geometry found after reload")
+ fa = sum(len(g.faces) for g in a.geometry.values() if isinstance(g, trimesh.Trimesh))
+ fb = sum(len(g.faces) for g in b.geometry.values() if isinstance(g, trimesh.Trimesh))
+ if fa != fb:
+ warnings.append(f"face count changed {fa} → {fb}")
+ return warnings
+
+
+def textured_summary(glb: Path | str) -> dict[str, int]:
+ """Counts for reports / tests: geometries, textured geometries, distinct images."""
+ s = load_scene(glb)
+ textured = 0
+ imgs: set[int] = set()
+ for g in s.geometry.values():
+ vis = getattr(g, "visual", None)
+ mat = getattr(vis, "material", None)
+ tex = getattr(mat, "baseColorTexture", None)
+ if tex is not None:
+ textured += 1
+ imgs.add(id(tex))
+ return {"geometries": len(s.geometry), "textured": textured, "images": len(imgs)}
diff --git a/harness/codeverse/texturing/gate.py b/harness/codeverse/texturing/gate.py
new file mode 100644
index 00000000..e178cf56
--- /dev/null
+++ b/harness/codeverse/texturing/gate.py
@@ -0,0 +1,164 @@
+"""Do-no-harm ship gate for a texture pass.
+
+1. ``seam_gate``: per-texture seam score (``tile.seam_score`` after mirror-blend)
+ must be ≤ ``SEAM_MAX``; failing textures are dropped (their parts keep flat
+ materials) — deterministic, free.
+2. ``judge_gate``: render BEFORE and AFTER (``render_glb``, quick 4 views) and
+ judge both with the same ``VlmJudge`` (rubric of the track, n_samples=1).
+ Ship iff ``Δoverall ≥ min_overall_delta`` (default −0.01) AND the rubric's
+ material criterion improved (``> min_materials_delta``, default 0). A degraded
+ verdict on either side → not shipped (a glitch is never a score).
+
+Everything is injectable (``render`` / ``judge`` callables) so tests run offline.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import Measurement, RenderSet
+from codeverse.contracts.common import Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem, StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
+from codeverse.texturing.generate import TextureAsset
+from codeverse.texturing.tile import SEAM_MAX
+
+log = logging.getLogger(__name__)
+
+MIN_OVERALL_DELTA = -0.01
+MIN_MATERIALS_DELTA = 0.0
+
+
+class SeamGateResult(BaseModel):
+ passed: dict[str, float] = Field(default_factory=dict, description="texture_id → seam score (kept)")
+ failed: dict[str, float] = Field(default_factory=dict, description="texture_id → seam score (dropped)")
+ threshold: float = SEAM_MAX
+
+
+def seam_gate(textures: dict[str, TextureAsset], *, max_seam: float = SEAM_MAX) -> SeamGateResult:
+ res = SeamGateResult(threshold=max_seam)
+ for tid, a in textures.items():
+ if not a.ok:
+ continue
+ (res.passed if a.seam_score <= max_seam else res.failed)[tid] = round(float(a.seam_score), 4)
+ return res
+
+
+class GateResult(BaseModel):
+ shipped: bool
+ reason: str = ""
+ overall_before: float | None = None
+ overall_after: float | None = None
+ delta: float | None = None
+ materials_criterion: str = ""
+ materials_before: float | None = None
+ materials_after: float | None = None
+ materials_delta: float | None = None
+ renders_before: RenderSet | None = None
+ renders_after: RenderSet | None = None
+ judgment_before: Judgment | None = None
+ judgment_after: Judgment | None = None
+ usage: Usage = Field(default_factory=Usage)
+ duration_s: float = 0.0
+
+
+def material_criterion(scores: dict[str, float], rubric_hint: str = "") -> str:
+ """The rubric criterion that tracks surface quality (``materials``,
+ ``material_color``, ``materials_shaders_effects``, ``material_truth`` ...)."""
+ for k in scores:
+ if k.startswith("material"):
+ return k
+ for k in scores:
+ if "material" in k or "texture" in k or "surface" in k:
+ return k
+ return ""
+
+
+def _plan_summary(plan: StaticPlan | None) -> str:
+ if plan is None:
+ return ""
+ parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
+ e = plan.overall_bbox.extents
+ return f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m. Parts: {parts}."
+
+
+def _degraded(j: Judgment) -> bool:
+ from codeverse.judges.scoring import is_degraded
+
+ return is_degraded(j)
+
+
+def judge_gate(
+ spec: Spec,
+ plan: StaticPlan | None,
+ glb_before: Path,
+ glb_after: Path,
+ out_dir: Path,
+ *,
+ judge: Any,
+ measurement: Measurement | None = None,
+ views: Sequence[ViewPreset] = OBJECT_VIEWS_QUICK,
+ render: Callable[..., RenderSet] | None = None,
+ size: int = 512,
+ min_overall_delta: float = MIN_OVERALL_DELTA,
+ min_materials_delta: float = MIN_MATERIALS_DELTA,
+) -> GateResult:
+ """Render + judge both GLBs; decide. ``judge`` is any object with
+ ``.judge(JudgeInput) -> Judgment`` (``VlmJudge`` or a fake)."""
+ from codeverse.judges.base import JudgeInput
+
+ t0 = time.time()
+ if render is None:
+ from codeverse.spatial.render import render_glb
+
+ render = render_glb
+ out_dir = Path(out_dir)
+ rs_before = render(glb_before, out_dir / "before", views=list(views), width=size, height=size)
+ rs_after = render(glb_after, out_dir / "after", views=list(views), width=size, height=size)
+ acceptance: list[AcceptanceItem] = list(getattr(plan, "acceptance", []) or [])
+ summary = _plan_summary(plan)
+ res = GateResult(shipped=False, renders_before=rs_before, renders_after=rs_after)
+ jb = judge.judge(JudgeInput(spec=spec, renders=rs_before, measurement=measurement, acceptance=acceptance,
+ plan_summary=summary, round_index=0,
+ extra_context="Texture gate: BEFORE texturing (flat materials)."))
+ ja = judge.judge(JudgeInput(spec=spec, renders=rs_after, measurement=measurement, acceptance=acceptance,
+ plan_summary=summary, round_index=0,
+ extra_context="Texture gate: AFTER texturing (image textures applied)."))
+ res.judgment_before, res.judgment_after = jb, ja
+ res.usage = jb.usage + ja.usage
+ res.duration_s = round(time.time() - t0, 2)
+ if _degraded(jb) or _degraded(ja):
+ res.reason = "judge degraded on one side — not shipped"
+ return res
+ res.overall_before, res.overall_after = float(jb.overall), float(ja.overall)
+ res.delta = round(res.overall_after - res.overall_before, 4)
+ crit = material_criterion(ja.scores)
+ res.materials_criterion = crit
+ if crit:
+ res.materials_before = float(jb.scores.get(crit, 0.0))
+ res.materials_after = float(ja.scores.get(crit, 0.0))
+ res.materials_delta = round(res.materials_after - res.materials_before, 4)
+ ok_overall = res.delta >= min_overall_delta
+ ok_mat = (res.materials_delta is None) or (res.materials_delta > min_materials_delta)
+ if crit and res.materials_delta is None:
+ ok_mat = False
+ res.shipped = bool(ok_overall and ok_mat)
+ if res.shipped:
+ res.reason = f"Δoverall {res.delta:+.3f} ≥ {min_overall_delta:+.2f} and {crit or 'overall'} {res.materials_delta:+.3f}" if crit \
+ else f"Δoverall {res.delta:+.3f} ≥ {min_overall_delta:+.2f}"
+ else:
+ why = []
+ if not ok_overall:
+ why.append(f"Δoverall {res.delta:+.3f} < {min_overall_delta:+.2f}")
+ if not ok_mat:
+ why.append(f"{crit} {res.materials_delta:+.3f} did not improve")
+ res.reason = "; ".join(why)
+ return res
diff --git a/harness/codeverse/texturing/generate.py b/harness/codeverse/texturing/generate.py
new file mode 100644
index 00000000..a93b4425
--- /dev/null
+++ b/harness/codeverse/texturing/generate.py
@@ -0,0 +1,232 @@
+"""Generate the texture images a ``TexturePlan`` (or a scene pack) needs.
+
+* one image per distinct prompt (parts sharing a ``texture_id`` share the image;
+ identical prompts under different ids are generated once and copied),
+* content cache ``<cache_dir>/textures/<sha(prompt|model|size|tile_version)>.png``
+ (the raw generation, BEFORE seam fixing, so a better ``make_tileable`` can be
+ re-applied without paying again),
+* parallel fan-out (ThreadPool) on the shared key pool,
+* every call yields a ``Usage`` (per texture and total),
+* the delivered asset is ``out_dir/<texture_id>.png``: ``make_tileable`` →
+ ``fit_size(size)`` → PNG, with its ``seam_score`` recorded.
+
+``FakeImageModel`` (procedural PIL images, deterministic per prompt) lets every
+test run offline with the exact same code path.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import shutil
+import threading
+import time
+from collections.abc import Sequence
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from PIL import Image
+from pydantic import BaseModel, Field
+
+from codeverse.config import get_settings
+from codeverse.contracts.common import Usage
+from codeverse.texturing.tile import fit_size, make_tileable, save_texture, seam_score
+
+log = logging.getLogger(__name__)
+
+#: bump when the cached raw image semantics change (prompt composition, model config)
+CACHE_VERSION = 1
+
+
+class TextureAsset(BaseModel):
+ texture_id: str
+ path: str
+ prompt: str
+ prompt_hash: str
+ seam_score: float = 0.0
+ seam_score_raw: float = 0.0
+ size: int = 1024
+ cached: bool = False
+ model: str = ""
+ usage: Usage = Field(default_factory=Usage)
+ error: str = ""
+
+ @property
+ def ok(self) -> bool:
+ return not self.error and Path(self.path).is_file()
+
+
+class TextureSet(BaseModel):
+ textures: dict[str, TextureAsset] = Field(default_factory=dict)
+ usage: Usage = Field(default_factory=Usage)
+ duration_s: float = 0.0
+
+ def paths(self) -> dict[str, Path]:
+ return {k: Path(v.path) for k, v in self.textures.items() if v.ok}
+
+ def failed(self) -> dict[str, str]:
+ return {k: v.error for k, v in self.textures.items() if v.error}
+
+
+def prompt_key(prompt: str, model_id: str, size: int) -> str:
+ return hashlib.sha256(f"v{CACHE_VERSION}|{model_id}|{size}|{prompt.strip()}".encode()).hexdigest()[:24]
+
+
+# --------------------------------------------------------------------------- fake model
+class FakeImageModel:
+ """Deterministic procedural textures (seeded by the prompt) for offline tests.
+ Records every prompt it was asked for in ``calls``."""
+
+ provider = "fake"
+
+ def __init__(self, model: str = "fake-image", *, latency_s: float = 0.0, fail_on: Sequence[str] = (),
+ usd_per_image: float = 0.001) -> None:
+ self.model = model
+ self.latency_s = latency_s
+ self.fail_on = tuple(fail_on)
+ self.usd_per_image = usd_per_image
+ self.calls: list[str] = []
+ self._lock = threading.Lock()
+
+ @property
+ def id(self) -> str:
+ return f"fake-image:{self.model}"
+
+ def generate(self, prompt: str, *, size: int = 1024, n: int = 1, seed: int | None = None,
+ reference_images: Sequence[Any] = ()) -> list[Image.Image]:
+ return self.generate_with_usage(prompt, size=size, n=n, seed=seed, reference_images=reference_images)[0]
+
+ def generate_with_usage(self, prompt: str, *, size: int = 1024, n: int = 1, seed: int | None = None,
+ reference_images: Sequence[Any] = ()) -> tuple[list[Image.Image], Usage]:
+ with self._lock:
+ self.calls.append(prompt)
+ if any(s in prompt for s in self.fail_on):
+ from codeverse.models.base import ModelError
+
+ raise ModelError(f"fake image model refused: {prompt[:40]}", retryable=False)
+ if self.latency_s:
+ time.sleep(self.latency_s)
+ images = [procedural_texture(prompt, size=size, seed=(seed or 0) + i) for i in range(n)]
+ usage = Usage(backend="fake-image", model=self.model, input_tokens=len(prompt.split()), output_tokens=1290 * n,
+ cost_usd=self.usd_per_image * n, latency_ms=int(self.latency_s * 1000))
+ return images, usage
+
+
+def procedural_texture(prompt: str, *, size: int = 256, seed: int = 0) -> Image.Image:
+ """Prompt-seeded noise + stripes in a prompt-derived colour. NOT tileable on
+ purpose (so tests exercise ``make_tileable``): a linear gradient is added."""
+ h = int(hashlib.sha256(prompt.encode()).hexdigest()[:8], 16)
+ rng = np.random.default_rng(h + seed)
+ base = np.array([(h >> 16) & 255, (h >> 8) & 255, h & 255], dtype=np.float32) / 255.0
+ base = 0.25 + 0.6 * base
+ y, x = np.mgrid[0:size, 0:size].astype(np.float32) / size
+ stripes = 0.08 * np.sin(2 * np.pi * (8 * x + 3 * np.sin(2 * np.pi * y)))
+ noise = 0.06 * rng.standard_normal((size, size)).astype(np.float32)
+ grad = 0.25 * x # seam-breaking gradient
+ lum = (stripes + noise + grad)[:, :, None]
+ img = np.clip(base[None, None, :] + lum, 0.0, 1.0)
+ return Image.fromarray((img * 255).astype(np.uint8), "RGB")
+
+
+# --------------------------------------------------------------------------- generation
+def _cache_dir(cache_dir: Path | None) -> Path:
+ d = (cache_dir or get_settings().cache_dir) / "textures"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def generate_one(
+ texture_id: str, prompt: str, out_dir: Path, image_model: Any, *, size: int = 1024, cache_dir: Path | None = None,
+ tileable: bool = True, border_frac: float = 0.12, use_cache: bool = True, seed: int | None = 0,
+) -> TextureAsset:
+ """Generate (or fetch from cache) one texture and deliver ``out_dir/<texture_id>.png``."""
+ model_id = getattr(image_model, "id", getattr(image_model, "model", "image"))
+ key = prompt_key(prompt, str(model_id), size)
+ raw_path = _cache_dir(cache_dir) / f"{key}.png"
+ asset = TextureAsset(texture_id=texture_id, path=str(Path(out_dir) / f"{texture_id}.png"), prompt=prompt,
+ prompt_hash=key, size=size, model=str(model_id))
+ t0 = time.time()
+ if use_cache and raw_path.is_file():
+ raw = Image.open(raw_path).convert("RGB")
+ asset.cached = True
+ else:
+ images, usage = image_model.generate_with_usage(prompt, size=size, n=1, seed=seed)
+ if not images:
+ raise RuntimeError(f"image model returned no image for {texture_id}")
+ raw = images[0].convert("RGB")
+ asset.usage = usage
+ if use_cache:
+ tmp = raw_path.with_suffix(".tmp.png")
+ raw.save(tmp, "PNG")
+ tmp.replace(raw_path)
+ asset.seam_score_raw = seam_score(raw)
+ img = fit_size(raw, size)
+ if tileable:
+ img = make_tileable(img, border_frac)
+ asset.seam_score = seam_score(img)
+ save_texture(img, Path(asset.path))
+ asset.usage.latency_ms = asset.usage.latency_ms or int((time.time() - t0) * 1000)
+ return asset
+
+
+def generate_textures(
+ prompts: dict[str, str] | Any,
+ out_dir: Path,
+ image_model: Any,
+ *,
+ size: int = 1024,
+ cache_dir: Path | None = None,
+ max_workers: int = 6,
+ tileable: bool = True,
+ border_frac: float = 0.12,
+ use_cache: bool = True,
+ seed: int = 0,
+) -> TextureSet:
+ """``prompts`` is ``{texture_id: prompt}`` or a ``TexturePlan`` (its ``.prompts()``).
+ Identical prompts are generated once and copied to every id. Failures are
+ recorded per texture (``TextureAsset.error``) — callers decide what to do."""
+ if hasattr(prompts, "prompts"):
+ prompts = prompts.prompts()
+ prompts = {str(k): str(v) for k, v in dict(prompts).items() if str(v).strip()}
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ t0 = time.time()
+ result = TextureSet()
+ if not prompts:
+ return result
+ # dedupe identical prompts → one generation, copies for the rest
+ leaders: dict[str, str] = {}
+ copies: dict[str, list[str]] = {}
+ for tid, pr in prompts.items():
+ k = pr.strip()
+ if k in leaders:
+ copies.setdefault(leaders[k], []).append(tid)
+ else:
+ leaders[k] = tid
+
+ def _job(tid: str) -> TextureAsset:
+ try:
+ return generate_one(tid, prompts[tid], out_dir, image_model, size=size, cache_dir=cache_dir,
+ tileable=tileable, border_frac=border_frac, use_cache=use_cache, seed=seed)
+ except Exception as e: # noqa: BLE001 — per-texture failure is data, not a crash
+ log.warning("texture %s failed: %s: %s", tid, type(e).__name__, e)
+ return TextureAsset(texture_id=tid, path=str(out_dir / f"{tid}.png"), prompt=prompts[tid],
+ prompt_hash=prompt_key(prompts[tid], str(getattr(image_model, "id", "")), size),
+ size=size, error=f"{type(e).__name__}: {e}")
+
+ ids = list(leaders.values())
+ with ThreadPoolExecutor(max_workers=max(1, min(max_workers, len(ids)))) as pool:
+ assets = list(pool.map(_job, ids))
+ for a in assets:
+ result.textures[a.texture_id] = a
+ result.usage = result.usage + a.usage
+ for other in copies.get(a.texture_id, []):
+ dup = a.model_copy(update={"texture_id": other, "path": str(out_dir / f"{other}.png"), "usage": Usage(),
+ "cached": True})
+ if a.ok:
+ shutil.copy2(a.path, dup.path)
+ result.textures[other] = dup
+ result.duration_s = round(time.time() - t0, 2)
+ return result
diff --git a/harness/codeverse/texturing/plan.py b/harness/codeverse/texturing/plan.py
new file mode 100644
index 00000000..04612a83
--- /dev/null
+++ b/harness/codeverse/texturing/plan.py
@@ -0,0 +1,348 @@
+"""Material plan: ONE vision call (contact sheet + plan parts table + brief) →
+``TexturePlan`` (per part: family, image prompt, projection, tile size, PBR factors,
+skip) validated in code with deterministic defaults, cached by content hash.
+
+``default_plan(plan)`` is the no-model fallback (keyword heuristics on the plan's
+``material`` strings) used by tests and when ``model_id`` is empty.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field, ValidationError
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderSet
+from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
+from codeverse.contracts.common import Usage
+from codeverse.contracts.plan import PartPlan, StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import to_snake
+from codeverse.models.schema_utils import parse_json_lenient
+from codeverse.prompts import load_text, prompt_hash, render
+
+log = logging.getLogger(__name__)
+
+MaterialFamily = Literal[
+ "wood", "metal", "fabric", "stone", "plastic", "leather", "glass", "ceramic", "painted", "rubber", "other"
+]
+Projection = Literal["box", "cylinder", "planar_y", "planar_z", "auto"]
+
+PLAN_TEMPLATE = "texturing/material_plan.md"
+STYLE_DOC = "texturing/image_prompt_style.md"
+#: parts whose largest extent is below this keep their flat material
+TINY_PART_M = 0.03
+
+STYLE_SUFFIX = (
+ "seamless tileable texture, perfectly repeating at the edges, top-down orthographic view, "
+ "flat even diffuse lighting, no shadows, no specular highlights, no vignette, no depth of field, "
+ "no text, no watermark, no border, fills the whole frame edge to edge, photoreal, uniform scale, 1:1 square"
+)
+
+
+class FamilyDefault(BaseModel):
+ roughness: float
+ metallic: float
+ tile_size_m: float
+ phrase: str
+ skip: bool = False
+
+
+FAMILY_DEFAULTS: dict[str, FamilyDefault] = {
+ "wood": FamilyDefault(roughness=0.55, metallic=0.0, tile_size_m=0.35, phrase="natural wood surface, visible grain and subtle pores"),
+ "metal": FamilyDefault(roughness=0.35, metallic=1.0, tile_size_m=0.3, phrase="metal surface albedo only, matte base colour, no reflections or environment"),
+ "fabric": FamilyDefault(roughness=0.9, metallic=0.0, tile_size_m=0.2, phrase="woven textile close-up, visible thread weave, soft matte"),
+ "stone": FamilyDefault(roughness=0.8, metallic=0.0, tile_size_m=0.6, phrase="stone surface, natural mineral variation, matte"),
+ "plastic": FamilyDefault(roughness=0.45, metallic=0.0, tile_size_m=0.3, phrase="smooth plastic surface, subtle fine noise, uniform colour"),
+ "leather": FamilyDefault(roughness=0.6, metallic=0.0, tile_size_m=0.25, phrase="leather surface, fine natural grain and pores, matte"),
+ "glass": FamilyDefault(roughness=0.05, metallic=0.0, tile_size_m=0.3, phrase="clear glass", skip=True),
+ "ceramic": FamilyDefault(roughness=0.3, metallic=0.0, tile_size_m=0.3, phrase="glazed ceramic surface, subtle speckle, uniform colour"),
+ "painted": FamilyDefault(roughness=0.5, metallic=0.0, tile_size_m=0.4, phrase="painted surface, subtle brush or roller micro-texture, uniform colour"),
+ "rubber": FamilyDefault(roughness=0.85, metallic=0.0, tile_size_m=0.2, phrase="matte rubber surface, fine uniform grain"),
+ "other": FamilyDefault(roughness=0.6, metallic=0.0, tile_size_m=0.3, phrase="matte natural surface material, fine detail", skip=True),
+}
+
+_FAMILY_KEYWORDS: list[tuple[str, tuple[str, ...]]] = [
+ ("glass", ("glass", "acrylic", "crystal")),
+ ("metal", ("steel", "iron", "aluminum", "aluminium", "brass", "bronze", "copper", "chrome", "metal", "nickel", "gold", "silver")),
+ ("wood", ("wood", "oak", "walnut", "pine", "teak", "maple", "ash", "beech", "birch", "mahogany", "bamboo", "plywood", "timber")),
+ ("fabric", ("fabric", "linen", "cotton", "velvet", "wool", "upholster", "textile", "canvas", "felt", "cloth", "boucle")),
+ ("leather", ("leather", "suede", "hide")),
+ ("stone", ("stone", "marble", "granite", "concrete", "slate", "terrazzo", "brick", "rock")),
+ ("ceramic", ("ceramic", "porcelain", "terracotta", "clay", "glazed")),
+ ("rubber", ("rubber", "silicone", "foam")),
+ ("painted", ("paint", "lacquer", "enamel", "powder-coated", "powder coated", "varnish")),
+ ("plastic", ("plastic", "abs", "polypropylene", "nylon", "resin", "vinyl", "pvc", "polycarbonate")),
+]
+_SKIP_WORDS = ("chrome", "mirror", "mirrored", "polished", "glossy", "emissive", "led", "transparent", "glass")
+
+
+def _words(text: str) -> set[str]:
+ return set(to_snake(text).split("_"))
+
+
+def family_from_text(text: str) -> str:
+ """Keyword → family on whole words (``oiled`` must not match ``led``)."""
+ ws = _words(text)
+ for fam, words in _FAMILY_KEYWORDS:
+ if any(w in ws for w in words):
+ return fam
+ return "other"
+
+
+def has_skip_word(text: str) -> bool:
+ return bool(_words(text) & set(_SKIP_WORDS))
+
+
+def compose_image_prompt(subject: str, family: str) -> str:
+ """Harness-owned composition: subject + family phrase + the style suffix."""
+ fam = FAMILY_DEFAULTS.get(family, FAMILY_DEFAULTS["other"])
+ subject = " ".join(subject.strip().rstrip(".,;").split())
+ return f"{subject}, {fam.phrase}, {STYLE_SUFFIX}"
+
+
+# --------------------------------------------------------------------------- models
+class TexturePart(BaseModel):
+ part: str = Field(description="plan part name (PascalCase)")
+ texture_id: str = Field(description="snake_case id; parts sharing a material share it")
+ material_family: MaterialFamily = "other"
+ prompt: str = Field(default="", description="full image prompt (harness-composed)")
+ subject: str = Field(default="", description="pattern description from the planner")
+ projection: Projection = "auto"
+ tile_size_m: float = Field(default=0.3, gt=0.0, le=20.0)
+ roughness: float = Field(default=0.6, ge=0.0, le=1.0)
+ metallic: float = Field(default=0.0, ge=0.0, le=1.0)
+ tint_rgb: tuple[float, float, float] | None = None
+ skip: bool = False
+ reason: str = ""
+
+
+class TexturePlan(BaseModel):
+ object_name: str = ""
+ parts: list[TexturePart] = Field(default_factory=list)
+ notes: str = ""
+ model_id: str = ""
+ source: Literal["vlm", "default", "cache"] = "default"
+ usage: Usage = Field(default_factory=Usage)
+
+ def textured(self) -> list[TexturePart]:
+ return [p for p in self.parts if not p.skip]
+
+ def texture_ids(self) -> list[str]:
+ seen: list[str] = []
+ for p in self.textured():
+ if p.texture_id not in seen:
+ seen.append(p.texture_id)
+ return seen
+
+ def prompts(self) -> dict[str, str]:
+ """texture_id → image prompt (first part wins; ids share prompts by construction)."""
+ out: dict[str, str] = {}
+ for p in self.textured():
+ out.setdefault(p.texture_id, p.prompt)
+ return out
+
+ def by_part(self) -> dict[str, TexturePart]:
+ return {to_snake(p.part): p for p in self.parts}
+
+
+class PlannerPart(BaseModel):
+ """What the VLM returns per part (all optional but part/texture_id/subject)."""
+
+ part: str
+ texture_id: str
+ material_family: MaterialFamily = "other"
+ subject: str = ""
+ projection: Projection = "auto"
+ tile_size_m: float | None = None
+ roughness: float | None = None
+ metallic: float | None = None
+ tint_rgb: list[float] | None = None
+ skip: bool = False
+ reason: str = ""
+
+
+class PlannerOutput(BaseModel):
+ parts: list[PlannerPart]
+ notes: str = ""
+
+
+# --------------------------------------------------------------------------- finalise
+def _max_extent(p: PartPlan) -> float:
+ return max(float(e) for e in p.bbox.extents)
+
+
+def _clean_id(s: str, fallback: str) -> str:
+ return to_snake(s) if s.strip() else fallback
+
+
+def finalize_part(raw: PlannerPart, plan_part: PartPlan) -> TexturePart:
+ fam = raw.material_family if raw.material_family in FAMILY_DEFAULTS else "other"
+ d = FAMILY_DEFAULTS[fam]
+ subject = raw.subject.strip() or (plan_part.material.strip() or f"{fam} surface")
+ skip, reason = bool(raw.skip), raw.reason
+ if _max_extent(plan_part) < TINY_PART_M:
+ skip, reason = True, reason or f"tiny part (< {TINY_PART_M * 100:.0f} cm)"
+ if fam == "glass" or d.skip and not raw.subject.strip():
+ skip, reason = True, reason or f"{fam} keeps its flat material"
+ if _words(plan_part.material + " " + subject) & {"chrome", "mirror", "mirrored"}:
+ skip, reason = True, reason or "mirror-like finish"
+ tint = None
+ if raw.tint_rgb and len(raw.tint_rgb) == 3:
+ tint = tuple(min(1.0, max(0.0, float(c))) for c in raw.tint_rgb) # type: ignore[assignment]
+ return TexturePart(
+ part=plan_part.name,
+ texture_id=_clean_id(raw.texture_id, f"{fam}_{to_snake(plan_part.name)}"),
+ material_family=fam, # type: ignore[arg-type]
+ subject=subject,
+ prompt=compose_image_prompt(subject, fam),
+ projection=raw.projection,
+ tile_size_m=float(raw.tile_size_m) if raw.tile_size_m and raw.tile_size_m > 0 else d.tile_size_m,
+ roughness=float(raw.roughness) if raw.roughness is not None else d.roughness,
+ metallic=float(raw.metallic) if raw.metallic is not None else d.metallic,
+ tint_rgb=tint,
+ skip=skip,
+ reason=reason,
+ )
+
+
+def finalize_plan(out: PlannerOutput, plan: StaticPlan, *, model_id: str = "", usage: Usage | None = None,
+ source: Literal["vlm", "default", "cache"] = "vlm") -> TexturePlan:
+ """Validate against the plan parts; unknown names dropped, missing parts defaulted;
+ parts sharing a texture_id are forced onto ONE prompt/family (first wins)."""
+ by_name = {to_snake(p.part): p for p in out.parts}
+ parts: list[TexturePart] = []
+ for pp in plan.parts:
+ raw = by_name.get(to_snake(pp.name))
+ if raw is None:
+ raw = _default_raw(pp)
+ parts.append(finalize_part(raw, pp))
+ unknown = sorted(set(by_name) - {to_snake(p.name) for p in plan.parts})
+ if unknown:
+ log.warning("texture plan: dropping unknown parts %s", unknown)
+ first: dict[str, TexturePart] = {}
+ for tp in parts:
+ if tp.skip:
+ continue
+ head = first.setdefault(tp.texture_id, tp)
+ if head is not tp:
+ tp.prompt, tp.subject, tp.material_family = head.prompt, head.subject, head.material_family
+ return TexturePlan(object_name=plan.object_name, parts=parts, notes=out.notes, model_id=model_id,
+ source=source, usage=usage or Usage())
+
+
+def _default_raw(pp: PartPlan) -> PlannerPart:
+ fam = family_from_text(pp.material or pp.description)
+ skip = fam in ("glass", "other") or has_skip_word(pp.material)
+ words = [w for w in to_snake(pp.material).split("_") if w][:2]
+ tid = "_".join([fam, *words]) if words else fam
+ return PlannerPart(part=pp.name, texture_id=tid, material_family=fam, subject=pp.material.strip(), # type: ignore[arg-type]
+ skip=skip, reason="default plan" if not skip else "default plan: unknown/glass/gloss material")
+
+
+def default_plan(plan: StaticPlan) -> TexturePlan:
+ """Deterministic plan without any model call (keyword heuristics)."""
+ out = PlannerOutput(parts=[_default_raw(p) for p in plan.parts], notes="heuristic default plan")
+ return finalize_plan(out, plan, source="default")
+
+
+# --------------------------------------------------------------------------- prompt + call
+def parts_table(plan: StaticPlan) -> str:
+ rows = []
+ for p in plan.parts:
+ w, d, h = (f"{float(e):.3f}" for e in p.bbox.extents)
+ rows.append(f"- {p.name} · {p.role} · {p.material or '(unspecified)'} · {w}×{d}×{h} · ×{p.instances}")
+ return "\n".join(rows)
+
+
+def _sheet_images(renders: RenderSet | Path | str | Sequence[Path | str] | None, max_views: int = 4) -> list[Path]:
+ if renders is None:
+ return []
+ if isinstance(renders, RenderSet):
+ if renders.contact_sheet and Path(renders.contact_sheet).is_file():
+ return [Path(renders.contact_sheet)]
+ return [Path(v.path) for v in renders.views[:max_views] if Path(v.path).is_file()]
+ if isinstance(renders, (str, Path)):
+ return [Path(renders)] if Path(renders).is_file() else []
+ return [Path(p) for p in renders if Path(p).is_file()][:max_views]
+
+
+def plan_cache_key(spec: Spec, plan: StaticPlan, images: Sequence[Path], model_id: str) -> str:
+ h = hashlib.sha256()
+ h.update(prompt_hash(load_text(PLAN_TEMPLATE)).encode())
+ h.update(spec.prompt.encode())
+ h.update(plan.model_dump_json().encode())
+ h.update(model_id.encode())
+ for p in images:
+ h.update(hashlib.sha256(p.read_bytes()).hexdigest().encode())
+ return h.hexdigest()[:20]
+
+
+def material_plan(
+ spec: Spec,
+ plan: StaticPlan,
+ renders: RenderSet | Path | str | Sequence[Path | str] | None,
+ model_id: str,
+ *,
+ model: Any | None = None,
+ cache_dir: Path | None = None,
+ use_cache: bool = True,
+ temperature: float = 0.3,
+) -> TexturePlan:
+ """One structured vision call → validated ``TexturePlan``. ``model`` may be any
+ ``ChatModel`` (tests inject a fake); empty ``model_id`` and no model → default plan."""
+ if not model_id and model is None:
+ return default_plan(plan)
+ images = _sheet_images(renders)
+ cache_root = (cache_dir or get_settings().cache_dir) / "texture_plans"
+ key = plan_cache_key(spec, plan, images, model_id)
+ cached = cache_root / f"{key}.json"
+ if use_cache and cached.is_file():
+ try:
+ tp = TexturePlan.model_validate_json(cached.read_text())
+ tp.source, tp.usage = "cache", Usage()
+ return tp
+ except ValidationError:
+ cached.unlink(missing_ok=True)
+ if model is None:
+ from codeverse.models import get_chat_model
+
+ model = get_chat_model(model_id)
+ text = render(PLAN_TEMPLATE, spec_prompt=spec.prompt, style_notes=getattr(plan, "style_notes", ""),
+ n_parts=len(plan.parts), parts_table=parts_table(plan))
+ req = ChatRequest(
+ messages=[ChatMessage.user(text, images=[ImagePart(path=str(p), label=p.stem) for p in images])],
+ system="You plan PBR textures for 3D assets. Answer with JSON only.",
+ response_schema=PlannerOutput.model_json_schema(), temperature=temperature, thinking="low",
+ max_output_tokens=8000, label="texture_plan",
+ )
+ resp = model.generate(req)
+ payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
+ try:
+ out = PlannerOutput.model_validate(payload)
+ except ValidationError as e:
+ raise ValueError(f"texture planner returned invalid JSON for the schema: {e}") from e
+ tp = finalize_plan(out, plan, model_id=model_id, usage=resp.usage, source="vlm")
+ if use_cache:
+ cache_root.mkdir(parents=True, exist_ok=True)
+ cached.write_text(tp.model_dump_json(indent=2))
+ return tp
+
+
+def plan_table(tp: TexturePlan) -> str:
+ """Human-readable summary (CLI / report)."""
+ rows = [f"{'part':24} {'texture_id':20} {'family':8} {'proj':9} {'tile':6} {'rough':5} {'met':4} skip"]
+ for p in tp.parts:
+ rows.append(f"{p.part:24} {p.texture_id:20} {p.material_family:8} {p.projection:9} {p.tile_size_m:<6.2f} "
+ f"{p.roughness:<5.2f} {p.metallic:<4.1f} {'yes' if p.skip else 'no'}{(' — ' + p.reason) if p.skip and p.reason else ''}")
+ return "\n".join(rows)
+
+
+def plan_to_json(tp: TexturePlan) -> dict[str, Any]:
+ return json.loads(tp.model_dump_json())
diff --git a/harness/codeverse/texturing/run.py b/harness/codeverse/texturing/run.py
new file mode 100644
index 00000000..599d76a6
--- /dev/null
+++ b/harness/codeverse/texturing/run.py
@@ -0,0 +1,229 @@
+"""``texture_pass``: the orchestrating entry for object texturing.
+
+ renders (latest sheet or a quick render) → material_plan (1 vision call)
+ → generate_textures (image model, cached, parallel) → seam_gate
+ → apply_textures → artifacts/object_textured.glb
+ → judge_gate (before/after, n=1) → TextureReport (+ artifacts/texturing.json,
+ record.json extra["texturing"] when a record exists)
+
+Code stays the truth: ``artifacts/object.glb`` is never overwritten; the textured
+GLB and ``artifacts/textures/`` are a derived asset pack recorded with the run.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import Measurement, RenderSet
+from codeverse.contracts.common import Track, Usage
+from codeverse.contracts.plan import StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
+from codeverse.events import EventLog
+from codeverse.texturing.apply import ApplyReport, apply_textures
+from codeverse.texturing.gate import GateResult, SeamGateResult, judge_gate, seam_gate
+from codeverse.texturing.generate import TextureSet, generate_textures
+from codeverse.texturing.plan import TexturePlan, material_plan
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+TEXTURED_GLB = "object_textured.glb"
+TEXTURES_DIR = "textures"
+REPORT_NAME = "texturing.json"
+RUBRIC_BY_TRACK: dict[Track, str] = {
+ Track.STATIC_OBJECT: "static_object_v1",
+ Track.ARTICULATED_OBJECT: "articulated_v1",
+}
+
+
+class TextureReport(BaseModel):
+ plan: TexturePlan
+ textures: TextureSet
+ seam: SeamGateResult
+ apply: ApplyReport | None = None
+ gate: GateResult | None = None
+ glb_in: str
+ glb_out: str = ""
+ shipped: bool = False
+ delta: float | None = None
+ usage: Usage = Field(default_factory=Usage)
+ duration_s: float = 0.0
+ notes: list[str] = Field(default_factory=list)
+
+ def summary(self) -> dict[str, Any]:
+ return {
+ "shipped": self.shipped, "delta": self.delta, "glb_out": self.glb_out,
+ "n_textures": len(self.textures.paths()), "seam_failed": sorted(self.seam.failed),
+ "parts_textured": len(self.apply.parts_textured) if self.apply else 0,
+ "materials_delta": self.gate.materials_delta if self.gate else None,
+ "cost_usd": round(self.usage.cost_usd, 4), "duration_s": self.duration_s,
+ "plan_source": self.plan.source, "reason": self.gate.reason if self.gate else "; ".join(self.notes),
+ }
+
+
+def latest_sheet(ws: Workspace) -> Path | None:
+ """The most recent round's contact sheet (``artifacts/renders/rNN/sheet.png``)."""
+ rdir = ws.artifacts / "renders"
+ if not rdir.is_dir():
+ return None
+ rounds = sorted((p for p in rdir.glob("r[0-9][0-9]") if (p / "sheet.png").is_file()), key=lambda p: p.name)
+ return rounds[-1] / "sheet.png" if rounds else None
+
+
+def _render_quick(glb: Path, out_dir: Path, views: Sequence[ViewPreset], render: Any | None) -> RenderSet:
+ if render is None:
+ from codeverse.spatial.render import render_glb
+
+ render = render_glb
+ return render(glb, out_dir, views=list(views), width=512, height=512)
+
+
+def _measure(glb: Path) -> Measurement | None:
+ try:
+ from codeverse.spatial.measure import measure_glb
+
+ return measure_glb(glb)
+ except Exception as e: # noqa: BLE001 — measurement is judge context only
+ log.warning("measure_glb failed for texture gate: %s", e)
+ return None
+
+
+def texture_pass(
+ ws: Workspace,
+ spec: Spec,
+ plan: StaticPlan,
+ *,
+ model_id: str,
+ image_model: Any | None = None,
+ judge: bool | Any = True,
+ judge_model_id: str | None = None,
+ rubric: str | None = None,
+ glb_in: Path | None = None,
+ views: Sequence[ViewPreset] = OBJECT_VIEWS_QUICK,
+ size: int = 1024,
+ plan_model: Any | None = None,
+ render: Any | None = None,
+ cache_dir: Path | None = None,
+ events: EventLog | None = None,
+ update_record: bool = True,
+) -> TextureReport:
+ """Run the whole pass on ``ws``. ``judge`` may be ``True`` (build a VlmJudge on
+ ``judge_model_id or spec.backends.judge``), ``False`` (skip the gate → ship iff
+ something was textured and no seam failed) or a judge object (tests)."""
+ t0 = time.time()
+ events = events or EventLog(ws.events_path)
+ glb_in = Path(glb_in) if glb_in else ws.artifacts / "object.glb"
+ if not glb_in.is_file():
+ raise FileNotFoundError(f"no GLB to texture: {glb_in}")
+ tex_dir = ws.artifacts / TEXTURES_DIR
+ glb_out = ws.artifacts / TEXTURED_GLB
+ notes: list[str] = []
+ events.emit("texture.start", model=model_id, glb=glb_in.name)
+
+ # 1. renders for the planner (reuse the latest sheet; else a quick render)
+ sheet = latest_sheet(ws)
+ if sheet is None:
+ rs = _render_quick(glb_in, tex_dir / "planner_views", views, render)
+ sheet = Path(rs.contact_sheet) if rs.contact_sheet else (Path(rs.views[0].path) if rs.views else None)
+
+ # 2. material plan
+ tplan = material_plan(spec, plan, sheet, model_id, model=plan_model, cache_dir=cache_dir)
+ usage = tplan.usage
+ events.emit("texture.plan", source=tplan.source, n_parts=len(tplan.parts), n_textured=len(tplan.textured()),
+ n_textures=len(tplan.texture_ids()), cost_usd=round(tplan.usage.cost_usd, 4))
+ ws.write_json(tex_dir / "texture_plan.json", tplan)
+
+ # 3. images
+ if image_model is None:
+ from codeverse.models.gemini_image import GeminiImageModel
+
+ image_model = GeminiImageModel()
+ tset = generate_textures(tplan, tex_dir, image_model, size=size, cache_dir=cache_dir)
+ usage = usage + tset.usage
+ seam = seam_gate(tset.textures)
+ events.emit("texture.generated", n=len(tset.textures), failed=sorted(tset.failed()), seam_failed=sorted(seam.failed),
+ cost_usd=round(tset.usage.cost_usd, 4), duration_s=tset.duration_s)
+ for tid, err in tset.failed().items():
+ notes.append(f"texture {tid} failed: {err}")
+ keep = {tid: Path(tset.textures[tid].path) for tid in seam.passed}
+ report = TextureReport(plan=tplan, textures=tset, seam=seam, glb_in=str(glb_in), usage=usage, notes=notes)
+ notes = report.notes # pydantic copied the list; keep appending to the report's own
+ if not keep:
+ notes.append("no usable textures (all failed or seams too strong) — nothing applied")
+ return _finish(ws, report, t0, events, update_record)
+
+ # 4. apply
+ report.apply = apply_textures(glb_in, tplan, keep, glb_out)
+ report.glb_out = str(glb_out)
+ notes.extend(report.apply.warnings)
+ events.emit("texture.applied", parts=len(report.apply.parts_textured), skipped=len(report.apply.parts_skipped),
+ materials=report.apply.n_materials, warnings=len(report.apply.warnings))
+ if not report.apply.parts_textured:
+ notes.append("no part was textured")
+ return _finish(ws, report, t0, events, update_record)
+
+ # 5. gate
+ if judge is False:
+ report.shipped = True
+ notes.append("judge gate skipped (--no-judge): shipped on seam gate only")
+ return _finish(ws, report, t0, events, update_record)
+ judge_obj = judge if judge is not True else _make_judge(spec, rubric, judge_model_id)
+ gate = judge_gate(spec, plan, glb_in, glb_out, tex_dir / "gate", judge=judge_obj, measurement=_measure(glb_in),
+ views=views, render=render)
+ report.gate, report.shipped, report.delta = gate, gate.shipped, gate.delta
+ report.usage = report.usage + gate.usage
+ events.emit("texture.gate", shipped=gate.shipped, delta=gate.delta, materials_delta=gate.materials_delta,
+ before=gate.overall_before, after=gate.overall_after, reason=gate.reason,
+ cost_usd=round(gate.usage.cost_usd, 4))
+ return _finish(ws, report, t0, events, update_record)
+
+
+def _make_judge(spec: Spec, rubric: str | None, judge_model_id: str | None) -> Any:
+ from codeverse.judges.vlm_judge import VlmJudge
+
+ name = rubric or RUBRIC_BY_TRACK.get(spec.track, "static_object_v1")
+ return VlmJudge(rubric=name, model_id=judge_model_id or spec.backends.judge, n_samples=1, label="texture_gate")
+
+
+def _finish(ws: Workspace, report: TextureReport, t0: float, events: EventLog, update_record: bool) -> TextureReport:
+ report.duration_s = round(time.time() - t0, 2)
+ ws.write_json(ws.artifacts / TEXTURES_DIR / REPORT_NAME, report)
+ if update_record:
+ record_texturing(ws, report)
+ events.emit("texture.done", **report.summary())
+ return report
+
+
+def record_texturing(ws: Workspace, report: TextureReport) -> bool:
+ """``record.json`` extra["texturing"] = summary (+ asset paths) when a record exists."""
+ if not ws.record_path.is_file():
+ return False
+ try:
+ data = json.loads(ws.record_path.read_text())
+ except json.JSONDecodeError:
+ return False
+ extra = data.setdefault("extra", {})
+ extra["texturing"] = {
+ **report.summary(),
+ "glb_textured": str(Path(report.glb_out).relative_to(ws.root)) if report.glb_out else "",
+ "textures_dir": f"artifacts/{TEXTURES_DIR}",
+ "textures": {tid: Path(a.path).name for tid, a in report.textures.textures.items() if a.ok},
+ "texture_plan": {p.part: p.texture_id for p in report.plan.textured()},
+ }
+ ws.write_json(ws.record_path, data)
+ return True
+
+
+def load_report(ws: Workspace) -> TextureReport:
+ p = ws.artifacts / TEXTURES_DIR / REPORT_NAME
+ if not p.is_file():
+ raise FileNotFoundError(f"no texturing report at {p}")
+ return TextureReport.model_validate_json(p.read_text())
diff --git a/harness/codeverse/texturing/scene_pack.py b/harness/codeverse/texturing/scene_pack.py
new file mode 100644
index 00000000..7807c52a
--- /dev/null
+++ b/harness/codeverse/texturing/scene_pack.py
@@ -0,0 +1,239 @@
+"""Scene texture pack: the 6-12 tileable albedo textures a ``ScenePlan`` implies,
+generated BEFORE zone generation so scene code can load them.
+
+* ``scene_pack_plan(plan, model_id)``: one text-only structured call → entries
+ (name, family, subject, tile size, role, PBR factors); ``default_scene_pack_plan``
+ is the keyword fallback (no model).
+* ``scene_texture_pack(plan, out_dir, image_model, model_id)``: generate + seam-fix
+ → ``out_dir/<name>.png`` + ``out_dir/manifest.json``
+ ``{name: {file, tile_size_m, family, role, prompt, seam_score}}``.
+* ``texture_pack_prompt(manifest)``: the snippet the scene track injects into zone /
+ env prompts (URL, tile size, exact three.js loading lines).
+
+Served URL: the workspace root is served at ``/`` (``runtime_js/lib/_compat.mjs``),
+so ``public/textures/<name>.png`` is reachable as ``/public/textures/<name>.png``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field, ValidationError
+
+from codeverse.contracts.chat import ChatMessage, ChatRequest
+from codeverse.contracts.common import Usage
+from codeverse.contracts.plan import ScenePlan
+from codeverse.conventions import to_snake
+from codeverse.models.schema_utils import parse_json_lenient
+from codeverse.prompts import render
+from codeverse.texturing.generate import TextureSet, generate_textures
+from codeverse.texturing.plan import FAMILY_DEFAULTS, MaterialFamily, compose_image_prompt
+
+log = logging.getLogger(__name__)
+
+PACK_TEMPLATE = "texturing/scene_pack.md"
+DEFAULT_URL_PREFIX = "/public/textures"
+MANIFEST_NAME = "manifest.json"
+
+
+class PackEntry(BaseModel):
+ name: str
+ material_family: MaterialFamily = "other"
+ subject: str = ""
+ prompt: str = ""
+ tile_size_m: float = Field(default=1.0, gt=0.0, le=50.0)
+ role: str = "ground"
+ roughness: float = Field(default=0.8, ge=0.0, le=1.0)
+ metallic: float = Field(default=0.0, ge=0.0, le=1.0)
+ file: str = ""
+ seam_score: float = 0.0
+ error: str = ""
+
+
+class PackOutput(BaseModel):
+ textures: list[PackEntry]
+ notes: str = ""
+
+
+class ScenePack(BaseModel):
+ out_dir: str
+ entries: dict[str, PackEntry] = Field(default_factory=dict)
+ notes: str = ""
+ model_id: str = ""
+ source: str = "default"
+ usage: Usage = Field(default_factory=Usage)
+ manifest_path: str = ""
+
+ def manifest(self) -> dict[str, dict[str, Any]]:
+ return {n: {"file": e.file, "tile_size_m": e.tile_size_m, "family": e.material_family, "role": e.role,
+ "prompt": e.prompt, "seam_score": e.seam_score, "roughness": e.roughness, "metallic": e.metallic}
+ for n, e in self.entries.items() if e.file and not e.error}
+
+
+# --------------------------------------------------------------------------- planning
+_GROUND_RULES: list[tuple[tuple[str, ...], PackEntry]] = [
+ (("grass", "lawn", "meadow", "garden", "park"), PackEntry(name="grass_ground", subject="short green lawn grass seen from above, fine blades, slight colour variation", tile_size_m=1.5, role="ground")),
+ (("moss", "mossy", "forest", "woodland"), PackEntry(name="moss_ground", subject="dense green moss carpet, soft velvety clumps", tile_size_m=1.0, role="ground")),
+ (("gravel", "karesansui", "zen", "raked"), PackEntry(name="fine_gravel", material_family="stone", subject="fine pale grey granite gravel, small even pebbles", tile_size_m=0.8, role="ground")),
+ (("sand", "beach", "desert", "dune"), PackEntry(name="sand_ground", subject="fine pale beige sand with soft ripples", tile_size_m=1.0, role="ground")),
+ (("soil", "dirt", "earth", "mud", "path", "trail"), PackEntry(name="packed_soil", subject="dark brown packed earth with small pebbles", tile_size_m=1.0, role="path")),
+ (("cobble", "pavement", "plaza", "street", "square", "town"), PackEntry(name="cobblestone", material_family="stone", subject="grey granite cobblestones with dark mortar joints", tile_size_m=1.2, role="path")),
+ (("stone", "rock", "boulder", "granite", "cliff"), PackEntry(name="rough_granite", material_family="stone", subject="rough grey granite rock with lichen speckles", tile_size_m=1.0, role="prop")),
+ (("wood", "plank", "bridge", "deck", "dock", "pier", "timber", "cabin", "fence"), PackEntry(name="weathered_planks", material_family="wood", subject="weathered grey-brown wooden planks, straight grain, narrow gaps", tile_size_m=0.8, role="prop")),
+ (("roof", "tile", "shingle", "house", "temple", "hut"), PackEntry(name="clay_roof_tiles", material_family="ceramic", subject="terracotta clay roof tiles in overlapping rows", tile_size_m=1.0, role="roof")),
+ (("brick", "wall"), PackEntry(name="red_brick", material_family="stone", subject="red clay bricks with light grey mortar, running bond", tile_size_m=1.0, role="wall")),
+ (("bark", "tree", "trunk", "maple", "oak", "pine"), PackEntry(name="tree_bark", material_family="wood", subject="dark grey-brown tree bark with vertical furrows", tile_size_m=0.5, role="prop")),
+ (("water", "pond", "lake", "river", "sea", "harbour", "harbor"), PackEntry(name="pond_bed", material_family="stone", subject="dark silty pond bed with scattered small pebbles and algae", tile_size_m=1.0, role="water_bed")),
+ (("fabric", "tent", "cloth", "banner", "awning", "canvas"), PackEntry(name="canvas_fabric", material_family="fabric", subject="natural off-white woven canvas", tile_size_m=0.3, role="fabric")),
+ (("metal", "steel", "iron", "rust"), PackEntry(name="rusty_steel", material_family="metal", subject="rust-streaked painted steel plate, matte", tile_size_m=0.5, role="prop")),
+ (("concrete", "asphalt", "road", "industrial"), PackEntry(name="concrete", material_family="stone", subject="smooth grey concrete with fine pores", tile_size_m=1.0, role="ground")),
+ (("bamboo",), PackEntry(name="bamboo_poles", material_family="wood", subject="vertical cured yellow bamboo poles with dark nodes", tile_size_m=0.5, role="prop")),
+]
+
+
+def _plan_text(plan: ScenePlan) -> str:
+ bits = [plan.title, plan.summary, plan.setting, plan.mood, plan.environment]
+ bits += [f"{z.name} {z.description}" for z in plan.zones]
+ bits += [f"{a.name} {a.description}" for a in plan.assets]
+ return " ".join(bits)
+
+
+def _finalize_entry(e: PackEntry) -> PackEntry:
+ fam = e.material_family if e.material_family in FAMILY_DEFAULTS else "other"
+ d = FAMILY_DEFAULTS[fam]
+ name = to_snake(e.name) or f"{fam}_texture"
+ subject = e.subject.strip() or name.replace("_", " ")
+ return e.model_copy(update={
+ "name": name, "material_family": fam, "subject": subject, "prompt": compose_image_prompt(subject, fam),
+ "tile_size_m": float(e.tile_size_m) if e.tile_size_m > 0 else d.tile_size_m,
+ "roughness": float(e.roughness) if e.roughness is not None else d.roughness,
+ "metallic": float(e.metallic) if e.metallic is not None else d.metallic,
+ })
+
+
+def default_scene_pack_plan(plan: ScenePlan, *, n_min: int = 6, n_max: int = 12) -> list[PackEntry]:
+ """Keyword fallback: textures whose trigger words appear in the plan; always a
+ ground; padded with generic ground/stone/wood up to ``n_min``."""
+ words = set(to_snake(_plan_text(plan)).split("_"))
+ out: list[PackEntry] = []
+ for keys, entry in _GROUND_RULES:
+ if any(k in words for k in keys) and len(out) < n_max:
+ out.append(entry)
+ names = {e.name for e in out}
+ for _, entry in _GROUND_RULES:
+ if len(out) >= n_min:
+ break
+ if entry.name not in names:
+ out.append(entry)
+ names.add(entry.name)
+ return [_finalize_entry(e) for e in out[:n_max]]
+
+
+def scene_pack_plan(
+ plan: ScenePlan, model_id: str, *, model: Any | None = None, n_min: int = 6, n_max: int = 12, temperature: float = 0.4,
+) -> tuple[list[PackEntry], str, Usage]:
+ """Structured text call → entries. Empty ``model_id`` and no model → default plan."""
+ if not model_id and model is None:
+ return default_scene_pack_plan(plan, n_min=n_min, n_max=n_max), "default", Usage()
+ if model is None:
+ from codeverse.models import get_chat_model
+
+ model = get_chat_model(model_id)
+ zones = "\n".join(f"- {z.name}: {z.description}" for z in plan.zones)
+ assets = "\n".join(f"- {a.name} ({a.kind}): {a.description}" for a in plan.assets) or "- (none)"
+ text = render(PACK_TEMPLATE, n_min=n_min, n_max=n_max, title=plan.title, setting=plan.setting, mood=plan.mood,
+ environment=plan.environment, zones=zones, assets=assets)
+ req = ChatRequest(messages=[ChatMessage.user(text)], system="You plan texture packs for 3D scenes. JSON only.",
+ response_schema=PackOutput.model_json_schema(), temperature=temperature, thinking="low",
+ max_output_tokens=8000, label="scene_texture_pack")
+ resp = model.generate(req)
+ payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
+ try:
+ out = PackOutput.model_validate(payload)
+ except ValidationError as e:
+ raise ValueError(f"scene pack planner returned invalid JSON: {e}") from e
+ entries: list[PackEntry] = []
+ seen: set[str] = set()
+ for e in out.textures:
+ fe = _finalize_entry(e)
+ if fe.name in seen:
+ continue
+ seen.add(fe.name)
+ entries.append(fe)
+ if not entries:
+ raise ValueError("scene pack planner returned no textures")
+ return entries[:n_max], out.notes, resp.usage
+
+
+# --------------------------------------------------------------------------- generation
+def scene_texture_pack(
+ scene_plan: ScenePlan,
+ out_dir: Path,
+ image_model: Any,
+ model_id: str = "",
+ *,
+ model: Any | None = None,
+ size: int = 1024,
+ cache_dir: Path | None = None,
+ n_min: int = 6,
+ n_max: int = 12,
+ max_workers: int = 6,
+ use_cache: bool = True,
+) -> ScenePack:
+ """Plan + generate the pack into ``out_dir`` and write ``manifest.json``."""
+ out_dir = Path(out_dir)
+ entries, notes, usage = scene_pack_plan(scene_plan, model_id, model=model, n_min=n_min, n_max=n_max)
+ pack = ScenePack(out_dir=str(out_dir), notes=notes, model_id=model_id, source="vlm" if (model_id or model) else "default",
+ usage=usage)
+ ts: TextureSet = generate_textures({e.name: e.prompt for e in entries}, out_dir, image_model, size=size,
+ cache_dir=cache_dir, max_workers=max_workers, use_cache=use_cache)
+ pack.usage = pack.usage + ts.usage
+ for e in entries:
+ a = ts.textures.get(e.name)
+ if a is None:
+ continue
+ e = e.model_copy(update={"file": Path(a.path).name if a.ok else "", "seam_score": round(a.seam_score, 4), "error": a.error})
+ pack.entries[e.name] = e
+ pack.manifest_path = str(write_manifest(pack, out_dir))
+ return pack
+
+
+def write_manifest(pack: ScenePack, out_dir: Path) -> Path:
+ p = Path(out_dir) / MANIFEST_NAME
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps(pack.manifest(), indent=2))
+ return p
+
+
+def load_manifest(path: Path) -> dict[str, dict[str, Any]]:
+ p = Path(path)
+ if p.is_dir():
+ p = p / MANIFEST_NAME
+ return json.loads(p.read_text())
+
+
+def texture_pack_prompt(manifest: dict[str, dict[str, Any]], *, url_prefix: str = DEFAULT_URL_PREFIX) -> str:
+ """Prompt snippet for zone/env generation: what exists and the exact loading idiom."""
+ if not manifest:
+ return ""
+ lines = ["## Available textures (seamless tileable albedo PNGs, generated for this scene)"]
+ for name, e in manifest.items():
+ lines.append(f"- `{url_prefix}/{e['file']}` — {name} ({e.get('family', 'other')}, {e.get('role', '')}; "
+ f"one tile = {float(e['tile_size_m']):.2f} m; roughness {float(e.get('roughness', 0.8)):.2f})")
+ lines.append(
+ "Load with the provided loader ONLY (no TextureLoader of your own, no DataTexture):\n"
+ "```js\n"
+ f"const tex = loaders.texture.load('{url_prefix}/{next(iter(manifest.values()))['file']}');\n"
+ "tex.wrapS = tex.wrapT = THREE.RepeatWrapping;\n"
+ "tex.colorSpace = THREE.SRGBColorSpace;\n"
+ "tex.anisotropy = 8;\n"
+ "tex.repeat.set(sizeX / TILE_M, sizeZ / TILE_M); // TILE_M = the tile size listed above, sizeX/Z = the surface's world size in m\n"
+ "const mat = new THREE.MeshStandardMaterial({ map: tex, roughness: 0.8, metalness: 0.0 });\n"
+ "```\n"
+ "Use `texture.clone()` (+ `needsUpdate = true`) when the same image needs a different repeat. "
+ "Keep vertex-colour / procedural materials where no texture fits; never invent texture URLs."
+ )
+ return "\n".join(lines)
diff --git a/harness/codeverse/texturing/tile.py b/harness/codeverse/texturing/tile.py
new file mode 100644
index 00000000..7edbd501
--- /dev/null
+++ b/harness/codeverse/texturing/tile.py
@@ -0,0 +1,118 @@
+"""Tileability: seam scoring, mirror-blend seam fixing, resizing and saving.
+
+* ``seam_score(img)``: mean absolute difference (0..1) between the left/right and
+ top/bottom wrap edges, normalised by the image's own local contrast so a noisy
+ texture is not penalised for being noisy. ≈0 = perfect wrap.
+* ``make_tileable(img, border_frac)``: cross-fades each edge band with the mirrored
+ opposite band (a smoothstep ramp over ``border_frac`` of the width) so the wrap
+ seam disappears; content in the middle is untouched.
+* ``offset_check(img)``: half-offset the image (seams move to the centre) — the
+ classic visual check; returns the offset image for inspection.
+* ``fit_size`` / ``save_texture``: power-of-two downscale + PNG or JPEG q90.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+#: seam score above which a texture is considered NOT tileable (after make_tileable)
+SEAM_MAX = 0.08
+
+
+def _arr(img: Image.Image) -> np.ndarray:
+ return np.asarray(img.convert("RGB"), dtype=np.float32) / 255.0
+
+
+def seam_score(img: Image.Image | np.ndarray) -> float:
+ """Mean |Δ| across the wrap seams relative to the mean |Δ| between neighbouring
+ pixel columns/rows inside the image (so 1.0 ≈ 'the seam is as strong as the
+ texture's own detail'); clamped to [0, 1]."""
+ a = _arr(img) if isinstance(img, Image.Image) else np.asarray(img, dtype=np.float32)
+ if a.ndim == 2:
+ a = a[:, :, None]
+ h, w = a.shape[:2]
+ if h < 4 or w < 4:
+ return 0.0
+ seam_lr = np.abs(a[:, 0, :] - a[:, -1, :]).mean()
+ seam_tb = np.abs(a[0, :, :] - a[-1, :, :]).mean()
+ # typical one-step difference inside the image (excluding the seam)
+ inner_lr = np.abs(a[:, 1:, :] - a[:, :-1, :]).mean()
+ inner_tb = np.abs(a[1:, :, :] - a[:-1, :, :]).mean()
+ # a seam is bad when it exceeds the local detail noticeably; blend absolute + relative
+ rel = 0.5 * (seam_lr / max(inner_lr, 1e-3) + seam_tb / max(inner_tb, 1e-3))
+ absolute = 0.5 * (seam_lr + seam_tb)
+ score = 0.5 * absolute + 0.5 * min(1.0, max(0.0, (rel - 1.0) / 8.0))
+ return float(min(1.0, max(0.0, score)))
+
+
+def _ramp(n: int) -> np.ndarray:
+ t = (np.arange(n, dtype=np.float32) + 0.5) / n
+ return t * t * (3.0 - 2.0 * t) # smoothstep 0 → 1
+
+
+def make_tileable(img: Image.Image, border_frac: float = 0.12) -> Image.Image:
+ """Mirror-blend the wrap seams. Along X: the left band is cross-faded with the
+ mirrored right band and vice versa (weights symmetric so the wrap is exact);
+ then the same along Y. ``border_frac`` ∈ [0.05, 0.3] of the size."""
+ border_frac = float(min(0.3, max(0.05, border_frac)))
+ a = _arr(img)
+ h, w = a.shape[:2]
+ bw, bh = max(2, int(round(w * border_frac))), max(2, int(round(h * border_frac)))
+ out = a.copy()
+ # horizontal: blend left band with mirrored right band
+ r = _ramp(bw)[None, :, None] # 0 at the outer edge → 1 inside
+ left, right = a[:, :bw, :], a[:, w - bw:, :]
+ mir_right = right[:, ::-1, :] # right band mirrored so its outer edge meets the left edge
+ mir_left = left[:, ::-1, :]
+ out[:, :bw, :] = left * (0.5 + 0.5 * r) + mir_right * (0.5 - 0.5 * r)
+ out[:, w - bw:, :] = right * (0.5 + 0.5 * r[:, ::-1, :]) + mir_left * (0.5 - 0.5 * r[:, ::-1, :])
+ a = out.copy()
+ r = _ramp(bh)[:, None, None]
+ top, bottom = a[:bh, :, :], a[h - bh:, :, :]
+ mir_bottom, mir_top = bottom[::-1, :, :], top[::-1, :, :]
+ out[:bh, :, :] = top * (0.5 + 0.5 * r) + mir_bottom * (0.5 - 0.5 * r)
+ out[h - bh:, :, :] = bottom * (0.5 + 0.5 * r[::-1, :, :]) + mir_top * (0.5 - 0.5 * r[::-1, :, :])
+ return Image.fromarray((np.clip(out, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8), "RGB")
+
+
+def offset_check(img: Image.Image) -> Image.Image:
+ """Roll the image by half its size so the wrap seams sit in the centre."""
+ a = _arr(img)
+ h, w = a.shape[:2]
+ rolled = np.roll(np.roll(a, w // 2, axis=1), h // 2, axis=0)
+ return Image.fromarray((rolled * 255.0 + 0.5).astype(np.uint8), "RGB")
+
+
+def fit_size(img: Image.Image, size: int) -> Image.Image:
+ """Square, power-of-two-ish downscale to ``size`` (never upscales)."""
+ w, h = img.size
+ if w != h:
+ s = min(w, h)
+ img = img.crop(((w - s) // 2, (h - s) // 2, (w - s) // 2 + s, (h - s) // 2 + s))
+ if img.size[0] > size:
+ img = img.resize((size, size), Image.LANCZOS)
+ return img.convert("RGB")
+
+
+def save_texture(img: Image.Image, path: Path, *, fmt: str | None = None, quality: int = 90) -> Path:
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fmt = (fmt or ("JPEG" if path.suffix.lower() in (".jpg", ".jpeg") else "PNG")).upper()
+ if fmt == "JPEG":
+ img.convert("RGB").save(path, "JPEG", quality=quality, optimize=True)
+ else:
+ img.convert("RGB").save(path, "PNG", optimize=True)
+ return path
+
+
+def tile_preview(img: Image.Image, reps: int = 2, size: int = 512) -> Image.Image:
+ """``reps × reps`` repetition for eyeballing tileability."""
+ t = img.convert("RGB").resize((size // reps, size // reps), Image.LANCZOS)
+ out = Image.new("RGB", (t.size[0] * reps, t.size[1] * reps))
+ for i in range(reps):
+ for j in range(reps):
+ out.paste(t, (i * t.size[0], j * t.size[1]))
+ return out
diff --git a/harness/codeverse/texturing/uv.py b/harness/codeverse/texturing/uv.py
new file mode 100644
index 00000000..a263443e
--- /dev/null
+++ b/harness/codeverse/texturing/uv.py
@@ -0,0 +1,176 @@
+"""Analytic UVs per part: box (per-face dominant axis), cylinder (around the long
+axis, planar caps) or planar projections, all in WORLD metres divided by
+``tile_size_m`` so a pattern has the same physical size on every part.
+
+Vertices are split only where two incident faces disagree on the projection key
+(box axis, cylinder seam / cap) so smooth shading is preserved elsewhere; vertex
+normals are carried along. The mesh geometry (positions, node transforms) is
+never changed — only TEXCOORD_0 is added.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+#: long/mid extent ratio above which ``auto`` picks a cylinder projection ...
+CYLINDER_ASPECT = 2.5
+#: ... provided the cross-section is roughly round (mid/min below this); slabs → box
+CYLINDER_SECTION = 2.0
+#: |n · axis| above which a face is a cylinder cap (planar projected)
+CAP_COS = 0.75
+
+
+@dataclass
+class Unwrapped:
+ vertices: np.ndarray # (N', 3) LOCAL coordinates (possibly split)
+ faces: np.ndarray # (F, 3)
+ normals: np.ndarray | None # (N', 3) local normals or None
+ uv: np.ndarray # (N', 2)
+ projection: str # box | cylinder | planar_y | planar_z
+ axis: int # projection axis (cylinder axis / planar normal axis)
+ n_split: int # vertices added by seam splitting
+
+
+def choose_projection(extents_world: np.ndarray, requested: str) -> tuple[str, int]:
+ """Resolve ``auto`` → (projection, axis). Elongated with a round-ish section →
+ cylinder around the long axis; everything else (slabs, boxes, frames) → box. Explicit projections pass through (cylinder axis =
+ the longest world axis; planar axes are fixed: planar_y → 1, planar_z → 2)."""
+ e = np.asarray(extents_world, dtype=float)
+ order = np.argsort(e)[::-1]
+ long_axis = int(order[0])
+ if requested == "cylinder":
+ return "cylinder", long_axis
+ if requested == "planar_y":
+ return "planar_y", 1
+ if requested == "planar_z":
+ return "planar_z", 2
+ if requested == "box":
+ return "box", int(np.argmin(e))
+ mid = max(float(e[order[1]]), 1e-9)
+ small = max(float(e[order[2]]), 1e-9)
+ if float(e[order[0]]) / mid >= CYLINDER_ASPECT and mid / small <= CYLINDER_SECTION:
+ return "cylinder", long_axis
+ return "box", int(np.argmin(e))
+
+
+def _face_normals(P: np.ndarray, F: np.ndarray) -> np.ndarray:
+ a, b, c = P[F[:, 0]], P[F[:, 1]], P[F[:, 2]]
+ n = np.cross(b - a, c - a)
+ ln = np.linalg.norm(n, axis=1, keepdims=True)
+ return n / np.maximum(ln, 1e-12)
+
+
+def _box_uv(P: np.ndarray, F: np.ndarray, tile: float) -> tuple[np.ndarray, np.ndarray]:
+ """Per-face dominant axis of the face normal → planar projection on the other two."""
+ n = _face_normals(P, F)
+ axis = np.argmax(np.abs(n), axis=1) # (F,)
+ sign = np.sign(n[np.arange(len(F)), axis])
+ sign[sign == 0] = 1.0
+ other = np.array([[2, 1], [0, 2], [0, 1]]) # axis → (u axis, v axis)
+ corners = P[F] # (F,3,3)
+ ua, va = other[axis, 0], other[axis, 1]
+ u = np.take_along_axis(corners, ua[:, None, None].repeat(3, 1), axis=2)[:, :, 0]
+ v = np.take_along_axis(corners, va[:, None, None].repeat(3, 1), axis=2)[:, :, 0]
+ u = u * sign[:, None] # keep handedness consistent on opposite faces
+ uv = np.stack([u, v], axis=2) / tile
+ key = axis[:, None].repeat(3, 1) * 2 + (sign[:, None].repeat(3, 1) < 0).astype(int)
+ return uv, key
+
+
+def _planar_uv(P: np.ndarray, F: np.ndarray, axis: int, tile: float) -> tuple[np.ndarray, np.ndarray]:
+ other = {0: (2, 1), 1: (0, 2), 2: (0, 1)}[axis]
+ corners = P[F]
+ uv = np.stack([corners[:, :, other[0]], corners[:, :, other[1]]], axis=2) / tile
+ return uv, np.zeros((len(F), 3), dtype=int)
+
+
+def _cylinder_uv(P: np.ndarray, F: np.ndarray, axis: int, tile: float) -> tuple[np.ndarray, np.ndarray]:
+ a, b = [i for i in range(3) if i != axis]
+ center = 0.5 * (P.min(axis=0) + P.max(axis=0))
+ d = P - center
+ radius = float(np.mean(np.hypot(d[:, a], d[:, b])))
+ radius = max(radius, 1e-4)
+ circ = 2.0 * np.pi * radius
+ ang = np.arctan2(d[:, b], d[:, a]) # (-π, π]
+ u_v = (ang + np.pi) / (2.0 * np.pi) * circ / tile # 0..circ/tile
+ v_v = P[:, axis] / tile
+ u = u_v[F] # (F,3)
+ v = v_v[F]
+ key = np.zeros((len(F), 3), dtype=int)
+ # seam: faces straddling angle ±π have a u spread > half circumference → shift the low corners
+ span = u.max(axis=1) - u.min(axis=1)
+ wrap = span > 0.5 * circ / tile
+ if wrap.any():
+ low = u < (u.max(axis=1, keepdims=True) - 0.5 * circ / tile)
+ shift = wrap[:, None] & low
+ u = u + shift * (circ / tile)
+ key = key + shift.astype(int)
+ # caps: planar
+ n = _face_normals(P, F)
+ cap = np.abs(n[:, axis]) > CAP_COS
+ if cap.any():
+ corners = P[F]
+ u = np.where(cap[:, None], corners[:, :, a] / tile, u)
+ v = np.where(cap[:, None], corners[:, :, b] / tile, v)
+ key = np.where(cap[:, None], 2, key)
+ return np.stack([u, v], axis=2), key
+
+
+def split_by_key(
+ vertices: np.ndarray, faces: np.ndarray, normals: np.ndarray | None, uv_corner: np.ndarray, key_corner: np.ndarray
+) -> tuple[np.ndarray, np.ndarray, np.ndarray | None, np.ndarray, int]:
+ """Duplicate a vertex once per distinct (vertex, key) pair; UV per new vertex =
+ mean of its corner UVs (they agree within a key by construction)."""
+ F = faces
+ flat_v = F.reshape(-1)
+ flat_k = key_corner.reshape(-1)
+ pair = flat_v.astype(np.int64) * (int(flat_k.max()) + 1 if flat_k.size else 1) + flat_k
+ uniq, inverse = np.unique(pair, return_inverse=True)
+ n_new = len(uniq)
+ src = np.zeros(n_new, dtype=np.int64)
+ src[inverse] = flat_v
+ new_vertices = vertices[src]
+ new_normals = normals[src] if normals is not None else None
+ new_uv = np.zeros((n_new, 2), dtype=np.float64)
+ counts = np.zeros(n_new, dtype=np.float64)
+ np.add.at(new_uv, inverse, uv_corner.reshape(-1, 2))
+ np.add.at(counts, inverse, 1.0)
+ new_uv /= np.maximum(counts, 1.0)[:, None]
+ new_faces = inverse.reshape(-1, 3)
+ return new_vertices, new_faces, new_normals, new_uv, int(n_new - len(vertices))
+
+
+def unwrap(
+ vertices_local: np.ndarray,
+ faces: np.ndarray,
+ transform: np.ndarray,
+ *,
+ projection: str = "auto",
+ tile_size_m: float = 0.3,
+ normals_local: np.ndarray | None = None,
+) -> Unwrapped:
+ """Compute UVs for one mesh given its 4×4 world ``transform``. Returns the
+ (possibly vertex-split) mesh in LOCAL coordinates plus per-vertex UVs."""
+ V = np.asarray(vertices_local, dtype=np.float64)
+ F = np.asarray(faces, dtype=np.int64)
+ if V.ndim != 2 or V.shape[1] != 3 or F.ndim != 2 or F.shape[1] != 3 or len(F) == 0:
+ raise ValueError("unwrap needs (N,3) vertices and (F,3) triangles")
+ tile = float(tile_size_m)
+ if not tile > 0:
+ raise ValueError("tile_size_m must be > 0")
+ T = np.asarray(transform, dtype=np.float64)
+ P = V @ T[:3, :3].T + T[:3, 3]
+ ext = P.max(axis=0) - P.min(axis=0)
+ proj, axis = choose_projection(ext, projection)
+ if proj == "box":
+ uv_c, key_c = _box_uv(P, F, tile)
+ elif proj == "cylinder":
+ uv_c, key_c = _cylinder_uv(P, F, axis, tile)
+ else:
+ uv_c, key_c = _planar_uv(P, F, axis, tile)
+ nv, nf, nn, uv, n_split = split_by_key(V, F, normals_local, uv_c, key_c)
+ # keep numbers small for float32 TEXCOORD precision (pattern is periodic anyway)
+ uv = uv - np.floor(uv.min(axis=0))
+ return Unwrapped(vertices=nv, faces=nf, normals=nn, uv=uv, projection=proj, axis=axis, n_split=n_split)
diff --git a/harness/codeverse/tracks/articulated_object.py b/harness/codeverse/tracks/articulated_object.py
index 8d084b34..7272abe2 100644
--- a/harness/codeverse/tracks/articulated_object.py
+++ b/harness/codeverse/tracks/articulated_object.py
@@ -42,8 +42,22 @@ class ArticulatedPipeline(ObjectPipeline):
ctx.extra["pose_views"] = views
ctx.extra["sweep_report"] = report
out.append(report)
+ motion = self._motion_gate(ctx)
+ if motion is not None:
+ ctx.extra["motion_report"] = motion
+ out.append(motion)
return out
+ @staticmethod
+ def _motion_gate(ctx: RunContext) -> GateReport | None:
+ """Planned motion text ("pulls out to the front") vs the URDF's real direction."""
+ try:
+ return ctx.services.motion_checks(ctx.ws, ctx.plan)
+ except Exception as e: # noqa: BLE001 — advisory gate; the sweep gate is the hard one
+ log.warning("motion direction checks failed: %s", e)
+ ctx.events.emit("gate.motion_failed", error=f"{type(e).__name__}: {e}")
+ return None
+
def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
rs = super().render(ctx, round_index, build, measurement)
pose_views: list[RenderView] = ctx.extra.pop("pose_views", []) or []
@@ -61,11 +75,16 @@ class ArticulatedPipeline(ObjectPipeline):
def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
report: GateReport | None = ctx.extra.pop("sweep_report", None)
+ motion: GateReport | None = ctx.extra.pop("motion_report", None)
lines = ["Articulation sheet: the pose_* views show the object at rest, each joint at its lower and upper limit."]
if report is not None:
errs = [f"- {f.target or 'joint'}: {f.message}" for f in report.errors]
lines.append(f"Joint sweep: {'no penetrations' if not errs else str(len(errs)) + ' problems'}")
lines.extend(errs[:10])
+ if motion is not None:
+ wrong = [f"- {f.target}: {f.message}" for f in motion.errors]
+ lines.append("Motion direction (harness FK check): " + ("all planned directions realised" if not wrong else f"{len(wrong)} WRONG"))
+ lines.extend(wrong[:6])
return "\n".join(lines)
diff --git a/harness/codeverse/tracks/base.py b/harness/codeverse/tracks/base.py
index d4e2932d..a15d05d4 100644
--- a/harness/codeverse/tracks/base.py
+++ b/harness/codeverse/tracks/base.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Protocol
+from typing import Any, Protocol
from codeverse.contracts.common import Track
from codeverse.contracts.plan import Plan
@@ -24,16 +24,22 @@ class TrackPipeline(Protocol):
...
-def get_track(track: Track | str) -> TrackPipeline:
+def get_track(track: Track | str, **options: Any) -> TrackPipeline:
+ """Track instance for ``track``. ``options`` are forwarded to the track
+ constructor (e.g. ``n_candidates=2`` for a best-of-N baseline, ``policy=``)."""
t = Track(track)
if t is Track.STATIC_OBJECT:
from codeverse.tracks.static_object import StaticObjectTrack
- return StaticObjectTrack()
+ return StaticObjectTrack(**options)
if t is Track.ARTICULATED_OBJECT:
from codeverse.tracks.articulated_object import ArticulatedObjectTrack
- return ArticulatedObjectTrack()
+ return ArticulatedObjectTrack(**options)
+ if t is Track.GRAPHICS:
+ from codeverse.tracks.graphics import GraphicsTrack
+
+ return GraphicsTrack(**options)
from codeverse.tracks.scene import SceneTrack
- return SceneTrack()
+ return SceneTrack(**options)
diff --git a/harness/codeverse/tracks/candidates.py b/harness/codeverse/tracks/candidates.py
new file mode 100644
index 00000000..c17c19d5
--- /dev/null
+++ b/harness/codeverse/tracks/candidates.py
@@ -0,0 +1,304 @@
+"""Best-of-N baseline and pairwise best-round selection (track side).
+
+* ``run_best_of_n`` — N baseline candidates are generated IN PARALLEL, each in
+ its own throw-away sub-workspace (``<ws>/_cand/c<k>``: own git repo, copy of
+ the skeleton + spec + plan, own AGENTS.md/MCP config), built (+repair),
+ gated, quick-rendered (4 views) and quick-judged (n_samples=1). The winner
+ (quick score → fewer gate errors; a pairwise tie-break when the top two are
+ within judge noise) is copied back into the run workspace and the ordinary
+ round-0 pipeline (build → gates → 8-view render → full judge) runs on it.
+ Every candidate is charged to the run budget and persisted in
+ ``rounds/candidates.json``.
+* ``choose_best_round`` — after each round: when the new score is within
+ ``policy.pairwise_margin`` of the current best, a position-swapped pairwise
+ comparison decides (confidence ≥ ``policy.pairwise_min_confidence`` to replace).
+"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+import time
+from collections.abc import Sequence
+from dataclasses import replace
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.artifacts import GateReport, RenderSet
+from codeverse.contracts.common import Usage
+from codeverse.contracts.run import RoundRecord
+from codeverse.conventions import OBJECT_VIEWS_QUICK
+from codeverse.orchestrator.budget import BudgetExceeded
+from codeverse.orchestrator.candidates import (
+ CandidateRecord,
+ PairwiseNote,
+ decide_best,
+ rank_candidates,
+)
+from codeverse.orchestrator.fanout import fan_out
+from codeverse.orchestrator.rounds import BestSelector
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import GenerationTask
+from codeverse.tracks.repair import build_with_repair
+from codeverse.tracks.steps import (
+ RoundFailed,
+ RoundPipeline,
+ round_record_path,
+ run_generation_tasks,
+ run_round,
+)
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+CAND_DIR = "_cand"
+QUICK_PX = 512
+
+
+# ----------------------------------------------------------------------------- best-of-N
+def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask], pipeline: RoundPipeline, *,
+ files_hint: Sequence[str] = ()) -> RoundRecord:
+ """Baseline round with ``ctx.policy.n_candidates`` parallel candidates; returns the r00 record."""
+ n = max(1, ctx.policy.n_candidates)
+ ctx.events.emit("candidates.start", round=0, n=n, parallel=min(n, ctx.settings.limits.max_parallel_agents))
+ _ignore_candidates(ctx.ws)
+ subs = [make_candidate_context(track, ctx, k) for k in range(n)]
+
+ def _one(k: int) -> tuple[CandidateRecord, RenderSet | None]:
+ return run_candidate(track, subs[k], k, tasks, pipeline, files_hint=files_hint)
+
+ results = fan_out(list(range(n)), _one, max_workers=ctx.settings.limits.max_parallel_agents, label="candidates",
+ item_name=lambda k: f"c{k}")
+ # one retry for candidates that crashed (transient 503s, parse failures) — not for budget stops
+ retry = [k for k, r in enumerate(results) if isinstance(r, Exception) and not isinstance(r, BudgetExceeded)]
+ if retry and ctx.budget.ok():
+ for k in retry:
+ ctx.events.emit("candidate.retry", candidate=k, error=f"{type(results[k]).__name__}: {results[k]}"[:300])
+ subs[k] = make_candidate_context(track, ctx, k)
+ again = fan_out(retry, _one, max_workers=ctx.settings.limits.max_parallel_agents, label="candidates-retry",
+ item_name=lambda k: f"c{k}")
+ for k, r in zip(retry, again, strict=True):
+ results[k] = r
+ records: list[CandidateRecord] = []
+ renders: dict[int, RenderSet] = {}
+ for k, r in enumerate(results):
+ if isinstance(r, BudgetExceeded):
+ raise r
+ if isinstance(r, Exception):
+ records.append(CandidateRecord(index=k, label=f"c{k}", workspace=str(subs[k].ws.root),
+ notes=f"{type(r).__name__}: {r}"[:300]))
+ ctx.events.emit("candidate.failed", candidate=k, error=f"{type(r).__name__}: {r}"[:300])
+ continue
+ rec, rs = r
+ records.append(rec)
+ if rs is not None:
+ renders[k] = rs
+ if not any(r.commit for r in records):
+ raise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in records) or "every candidate failed")
+ best, note = select_candidate(ctx, records, renders)
+ records[best].selected = True
+ usage = Usage()
+ for rec in records:
+ usage = usage + rec.usage
+ if note is not None:
+ usage = usage + note.usage
+ ctx.ws.write_json(ctx.ws.root / "rounds" / "candidates.json",
+ {"n": n, "selected": best, "candidates": [r.model_dump(mode="json") for r in records],
+ "pairwise": note.model_dump(mode="json") if note else None})
+ ctx.state.extra["candidates"] = {"n": n, "selected": best,
+ "scores": {r.label: r.score for r in records}}
+ ctx.events.emit("candidate.selected", round=0, candidate=best, label=records[best].label, score=records[best].score,
+ build_ok=records[best].build_ok, scores={r.label: r.score for r in records},
+ cost_usd=round(usage.cost_usd, 4))
+ adopt_candidate(ctx, subs[best].ws)
+ ctx.ws.commit(f"r00 baseline: candidate {records[best].label} selected (best of {n})")
+ others = ", ".join(f"{r.label}={r.score:.3f}" if r.score is not None else f"{r.label}=n/a"
+ for r in records if r.index != best)
+ notes = [f"best-of-{n}: selected {records[best].label} "
+ f"(quick score {records[best].score if records[best].score is None else round(records[best].score, 3)}; others: {others or '-'})"]
+ if note is not None:
+ notes.append(note.line())
+ return run_round(ctx, index=0, kind="baseline", tasks=[], pipeline=pipeline, files_hint=list(files_hint),
+ extra_usage=usage, extra_notes=notes)
+
+
+def make_candidate_context(track: Any, ctx: RunContext, k: int) -> RunContext:
+ """A self-contained sub-workspace (skeleton + spec + plan + agent files) and its context."""
+ sub_ws = Workspace(ctx.ws.root / CAND_DIR / f"c{k}")
+ if sub_ws.root.exists():
+ shutil.rmtree(sub_ws.root)
+ sub_ws.create()
+ for rel in ("src", "public"):
+ src = ctx.ws.root / rel
+ if src.is_dir():
+ shutil.rmtree(sub_ws.root / rel, ignore_errors=True)
+ shutil.copytree(src, sub_ws.root / rel, ignore=shutil.ignore_patterns("node_modules", "__pycache__"))
+ for path in (ctx.ws.spec_path, ctx.ws.plan_path):
+ if path.is_file():
+ shutil.copyfile(path, sub_ws.root / path.name)
+ if not ctx.single_shot:
+ kind = ctx.agent_id.split(":", 1)[0]
+ ctx.services.materialize(sub_ws, agent_kind=kind, contract_md=track.agent_contract_md(ctx), cookbook_rel=ctx.cookbook_rel,
+ spatial_tools=True,
+ mcp_command=["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(sub_ws.root)])
+ sub_ws.commit("skeleton")
+ return replace(ctx, ws=sub_ws, extra={})
+
+
+def run_candidate(track: Any, sub: RunContext, k: int, tasks: Sequence[GenerationTask], pipeline: RoundPipeline, *,
+ files_hint: Sequence[str] = ()) -> tuple[CandidateRecord, RenderSet | None]:
+ """generate → build(+repair) → gates → quick 4-view render → quick judge, in the sub-workspace."""
+ t0 = time.time()
+ label = f"c{k}"
+ sub.events.emit("candidate.start", candidate=k, workspace=str(sub.ws.root))
+ rec = CandidateRecord(index=k, label=label, workspace=str(sub.ws.root))
+ usage = Usage()
+ tasks_k = [t.model_copy(update={"label": f"{t.label}_{label}"}) for t in tasks]
+ gens = run_generation_tasks(sub, tasks_k) # RoundFailed propagates → candidate failed
+ for g in gens:
+ usage = usage + g.usage
+ sub.ws.commit(f"{label}: generated")
+ outcome = build_with_repair(sub, round_index=0, label=label, files_hint=list(files_hint))
+ usage = usage + outcome.usage
+ rec.build_ok = outcome.build.ok
+ gates: list[GateReport] = [outcome.lint]
+ renders: RenderSet | None = None
+ if outcome.build.ok:
+ measurement = pipeline.measure(sub, outcome.build)
+ gates.extend(pipeline.gates(sub, 0, outcome.build, measurement))
+ renders = quick_render(sub, outcome.build.glb_path)
+ if renders is not None and renders.views:
+ rec.sheet = renders.contact_sheet or ""
+ judgment = quick_judge(track, sub, pipeline, outcome.build, gates, measurement, renders)
+ if judgment is not None:
+ rec.score = judgment.overall
+ usage = usage + judgment.usage
+ else:
+ rec.notes = f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:160]}"
+ rec.gate_errors = sum(len(g.errors) for g in gates)
+ rec.commit = sub.ws.commit(f"candidate {label}")
+ rec.usage = usage
+ rec.duration_s = round(time.time() - t0, 2)
+ sub.events.emit("candidate.done", candidate=k, score=rec.score, build_ok=rec.build_ok, gate_errors=rec.gate_errors,
+ duration_s=rec.duration_s, cost_usd=round(usage.cost_usd, 4), commit=rec.commit[:10])
+ return rec, renders
+
+
+def quick_render(ctx: RunContext, glb_path: str | None) -> RenderSet | None:
+ if not glb_path:
+ return None
+ out_dir = ctx.ws.renders_dir(0) / "quick"
+ try:
+ return ctx.services.render_object(Path(glb_path), out_dir, views=OBJECT_VIEWS_QUICK, width=QUICK_PX, height=QUICK_PX)
+ except Exception as e: # noqa: BLE001 — a candidate without renders is ranked by gates only
+ log.warning("quick render failed for %s: %s", ctx.ws.root, e)
+ ctx.events.emit("candidate.render_failed", workspace=str(ctx.ws.root), error=f"{type(e).__name__}: {e}")
+ return None
+
+
+def quick_judge(track: Any, ctx: RunContext, pipeline: RoundPipeline, build: Any, gates: list[GateReport],
+ measurement: Any, renders: RenderSet) -> Any | None:
+ from codeverse.judges.base import JudgeInput
+
+ try:
+ judge = track.make_judge(ctx, n_samples=1)
+ inp = JudgeInput(spec=ctx.spec, renders=renders, measurement=measurement, gates=gates,
+ acceptance=list(getattr(ctx.plan, "acceptance", []) or []), plan_summary=pipeline.plan_summary(ctx),
+ round_index=0, extra_context=pipeline.judge_context(ctx, 0, build, gates))
+ judgment = judge.judge(inp)
+ except Exception as e: # noqa: BLE001 — judge outage: candidate ranked by gates only
+ log.warning("quick judge failed for %s: %s", ctx.ws.root, e)
+ ctx.events.emit("candidate.judge_failed", workspace=str(ctx.ws.root), error=f"{type(e).__name__}: {e}")
+ return None
+ ctx.budget.add(judgment.usage) # verdict already paid for; the loop stops at its next check
+ ctx.ws.write_json(ctx.ws.judge_path(0, "_quick"), judgment)
+ return judgment
+
+
+def select_candidate(ctx: RunContext, records: Sequence[CandidateRecord], renders: dict[int, RenderSet]) -> tuple[int, PairwiseNote | None]:
+ """Best candidate index (+ pairwise note when the top two were within judge noise)."""
+ order = rank_candidates(records)
+ best = order[0]
+ if len(order) < 2:
+ return best, None
+ a, b = records[order[0]], records[order[1]]
+ if not (a.build_ok and b.build_ok and a.index in renders and b.index in renders):
+ return best, None
+ compare = _pairwise_fn(ctx, renders[a.index], renders[b.index])
+ decision, note = decide_best(a.score, b.score, margin=ctx.policy.pairwise_margin,
+ min_confidence=ctx.policy.pairwise_min_confidence, compare=compare, labels=(a.label, b.label))
+ if note is not None:
+ ctx.budget.add(note.usage) # post-hoc accounting of a finished comparison
+ ctx.events.emit("pairwise.done", stage="candidates", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,
+ accepted=note.accepted, error=note.error, cost_usd=round(note.usage.cost_usd, 4))
+ if decision == "pairwise":
+ best = b.index
+ return best, note
+
+
+def adopt_candidate(ctx: RunContext, sub_ws: Workspace) -> None:
+ """Copy the winner's src/ + public/ into the run workspace and keep its trajectories."""
+ for rel in ("src", "public"):
+ src = sub_ws.root / rel
+ dest = ctx.ws.root / rel
+ if dest.exists():
+ shutil.rmtree(dest)
+ if src.is_dir():
+ shutil.copytree(src, dest, ignore=shutil.ignore_patterns("node_modules", "__pycache__"))
+ else:
+ dest.mkdir(parents=True, exist_ok=True)
+ if sub_ws.trajectories.is_dir():
+ shutil.copytree(sub_ws.trajectories, ctx.ws.trajectories, dirs_exist_ok=True)
+
+
+def _ignore_candidates(ws: Workspace) -> None:
+ gi = ws.root / ".gitignore"
+ text = gi.read_text() if gi.is_file() else ""
+ if f"{CAND_DIR}/" not in text:
+ gi.write_text(text.rstrip("\n") + f"\n{CAND_DIR}/\n")
+
+
+# ----------------------------------------------------------------------------- best round (pairwise tie-break)
+def choose_best_round(ctx: RunContext, rounds: list[RoundRecord], selector: BestSelector, new_index: int) -> int | None:
+ """Index of the best round after ``rounds[new_index]`` finished.
+
+ Ordinary ranking (score → fewer gate errors) unless the new round's score is
+ within ``policy.pairwise_margin`` of the current best: then a pairwise
+ comparison of the two render sets decides, and the new round replaces the
+ best only when it wins with ``confidence ≥ policy.pairwise_min_confidence``.
+ The verdict is appended to the new round's notes and re-persisted."""
+ incumbent = ctx.state.best_round
+ if incumbent is None or incumbent >= len(rounds) or incumbent == new_index:
+ return selector.pick(rounds)
+ inc, new = rounds[incumbent], rounds[new_index]
+ if new.score is None or inc.score is None:
+ return selector.pick(rounds)
+ compare = _pairwise_fn(ctx, inc.renders, new.renders) if (inc.renders and new.renders) else None
+ decision, note = decide_best(inc.score, new.score, margin=ctx.policy.pairwise_margin,
+ min_confidence=ctx.policy.pairwise_min_confidence, compare=compare,
+ labels=(f"r{incumbent:02d}", f"r{new_index:02d}"))
+ if note is not None:
+ ctx.budget.add(note.usage) # post-hoc accounting of a finished comparison
+ new.usage = new.usage + note.usage
+ new.notes = (new.notes + "; " if new.notes else "") + note.line()
+ ctx.ws.write_json(round_record_path(ctx, new_index), new)
+ ctx.events.emit("pairwise.done", stage="rounds", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,
+ accepted=note.accepted, error=note.error, cost_usd=round(note.usage.cost_usd, 4))
+ if decision == "score":
+ return selector.pick(rounds)
+ return new_index if decision == "pairwise" else incumbent
+
+
+def _pairwise_fn(ctx: RunContext, renders_a: RenderSet | None, renders_b: RenderSet | None):
+ if renders_a is None or renders_b is None:
+ return None
+
+ def _compare() -> Any:
+ judge = ctx.services.pairwise(ctx.spec.backends.judge)
+ return judge.compare(ctx.spec, renders_a, renders_b, rubric=ctx.rubric)
+
+ return _compare
+
+
+__all__ = ["CAND_DIR", "adopt_candidate", "choose_best_round", "make_candidate_context", "run_best_of_n", "run_candidate",
+ "select_candidate"]
diff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.py
index 89f80665..99647157 100644
--- a/harness/codeverse/tracks/common.py
+++ b/harness/codeverse/tracks/common.py
@@ -17,15 +17,15 @@ from typing import Any
from codeverse.config import Settings
from codeverse.contracts.artifacts import GateReport, Measurement, RenderSet, RenderView
from codeverse.contracts.common import Language, Track
-from codeverse.contracts.plan import CameraPlan, Plan, StaticPlan
+from codeverse.contracts.plan import CameraPlan, Plan
from codeverse.contracts.run import RunRecord
-from codeverse.conventions import LANGUAGE_FRAME, Frame, ViewPreset, frame_doc, to_snake
+from codeverse.conventions import ViewPreset
from codeverse.events import EventLog
from codeverse.orchestrator.budget import BudgetGuard
from codeverse.orchestrator.rounds import RoundPolicy
from codeverse.orchestrator.state import RunState
from codeverse.prompts import load_text, prompt_hash
-from codeverse.tracks.generation import SINGLE_SHOT_FORMAT, is_single_shot
+from codeverse.tracks.generation import is_single_shot
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
@@ -61,6 +61,14 @@ class Services:
def judge(self, rubric: str, model_id: str, n_samples: int = 1) -> Any:
return _import("codeverse.judges.vlm_judge", "VlmJudge")(rubric=rubric, model_id=model_id, n_samples=n_samples)
+ def reference_judge(self, model_id: str, n_samples: int = 1, rubric: str = "reference_v1") -> Any:
+ """Image-conditioned judge (spec has reference images): renders + references + silhouette IoU."""
+ return _import("codeverse.judges.reference", "ReferenceJudge")(model_id=model_id, n_samples=n_samples, rubric=rubric)
+
+ def pairwise(self, model_id: str) -> Any:
+ """Position-swapped A/B judge: ``.compare(spec, renders_a, renders_b, rubric=...)``."""
+ return _import("codeverse.judges.pairwise", "PairwiseJudge")(model_id)
+
def runtime(self, language: Language) -> Any:
return _import("codeverse.languages", "get_runtime")(language)
@@ -75,8 +83,9 @@ class Services:
def measure(self, glb: Path) -> Measurement:
return _import("codeverse.spatial.measure", "measure_glb")(glb)
- def connectivity(self, glb: Path) -> GateReport:
- return _import("codeverse.spatial.connectivity", "check_connectivity")(glb)
+ def connectivity(self, glb: Path, language: str = "") -> GateReport:
+ """``language`` selects the frame of the fix hints (the author's frame, not the GLB's)."""
+ return _import("codeverse.spatial.connectivity", "check_connectivity")(glb, language=language)
def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
return _import("codeverse.spatial.contract", "check_contract")(measurement, plan, language=language, tol_m=tol_m)
@@ -89,9 +98,36 @@ class Services:
return _import("codeverse.spatial.render", "render_scene")(ws, out_dir, cameras=cameras, orbit=True, times=tuple(times),
width=width, height=height, sheet=True)
+ def render_geometry(self, glb: Path, out_dir: Path, *, views: Sequence[ViewPreset]) -> RenderSet:
+ """Clay renders (no materials/textures) exposing holes/intersections for the judge's
+ geometry montage — cheap thanks to the render cache."""
+ return _import("codeverse.spatial.render", "render_glb")(glb, out_dir, views=list(views), mode="clay", sheet=False)
+
+ def frame_gate(self, renders: RenderSet) -> GateReport:
+ """``scene_frames`` gate from a scene RenderSet's metrics.json (missing metrics → passing empty report)."""
+ return _import("codeverse.spatial.frame_metrics", "frame_gate_from_renders")(renders)
+
+ def select_judge_views(self, renders: RenderSet, max_n: int = 10) -> RenderSet:
+ """The ≤ ``max_n`` scene views a judge should see; identity when the helper is unavailable."""
+ try:
+ fn = _import("codeverse.spatial.render_scene", "select_judge_views")
+ except ServiceUnavailable:
+ return renders
+ return fn(renders, max_n=max_n)
+
def contact_sheet(self, images: list[tuple[str, Path]], out: Path) -> Path:
return _import("codeverse.spatial.sheet", "contact_sheet")(images, out)
+ def silhouette(self, render_png: Path | str, reference_png: Path | str) -> dict[str, Any]:
+ """Outline IoU of a render vs a reference image (``{iou, reliable, ...}``)."""
+ return _import("codeverse.spatial.silhouette", "compare_silhouette")(render_png, reference_png)
+
+ def motion_checks(self, ws: Workspace, plan: Plan) -> GateReport | None:
+ """Planned joint motion text vs the built URDF's actual motion direction. See tracks/motion.py."""
+ from codeverse.tracks.motion import default_motion_checks
+
+ return default_motion_checks(ws, plan)
+
def joint_sweep(self, ws: Workspace, plan: Plan, out_dir: Path) -> tuple[GateReport, list[RenderView]]:
"""Pose sweep on the built URDF → (gate report, pose views). See articulated_object."""
from codeverse.tracks.articulated_object import default_joint_sweep
@@ -210,154 +246,15 @@ def cookbook_rel_for(language: Language) -> str:
return f"{language.value}/cookbook.md"
-def parts_table(plan: Plan) -> str:
- """Markdown table of parts with exact bboxes (meters, 3 decimals)."""
- parts = getattr(plan, "parts", None)
- if not parts:
- return "(no parts)"
- rows = ["| part | role | bbox centre (x,y,z) m | extents (x,y,z) m | attach_to | inst | material |",
- "|---|---|---|---|---|---|---|"]
- for p in parts:
- c = ", ".join(f"{v:.3f}" for v in p.bbox.center)
- e = ", ".join(f"{v:.3f}" for v in p.bbox.extents)
- rows.append(f"| {p.name} | {p.role} | ({c}) | ({e}) | {p.attach_to or '-'} | {p.instances} | {p.material or '-'} |")
- return "\n".join(rows)
-
-
-def part_details(plan: Plan) -> str:
- parts = getattr(plan, "parts", None) or []
- return "\n".join(f"- **{p.name}** ({p.symmetry if p.symmetry != 'none' else 'no symmetry'}): {p.description}" for p in parts)
-
-
-def joints_table(plan: Plan) -> str:
- joints = getattr(plan, "joints", None)
- if not joints:
- return "(no joints)"
- rows = ["| joint | type | parent | child | axis | pivot (world, m) | lower | upper | rest | motion |",
- "|---|---|---|---|---|---|---|---|---|---|"]
- for j in joints:
- ax = ", ".join(f"{v:.3f}" for v in j.axis)
- pv = ", ".join(f"{v:.3f}" for v in j.pivot)
- rows.append(f"| {j.name} | {j.type} | {j.parent} | {j.child} | ({ax}) | ({pv}) | {j.lower:.3f} | {j.upper:.3f} | {j.rest:.3f} | {j.motion} |")
- return "\n".join(rows)
-
-
-def acceptance_lines(plan: Plan | None) -> str:
- items = getattr(plan, "acceptance", None) or []
- if not items:
- return "(none)"
- return "\n".join(f"- [{a.id}] ({a.priority}, {a.how}) {a.text}" for a in items)
-
-
-def bbox_line(bbox: Any) -> str:
- c = ", ".join(f"{v:.3f}" for v in bbox.center)
- e = ", ".join(f"{v:.3f}" for v in bbox.extents)
- return f"centre ({c}) m, extents ({e}) m"
-
-
-def glb_to_plan_frame(v: Sequence[float], language: Language, *, extents: bool = False) -> tuple[float, float, float]:
- """Map a GLB-frame (Y-up, +Z front) vector into the language's authoring frame.
- Blender/CadQuery/URDF plans are Z-up with -Y front: glb (x, y, z) → (x, -z, y)."""
- x, y, z = float(v[0]), float(v[1]), float(v[2])
- if LANGUAGE_FRAME[language.value] is Frame.Z_UP_NEG_Y_FRONT:
- return (x, abs(z) if extents else -z, y)
- return (x, y, z)
-
-
-def constraints_text(spec: Any) -> str:
- c = spec.constraints
- lines = []
- if c.dimensions_m:
- lines.append("Dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in c.dimensions_m.items()))
- if c.max_triangles:
- lines.append(f"Max triangles: {c.max_triangles}")
- if c.style:
- lines.append(f"Style: {c.style}")
- for m in c.must_have:
- lines.append(f"MUST HAVE: {m}")
- for m in c.must_not:
- lines.append(f"MUST NOT: {m}")
- return "\n".join(lines) or "(none)"
-
-
-def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
- """Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""
- plan = ctx.plan
- object_name = getattr(plan, "object_name", None) or getattr(plan, "title", None) or "Object"
- d: dict[str, Any] = {
- "track": ctx.track.value,
- "language": ctx.language.value,
- "frame_doc": frame_doc(LANGUAGE_FRAME[ctx.language.value]),
- "contract": ctx.contract_text,
- "cookbook_rel": ctx.cookbook_rel,
- "cookbook_excerpt": ctx.cookbook_text[:6000],
- "tool_cards": ctx.tool_cards,
- "single_shot": ctx.single_shot,
- "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,
- "spec_prompt": ctx.spec.prompt,
- "constraints": constraints_text(ctx.spec),
- "object_name": object_name,
- "plan_summary": getattr(plan, "summary", "") if plan else "",
- "style_notes": getattr(plan, "style_notes", "") if plan else "",
- "overall_bbox": bbox_line(plan.overall_bbox) if isinstance(plan, StaticPlan) else "",
- "parts_table": parts_table(plan) if plan else "",
- "part_details": part_details(plan) if plan else "",
- "joints_table": joints_table(plan) if plan else "",
- "acceptance": acceptance_lines(plan),
- "entry_files": ", ".join(getattr(ctx.runtime, "entry_globs", ()) or ()),
- "n_parts": len(getattr(plan, "parts", []) or []) if plan else 0,
- "root_link": getattr(plan, "root_link", "") if plan else "",
- }
- d.update(extra)
- return d
-
-
-AGENT_OUTPUT_RULES = """HOW TO FINISH (agent mode): edit files under src/ only (and public/ for compiled assets).
-Before you finish you MUST run the `build` tool and fix every error it reports; then run `measure`
-(objects) or `scene_probe` (scenes) once and compare the numbers with the plan. Do not write
-reports, READMEs or notes — only the code files. Stop when the build is clean."""
-
-
-def file_for_target_factory(ctx: RunContext):
- """Return ``target → [files]`` for the current language, or ``None`` when the
- language is whole-object (one file). Prefers ``runtime.file_for_part``."""
- rt = ctx.runtime
- plan = ctx.plan
- custom = getattr(rt, "file_for_part", None)
- part_names = {to_snake(p.name): p.name for p in (getattr(plan, "parts", None) or [])}
- lang = ctx.language
-
- if lang is Language.THREEJS or callable(custom):
- def _threejs(target: str) -> list[str]:
- key = to_snake(target)
- if key in part_names:
- if callable(custom):
- try:
- out = custom(part_names[key])
- return [str(out)] if isinstance(out, (str, Path)) else [str(p) for p in out]
- except Exception as e: # noqa: BLE001
- log.warning("runtime.file_for_part failed for %s: %s", target, e)
- return [f"src/parts/{key}.js"]
- if key in ("overall", "assembly", "object", ""):
- return ["src/object.js"]
- return []
- return _threejs
-
- if lang is Language.SCENE_THREEJS:
- zones = {to_snake(z.name) for z in (getattr(plan, "zones", None) or [])}
- assets = {to_snake(a.name) for a in (getattr(plan, "assets", None) or [])}
- cameras = {to_snake(c.name) for c in (getattr(plan, "cameras", None) or [])}
-
- def _scene(target: str) -> list[str]:
- key = to_snake(target)
- if key in zones:
- return [f"src/zones/{key}.js"]
- if key in assets:
- return [f"src/assets/{key}.js"]
- if key in cameras or key in ("camera", "cameras", "composition"):
- return ["src/scene.js"]
- if key in ("env", "environment", "lighting", "sky", "fog", "ground", "water", "light"):
- return ["src/env.js"]
- return []
- return _scene
- return None
+_PROMPTING = {"parts_table", "part_details", "joints_table", "acceptance_lines", "bbox_line", "glb_to_plan_frame",
+ "constraints_text", "base_prompt_context", "reference_images", "reference_note", "AGENT_OUTPUT_RULES",
+ "file_for_target_factory"}
+
+
+def __getattr__(name: str) -> Any:
+ """Prompt-context helpers moved to ``tracks/prompting.py``; keep old import paths working."""
+ if name in _PROMPTING:
+ import importlib
+
+ return getattr(importlib.import_module("codeverse.tracks.prompting"), name)
+ raise AttributeError(name)
diff --git a/harness/codeverse/tracks/envelope.py b/harness/codeverse/tracks/envelope.py
new file mode 100644
index 00000000..6d856f32
--- /dev/null
+++ b/harness/codeverse/tracks/envelope.py
@@ -0,0 +1,156 @@
+"""Single-shot envelope: parse the ``=== FILE: ... ===`` format and write files.
+
+Split out of ``tracks/generation.py`` (kept re-exported there) so both modules
+stay under the ~400-line law. ``MultiFileParseError``/``GenerationError`` are
+defined here; ``generation`` re-exports them for its callers.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Callable
+from pathlib import Path
+
+from codeverse.contracts.agent import FileChange
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")
+
+SINGLE_SHOT_FORMAT = """OUTPUT FORMAT (exactly this, nothing else around it):
+For EVERY file you create or fully rewrite, emit one block:
+
+=== FILE: <relative path, e.g. src/parts/seat.js> ===
+<complete file contents — the whole file, not a diff>
+=== END FILE ===
+
+Rules: paths are relative to the workspace root and must start with src/ (or public/);
+emit the COMPLETE contents of each file (no "...rest unchanged"); no prose outside the blocks;
+no markdown fences inside a block (plain code). Files you do not emit are left untouched."""
+
+
+class GenerationError(RuntimeError):
+ """Raised when the generator cannot produce usable files (bad envelope, agent crash)."""
+
+
+class MultiFileParseError(GenerationError):
+ """The single-shot answer did not contain a parseable file envelope."""
+
+
+_BLOCK = re.compile(
+ r"^[ \t]*===\s*FILE:\s*(?P<path>[^\n=]+?)\s*===[ \t]*\r?\n(?P<body>.*?)(?:\r?\n)?^[ \t]*===\s*END FILE\s*===[ \t]*$",
+ re.S | re.M,
+)
+_FENCE = re.compile(r"```[a-zA-Z0-9_+\-]*[ \t]*(?:\r?\n)(?P<body>.*?)```", re.S)
+_FENCE_PATH_HINT = re.compile(
+ r"(?:^|\n)[^\n]*?(?P<path>(?:src|public)/[A-Za-z0-9_./\-]+\.[a-z]{1,5})[^\n]*\n[ \t]*```", re.S
+)
+
+
+def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> dict[str, str]:
+ """Parse ``SINGLE_SHOT_FORMAT`` → ``{path: content}``.
+
+ Tolerant to: a fenced block wrapping a file body; an answer that is ONE fenced
+ block when exactly one entry file is expected; fenced blocks preceded by a line
+ naming the path. Raises ``MultiFileParseError`` otherwise.
+ """
+ files: dict[str, str] = {}
+ for m in _BLOCK.finditer(text):
+ path = _clean_path(m.group("path"))
+ files[path] = _strip_fence(m.group("body"))
+ if files:
+ return files
+ fences = list(_FENCE.finditer(text))
+ expected = [_clean_path(p) for p in (expected_files or [])]
+ if fences:
+ # fenced blocks preceded by a path mention
+ for m in fences:
+ probe = text[: m.start()][-400:].rstrip(" \t")
+ probe += ("" if probe.endswith("\n") else "\n") + "```"
+ hint = _FENCE_PATH_HINT.findall(probe)
+ if hint:
+ files[_clean_path(hint[-1])] = m.group("body").rstrip("\n")
+ if files and (not expected or set(files) <= set(expected) or len(files) == len(fences)):
+ return files
+ if len(expected) == 1:
+ largest = max(fences, key=lambda m: len(m.group("body")))
+ return {expected[0]: largest.group("body").rstrip("\n")}
+ if len(expected) == 1 and _looks_like_code(text):
+ return {expected[0]: _strip_envelope_header(text.strip("\n"))}
+ raise MultiFileParseError(
+ "no '=== FILE: <path> ===' blocks found" + (f"; expected {expected}" if expected else "")
+ )
+
+
+_HEADER_LINE = re.compile(r"^[ \t]*===\s*FILE:\s*[^\n=]+?\s*===[ \t]*\r?\n")
+
+
+def _strip_envelope_header(body: str) -> str:
+ """A truncated answer (cut before ``=== END FILE ===``) reaches the single-file
+ fallback with its ``=== FILE: … ===`` header still attached; treat the
+ unterminated block as the file's body instead of shipping the header as line 1."""
+ m = _HEADER_LINE.match(body)
+ return body[m.end():] if m else body
+
+
+def _clean_path(p: str) -> str:
+ p = p.strip().strip("`'\"").replace("\\", "/")
+ while p.startswith("./"):
+ p = p[2:]
+ return p.lstrip("/")
+
+
+def _strip_fence(body: str) -> str:
+ s = body.strip("\n")
+ m = re.fullmatch(r"```[a-zA-Z0-9_+\-]*[ \t]*\n(.*?)\n?```", s, re.S)
+ return (m.group(1) if m else body).rstrip("\n")
+
+
+def _looks_like_code(text: str) -> bool:
+ t = text.strip()
+ return bool(t) and ("\n" in t) and not t.lower().startswith(("i ", "here", "sure", "sorry"))
+
+
+def safe_relpath(path: str, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> str:
+ """Validate a model-provided relative path: inside the workspace + allowed roots."""
+ p = _clean_path(path)
+ if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):
+ raise GenerationError(f"refusing to write outside the workspace: {path!r}")
+ if not any(p.startswith(root) for root in allowed_roots):
+ raise GenerationError(f"path {p!r} is outside the allowed roots {allowed_roots}")
+ return p
+
+
+def write_files(
+ ws: Workspace,
+ files: dict[str, str],
+ *,
+ allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,
+ on_skip: Callable[[str, str], None] | None = None,
+) -> list[FileChange]:
+ """Write parsed files under the workspace; returns git-style FileChange rows.
+
+ A block whose path is unsafe or outside ``allowed_roots`` (flash models love
+ to add README.md / package.json despite the format rule) is SKIPPED — reported
+ via ``on_skip`` — instead of aborting the whole write: the valid files were
+ already paid for."""
+ changes: list[FileChange] = []
+ for raw, content in files.items():
+ try:
+ rel = safe_relpath(raw, allowed_roots)
+ except GenerationError as e:
+ if on_skip is not None:
+ on_skip(raw, str(e))
+ log.warning("skipping out-of-root file from generator: %s", e)
+ continue
+ dest = ws.root / rel
+ existed = dest.exists()
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(content if content.endswith("\n") else content + "\n")
+ changes.append(FileChange(path=rel, status="modified" if existed else "added",
+ lines_added=content.count("\n") + 1))
+ return changes
+
+
diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.py
index 10656e2f..fd1b4678 100644
--- a/harness/codeverse/tracks/generation.py
+++ b/harness/codeverse/tracks/generation.py
@@ -16,12 +16,10 @@ tasks finished. Neither path builds; see ``tracks/repair.py``.
from __future__ import annotations
import logging
-import re
import subprocess
import threading
import time
from collections.abc import Callable
-from pathlib import Path
from typing import Any
from pydantic import BaseModel, Field
@@ -29,31 +27,20 @@ from pydantic import BaseModel, Field
from codeverse.contracts.agent import AgentJob, AgentResult, FileChange
from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
from codeverse.contracts.common import Usage
+from codeverse.tracks.envelope import ( # noqa: F401 — re-exported: this was their import path
+ ALLOWED_ROOTS,
+ SINGLE_SHOT_FORMAT,
+ GenerationError,
+ MultiFileParseError,
+ parse_multifile,
+ safe_relpath,
+ write_files,
+)
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
SINGLE_SHOT_PREFIX = "single-shot:"
-ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")
-
-SINGLE_SHOT_FORMAT = """OUTPUT FORMAT (exactly this, nothing else around it):
-For EVERY file you create or fully rewrite, emit one block:
-
-=== FILE: <relative path, e.g. src/parts/seat.js> ===
-<complete file contents — the whole file, not a diff>
-=== END FILE ===
-
-Rules: paths are relative to the workspace root and must start with src/ (or public/);
-emit the COMPLETE contents of each file (no "...rest unchanged"); no prose outside the blocks;
-no markdown fences inside a block (plain code). Files you do not emit are left untouched."""
-
-
-class GenerationError(RuntimeError):
- """Raised when the generator cannot produce usable files (bad envelope, agent crash)."""
-
-
-class MultiFileParseError(GenerationError):
- """The single-shot answer did not contain a parseable file envelope."""
class GenerationTask(BaseModel):
@@ -84,94 +71,6 @@ class GenerationResult(BaseModel):
label: str = ""
-# ----------------------------------------------------------------------------- envelope parsing
-_BLOCK = re.compile(
- r"^[ \t]*===\s*FILE:\s*(?P<path>[^\n=]+?)\s*===[ \t]*\r?\n(?P<body>.*?)(?:\r?\n)?^[ \t]*===\s*END FILE\s*===[ \t]*$",
- re.S | re.M,
-)
-_FENCE = re.compile(r"```[a-zA-Z0-9_+\-]*[ \t]*(?:\r?\n)(?P<body>.*?)```", re.S)
-_FENCE_PATH_HINT = re.compile(
- r"(?:^|\n)[^\n]*?(?P<path>(?:src|public)/[A-Za-z0-9_./\-]+\.[a-z]{1,5})[^\n]*\n[ \t]*```", re.S
-)
-
-
-def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> dict[str, str]:
- """Parse ``SINGLE_SHOT_FORMAT`` → ``{path: content}``.
-
- Tolerant to: a fenced block wrapping a file body; an answer that is ONE fenced
- block when exactly one entry file is expected; fenced blocks preceded by a line
- naming the path. Raises ``MultiFileParseError`` otherwise.
- """
- files: dict[str, str] = {}
- for m in _BLOCK.finditer(text):
- path = _clean_path(m.group("path"))
- files[path] = _strip_fence(m.group("body"))
- if files:
- return files
- fences = list(_FENCE.finditer(text))
- expected = [_clean_path(p) for p in (expected_files or [])]
- if fences:
- # fenced blocks preceded by a path mention
- for m in fences:
- probe = text[: m.start()][-400:].rstrip(" \t")
- probe += ("" if probe.endswith("\n") else "\n") + "```"
- hint = _FENCE_PATH_HINT.findall(probe)
- if hint:
- files[_clean_path(hint[-1])] = m.group("body").rstrip("\n")
- if files and (not expected or set(files) <= set(expected) or len(files) == len(fences)):
- return files
- if len(expected) == 1:
- largest = max(fences, key=lambda m: len(m.group("body")))
- return {expected[0]: largest.group("body").rstrip("\n")}
- if len(expected) == 1 and _looks_like_code(text):
- return {expected[0]: text.strip("\n")}
- raise MultiFileParseError(
- "no '=== FILE: <path> ===' blocks found" + (f"; expected {expected}" if expected else "")
- )
-
-
-def _clean_path(p: str) -> str:
- p = p.strip().strip("`'\"").replace("\\", "/")
- while p.startswith("./"):
- p = p[2:]
- return p.lstrip("/")
-
-
-def _strip_fence(body: str) -> str:
- s = body.strip("\n")
- m = re.fullmatch(r"```[a-zA-Z0-9_+\-]*[ \t]*\n(.*?)\n?```", s, re.S)
- return (m.group(1) if m else body).rstrip("\n")
-
-
-def _looks_like_code(text: str) -> bool:
- t = text.strip()
- return bool(t) and ("\n" in t) and not t.lower().startswith(("i ", "here", "sure", "sorry"))
-
-
-def safe_relpath(path: str, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> str:
- """Validate a model-provided relative path: inside the workspace + allowed roots."""
- p = _clean_path(path)
- if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):
- raise GenerationError(f"refusing to write outside the workspace: {path!r}")
- if not any(p.startswith(root) for root in allowed_roots):
- raise GenerationError(f"path {p!r} is outside the allowed roots {allowed_roots}")
- return p
-
-
-def write_files(ws: Workspace, files: dict[str, str], *, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> list[FileChange]:
- """Write parsed files under the workspace; returns git-style FileChange rows."""
- changes: list[FileChange] = []
- for raw, content in files.items():
- rel = safe_relpath(raw, allowed_roots)
- dest = ws.root / rel
- existed = dest.exists()
- dest.parent.mkdir(parents=True, exist_ok=True)
- dest.write_text(content if content.endswith("\n") else content + "\n")
- changes.append(FileChange(path=rel, status="modified" if existed else "added",
- lines_added=content.count("\n") + 1))
- return changes
-
-
# ----------------------------------------------------------------------------- git helpers
_GIT_LOCKS: dict[str, threading.Lock] = {}
_GIT_LOCKS_GUARD = threading.Lock()
@@ -245,9 +144,24 @@ def generate_files(
usage = resp.usage
if budget is not None:
budget.charge(usage)
+ if _is_truncated(resp):
+ # cut off by max_output_tokens: the envelope is unterminated — one retry with
+ # a doubled budget beats writing a half-file and burning repair attempts on it
+ if events is not None:
+ events.emit("generate.truncated", label=task.label, finish_reason=str(resp.finish_reason), retry=True)
+ req = req.model_copy(update={"max_output_tokens": min(task.max_output_tokens * 2, 65536)})
+ resp = model.generate(req)
+ usage = usage + resp.usage
+ if budget is not None:
+ budget.charge(resp.usage)
traj = ws.trajectory_dir(task.label.replace("/", "_"), task.round)
(traj / "prompt.md").write_text(f"# system\n{system}\n\n# user\n{task.prompt}\n")
(traj / "response.md").write_text(resp.text or "")
+ if _is_truncated(resp):
+ if events is not None:
+ events.emit("generate.truncated", label=task.label, finish_reason=str(resp.finish_reason), retry=False)
+ return GenerationResult(ok=False, usage=usage, notes=f"truncated: finish_reason={resp.finish_reason}",
+ text=(resp.text or "")[:2000], transcript_path=str(traj / "response.md"), label=task.label)
try:
files = parse_multifile(resp.text or "", expected_files=task.files_hint or None)
except MultiFileParseError as e:
@@ -255,12 +169,27 @@ def generate_files(
events.emit("generate.parse_failed", label=task.label, error=str(e))
return GenerationResult(ok=False, usage=usage, notes=f"parse failed: {e}", text=(resp.text or "")[:2000],
transcript_path=str(traj / "response.md"), label=task.label)
- changes = write_files(ws, files, allowed_roots=allowed_roots)
+ skipped: list[str] = []
+
+ def _skip(path: str, reason: str) -> None:
+ skipped.append(path)
+ if events is not None:
+ events.emit("generate.skipped_path", label=task.label, path=path, reason=reason[:200])
+
+ changes = write_files(ws, files, allowed_roots=allowed_roots, on_skip=_skip)
if events is not None:
events.emit("generate.done", label=task.label, strategy="single-shot", files=[c.path for c in changes],
cost_usd=round(usage.cost_usd, 4))
- return GenerationResult(ok=bool(changes), usage=usage, files_changed=changes, text=(resp.text or "")[:2000],
- transcript_path=str(traj / "response.md"), label=task.label)
+ notes = f"skipped out-of-root paths: {', '.join(skipped)}" if skipped else ""
+ return GenerationResult(ok=bool(changes), usage=usage, files_changed=changes, notes=notes,
+ text=(resp.text or "")[:2000], transcript_path=str(traj / "response.md"), label=task.label)
+
+
+_TRUNCATED_FINISH = {"max_tokens", "max_output_tokens", "length"}
+
+
+def _is_truncated(resp: Any) -> bool:
+ return str(getattr(resp, "finish_reason", "") or "").lower() in _TRUNCATED_FINISH
def run_agent_task(
@@ -277,8 +206,9 @@ def run_agent_task(
before = ws.head()
timeout = task.timeout_s or (settings.limits.agent_timeout_s if settings is not None else 1800)
# job.extra is honoured by every CodingAgent: round → trajectory dir + ToolContext,
- # language/track → spatial tool filtering (see agents/*).
- extra = {"round": task.round, "kind": task.kind}
+ # language/track → spatial tool filtering, files_hint → per-session attribution of
+ # files_changed when tasks run concurrently in ONE workspace (see agents/cli_common).
+ extra: dict[str, Any] = {"round": task.round, "kind": task.kind, "files_hint": list(task.files_hint)}
spec_path = ws.spec_path
if spec_path.is_file():
try:
@@ -294,7 +224,7 @@ def run_agent_task(
usage = res.usage
if budget is not None:
budget.charge(res.usage)
- changes = res.files_changed or changed_files_safe(ws, before)
+ changes = res.files_changed or _attributed_fallback(ws, task, before)
if retry_silent_bail and not changes and res.exit_reason not in ("timeout", "budget"):
if events is not None:
events.emit("generate.silent_bail", label=task.label, exit_reason=res.exit_reason)
@@ -305,7 +235,7 @@ def run_agent_task(
usage = usage + res.usage
if budget is not None:
budget.charge(res.usage)
- changes = res.files_changed or changed_files_safe(ws, before)
+ changes = res.files_changed or _attributed_fallback(ws, task, before)
notes = f"exit={res.exit_reason}" + (f"; errors={res.errors[:3]}" if res.errors else "")
if events is not None:
events.emit("generate.done", label=task.label, strategy=getattr(agent, "kind", "agent"),
@@ -315,6 +245,20 @@ def run_agent_task(
text=(res.text or "")[:2000], transcript_path=res.transcript_path, label=task.label)
+def _attributed_fallback(ws: Workspace, task: GenerationTask, before: str) -> list[FileChange]:
+ """Change detection when the agent did not report its own ``files_changed``.
+
+ A whole-worktree diff claims sibling tasks' files under fan_out (a task that
+ wrote nothing looked ok because its neighbours wrote files); attribute the diff
+ to this task instead: inside its write roots, never harness-owned paths."""
+ raw = changed_files_safe(ws, before)
+ try:
+ from codeverse.agents.cli_common import attribute_changes
+ except ImportError: # pragma: no cover — agents package always ships with tracks
+ return raw
+ return attribute_changes(raw, write_roots=list(task.write_roots), own_hints=frozenset(task.files_hint))
+
+
def generate(
ws: Workspace,
*,
diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.py
new file mode 100644
index 00000000..bde74c48
--- /dev/null
+++ b/harness/codeverse/tracks/graphics.py
@@ -0,0 +1,151 @@
+"""GraphicsTrack: plan (GraphicsPlan) → skeleton → baseline → refine rounds → finalise.
+
+Languages: glsl_shader (Shadertoy-style fragment shader) · opengl_python (raw
+moderngl program). Reuses ``BaseTrack`` (lifecycle) and ``run_round`` (steps)
+unchanged; the track-specific pieces are the planner template, the prompt
+context (no 3D frame), the ``gl_frames`` gate (frame statistics from the build)
+and the render step (the sampled frames + contact sheet as the RenderSet the
+``shader_v1`` judge sees). Refinement is always one whole-program task.
+
+The shared prompt helpers look the language up in ``conventions.LANGUAGE_FRAME``
+(repair prompts); graphics languages have no 3D frame, so they are registered
+here as Y-up/+Z-front (GL clip space) until conventions.py carries them.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+
+from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import GraphicsPlan, Plan
+from codeverse.contracts.run import RoundRecord
+from codeverse.conventions import LANGUAGE_FRAME, Frame
+from codeverse.events import EventLog
+from codeverse.languages.glsl_shader.gl_build import read_metrics
+from codeverse.orchestrator.rounds import TaskGroup, build_refine_instructions
+from codeverse.prompts import render
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import GenerationTask
+from codeverse.tracks.graphics_steps import (
+ expected_files,
+ frame_stats_text,
+ frames_render_set,
+ graphics_prompt_context,
+ plan_graphics,
+)
+from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.repair import format_error_report
+from codeverse.tracks.static_object import current_files, judge_digest, skeleton_files
+from codeverse.tracks.steps import failed_acceptance
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+for _lang in (Language.GLSL_SHADER, Language.OPENGL_PYTHON):
+ LANGUAGE_FRAME.setdefault(_lang.value, Frame.Y_UP_POS_Z_FRONT)
+
+
+class GraphicsPipeline:
+ """No measurement; gates = gl_frames (from artifacts/metrics.json); render = the frames."""
+
+ def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
+ return None
+
+ def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
+ m = read_metrics(ctx.ws)
+ if m is None:
+ return []
+ return [m[1]]
+
+ def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
+ return frames_render_set(ctx.ws, build, round_index)
+
+ def plan_summary(self, ctx: RunContext) -> str:
+ plan = ctx.plan
+ if not isinstance(plan, GraphicsPlan):
+ return ""
+ passes = ", ".join(f"{p.name} ({p.kind})" for p in plan.passes)
+ visuals = "; ".join(plan.key_visuals)
+ return (f"{plan.title}: {plan.summary} Style: {plan.style}. Passes: {passes}. Key visuals: {visuals}. "
+ f"Motion: {plan.motion or '(none planned)'}. {plan.resolution[0]}x{plan.resolution[1]}, loop {plan.duration_s:g}s.")
+
+ def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
+ renderer = build.census.get("renderer", "") if isinstance(build.census, dict) else ""
+ return f"FRAME METRICS (harness-measured, renderer {renderer or 'moderngl'}):\n{frame_stats_text(ctx.ws)}"
+
+
+class GraphicsTrack(BaseTrack):
+ track = Track.GRAPHICS
+ rubric = "shader_v1"
+ plan_model = GraphicsPlan
+ generate_template = "tracks/generate_graphics.j2"
+ refine_template = "tracks/refine_graphics.j2"
+
+ def make_pipeline(self, ctx: RunContext) -> GraphicsPipeline:
+ return GraphicsPipeline()
+
+ # ------------------------------------------------------------------ planning (own template / acceptance)
+ def plan(self, spec, ws: Workspace) -> Plan:
+ ws.create()
+ events = EventLog(ws.events_path)
+ runtime = self._runtime or self.services.runtime(spec.language)
+ return plan_graphics(spec, spec.backends.planner, ws, model=self._planner_model, events=events, runtime=runtime)
+
+ def _plan_stage(self, ctx: RunContext) -> Plan:
+ from codeverse.contracts.run import RunStatus
+
+ ctx.state.status = RunStatus.PLANNING
+ ctx.state.save(ctx.ws)
+ plan = plan_graphics(ctx.spec, ctx.spec.backends.planner, ctx.ws, model=self._planner_model, events=ctx.events,
+ budget=ctx.budget, runtime=ctx.runtime)
+ self._save_spent(ctx)
+ return plan
+
+ # ------------------------------------------------------------------ baseline
+ def system_prompt(self, ctx: RunContext) -> str:
+ what = "GLSL fragment-shader artist (Shadertoy style)" if ctx.language is Language.GLSL_SHADER else "raw OpenGL (moderngl) graphics programmer"
+ return (f"You are an expert {what} writing RAW code for a headless harness. Follow the contract exactly: "
+ f"no #version/uniform redeclarations (shader) · no window/context creation (program) · everything animates with time. "
+ f"Render and LOOK at your frames before finishing.")
+
+ def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
+ files = expected_files(ctx)
+ prompt = render(self.generate_template, **graphics_prompt_context(
+ ctx, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
+ ctx.record_prompt("generate", prompt)
+ return [GenerationTask(label="baseline", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=0,
+ kind="baseline", temperature=0.6, thinking="medium")]
+
+ def round_files_hint(self, ctx: RunContext) -> list[str]:
+ return expected_files(ctx)
+
+ # ------------------------------------------------------------------ refine
+ def refine_tasks(self, ctx: RunContext, last: RoundRecord, history: Sequence[RoundRecord]) -> tuple[list[GenerationTask], list[str]]:
+ index = len(history)
+ if last.build is None or not last.build.ok:
+ return [self._rebuild_task(ctx, last, index)], ["rebuild: previous round did not build"]
+ tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
+ file_for_target=None, max_tasks=ctx.policy.max_refine_tasks)
+ if not tasks:
+ return [], []
+ group = TaskGroup(tasks=tasks, files=expected_files(ctx))
+ prompt = render(self.refine_template, **graphics_prompt_context(
+ ctx, round_index=index, tasks=[t.line() for t in tasks], targets=group.targets, files=group.files,
+ judge_summary=judge_digest(last), frame_notes=frame_stats_text(ctx.ws),
+ current_files=current_files(ctx, group.files) if ctx.single_shot else {}))
+ ctx.record_prompt("refine", prompt)
+ ctx.events.emit("refine.planned", round=index, n_tasks=len(tasks), n_groups=1, parallel=False, targets=[group.targets])
+ task = GenerationTask(label="refine", prompt=prompt, system=self.system_prompt(ctx), files_hint=group.files, round=index,
+ kind="refine", temperature=0.5, thinking="medium")
+ return [task], [t.line() for t in tasks]
+
+ def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
+ files = expected_files(ctx)
+ lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
+ report = format_error_report(last.build, lint, ctx.cookbook_text) if last.build else "build did not run"
+ prompt = render(self.generate_template, **graphics_prompt_context(
+ ctx, skeleton_files=current_files(ctx, files) if ctx.single_shot else {}, previous_error=report))
+ return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
+ kind="rebuild", temperature=0.7, thinking="high")
diff --git a/harness/codeverse/tracks/graphics_steps.py b/harness/codeverse/tracks/graphics_steps.py
new file mode 100644
index 00000000..e2a5f67b
--- /dev/null
+++ b/harness/codeverse/tracks/graphics_steps.py
@@ -0,0 +1,228 @@
+"""Graphics-track helpers: planner (GraphicsPlan), prompt context, frame RenderSet.
+
+The shared planner / prompt helpers assume a 3D frame (``LANGUAGE_FRAME``,
+``ensure_acceptance`` adds a ground-contact item); shaders have neither, so the
+graphics track owns these three pieces and reuses everything else from
+``tracks/lifecycle.py`` + ``tracks/steps.py`` unchanged.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import shutil
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from pydantic import ValidationError
+
+from codeverse.contracts.artifacts import BuildResult, RenderSet, RenderView
+from codeverse.contracts.chat import ChatMessage, ChatRequest
+from codeverse.contracts.common import Language, Usage
+from codeverse.contracts.plan import AcceptanceItem, GraphicsPlan
+from codeverse.contracts.spec import Spec
+from codeverse.languages.glsl_shader.gl_build import SHEET_NAME, read_metrics
+from codeverse.prompts import prompt_hash, render
+from codeverse.tracks.common import RunContext, language_contract
+from codeverse.tracks.generation import SINGLE_SHOT_FORMAT
+from codeverse.tracks.planner import PlanningError, _parse_json
+from codeverse.tracks.prompting import (
+ AGENT_OUTPUT_RULES,
+ acceptance_lines,
+ constraints_text,
+ reference_note,
+)
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+PLAN_TEMPLATE = "tracks/plan_graphics.j2"
+EXPECTED_FILES: dict[Language, list[str]] = {
+ Language.GLSL_SHADER: ["src/shader.frag", "src/common.glsl"],
+ Language.OPENGL_PYTHON: ["src/program.py"],
+}
+
+
+# ----------------------------------------------------------------------------- planner
+def plan_example() -> dict[str, Any]:
+ return {
+ "title": "Neon rain on a window", "summary": "Looking through a rain-streaked window at a neon-lit street at night; "
+ "drops run down the glass, city lights turn into coloured bokeh discs that pulse.",
+ "style": "cyberpunk night: deep indigo/black base, magenta + cyan neon accents, warm sodium highlights; soft, filmic",
+ "resolution": [1280, 720], "duration_s": 8.0,
+ "passes": [
+ {"name": "CityBokeh", "kind": "fullscreen", "description": "background: 40-60 blurred bokeh discs (hash-placed, 3 depth layers, cyan/magenta/amber), slow horizontal parallax, pulsing brightness"},
+ {"name": "RainDrops", "kind": "fullscreen", "description": "grid-cell drops with hash offsets, running trails (fract(t) per cell), refraction offset applied when sampling the background"},
+ {"name": "Grade", "kind": "postprocess", "description": "vignette, slight chromatic aberration, tonemap + gamma"},
+ ],
+ "uniforms": ["u_time", "u_resolution"],
+ "motion": "drops slide down with gravity and wobble; bokeh drifts left 0.02/s and pulses at 0.5-1 Hz; no hard cuts",
+ "key_visuals": ["rain drops with trails on glass", "blurred neon bokeh discs", "dark night street behind", "magenta/cyan palette"],
+ "acceptance": [
+ {"id": "a1", "text": "Raindrops with trails visibly run down the glass (compare t=0 and t=1)", "how": "visual", "priority": "must"},
+ {"id": "a2", "text": "Blurred coloured bokeh lights are visible in the background", "how": "visual", "priority": "must"},
+ {"id": "a3", "text": "Frames change over time (no static image)", "how": "probe", "priority": "must"},
+ ],
+ }
+
+
+def build_plan_system_prompt(spec: Spec, *, runtime: Any | None = None) -> str:
+ return render(PLAN_TEMPLATE, track=spec.track.value, language=spec.language.value,
+ contract=language_contract(spec.language, runtime)[:6000],
+ example_json=json.dumps(plan_example(), indent=1),
+ schema_fields=", ".join(GraphicsPlan.model_json_schema().get("properties", {}).keys()))
+
+
+def build_plan_user_prompt(spec: Spec) -> str:
+ return "\n".join([f"REQUEST: {spec.prompt}", "", "CONSTRAINTS:", constraints_text(spec), "",
+ "Return the plan as JSON matching the schema."])
+
+
+def ensure_graphics_acceptance(plan: GraphicsPlan, spec: Spec) -> GraphicsPlan:
+ """Spec must_have / must_not → visual items; planned motion → a probe item (never 'ground contact')."""
+ items: list[AcceptanceItem] = list(plan.acceptance)
+ have = {a.text.strip().lower() for a in items}
+ ids = {a.id for a in items}
+
+ def _add(prefix: str, text: str, how: str) -> None:
+ if text.strip().lower() in have:
+ return
+ n = 1
+ while f"{prefix}{n}" in ids:
+ n += 1
+ ids.add(f"{prefix}{n}")
+ items.append(AcceptanceItem(id=f"{prefix}{n}", text=text, how=how, priority="must")) # type: ignore[arg-type]
+
+ for m in spec.constraints.must_have:
+ _add("must", f"Includes: {m}", "visual")
+ for m in spec.constraints.must_not:
+ _add("not", f"Does NOT include: {m}", "visual")
+ if plan.motion.strip() and not any("static" in a.text.lower() or "motion" in a.text.lower() or "change over time" in a.text.lower() for a in items):
+ _add("motion", "Frames change over time as planned (not a static image)", "probe")
+ plan.acceptance = items
+ return plan
+
+
+def plan_graphics(spec: Spec, model_id: str, ws: Workspace, *, model: Any | None = None, events: Any | None = None,
+ budget: Any | None = None, runtime: Any | None = None) -> GraphicsPlan:
+ """Structured planner call → validated GraphicsPlan (one re-ask with the validation errors)."""
+ if model is None:
+ from codeverse.models import get_chat_model
+
+ model = get_chat_model(model_id)
+ system = build_plan_system_prompt(spec, runtime=runtime)
+ messages = [ChatMessage.user(build_plan_user_prompt(spec))]
+ schema = GraphicsPlan.model_json_schema()
+ usage = Usage()
+ last_error = ""
+ for attempt in range(2):
+ req = ChatRequest(messages=messages, system=system, response_schema=schema, temperature=0.5, thinking="medium",
+ max_output_tokens=16000, label=f"planner{'-retry' if attempt else ''}")
+ resp = model.generate(req)
+ usage = usage + resp.usage
+ raw = resp.parsed if resp.parsed is not None else _parse_json(resp.text)
+ try:
+ if not isinstance(raw, dict):
+ raise ValueError(f"planner returned {type(raw).__name__}, expected a JSON object")
+ plan = GraphicsPlan.model_validate(raw)
+ except (ValidationError, ValueError) as e:
+ last_error = str(e)[:4000]
+ if events is not None:
+ events.emit("plan.invalid", attempt=attempt, error=last_error[:500])
+ messages = messages + [ChatMessage.assistant(json.dumps(raw)[:20000] if raw is not None else (resp.text or "")[:20000]),
+ ChatMessage.user("Your plan failed validation. Fix EXACTLY these problems and return the full corrected "
+ f"plan JSON again (same schema):\n{last_error}")]
+ continue
+ plan = ensure_graphics_acceptance(plan, spec)
+ ws.write_json(ws.plan_path, plan)
+ if budget is not None:
+ budget.charge(usage)
+ if events is not None:
+ events.emit("plan.done", model=model_id, attempt=attempt, n_passes=len(plan.passes), n_acceptance=len(plan.acceptance),
+ cost_usd=round(usage.cost_usd, 4), prompt_hash=prompt_hash(system))
+ return plan
+ if budget is not None:
+ budget.charge(usage)
+ raise PlanningError(f"graphics plan did not validate after re-ask: {last_error}")
+
+
+# ----------------------------------------------------------------------------- prompt context
+def expected_files(ctx: RunContext) -> list[str]:
+ return list(EXPECTED_FILES.get(ctx.language, ["src/shader.frag"]))
+
+
+def passes_table(plan: GraphicsPlan | None) -> str:
+ if plan is None or not plan.passes:
+ return "(no passes)"
+ rows = ["| pass | kind | what it draws / computes |", "|---|---|---|"]
+ rows += [f"| {p.name} | {p.kind} | {p.description} |" for p in plan.passes]
+ return "\n".join(rows)
+
+
+def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
+ """Every variable the graphics templates may reference (StrictUndefined)."""
+ plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None
+ res = plan.resolution if plan else (1280, 720)
+ d: dict[str, Any] = {
+ "track": ctx.track.value, "language": ctx.language.value, "contract": ctx.contract_text,
+ "cookbook_rel": ctx.cookbook_rel, "cookbook_excerpt": ctx.cookbook_text[:7000], "tool_cards": ctx.tool_cards,
+ "single_shot": ctx.single_shot, "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,
+ "spec_prompt": ctx.spec.prompt, "constraints": constraints_text(ctx.spec),
+ "title": plan.title if plan else "Untitled effect", "plan_summary": plan.summary if plan else "",
+ "style": plan.style if plan else "", "resolution": f"{res[0]}x{res[1]}", "duration": f"{plan.duration_s:g}" if plan else "8",
+ "passes_table": passes_table(plan), "motion": plan.motion if plan else "", "key_visuals": list(plan.key_visuals) if plan else [],
+ "uniforms": ", ".join(plan.uniforms) if plan and plan.uniforms else "u_time, u_resolution",
+ "acceptance": acceptance_lines(plan), "entry_files": ", ".join(getattr(ctx.runtime, "entry_globs", ()) or ()),
+ "expected_files": expected_files(ctx), "reference_note": reference_note(ctx),
+ "judge_times": "0, 1, 2.5, 4, 6 s",
+ }
+ d.update(extra)
+ return d
+
+
+# ----------------------------------------------------------------------------- renders / gates
+def frames_render_set(ws: Workspace, build: BuildResult, round_index: int) -> RenderSet:
+ """Copy the judged frames + sheet into renders/rNN and describe them as a RenderSet (views ``t=<s>s``)."""
+ out = ws.renders_dir(round_index)
+ out.mkdir(parents=True, exist_ok=True)
+ frames_dir = Path(build.extra_paths.get("frames", ws.artifacts / "frames"))
+ metrics = read_metrics(ws)
+ stats = metrics[0] if metrics else None
+ views: list[RenderView] = []
+ frames = stats.frames if stats else []
+ for f in frames:
+ src = Path(f.path)
+ if not src.is_file():
+ continue
+ dst = out / f"frame_t{f.time:05.2f}.png"
+ shutil.copy2(src, dst)
+ views.append(RenderView(name=f"t={f.time:g}s", path=str(dst), time_s=f.time))
+ if not views and frames_dir.is_dir(): # metrics missing: fall back to the raw frame files
+ for p in sorted(frames_dir.glob("f*_t*.png")):
+ dst = out / p.name
+ shutil.copy2(p, dst)
+ views.append(RenderView(name=p.stem.split("_t", 1)[-1] + "s", path=str(dst)))
+ sheet_src = Path(build.extra_paths.get("sheet", ws.artifacts / SHEET_NAME))
+ sheet = None
+ if sheet_src.is_file():
+ sheet = out / "sheet.png"
+ shutil.copy2(sheet_src, sheet)
+ renderer = str(build.census.get("renderer", "")) if isinstance(build.census, dict) else ""
+ return RenderSet(views=views, contact_sheet=str(sheet) if sheet else None, renderer=renderer or "moderngl",
+ duration_ms=build.duration_ms)
+
+
+def frame_stats_text(ws: Workspace) -> str:
+ m = read_metrics(ws)
+ if m is None:
+ return "(no frame metrics)"
+ stats, gate = m
+ lines = stats.summary_lines()
+ for f in gate.findings:
+ lines.append(f"- GATE gl_frames [{f.severity.value}] {f.message}" + (f" FIX: {f.fix_hint}" if f.fix_hint and f.severity.value != "info" else ""))
+ return "\n".join(lines)
+
+
+def refine_lines(tasks: Sequence[Any]) -> list[str]:
+ return [t.line() for t in tasks]
diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.py
index 9f2364b7..8354c366 100644
--- a/harness/codeverse/tracks/lifecycle.py
+++ b/harness/codeverse/tracks/lifecycle.py
@@ -12,6 +12,7 @@ import logging
import platform
import traceback
from collections.abc import Sequence
+from dataclasses import replace
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
@@ -26,6 +27,7 @@ from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard
from codeverse.orchestrator.rounds import BestSelector, RoundPolicy, StopPolicy, StopReason
from codeverse.orchestrator.runner import StageRunner
from codeverse.orchestrator.state import RunState
+from codeverse.tracks.candidates import choose_best_round, run_best_of_n
from codeverse.tracks.common import (
RunContext,
Services,
@@ -35,17 +37,44 @@ from codeverse.tracks.common import (
)
from codeverse.tracks.generation import GenerationTask, is_single_shot, single_shot_model_id
from codeverse.tracks.planner import plan as run_planner
-from codeverse.tracks.steps import RoundFailed, RoundPipeline, load_round_records, run_round, sum_usage
+from codeverse.tracks.steps import (
+ RoundFailed,
+ RoundPipeline,
+ load_round_records,
+ rejudge_round,
+ run_round,
+ sum_usage,
+)
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
+REFERENCE_RUBRIC = "reference_v1"
+
_STATUS: dict[str, RunStatus] = {
"pass": RunStatus.PASSED, "plateau": RunStatus.PLATEAU, "max_rounds": RunStatus.PLATEAU,
"budget": RunStatus.BUDGET,
+ # judge outage (degraded/crashed verdicts even after a retry): the code is intact
+ # and the best built round is delivered — a stop, not a failure.
+ "judge_unavailable": RunStatus.PLATEAU,
}
+def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
+ """Only the spec fields the PLAN depends on: hashing the whole Spec meant that
+ raising ``budget.max_usd`` in spec.json (the only way to continue a BUDGET-stopped
+ run) re-planned + re-skeletoned on resume, overwriting src/ under existing rounds."""
+ return {
+ "prompt": spec.prompt,
+ "track": spec.track.value,
+ "language": spec.language.value,
+ "constraints": spec.constraints,
+ "references": spec.references,
+ "planner": spec.backends.planner,
+ "seed": spec.seed,
+ }
+
+
class BaseTrack:
"""Shared lifecycle. Subclasses set ``track``, ``rubric``, ``plan_model``."""
@@ -64,6 +93,7 @@ class BaseTrack:
policy: RoundPolicy | None = None,
settings: Settings | None = None,
planner_model: Any | None = None,
+ n_candidates: int | None = None,
):
self.services = services or Services()
self._judge = judge
@@ -73,6 +103,7 @@ class BaseTrack:
self._policy = policy
self._settings = settings
self._planner_model = planner_model
+ self._n_candidates = n_candidates
# ------------------------------------------------------------------ hooks
def make_pipeline(self, ctx: RunContext) -> RoundPipeline:
@@ -113,7 +144,7 @@ class BaseTrack:
stop: StopReason | str = "failed"
error = ""
try:
- ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs={"spec": spec, "track": self.track.value},
+ ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs={"spec": plan_stage_inputs(spec), "track": self.track.value},
model=self.plan_model)
self.after_plan(ctx)
self.prepare(ctx, runner)
@@ -125,6 +156,7 @@ class BaseTrack:
except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud
error = f"{type(e).__name__}: {e}"
events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])
+ self._save_spent(ctx) # mid-round charges must survive for resume
state.status, state.error = RunStatus.FAILED, error
state.save(ws)
rec = self._record(ctx, rounds, RunStatus.FAILED, error=error, stop_reason="failed")
@@ -142,9 +174,13 @@ class BaseTrack:
spent = state.extra.get("spent_usage")
if spent:
budget.spent = Usage.model_validate(spent)
- policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)
+ n_cand = self._resolve_candidates(state, settings)
+ policy = (self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)).with_candidates(n_cand)
+ # reference images: static objects are scored with reference_v1 (adds the measured silhouette
+ # criterion); other tracks keep their rubric but the judge still sees the references.
+ rubric = REFERENCE_RUBRIC if spec.references and self.track is Track.STATIC_OBJECT else self.rubric
ctx = RunContext(spec=spec, ws=ws, events=events, settings=settings, budget=budget, runtime=runtime,
- services=self.services, state=state, policy=policy, track=self.track, rubric=self.rubric,
+ services=self.services, state=state, policy=policy, track=self.track, rubric=rubric,
agent_id=spec.backends.generator, agent=self._agent, model=self._model)
ctx.contract_text = language_contract(spec.language, runtime)
ctx.cookbook_rel = cookbook_rel_for(spec.language)
@@ -154,14 +190,34 @@ class BaseTrack:
ctx.record_prompt(name, text)
return ctx
+ def _resolve_candidates(self, state: RunState, settings: Settings) -> int:
+ """Best-of-N width: constructor (CLI --candidates) > persisted run state (resume) > settings default."""
+ n = self._n_candidates
+ if n is None:
+ n = state.extra.get("n_candidates")
+ if n is None:
+ n = getattr(settings, "default_candidates", 1)
+ n = max(1, int(n or 1))
+ state.extra["n_candidates"] = n
+ return n
+
+ def make_judge(self, ctx: RunContext, *, n_samples: int | None = None) -> Any:
+ """The main judge: injected → reference judge when the spec has images → rubric VLM judge."""
+ if self._judge is not None:
+ return self._judge
+ n_samples = ctx.policy.judge_samples if n_samples is None else n_samples
+ if ctx.spec.references:
+ return self.services.reference_judge(ctx.spec.backends.judge, n_samples=n_samples, rubric=ctx.rubric)
+ return self.services.judge(ctx.rubric, ctx.spec.backends.judge, n_samples=n_samples)
+
def after_plan(self, ctx: RunContext) -> None:
"""Bind judge / generator backends once the plan exists (rubric threshold → policy target)."""
if ctx.judge is None:
- ctx.judge = self._judge if self._judge is not None else self.services.judge(self.rubric, ctx.spec.backends.judge, n_samples=2)
+ ctx.judge = self.make_judge(ctx)
if self._policy is None:
- thr = self.services.rubric_threshold(self.rubric)
+ thr = self.services.rubric_threshold(ctx.rubric)
if thr is not None:
- ctx.policy = RoundPolicy(max_rounds=ctx.spec.budget.max_rounds, target=float(thr))
+ ctx.policy = replace(ctx.policy, target=float(thr))
if ctx.single_shot:
if ctx.model is None:
ctx.model = self.services.chat_model(single_shot_model_id(ctx.agent_id))
@@ -183,7 +239,13 @@ class BaseTrack:
ctx.ws.commit("skeleton")
return [str(Path(p).relative_to(ctx.ws.root)) if Path(p).is_absolute() else str(p) for p in paths]
- return runner.stage("skeleton", _do, inputs={"plan": ctx.plan, "language": ctx.language.value})
+ inputs = {"plan": ctx.plan, "language": ctx.language.value}
+ if ctx.state.completed_rounds and not runner.is_done("skeleton", inputs):
+ # stale skeleton hash on resume: rounds exist, so re-running the skeleton
+ # writer would overwrite agent-authored src/ — never do that.
+ ctx.events.emit("skeleton.skipped", reason="rounds_exist", rounds=len(ctx.state.completed_rounds))
+ return []
+ return runner.stage("skeleton", _do, inputs=inputs)
def ensure_materialized(self, ctx: RunContext) -> None:
"""Materialise AGENTS.md/MCP config once per run for agent generators."""
@@ -209,6 +271,7 @@ class BaseTrack:
pipeline = self.make_pipeline(ctx)
stop_policy = StopPolicy(ctx.policy)
selector = BestSelector()
+ rejudged: set[int] = set()
while True:
decision = stop_policy.decide(rounds, budget_ok=ctx.budget.ok()) if rounds else "continue"
if decision != "continue":
@@ -221,16 +284,36 @@ class BaseTrack:
tasks, instructions, kind = self.baseline_tasks(ctx), [], "baseline"
else:
ctx.state.status = RunStatus.REFINING
- tasks, instructions = self.refine_tasks(ctx, rounds[-1], rounds)
+ last = rounds[-1]
+ if last.judgment is None and last.build is not None and last.build.ok and last.index not in rejudged:
+ # judge outage/degraded verdict on a clean build: re-judge the SAME
+ # commit once (no regeneration) before planning refinements from nothing.
+ rejudged.add(last.index)
+ prev_j = rounds[-2].judgment if len(rounds) > 1 else None
+ if rejudge_round(ctx, pipeline, last, previous=prev_j):
+ best = choose_best_round(ctx, rounds, selector, last.index)
+ if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):
+ ctx.events.emit("best.updated", round=best, score=rounds[best].score)
+ self._save_spent(ctx)
+ continue # decide() re-runs with the recovered score
+ tasks, instructions = self.refine_tasks(ctx, last, rounds)
kind = "refine"
if not tasks:
+ if last.judgment is None and last.build is not None and last.build.ok:
+ # no tasks only because the judge never scored the round: stopping
+ # as 'plateau' would blame the code for a judge glitch
+ ctx.events.emit("stop", reason="judge_unavailable", rounds=len(rounds), best=ctx.state.best_round)
+ return "judge_unavailable"
ctx.events.emit("stop", reason="no_refine_tasks", rounds=len(rounds))
return "plateau"
ctx.state.current_round = index
ctx.state.save(ctx.ws)
try:
- rec = run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
- previous=previous, files_hint=self.round_files_hint(ctx))
+ if index == 0 and tasks and ctx.policy.n_candidates > 1:
+ rec = run_best_of_n(self, ctx, tasks, pipeline, files_hint=self.round_files_hint(ctx))
+ else:
+ rec = run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
+ previous=previous, files_hint=self.round_files_hint(ctx))
except RoundFailed as e:
if index == 0:
raise
@@ -242,7 +325,7 @@ class BaseTrack:
return "plateau"
rounds.append(rec)
ctx.state.mark_round_done(index, rec.commit)
- best = selector.pick(rounds)
+ best = choose_best_round(ctx, rounds, selector, index)
if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):
ctx.events.emit("best.updated", round=best, score=rounds[best].score)
self._save_spent(ctx)
@@ -253,8 +336,9 @@ class BaseTrack:
# ------------------------------------------------------------------ finalise
def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, stop_reason: str, error: str = "") -> RunRecord:
+ self._save_spent(ctx) # aborted-round / stage charges must survive for resume
best = ctx.state.best_round
- if best is not None and rounds and rounds[best].commit and ctx.ws.head() != rounds[best].commit:
+ if best is not None and best < len(rounds) and rounds[best].commit and self._needs_restore(ctx, rounds[best].commit):
ctx.ws.restore(rounds[best].commit)
ctx.ws.commit(f"restore best round r{best:02d}")
try:
@@ -262,6 +346,8 @@ class BaseTrack:
ctx.events.emit("finalise.rebuild", round=best, ok=build.ok)
except Exception as e: # noqa: BLE001 — the best round already built once; report, don't fail
ctx.events.emit("finalise.rebuild_failed", error=f"{type(e).__name__}: {e}")
+ if rounds and ("texture" in ctx.spec.tags or ctx.extra.get("texture")):
+ self._texture_pass(ctx)
ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, stop_reason, error
ctx.state.save(ctx.ws)
rec = self._record(ctx, rounds, status, error=error, stop_reason=stop_reason)
@@ -270,6 +356,34 @@ class BaseTrack:
final_score=rec.final_score, cost_usd=round(rec.total_usage.cost_usd, 4))
return rec
+ @staticmethod
+ def _needs_restore(ctx: RunContext, best_commit: str) -> bool:
+ """src/ != best commit: HEAD moved on, OR an aborted round dirtied the tree
+ without committing (budget stop mid-generation) — HEAD alone cannot see that."""
+ if ctx.ws.head() != best_commit:
+ return True
+ try:
+ return bool(ctx.ws.changed_files())
+ except Exception as e: # noqa: BLE001 — a git hiccup must not block finalise
+ log.warning("changed_files failed in finalise: %s", e)
+ return False
+
+ def _texture_pass(self, ctx: RunContext) -> None:
+ """Optional post-hoc texture pass (spec tag 'texture'). Additive: any failure
+ is logged + emitted, never fatal; usage is added to the budget totals."""
+ try:
+ from codeverse.texturing.run import texture_pass
+
+ trep = texture_pass(ctx.ws, ctx.spec, ctx.plan, model_id=ctx.spec.backends.planner, judge=True,
+ judge_model_id=ctx.spec.backends.judge, rubric=self.rubric, events=ctx.events,
+ update_record=False)
+ except Exception as e: # noqa: BLE001 — texturing is a derived asset pack, never run-fatal
+ log.warning("texture pass failed: %s", e)
+ ctx.events.emit("texture.failed", error=f"{type(e).__name__}: {e}")
+ return
+ ctx.budget.add(trep.usage)
+ ctx.extra["texturing"] = trep.summary()
+
def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str, stop_reason: str) -> RunRecord:
best = ctx.state.best_round
baseline = rounds[0].score if rounds else None
@@ -278,6 +392,10 @@ class BaseTrack:
# planner + other non-round calls are in the budget guard but not in rounds
if ctx.budget.spent.cost_usd > total.cost_usd:
total = ctx.budget.spent
+ extra: dict[str, Any] = {"stop_reason": stop_reason, "rubric": ctx.rubric, "budget": ctx.budget.summary(),
+ "n_candidates": ctx.policy.n_candidates, "candidates": ctx.state.extra.get("candidates")}
+ if ctx.extra.get("texturing"):
+ extra["texturing"] = ctx.extra["texturing"]
return RunRecord(
spec=ctx.spec, plan=ctx.plan, workspace=str(ctx.ws.root), status=status, rounds=rounds, best_round=best,
baseline_score=baseline, final_score=final, total_usage=total,
@@ -285,7 +403,7 @@ class BaseTrack:
"language": ctx.language.value, "generator": ctx.agent_id},
prompt_hashes=dict(ctx.prompt_hashes), started_at=ctx.state.started_at,
finished_at=datetime.now(UTC), error=error,
- extra={"stop_reason": stop_reason, "rubric": self.rubric, "budget": ctx.budget.summary()},
+ extra=extra,
)
diff --git a/harness/codeverse/tracks/motion.py b/harness/codeverse/tracks/motion.py
new file mode 100644
index 00000000..33ca8f07
--- /dev/null
+++ b/harness/codeverse/tracks/motion.py
@@ -0,0 +1,150 @@
+"""Planned joint motion → expected direction → deterministic check on the built URDF.
+
+The planner writes one line per joint ("drawer pulls out towards -Y", "lid
+opens upward", "door swings to the left"). When that text names an obvious
+direction we map it to one of ``codeverse.spatial.joints`` direction keys
+(Z-up, -Y front — the URDF/Blender authoring frame) and ask
+``motion_direction_check`` whether the child link really moves that way when
+the joint moves positively from rest. A wrong direction is a gate ERROR with
+the concrete fix (negate the axis / swap the limits); ambiguous or silent text
+is skipped — this gate never guesses.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from collections.abc import Sequence
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.plan import Plan
+from codeverse.conventions import to_snake
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+MOTION_GATE = "motion_direction"
+
+#: phrase → direction key understood by ``spatial.joints.motion_direction_check``.
+#: Longer phrases first so "pulls out" wins over "out"; explicit axes first of all.
+_PHRASES: tuple[tuple[str, str], ...] = (
+ ("-y", "-y"), ("+y", "+y"), ("-z", "-z"), ("+z", "+z"), ("-x", "-x"), ("+x", "+x"),
+ ("towards the front", "front"), ("toward the front", "front"), ("to the front", "front"),
+ ("opens to the front", "front"), ("opens out", "front"), ("pulls out", "front"), ("slides out", "front"),
+ ("pull out", "front"), ("slide out", "front"), ("swings out", "front"), ("outward", "front"), ("forward", "front"),
+ ("towards the viewer", "front"), ("toward the viewer", "front"), ("frontward", "front"),
+ ("towards the back", "back"), ("toward the back", "back"), ("to the back", "back"), ("pushes in", "back"),
+ ("slides in", "back"), ("backward", "back"), ("rearward", "back"), ("inward", "back"),
+ ("upward", "up"), ("upwards", "up"), ("opens up", "up"), ("lifts", "up"), ("lift", "up"), ("raises", "up"),
+ ("raise", "up"), ("rises", "up"),
+ ("downward", "down"), ("downwards", "down"), ("lowers", "down"), ("drops", "down"),
+ ("folds down", "down"), ("opens down", "down"),
+ ("to the left", "left"), ("leftward", "left"), ("swings left", "left"),
+ ("to the right", "right"), ("rightward", "right"), ("swings right", "right"),
+ ("front", "front"), ("back", "back"), ("up", "up"), ("down", "down"), ("left", "left"), ("right", "right"),
+ ("out", "front"),
+)
+
+_SKIP_MARKERS = ("not ", "n't", "either", "both", "around", "rotates about", "spins")
+_DIR_GROUPS = {"front": "y", "back": "y", "-y": "y", "+y": "y", "up": "z", "down": "z", "+z": "z", "-z": "z",
+ "left": "x", "right": "x", "-x": "x", "+x": "x"}
+
+
+def expected_direction(motion: str) -> str | None:
+ """Direction key for an obvious motion description, else ``None``.
+
+ Rules: explicit signed axes win; otherwise the first (longest) phrase hit;
+ text naming two different axes ("up and to the left"), negations or pure
+ rotations ("spins around its axis") → ``None`` (ambiguous — skip)."""
+ text = " ".join((motion or "").lower().replace("_", " ").split())
+ if not text or any(m in text for m in _SKIP_MARKERS):
+ return None
+ padded = f" {text} "
+ hits: list[str] = []
+ for phrase, key in _PHRASES:
+ if _contains_word(padded, phrase):
+ hits.append(key)
+ if key in ("-y", "+y", "-z", "+z", "-x", "+x"):
+ return key
+ if not hits:
+ return None
+ axes = {_DIR_GROUPS[h] for h in hits}
+ if len(axes) > 1:
+ # "opens up and out" — up/front conflict: the longest phrase decides only if one axis dominates
+ first_axis = _DIR_GROUPS[hits[0]]
+ if any(_DIR_GROUPS[h] != first_axis for h in hits[1:]):
+ return None
+ return hits[0]
+
+
+def _contains_word(padded: str, phrase: str) -> bool:
+ """Whole-word containment (phrase boundaries are spaces or punctuation)."""
+ i = padded.find(phrase)
+ while i >= 0:
+ before = padded[i - 1] if i > 0 else " "
+ after = padded[i + len(phrase)] if i + len(phrase) < len(padded) else " "
+ if not before.isalnum() and not after.isalnum():
+ return True
+ i = padded.find(phrase, i + 1)
+ return False
+
+
+def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str) -> str:
+ if axis is not None and len(axis) == 3:
+ neg = tuple(-float(a) for a in axis)
+ return (f"in src/robot.urdf set joint '{joint_name}' <axis xyz=\"{neg[0]:g} {neg[1]:g} {neg[2]:g}\"/> "
+ f"(negate the axis) — or swap lower/upper so positive motion goes {expected}")
+ return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (or swap lower/upper) so motion goes {expected}"
+
+
+def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None:
+ """Run ``motion_direction_check`` for every plan joint with an obvious motion
+ direction. ``None`` when the plan has no such joints; unknown joints /
+ missing meshes are WARN findings (the sweep gate already reports them)."""
+ joints = list(getattr(plan, "joints", None) or [])
+ wanted = [(j, expected_direction(j.motion)) for j in joints]
+ wanted = [(j, d) for j, d in wanted if d is not None]
+ if not wanted:
+ return None
+ from codeverse.spatial import joints as sj
+
+ urdf = _find_urdf(ws)
+ if urdf is None:
+ return None
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ try:
+ robot = sj.load_urdf(urdf, ws.artifacts / "meshes")
+ except sj.UrdfError as e:
+ return GateReport(gate=MOTION_GATE, passed=True, findings=[GateFinding(
+ gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}")])
+ urdf_names = {to_snake(n): n for n in getattr(robot, "joints", {})}
+ for j, expected in wanted:
+ name = urdf_names.get(to_snake(j.name), j.name) # URDF joint named like the plan joint (any casing)
+ try:
+ chk = sj.motion_direction_check(robot, name, expected)
+ except sj.UrdfError as e:
+ findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.WARN, target=j.name,
+ message=f"motion check skipped: {e}", data={"expected": expected}))
+ continue
+ data = {"expected": expected, "observed_dir": list(chk.observed_dir), "motion": j.motion}
+ if chk.ok:
+ findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))
+ else:
+ findings.append(GateFinding(
+ gate=MOTION_GATE, severity=Severity.ERROR, target=j.name,
+ message=f"{chk.message}. Plan says: \"{j.motion}\"",
+ fix_hint=axis_fix_hint(j.name, getattr(j, "axis", None), expected), data=data))
+ return GateReport(gate=MOTION_GATE, passed=not any(f.severity == Severity.ERROR for f in findings),
+ findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+def _find_urdf(ws: Workspace) -> Path | None:
+ for cand in (ws.artifacts / "robot.urdf", ws.src / "robot.urdf"):
+ if cand.is_file():
+ return cand
+ return None
+
+
+__all__ = ["MOTION_GATE", "axis_fix_hint", "default_motion_checks", "expected_direction"]
diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.py
index 4ad59fa2..03ee5931 100644
--- a/harness/codeverse/tracks/planner.py
+++ b/harness/codeverse/tracks/planner.py
@@ -23,7 +23,8 @@ from codeverse.contracts.plan import AcceptanceItem, ArticulatedPlan, ScenePlan,
from codeverse.contracts.spec import Spec
from codeverse.conventions import LANGUAGE_FRAME, frame_doc, to_pascal
from codeverse.prompts import prompt_hash, render
-from codeverse.tracks.common import constraints_text, language_contract, load_prompt_or
+from codeverse.tracks.common import language_contract, load_prompt_or
+from codeverse.tracks.prompting import constraints_text
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
new file mode 100644
index 00000000..19e30e3e
--- /dev/null
+++ b/harness/codeverse/tracks/prompting.py
@@ -0,0 +1,216 @@
+"""Prompt context for the tracks' jinja templates (``prompts/tracks/*.j2``).
+
+Everything a template may reference is produced here from the spec, the plan
+and the run context — exact numbers (bbox tables in meters), acceptance lines,
+the language frame doc, reference-image notes — plus ``file_for_target_factory``
+which maps a refine target (part / zone / asset) to the files that own it.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.chat import ImagePart
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan, StaticPlan
+from codeverse.conventions import LANGUAGE_FRAME, Frame, frame_doc, to_snake
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import SINGLE_SHOT_FORMAT
+
+log = logging.getLogger(__name__)
+
+
+def parts_table(plan: Plan) -> str:
+ """Markdown table of parts with exact bboxes (meters, 3 decimals)."""
+ parts = getattr(plan, "parts", None)
+ if not parts:
+ return "(no parts)"
+ rows = ["| part | role | bbox centre (x,y,z) m | extents (x,y,z) m | attach_to | inst | material |",
+ "|---|---|---|---|---|---|---|"]
+ for p in parts:
+ c = ", ".join(f"{v:.3f}" for v in p.bbox.center)
+ e = ", ".join(f"{v:.3f}" for v in p.bbox.extents)
+ rows.append(f"| {p.name} | {p.role} | ({c}) | ({e}) | {p.attach_to or '-'} | {p.instances} | {p.material or '-'} |")
+ return "\n".join(rows)
+
+
+def part_details(plan: Plan) -> str:
+ parts = getattr(plan, "parts", None) or []
+ return "\n".join(f"- **{p.name}** ({p.symmetry if p.symmetry != 'none' else 'no symmetry'}): {p.description}" for p in parts)
+
+
+def joints_table(plan: Plan) -> str:
+ joints = getattr(plan, "joints", None)
+ if not joints:
+ return "(no joints)"
+ rows = ["| joint | type | parent | child | axis | pivot (world, m) | lower | upper | rest | motion |",
+ "|---|---|---|---|---|---|---|---|---|---|"]
+ for j in joints:
+ ax = ", ".join(f"{v:.3f}" for v in j.axis)
+ pv = ", ".join(f"{v:.3f}" for v in j.pivot)
+ rows.append(f"| {j.name} | {j.type} | {j.parent} | {j.child} | ({ax}) | ({pv}) | {j.lower:.3f} | {j.upper:.3f} | {j.rest:.3f} | {j.motion} |")
+ return "\n".join(rows)
+
+
+def acceptance_lines(plan: Plan | None) -> str:
+ items = getattr(plan, "acceptance", None) or []
+ if not items:
+ return "(none)"
+ return "\n".join(f"- [{a.id}] ({a.priority}, {a.how}) {a.text}" for a in items)
+
+
+def bbox_line(bbox: Any) -> str:
+ c = ", ".join(f"{v:.3f}" for v in bbox.center)
+ e = ", ".join(f"{v:.3f}" for v in bbox.extents)
+ return f"centre ({c}) m, extents ({e}) m"
+
+
+def glb_to_plan_frame(v: Sequence[float], language: Language, *, extents: bool = False) -> tuple[float, float, float]:
+ """Map a GLB-frame (Y-up, +Z front) vector into the language's authoring frame.
+ Blender/CadQuery/URDF plans are Z-up with -Y front: glb (x, y, z) → (x, -z, y)."""
+ x, y, z = float(v[0]), float(v[1]), float(v[2])
+ if LANGUAGE_FRAME[language.value] is Frame.Z_UP_NEG_Y_FRONT:
+ return (x, abs(z) if extents else -z, y)
+ return (x, y, z)
+
+
+def constraints_text(spec: Any) -> str:
+ c = spec.constraints
+ lines = []
+ if c.dimensions_m:
+ lines.append("Dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in c.dimensions_m.items()))
+ if c.max_triangles:
+ lines.append(f"Max triangles: {c.max_triangles}")
+ if c.style:
+ lines.append(f"Style: {c.style}")
+ for m in c.must_have:
+ lines.append(f"MUST HAVE: {m}")
+ for m in c.must_not:
+ lines.append(f"MUST NOT: {m}")
+ return "\n".join(lines) or "(none)"
+
+
+def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
+ """Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""
+ plan = ctx.plan
+ object_name = getattr(plan, "object_name", None) or getattr(plan, "title", None) or "Object"
+ d: dict[str, Any] = {
+ "track": ctx.track.value,
+ "language": ctx.language.value,
+ "frame_doc": frame_doc(LANGUAGE_FRAME[ctx.language.value]),
+ "contract": ctx.contract_text,
+ "cookbook_rel": ctx.cookbook_rel,
+ "cookbook_excerpt": ctx.cookbook_text[:6000],
+ "tool_cards": ctx.tool_cards,
+ "single_shot": ctx.single_shot,
+ "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,
+ "spec_prompt": ctx.spec.prompt,
+ "constraints": constraints_text(ctx.spec),
+ "object_name": object_name,
+ "plan_summary": getattr(plan, "summary", "") if plan else "",
+ "style_notes": getattr(plan, "style_notes", "") if plan else "",
+ "overall_bbox": bbox_line(plan.overall_bbox) if isinstance(plan, StaticPlan) else "",
+ "parts_table": parts_table(plan) if plan else "",
+ "part_details": part_details(plan) if plan else "",
+ "joints_table": joints_table(plan) if plan else "",
+ "acceptance": acceptance_lines(plan),
+ "entry_files": ", ".join(getattr(ctx.runtime, "entry_globs", ()) or ()),
+ "n_parts": len(getattr(plan, "parts", []) or []) if plan else 0,
+ "root_link": getattr(plan, "root_link", "") if plan else "",
+ "reference_note": reference_note(ctx),
+ }
+ d.update(extra)
+ return d
+
+
+def reference_images(ctx: RunContext, limit: int = 3) -> list[ImagePart]:
+ """The spec's reference images as inline image parts (single-shot prompts)."""
+ out: list[ImagePart] = []
+ for r in list(ctx.spec.references)[:limit]:
+ if Path(r.path).is_file():
+ out.append(ImagePart(path=r.path, label=f"reference ({r.role}){': ' + r.note if r.note else ''}"))
+ return out
+
+
+def reference_note(ctx: RunContext) -> str:
+ """Prompt paragraph telling the generator how to use the reference images (empty when none)."""
+ refs = [r for r in ctx.spec.references if Path(r.path).is_file()]
+ if not refs:
+ return ""
+ lines = [f"REFERENCE IMAGES ({len(refs)}): match their silhouette, proportions and visible details — they "
+ "outrank the text when the two disagree. A harness measures the front-view outline IoU against the "
+ "target reference; aim for IoU ≥ 0.6."]
+ for i, r in enumerate(refs, 1):
+ lines.append(f"- reference {i} ({r.role}): `{r.path}`" + (f" — {r.note}" if r.note else ""))
+ if ctx.single_shot:
+ lines.append("The images are attached to this message.")
+ else:
+ tgt = next((r.path for r in refs if r.role == "target"), refs[0].path)
+ lines.append(f"Use the `compare_silhouette` tool (render_png=<your front render>, reference_png=`{tgt}`) "
+ "after building to check the outline, and `render_views` to look at your model.")
+ return "\n".join(lines)
+
+
+AGENT_OUTPUT_RULES = """HOW TO FINISH (agent mode): edit files under src/ only (and public/ for compiled assets).
+Before you finish you MUST run the `build` tool and fix every error it reports; then run `measure`
+(objects) or `scene_probe` (scenes) once and compare the numbers with the plan. Do not write
+reports, READMEs or notes — only the code files. Stop when the build is clean."""
+
+
+def file_for_target_factory(ctx: RunContext):
+ """Return ``target → [files]`` for the current language, or ``None`` when the
+ language is whole-object (one file). Prefers ``runtime.file_for_part``."""
+ rt = ctx.runtime
+ plan = ctx.plan
+ custom = getattr(rt, "file_for_part", None)
+ part_names = {to_snake(p.name): p.name for p in (getattr(plan, "parts", None) or [])}
+ lang = ctx.language
+
+ if lang is Language.THREEJS or callable(custom):
+ entry = "src/object.js" if lang is Language.THREEJS else "src/model.py"
+
+ def _per_part(target: str) -> list[str]:
+ key = to_snake(target)
+ if key in part_names:
+ if callable(custom):
+ try:
+ out = custom(part_names[key])
+ if out:
+ return [str(out)] if isinstance(out, (str, Path)) else [str(p) for p in out]
+ except Exception as e: # noqa: BLE001
+ log.warning("runtime.file_for_part failed for %s: %s", target, e)
+ return [f"src/parts/{key}.js"] if lang is Language.THREEJS else [entry]
+ if key in ("overall", "assembly", "object", ""):
+ whole = getattr(rt, "file_for_target", None) # blender: 'overall' → src/model.py
+ if callable(whole):
+ try:
+ out = whole(target)
+ if out:
+ return [str(out)] if isinstance(out, (str, Path)) else [str(p) for p in out]
+ except Exception as e: # noqa: BLE001
+ log.warning("runtime.file_for_target failed for %s: %s", target, e)
+ return [entry]
+ return []
+ return _per_part
+
+ if lang is Language.SCENE_THREEJS:
+ zones = {to_snake(z.name) for z in (getattr(plan, "zones", None) or [])}
+ assets = {to_snake(a.name) for a in (getattr(plan, "assets", None) or [])}
+ cameras = {to_snake(c.name) for c in (getattr(plan, "cameras", None) or [])}
+
+ def _scene(target: str) -> list[str]:
+ key = to_snake(target)
+ if key in zones:
+ return [f"src/zones/{key}.js"]
+ if key in assets:
+ return [f"src/assets/{key}.js"]
+ if key in cameras or key in ("camera", "cameras", "composition"):
+ return ["src/scene.js"]
+ if key in ("env", "environment", "lighting", "sky", "fog", "ground", "water", "light"):
+ return ["src/env.js"]
+ return []
+ return _scene
+ return None
diff --git a/harness/codeverse/tracks/reference.py b/harness/codeverse/tracks/reference.py
new file mode 100644
index 00000000..ec78b501
--- /dev/null
+++ b/harness/codeverse/tracks/reference.py
@@ -0,0 +1,112 @@
+"""Reference-image support for object tracks.
+
+When ``spec.references`` is non-empty the planner already sees the images; the
+generator prompts carry a reference note (``prompting.reference_note``) and, for
+single-shot, the images themselves; the main judge becomes ``ReferenceJudge``
+(rubric ``reference_v1``). This module adds the deterministic part:
+
+* ``silhouette_gate`` — after rendering, the front view's outline IoU against
+ the *target* reference (``spatial.silhouette.compare_silhouette``) becomes a
+ ``reference_silhouette`` gate finding (WARN, with the numbers in ``data``).
+* ``reference_refine_tasks`` — when that IoU is below ``IOU_REFINE_THRESHOLD``
+ the next refine round gets a priority-1 task saying so, with the numbers.
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, RenderSet, RenderView, Severity
+from codeverse.contracts.run import RoundRecord
+from codeverse.orchestrator.rounds import RefineTask
+from codeverse.tracks.common import RunContext
+
+log = logging.getLogger(__name__)
+
+SILHOUETTE_GATE = "reference_silhouette"
+IOU_REFINE_THRESHOLD = 0.6
+FRONT_VIEW_NAMES: tuple[str, ...] = ("front", "front_right_34", "front_left_34")
+
+
+def target_reference(ctx: RunContext) -> str | None:
+ """Path of the reference image to match the silhouette against (role ``target`` first)."""
+ refs = [r for r in ctx.spec.references if Path(r.path).is_file()]
+ if not refs:
+ return None
+ return next((r.path for r in refs if r.role == "target"), refs[0].path)
+
+
+def front_view(renders: RenderSet) -> RenderView | None:
+ for name in FRONT_VIEW_NAMES:
+ for v in renders.views:
+ if v.name == name:
+ return v
+ return renders.views[0] if renders.views else None
+
+
+def silhouette_gate(ctx: RunContext, renders: RenderSet) -> GateReport | None:
+ """``None`` when the spec has no reference images or nothing could be compared."""
+ ref = target_reference(ctx)
+ view = front_view(renders)
+ if ref is None or view is None:
+ return None
+ try:
+ res = ctx.services.silhouette(view.path, ref)
+ except Exception as e: # noqa: BLE001 — advisory measurement; never fails a round
+ log.warning("compare_silhouette failed: %s", e)
+ return GateReport(gate=SILHOUETTE_GATE, passed=True, findings=[GateFinding(
+ gate=SILHOUETTE_GATE, severity=Severity.INFO, target="overall", message=f"silhouette comparison unavailable: {e}")])
+ iou = float(res.get("iou", 0.0)) if isinstance(res, dict) else 0.0
+ reliable = bool(res.get("reliable", True)) if isinstance(res, dict) else False
+ data = {k: v for k, v in (res.items() if isinstance(res, dict) else []) if isinstance(v, (int, float, str, bool))}
+ data["view"] = view.name
+ data["reference"] = ref
+ low = reliable and iou < IOU_REFINE_THRESHOLD
+ msg = (f"front-view outline IoU vs reference = {iou:.3f}" + ("" if reliable else " (unreliable mask)")
+ + (f" — below {IOU_REFINE_THRESHOLD:.1f}" if low else ""))
+ finding = GateFinding(gate=SILHOUETTE_GATE, severity=Severity.WARN if low else Severity.INFO, target="overall",
+ message=msg, data=data,
+ fix_hint=("match the reference outline: compare proportions (aspect ratio), overall extents and the "
+ "silhouette of each major part against the reference image" if low else ""))
+ return GateReport(gate=SILHOUETTE_GATE, passed=True, findings=[finding])
+
+
+def silhouette_iou(rec: RoundRecord) -> tuple[float, dict] | None:
+ """(iou, data) recorded by ``silhouette_gate`` in a round, if any."""
+ for g in rec.gates:
+ if g.gate != SILHOUETTE_GATE:
+ continue
+ for f in g.findings:
+ if "iou" in f.data:
+ try:
+ return float(f.data["iou"]), dict(f.data)
+ except (TypeError, ValueError):
+ return None
+ return None
+
+
+def reference_refine_tasks(ctx: RunContext, last: RoundRecord) -> list[RefineTask]:
+ """A priority-1 refine task when the last round's silhouette IoU was below threshold."""
+ if not ctx.spec.references:
+ return []
+ hit = silhouette_iou(last)
+ if hit is None:
+ return []
+ iou, data = hit
+ if iou >= IOU_REFINE_THRESHOLD or data.get("reliable") is False:
+ return []
+ bits = [f"Front-view silhouette IoU vs the reference image is {iou:.2f} (target ≥ {IOU_REFINE_THRESHOLD:.1f})."]
+ aspect = data.get("aspect_ratio_err")
+ if isinstance(aspect, (int, float)):
+ ra, rr = data.get("ref_aspect"), data.get("render_aspect")
+ if isinstance(ra, (int, float)) and isinstance(rr, (int, float)):
+ bits.append(f"Aspect (w/h): reference {ra:.2f} vs model {rr:.2f} — " +
+ ("make the object wider relative to its height" if rr < ra else "make the object taller relative to its width") + ".")
+ bits.append("Re-read the reference: match the outline of every major part (overall proportions first, then part shapes), "
+ "keeping names and the plan's dimensions unless the reference clearly disagrees.")
+ return [RefineTask(target="overall", kind="reference", instruction=" ".join(bits), priority=1, source="gate")]
+
+
+__all__ = ["FRONT_VIEW_NAMES", "IOU_REFINE_THRESHOLD", "SILHOUETTE_GATE", "front_view", "reference_refine_tasks",
+ "silhouette_gate", "silhouette_iou", "target_reference"]
diff --git a/harness/codeverse/tracks/repair.py b/harness/codeverse/tracks/repair.py
index e4769ad0..73160f74 100644
--- a/harness/codeverse/tracks/repair.py
+++ b/harness/codeverse/tracks/repair.py
@@ -19,8 +19,9 @@ from pydantic import BaseModel, Field
from codeverse.contracts.artifacts import BuildResult, GateReport
from codeverse.contracts.common import Usage
from codeverse.prompts import render
-from codeverse.tracks.common import RunContext, base_prompt_context
+from codeverse.tracks.common import RunContext
from codeverse.tracks.generation import GenerationResult, GenerationTask, generate
+from codeverse.tracks.prompting import base_prompt_context
log = logging.getLogger(__name__)
diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.py
index 4cf0072a..9201fb08 100644
--- a/harness/codeverse/tracks/scene.py
+++ b/harness/codeverse/tracks/scene.py
@@ -26,18 +26,19 @@ from codeverse.contracts.plan import ScenePlan, ZonePlan
from codeverse.contracts.run import RoundRecord
from codeverse.conventions import to_snake
from codeverse.orchestrator.fanout import fan_out
-from codeverse.orchestrator.rounds import TaskGroup, build_refine_instructions, plan_parallel_groups
+from codeverse.orchestrator.rounds import (
+ TaskGroup,
+ build_refine_instructions,
+ compact_instructions,
+ plan_parallel_groups,
+)
from codeverse.orchestrator.runner import StageRunner
from codeverse.prompts import render
-from codeverse.tracks.common import (
- RunContext,
- ServiceUnavailable,
- base_prompt_context,
- bbox_line,
- file_for_target_factory,
-)
+from codeverse.tracks.common import RunContext, ServiceUnavailable
from codeverse.tracks.generation import GenerationResult, GenerationTask, generate
from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.prompting import base_prompt_context, bbox_line, file_for_target_factory
+from codeverse.tracks.repair import format_error_report
from codeverse.tracks.scene_assets import AssetResult, asset_api_summary, run_asset_stage
from codeverse.tracks.static_object import current_files, judge_digest
from codeverse.tracks.steps import failed_acceptance
@@ -46,6 +47,7 @@ log = logging.getLogger(__name__)
SCENE_TIMES: tuple[float, float] = (0.0, 1.5)
MAX_CONSOLE_ERRORS = 8
+JUDGE_MAX_VIEWS = 10
class ScenePipeline:
@@ -78,7 +80,20 @@ class ScenePipeline:
if renders.fps is not None and renders.fps < 20:
findings.append(GateFinding(gate="render_console", severity=Severity.WARN, target="overall",
message=f"low frame rate {renders.fps:.0f} fps", fix_hint="reduce triangle/draw counts: merge geometries, use InstancedMesh"))
- return [GateReport(gate="render_console", passed=not errs, findings=findings)]
+ out = [GateReport(gate="render_console", passed=not errs, findings=findings)]
+ try:
+ # scene_frames: exposure / camera-in-geometry / coverage checks from metrics.json
+ # (missing metrics → a passing empty report); its ERROR findings carry fix hints
+ # that build_refine_instructions routes into the next round's tasks.
+ out.append(ctx.services.frame_gate(renders))
+ except Exception as e: # noqa: BLE001 — the frame gate is advisory instrumentation
+ log.warning("scene frame gate failed: %s", e)
+ ctx.events.emit("gate.frames_failed", round=round_index, error=f"{type(e).__name__}: {e}")
+ return out
+
+ def judge_views(self, ctx: RunContext, renders: RenderSet) -> RenderSet:
+ """The ≤ 10 views the judge sees (authored@t0 first); the full set stays on disk."""
+ return ctx.services.select_judge_views(renders, max_n=JUDGE_MAX_VIEWS)
def plan_summary(self, ctx: RunContext) -> str:
plan: ScenePlan = ctx.plan # type: ignore[assignment]
@@ -185,11 +200,13 @@ class SceneTrack(BaseTrack):
def refine_tasks(self, ctx: RunContext, last: RoundRecord, history: Sequence[RoundRecord]) -> tuple[list[GenerationTask], list[str]]:
index = len(history)
+ if last.build is None or not last.build.ok:
+ # no rebuild path meant a probe/console failure that lint does not flag
+ # yielded zero tasks and the run ended as 'plateau' with budget left
+ return [self._rebuild_task(ctx, last, index)], ["rebuild: previous round did not build"]
fft = file_for_target_factory(ctx)
tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
file_for_target=fft, max_tasks=ctx.policy.max_refine_tasks)
- if not tasks and last.build is not None and not last.build.ok:
- tasks = build_refine_instructions(None, last.gates, [], ctx.plan, file_for_target=fft)
if not tasks:
return [], []
groups = plan_parallel_groups(tasks)
@@ -199,7 +216,8 @@ class SceneTrack(BaseTrack):
gen = []
for g in groups:
files = g.files or ["src/scene.js", "src/env.js"]
- prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, round_index=index, tasks=[t.line() for t in g.tasks],
+ lines = compact_instructions(g.tasks, max_lines=ctx.policy.max_instructions_per_task)
+ prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, round_index=index, tasks=lines,
targets=g.targets, files=files, edit_only_these=parallel,
judge_summary=judge_digest(last),
current_files=current_files(ctx, files) if ctx.single_shot else {}))
@@ -209,6 +227,28 @@ class SceneTrack(BaseTrack):
ctx.events.emit("refine.planned", round=index, n_tasks=len(tasks), n_groups=len(groups), parallel=parallel)
return gen, [t.line() for t in tasks]
+ def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
+ """One repair task carrying the structured error report (build + lint + census
+ errors), targeted at the failing module when the build names one."""
+ lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
+ report = format_error_report(last.build, lint, ctx.cookbook_text) if last.build else "build did not run"
+ census = census_gate_report(last.build) if last.build else None
+ lines = [report] + [f"- {f.message}" + (f" FIX: {f.fix_hint}" if f.fix_hint else "")
+ for f in (census.errors if census else [])][:8]
+ files: list[str] = []
+ if last.build is not None and last.build.error_file:
+ rel = last.build.error_file.removeprefix(str(ctx.ws.root)).lstrip("/")
+ if (ctx.ws.root / rel).is_file():
+ files = [rel]
+ files = files or self.round_files_hint(ctx)
+ prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, round_index=index, tasks=lines, targets=["build"],
+ files=files, edit_only_these=False,
+ judge_summary="(no judgment: the scene did not build — fix the errors above first)",
+ current_files=current_files(ctx, files) if ctx.single_shot else {}))
+ ctx.record_prompt("scene_refine", prompt)
+ return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
+ kind="rebuild", temperature=0.7, thinking="high")
+
# ------------------------------------------------------------------ helpers
def system_prompt(self, ctx: RunContext) -> str:
return ("You are an expert three.js + GLSL graphics programmer writing RAW ESM modules for a multi-file scene. "
diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.py
index f65ce9e8..e5d5a196 100644
--- a/harness/codeverse/tracks/scene_assets.py
+++ b/harness/codeverse/tracks/scene_assets.py
@@ -26,13 +26,9 @@ from codeverse.contracts.spec import Spec
from codeverse.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake
from codeverse.orchestrator.fanout import fan_out
from codeverse.prompts import render
-from codeverse.tracks.common import (
- RunContext,
- base_prompt_context,
- language_contract,
- load_prompt_or,
-)
+from codeverse.tracks.common import RunContext, language_contract, load_prompt_or
from codeverse.tracks.generation import GenerationTask, generate
+from codeverse.tracks.prompting import base_prompt_context
from codeverse.tracks.repair import build_with_repair
from codeverse.workspace import Workspace
diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.py
index cf0807d4..481cd9a2 100644
--- a/harness/codeverse/tracks/static_object.py
+++ b/harness/codeverse/tracks/static_object.py
@@ -20,17 +20,20 @@ from codeverse.orchestrator.rounds import (
RefineTask,
TaskGroup,
build_refine_instructions,
+ compact_instructions,
plan_parallel_groups,
)
from codeverse.prompts import render
-from codeverse.tracks.common import (
- RunContext,
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import GenerationTask
+from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.prompting import (
base_prompt_context,
file_for_target_factory,
glb_to_plan_frame,
+ reference_images,
)
-from codeverse.tracks.generation import GenerationTask
-from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.reference import reference_refine_tasks, silhouette_gate
from codeverse.tracks.repair import format_error_report
from codeverse.tracks.steps import failed_acceptance
@@ -38,6 +41,10 @@ log = logging.getLogger(__name__)
MAX_SKELETON_CHARS = 14_000
+#: the 4 clay views judged for holes/intersections (subset of OBJECT_VIEWS by name)
+GEOMETRY_VIEW_NAMES: tuple[str, ...] = ("front_right_34", "back_left_34", "top", "low_front_left")
+GEOMETRY_VIEWS = tuple(v for v in OBJECT_VIEWS if v.name in GEOMETRY_VIEW_NAMES)
+
class ObjectPipeline:
"""Measure → connectivity + contract (+ runtime extra gates) → 8-view render."""
@@ -51,7 +58,7 @@ class ObjectPipeline:
out: list[GateReport] = []
glb = Path(build.glb_path) if build.glb_path else None
if glb is not None:
- out.append(ctx.services.connectivity(glb))
+ out.append(ctx.services.connectivity(glb, ctx.language.value)) # fix hints in the author's frame
if measurement is not None and ctx.plan is not None:
out.append(ctx.services.contract(measurement, ctx.plan, BBOX_TOLERANCE_M, ctx.language.value))
extra = getattr(ctx.runtime, "extra_gates", None)
@@ -64,13 +71,36 @@ class ObjectPipeline:
return ctx.services.render_object(Path(build.glb_path), ctx.ws.renders_dir(round_index), views=self.views,
width=r.width, height=r.height)
+ def post_render_gates(self, ctx: RunContext, round_index: int, renders: RenderSet) -> list[GateReport]:
+ """Reference-image runs: front-view outline IoU vs the target image (WARN finding with the number)."""
+ gate = silhouette_gate(ctx, renders)
+ return [gate] if gate is not None else []
+
+ def geometry_views(self, ctx: RunContext, round_index: int, build: BuildResult) -> RenderSet | None:
+ """4 clay views for the judge's geometry montage (holes, intersections).
+
+ The plain-geometry render exposes defects that materials hide; cached, so
+ near-free. Object tracks only — scenes/graphics have no single GLB."""
+ if not build.glb_path:
+ return None
+ out_dir = ctx.ws.renders_dir(round_index) / "clay"
+ try:
+ return ctx.services.render_geometry(Path(build.glb_path), out_dir, views=GEOMETRY_VIEWS)
+ except Exception as e: # noqa: BLE001 — optional judge context, never round-fatal
+ log.warning("clay geometry render failed: %s", e)
+ ctx.events.emit("render.geometry_failed", round=round_index, error=f"{type(e).__name__}: {e}")
+ return None
+
def plan_summary(self, ctx: RunContext) -> str:
plan = ctx.plan
if plan is None:
return ""
parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
- e = plan.overall_bbox.extents
- return f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m. Parts: {parts}."
+ # reorder into the measurement table's frame (W×H×D, Y-up): the (x,|z|,y) swap is
+ # self-inverse for extents, so Z-up plans (W,D,H) → (W,H,D), threejs is identity —
+ # otherwise the judge compares the digest position-wise against swapped numbers.
+ e = glb_to_plan_frame(plan.overall_bbox.extents, ctx.language, extents=True)
+ return f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m (W×H×D). Parts: {parts}."
def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
return ""
@@ -93,7 +123,7 @@ class StaticObjectTrack(BaseTrack):
ctx, expected_files=files, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
ctx.record_prompt("generate", prompt)
return [GenerationTask(label="baseline", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=0,
- kind="baseline", temperature=0.5, thinking="medium")]
+ kind="baseline", temperature=0.5, thinking="medium", images=reference_images(ctx))]
def system_prompt(self, ctx: RunContext) -> str:
return (f"You are an expert {ctx.language.value} 3D modeller writing RAW code (no SDKs, no helper libraries). "
@@ -109,7 +139,8 @@ class StaticObjectTrack(BaseTrack):
return [self._rebuild_task(ctx, last, index)], ["rebuild: previous round did not build"]
fft = file_for_target_factory(ctx)
tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
- file_for_target=fft, max_tasks=ctx.policy.max_refine_tasks)
+ file_for_target=fft, max_tasks=ctx.policy.max_refine_tasks,
+ extra=reference_refine_tasks(ctx, last))
if not tasks:
return [], []
groups = plan_parallel_groups(tasks)
@@ -123,13 +154,15 @@ class StaticObjectTrack(BaseTrack):
def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
files = group.files if parallel else (group.files or expected_files(ctx))
+ lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)
prompt = render(self.refine_template, **base_prompt_context(
- ctx, round_index=index, tasks=[t.line() for t in group.tasks], targets=group.targets, files=files,
+ ctx, round_index=index, tasks=lines, targets=group.targets, files=files,
edit_only_these=parallel, judge_summary=judge_digest(last), measurement_notes=measurement_vs_plan(last, ctx.plan, ctx.language),
current_files=current_files(ctx, files) if ctx.single_shot else {}))
ctx.record_prompt("refine", prompt)
return GenerationTask(label=f"refine_{group.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),
- files_hint=files, round=index, kind="refine", temperature=0.4, thinking="medium")
+ files_hint=files, round=index, kind="refine", temperature=0.4, thinking="medium",
+ images=reference_images(ctx))
def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
files = expected_files(ctx)
@@ -153,7 +186,18 @@ def expected_files(ctx: RunContext) -> list[str]:
return ["src/model.py", "src/robot.urdf"]
if lang is Language.SCENE_THREEJS:
return ["src/scene.js", "src/env.js"]
- return ["src/model.py"]
+ files = ["src/model.py"]
+ custom = getattr(ctx.runtime, "file_for_part", None) # blender: src/parts/<snake>.py per part
+ if callable(custom):
+ for p in parts:
+ try:
+ rel = custom(p.name)
+ except Exception as e: # noqa: BLE001
+ log.warning("runtime.file_for_part failed for %s: %s", p.name, e)
+ continue
+ if rel and str(rel) not in files:
+ files.append(str(rel))
+ return files
def skeleton_files(ctx: RunContext, max_chars: int = MAX_SKELETON_CHARS) -> dict[str, str]:
diff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.py
index 0dd25885..94d5eb21 100644
--- a/harness/codeverse/tracks/steps.py
+++ b/harness/codeverse/tracks/steps.py
@@ -69,11 +69,10 @@ def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask]) -> li
return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model,
settings=ctx.settings, budget=ctx.budget, events=ctx.events)
- if len(tasks) == 1:
- results: list[GenerationResult | Exception] = [_one(tasks[0])]
- else:
- results = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,
- label="generate", item_name=lambda t: t.label)
+ # fan_out also for ONE task: a crashing generator (503 storm, parse error) becomes a failed
+ # result → RoundFailed (refine rounds treat that as a plateau) instead of killing the run.
+ results = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,
+ label="generate", item_name=lambda t: t.label)
out: list[GenerationResult] = []
for task, r in zip(tasks, results, strict=True):
if isinstance(r, Exception):
@@ -100,14 +99,21 @@ def run_round(
instructions: Sequence[str] = (),
previous: Judgment | None = None,
files_hint: Sequence[str] = (),
+ extra_usage: Usage | None = None,
+ extra_notes: Sequence[str] = (),
) -> RoundRecord:
- """Execute one round and persist its record. Budget is charged as it goes."""
+ """Execute one round and persist its record. Budget is charged as it goes.
+
+ ``tasks`` may be empty when the code is already in place (scene stages,
+ best-of-N winner copied in): the round is then build → gates → render →
+ judge only. ``extra_usage`` / ``extra_notes`` fold pre-round work
+ (candidate generation) into the record."""
t0 = time.time()
ctx.events.emit("round.start", round=index, kind=kind, n_tasks=len(tasks))
rec = RoundRecord(index=index, kind=kind, agent_backend=ctx.agent_id, instructions=list(instructions),
started_at=datetime.now(UTC))
- usage = Usage()
- notes: list[str] = []
+ usage = extra_usage or Usage()
+ notes: list[str] = list(extra_notes)
gens = run_generation_tasks(ctx, tasks)
for g in gens:
@@ -138,7 +144,10 @@ def run_round(
rec.judgment = _judge(ctx, pipeline, index, outcome.build, gates, rec, previous)
if rec.judgment is not None:
usage = usage + rec.judgment.usage
- ctx.budget.charge(rec.judgment.usage)
+ # add, never charge: the verdict exists and is paid for — raising here
+ # would drop a fully judged round before it is committed/recorded
+ # (the loop stops at its next budget_ok check instead, AFTER best promotion).
+ ctx.budget.add(rec.judgment.usage)
elif ctx.judge is None:
notes.append("no judge configured")
else:
@@ -162,10 +171,27 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildRes
rec: RoundRecord, previous: Judgment | None) -> Judgment | None:
from codeverse.judges.base import JudgeInput
+ renders = rec.renders
+ jv = getattr(pipeline, "judge_views", None)
+ if callable(jv) and renders is not None:
+ try:
+ renders = jv(ctx, renders) or renders
+ except Exception as e: # noqa: BLE001 — view selection is an optimisation, never a blocker
+ log.warning("judge_views selection failed: %s", e)
+ renders = rec.renders
+ geometry = None
+ gv = getattr(pipeline, "geometry_views", None)
+ if callable(gv):
+ try:
+ geometry = gv(ctx, index, build)
+ except Exception as e: # noqa: BLE001 — clay views are optional judge context
+ log.warning("geometry views failed in round %d: %s", index, e)
+ ctx.events.emit("judge.geometry_views_failed", round=index, error=f"{type(e).__name__}: {e}")
inp = JudgeInput(
- spec=ctx.spec, renders=rec.renders, measurement=rec.measurement, gates=gates,
+ spec=ctx.spec, renders=renders, measurement=rec.measurement, gates=gates,
acceptance=list(getattr(ctx.plan, "acceptance", []) or []), plan_summary=pipeline.plan_summary(ctx),
round_index=index, previous=previous, extra_context=pipeline.judge_context(ctx, index, build, gates),
+ geometry_views=geometry,
)
t0 = time.time()
try:
@@ -176,12 +202,47 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildRes
rec.notes = (rec.notes + "; " if rec.notes else "") + f"judge failed: {type(e).__name__}: {e}"
return None
ctx.ws.write_json(ctx.ws.judge_path(index), judgment)
+ if _is_degraded(judgment):
+ # a glitch, never a score: keep the raw verdict on disk, pay for it, but do not
+ # let 0.0 poison plateau/best/refine (judges/scoring.degraded_judgment contract)
+ ctx.budget.add(judgment.usage)
+ ctx.events.emit("judge.degraded", round=index, error=judgment.summary[:300],
+ cost_usd=round(judgment.usage.cost_usd, 4))
+ rec.notes = (rec.notes + "; " if rec.notes else "") + f"judge degraded: {judgment.summary[:200]}"
+ return None
ctx.events.emit("judge.done", round=index, overall=round(judgment.overall, 3), passed=judgment.passed,
n_issues=len(judgment.issues), n_plan=len(judgment.improvement_plan),
duration_s=round(time.time() - t0, 1), cost_usd=round(judgment.usage.cost_usd, 4))
return judgment
+def _is_degraded(judgment: Judgment) -> bool:
+ try:
+ from codeverse.judges.scoring import is_degraded
+ except ImportError: # pragma: no cover — judges package always ships with tracks
+ return False
+ return is_degraded(judgment)
+
+
+def rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, previous: Judgment | None = None) -> bool:
+ """Re-judge an already built+rendered round whose judgment failed or was degraded.
+
+ No regeneration, no rebuild: the same commit is judged again. On success the
+ round record is updated in place and re-persisted. Returns True when the
+ round now has a usable judgment."""
+ if rec.build is None or not rec.build.ok or rec.renders is None or not rec.renders.views:
+ return False
+ ctx.events.emit("judge.retry", round=rec.index)
+ judgment = _judge(ctx, pipeline, rec.index, rec.build, list(rec.gates), rec, previous)
+ if judgment is None:
+ return False
+ rec.judgment = judgment
+ rec.usage = rec.usage + judgment.usage
+ ctx.budget.add(judgment.usage)
+ ctx.ws.write_json(round_record_path(ctx, rec.index), rec)
+ return True
+
+
def _write_gate_reports(ctx: RunContext, index: int, gates: list[GateReport]) -> None:
d = ctx.ws.gates_dir(index)
d.mkdir(parents=True, exist_ok=True)
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index 7b43d2da..576312a5 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -119,8 +119,8 @@ class Workspace:
for attempt in range(4):
proc = subprocess.run(
["git", *args], cwd=self.root, text=True, capture_output=True, check=False,
- env={"GIT_AUTHOR_NAME": "c3v", "GIT_AUTHOR_EMAIL": "c3v@local",
- "GIT_COMMITTER_NAME": "c3v", "GIT_COMMITTER_EMAIL": "c3v@local",
+ env={"GIT_AUTHOR_NAME": "3dcv", "GIT_AUTHOR_EMAIL": "3dcv@local",
+ "GIT_COMMITTER_NAME": "3dcv", "GIT_COMMITTER_EMAIL": "3dcv@local",
"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": str(self.root)},
)
if proc.returncode == 0 or "index.lock" not in (proc.stderr or ""):
@@ -136,7 +136,7 @@ class Workspace:
self._git("init", "-q")
(self.root / ".gitignore").write_text(
"# harness-owned run state is never part of the code snapshot\n"
- "artifacts/\ntrajectories/\nstages/\nrounds/\n_assets/\n.c3v/\n.gemini/\n.claude/\n"
+ "artifacts/\ntrajectories/\nstages/\nrounds/\n_assets/\n.3dcv/\n.gemini/\n.claude/\n"
"events.jsonl\nrun_state.json\nrecord.json\n*.log\nnode_modules/\n*.tmp\n__pycache__/\n"
)
self._git("add", "-A")
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 9b2e62d1..dea8e564 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -1,172 +1,319 @@
# 3dcodeverse harness — architecture
-Package `codeverse`, CLI `c3v`. Backend only. Python 3.11+ and a small Node
-runtime (`runtime_js/`) for everything Three.js / headless-Chrome.
+Package `codeverse`, CLI `3dcodeverse` (short alias `3dcv`), repo location
+`/home/yipeng/3dcodeverse/harness`. Backend only. Python 3.11+, a small Node
+runtime (`runtime_js/`) for everything Three.js / headless Chrome, and moderngl
+for the graphics track. Reconciled against the code and the live runs on
+2026-08-23 (waves 2–3 + fix batch 1); design history and deviations are in
+`docs/DECISIONS.md`, how-to in `docs/RUNBOOK.md`, evaluation protocol in
+`docs/EVAL.md`, binding signatures in `docs/INTERFACES.md`.
## 0. What it is
A data-flywheel harness in which LLMs write **raw executable 3D code** — no SDK
-layered on top of the language — for three **tracks**:
+layered on top of the language — for four **tracks**:
| track | languages | deliverable |
|---|---|---|
| `static_object` | `blender` (bpy), `cadquery`, `threejs` | code + canonical `object.glb` (+stl/step) |
-| `articulated_object` | `urdf_blender` (bpy link meshes + hand-written URDF) | code + `robot.urdf` + `meshes/*.glb` + `object.glb` (node hierarchy) |
-| `scene` | `scene_threejs` (multi-file three.js + GLSL; optional bpy-built GLB assets) | `src/**` + renders + probes |
+| `articulated_object` | `urdf_blender` (bpy link meshes + hand-written URDF) | code + `robot.urdf` + `meshes/*.glb` (raw link frames) + `object.glb` (node hierarchy with joint extras) |
+| `scene` | `scene_threejs` (multi-file three.js + GLSL; optional bpy-built GLB assets) | `src/**` + `public/assets/*.glb` + renders + probes |
+| `graphics` | `glsl_shader` (Shadertoy-style fragment shader), `opengl_python` (raw moderngl + GLSL, multi-pass) | shader/program source + judged animation frames + sheet + GIF + frame metrics |
…driven by **any** of these backends behind two protocols:
-* `ChatModel` (API): `gemini:*`, `anthropic:*`, `openai:*` — used by the planner,
- the judge, the captioner, and by the in-process `api-agent`.
+* `ChatModel` (API): `gemini:*`, `anthropic:*`, `openai:*` — planner, judge,
+ captioner, single-shot generation, and the in-process `api-agent`.
* `CodingAgent` (agentic session on a workspace): `gemini-cli:*`, `claude-code:*`,
- `codex:*`, `agy:*` (Antigravity), and `api-agent:<chat-model>` (our own
- tool loop so API-only users get parity).
+ `codex:*`, `agy:*` (Antigravity), `api-agent:<chat-model>` (our own tool loop so
+ API-only users get parity). Plus `single-shot:<chat-model>` (one envelope of
+ files, no tools) handled inside `tracks/generation.py`.
-Every run is: **spec → plan → generate → lint → build → gates → measure →
-render → judge → refine… → record**. The record (plus git history of `src/`)
-is the flywheel unit.
+Every run is: **spec → plan → skeleton → [scene stages] → baseline round
+(optionally best-of-N candidates) → refine rounds → finalise → record**, with an
+optional post-hoc **texture pass**. The record (plus git history of `src/`) is
+the flywheel unit.
## 1. Design laws (from the reference post-mortems)
1. **Code is truth; artifacts are derived.** Raw code in `src/` is the
- deliverable; GLB/renders are regenerated from it.
-2. **Concrete beats abstract.** Compliance of flash-class models is
- probabilistic and set by concreteness: contracts are delivered as *skeleton
- code, exact numbers, copyable snippets* (cookbooks), never as clauses.
-3. **Code answers when code can answer.** Deterministic gates / measurements
- / normalisers run by the harness (never pasted by the agent) catch the
- residue; the VLM is used only for perception and judgement.
-4. **Move responsibility out of agent code** where possible: export wrappers,
- camera rigs, placement validation, URDF composition math, scene assembly.
+ deliverable; GLB/renders are regenerated from it (finalise restores the best
+ commit and rebuilds). Textures are a *derived asset pack*
+ (`object_textured.glb` + `artifacts/textures/`); `object.glb` is never touched.
+2. **Concrete beats abstract.** Contracts are delivered as skeleton code, exact
+ numbers and copyable snippets (cookbooks), never as clauses.
+3. **Code answers when code can answer.** Deterministic gates / measurements run
+ by the harness; the VLM is used only for perception and judgement, and its
+ score is computed in code from rubric weights.
+4. **Move responsibility out of agent code**: export wrappers, camera rigs,
+ placement validation, URDF composition math, scene assembly, GLSL headers.
5. **Evidence-based acceptance.** Every plan carries an acceptance checklist;
- items are proved by measurements/probes/judge evidence, not by prose.
-6. **Typed everything.** One contracts package; no regex-on-id control flow,
- no stringly-typed dict conventions, no god files (target ≤ 400 lines).
-7. **Cheap first.** Static lint → build → deterministic gates → quick 4-view
- sheet → VLM. Never call a VLM on something a gate already rejected.
+ items are proved by measurements/probes/judge votes, not prose.
+6. **Typed everything.** One contracts package; no regex-on-id control flow, no
+ stringly-typed dicts, no god files (≤ ~400 lines).
+7. **Cheap first.** Lint → build → deterministic gates → montaged views → VLM.
8. **Separate generator from judge.** The judge sees spec + renders +
measurements + acceptance list; never the generator's reasoning.
-9. **Cost is a budget, not a log.** Hard per-run ceilings; key pools with
- per-key limiters; every call yields a `Usage`.
+9. **Cost is a budget, not a log.** Hard per-run ceilings (`BudgetGuard`), key
+ pools with per-key limiters, every call yields a `Usage`.
10. **Reproducible.** Prompt/rubric/cookbook hashes and tool versions are
- recorded on every round.
+ recorded on every run (`record.prompt_hashes`, `record.environment`).
+11. **Export as authored.** No wrapper re-centres, rescales or grounds the
+ object; builds warn, `check_contract`/`check_connectivity` gate, the agent
+ fixes the source.
-## 2. Package map
+## 2. Package map (as built)
```
codeverse/
- conventions.py frames, units, view presets, name normalisation (THE source)
- config.py Settings (keys, binaries, dirs, defaults) from env/yaml
- contracts/ pydantic: Spec, Plan(s), BuildResult, Measurement, RenderSet,
- GateReport, Judgment, RoundRecord/RunRecord, Chat*, Agent*
- workspace.py run-dir layout + git snapshots
- events.py JSONL event log per run
- models/ ChatModel protocol; gemini.py anthropic.py openai.py;
- keypool.py (RPM/TPM buckets, rotate on 429); pricing.py; registry.py
- agents/ CodingAgent protocol; gemini_cli.py claude_code.py codex.py
- antigravity.py api_agent.py (tool loop); materialize.py
- (AGENTS.md/GEMINI.md/CLAUDE.md + MCP config per workspace);
- watchdog.py (activity-aware subprocess); registry.py
- languages/ LanguageRuntime protocol; blender/ cadquery/ threejs/ urdf/
- scene_threejs/ — each: runtime.py (build+export), lint.py,
- skeleton.py (starter files from plan), wrappers/ (bpy/node
- scripts the harness runs — NOT imported by agent code)
- spatial/ language-agnostic tools on GLB/URDF/scene: measure.py,
- connectivity.py, render.py (three headless GPU), sections.py,
- silhouette.py, joints.py (FK, pose sweep, collisions),
- probes.py (scene census/fps/errors), registry.py (@tool →
- python fn + JSON schema + prompt card), mcp_server.py
- judges/ vlm_judge.py (rubric yaml → Judgment, n-sample, code-computed
- score, floors), pairwise.py, reference.py, metrics.py, rubrics/
- tracks/ base.py (Track protocol), static_object.py,
- articulated_object.py, scene.py — each composes stages
- orchestrator/ runner.py (stages+resume), rounds.py (refine loop, stop
- policy, best selection), fanout.py, budget.py
- flywheel/ record.py, export.py (sample folders + parquet), pairs.py
- (preference/repair pairs), captions.py, dedupe.py
- prompts/ system/*.md, <language>/cookbook.md + skeletons, tracks/*.j2
- cli/main.py c3v make | resume | judge | render | tools | flywheel | bench | doctor
-runtime_js/ node package: export_glb.mjs, render_glb.mjs, render_scene.mjs,
- probe_scene.mjs, check_shaders.mjs, gpu_launch.cjs, serve.cjs
+ conventions.py frames (LANGUAGE_FRAME, GLB_FRAME), units, OBJECT_VIEWS/_QUICK, SCENE_VIEWS,
+ to_snake/to_pascal/slugify, MAX_TRIS_*, BBOX_TOLERANCE_M, CONTACT_GAP_M (THE source)
+ config.py Settings (CV3D_* env, ~/.config/codeverse/config.yaml; default_judge=gemini-3.1-pro-preview,
+ default_candidates=1)
+ contracts/ pydantic: common (Track, Language, Usage, Budget, Backends), spec, plan, artifacts,
+ judgment, run, chat, agent
+ workspace.py run-dir layout + git snapshots ; events.py JSONL event log
+ models/ ChatModel; gemini.py (dead-key + free 429 rotation), gemini_image.py (ImageModel),
+ anthropic.py openai.py, keypool.py ('dead' outcome), pricing.py (version-suffix-only
+ fallback), retry.py, schema_utils.py (strict schema: no null-for-default), registry.py
+ agents/ CodingAgent; gemini_cli.py claude_code.py codex.py antigravity.py api_agent.py
+ (+ api_tools.py run_shell policy), materialize.py, cli_common.py (sessions, retry
+ trajectory naming, files_changed attribution), watchdog.py, transcript.py, registry.py
+ languages/ LanguageRuntime; blender/ (multi-file: layout.py, model.py + parts/*.py) cadquery/
+ threejs/ urdf/ scene_threejs/ glsl_shader/ (wrap.py header+line-map, gl_build.py)
+ opengl_python/ (wrappers/run_gl.py) — each runtime.py, lint.py, skeleton.py, wrappers/
+ spatial/ node.py, render.py, render_scene.py (judge view subset, content-fitted orbit),
+ frame_metrics.py (scene_frames gate), gl_render.py (GlHost), frame_stats.py (gl_frames),
+ sheet.py (montage_2x2, crop_region), turntable.py, measure.py, connectivity.py,
+ contract.py (authoring-frame hints), sections.py, silhouette.py, probes.py,
+ joints*.py + joints_collide.py (deterministic penetration), registry.py, tools*.py
+ (tools_texture.py, tools_graphics.py), mcp_server.py (MCP name: 3dcv)
+ judges/ rubrics.py + rubrics/*.yaml (defect checklists), vlm_judge.py, montage.py,
+ prompt_builder.py, output_schema.py, scoring.py, caps.py, images.py, pairwise.py
+ (compare_many), reference.py, calibration.py, metrics.py
+ texturing/ plan.py (VLM material plan), generate.py (+ tile.py seam fix), uv.py (world-metre
+ unwrap), apply.py, gate.py (seam + before/after judge), scene_pack.py, run.py (texture_pass)
+ orchestrator/ runner.py, state.py, rounds.py (RoundPolicy, compaction), candidates.py (best-of-N
+ + pairwise decisions), fanout.py, budget.py
+ tracks/ base.py (get_track(track, **options)), lifecycle.py, steps.py, candidates.py,
+ generation.py, repair.py, planner.py, prompting.py (prompt helpers, split from common),
+ common.py (RunContext, Services), motion.py, reference.py, static_object.py,
+ articulated_object.py, scene.py, scene_assets.py, graphics.py + graphics_steps.py
+ flywheel/ record.py, export.py, pack.py, sample.py, pairs.py, trajectories.py (repair-pair
+ mining), captions.py, quality.py (tiers + dedupe), gallery.py, dedupe.py, index.py
+ prompts/ system/*, <lang>/{contract,cookbook}.md (incl. glsl_shader/, opengl_python/),
+ texturing/*.md, tracks/*.j2 (incl. plan/generate/refine_graphics.j2)
+ cli/ main.py, tools_cmd.py, flywheel_cmd.py, bench_cmd.py, texture_cmd.py, doctor.py
+bench/ run_bench.py, report.py (reuses flywheel gallery), compare_backends.py,
+ prompts/{static_objects_v1 (24), articulated_v1 (12), scenes_v1 (12), compare_v1 (8)}.yaml
+runtime_js/ export_glb.mjs (placement policy, instance baking, selfcheck) render_glb.mjs
+ render_scene.mjs probe_scene.mjs check_shaders.mjs gpu_launch.cjs serve.cjs
+ lib/{resolve_three, scene_host, host_coverage, orbit, instances, census, glsl_audit, browser/…}
+tests/ core models agents blender_cadquery threejs_render urdf_joints scene_runtime scene_gates
+ spatial_tools judges orchestrator_tracks flywheel_cli graphics texturing prompts (~860 offline)
```
-## 3. Workspace layout (one run)
+## 3. Workspace layout (one run, as observed)
```
runs/<slug>/
spec.json plan.json run_state.json record.json events.jsonl
- src/ agent-authored RAW code (git repo; one commit per round)
- public/ (scene) compiled assets e.g. GLBs built from bpy
- artifacts/ object.glb object.stl robot.urdf meshes/ measurement.json
- renders/rNN/ view_*.png sheet.png turntable.mp4
- gates/rNN/ *.json
- judge/rNN.json
- trajectories/<stage>_rNN/ prompt.md transcript.jsonl result.json
- AGENTS.md GEMINI.md CLAUDE.md .mcp.json .gemini/settings.json (materialised)
+ src/ agent-authored RAW code (git repo; commits: spec, skeleton, pre:/agent:<label>, rNN <kind>)
+ public/ (scene) compiled assets public/assets/<snake>.glb; (textured scenes) public/textures/*.png + manifest.json
+ _assets/<snake>/ (scene) sub-workspaces for blender_glb assets (gitignored)
+ _cand/c<k>/ (--candidates N) throw-away best-of-N sub-workspaces (gitignored, kept for the flywheel)
+ stages/<name>.json rounds/rNN.json rounds/candidates.json
+ artifacts/ object.glb object.stl|step robot.urdf meshes/ articulation.json build.json census.json
+ measurement.json … ; graphics: frames/fNN_tT.png frames_sheet.png preview.gif metrics.json
+ texturing: object_textured.glb textures/{<id>.png, texture_plan.json, texturing.json, gate/}
+ renders/rNN/ view_<name>.png sheet.png views.json (judge flags) (+ poses/ articulated; <cam>_t<t>.png metrics.json scenes)
+ gates/rNN/ lint_<lang>.json connectivity.json contract.json joint_sweep.json motion_direction.json … (+ *_tool.json)
+ judge/rNN.json (+ rNN_cli.json from `3dcv judge`)
+ tool_renders/rNN_<hash>/
+ trajectories/<label>_rNN/ prompt.md transcript.jsonl stdout.json stderr.log result.json
+ (a retried label lands in <label>.a2_rNN — first attempt preserved)
+ AGENTS.md GEMINI.md CLAUDE.md .mcp.json .gemini/settings.json .3dcv/cookbook.md .geminiignore .aiexclude
```
## 4. Per-language authoring contracts (raw code; the harness owns export)
-* **blender**: `src/model.py` — pure bpy, Z-up, -Y front, meters; builds named
- objects (PascalCase = part names) into the current scene; no camera/lights/
- render/export calls. Harness: `blender -b --factory-startup --python
- wrappers/run_bpy.py -- --script src/model.py --out artifacts/` → clears scene,
- runs script with RLIMIT, collects census, applies transforms, exports GLB+STL.
-* **cadquery**: `src/model.py` — `import cadquery as cq` only; module-level
- `result` = `cq.Assembly` (named parts) or `Workplane`. Harness exports
- STEP/STL per part → GLB with named nodes.
-* **threejs** (static): `src/parts/<snake>.js` each `export function
- build<Pascal>(THREE) → THREE.Group` at world pose (Y-up, +Z front, meters);
- `src/object.js` `export function build(THREE) → THREE.Group` assembling parts;
- optional `userData.tick(dt)`. Harness exports GLB via node GLTFExporter.
-* **urdf_blender**: `src/model.py` (bpy) builds one object per link named
- `<link>`; `src/robot.urdf` written by the agent (native URDF, meshes as
- `meshes/<link>.glb`, joint frames per URDF semantics). Harness exports per-link
- meshes, lints URDF, composes FK, sweeps poses, builds `object.glb` with nodes.
-* **scene_threejs**: `src/scene.js` `export function createScene({THREE, renderer,
- loaders}) → {scene, cameras, update(t,dt)}`; `src/env.js`, `src/zones/*.js`,
- `src/assets/*.js`, `src/shaders/*.js`; Blender-built assets compiled to
- `public/assets/<name>.glb` and loaded via GLTFLoader; GLSL inline via
- ShaderMaterial / onBeforeCompile using the cookbook's copyable boilerplate.
+Authoritative text lives in `codeverse/prompts/<lang>/contract.md` (+ cookbook);
+summary:
+
+* **blender** (multi-file): `src/model.py` entry + `src/parts/<snake>.py` each
+ defining `def build_<snake>()` (self-contained; optional `src/parts/_x.py`
+ helpers) — pure bpy, Z-up, -Y front, meters; PascalCase object names = part
+ names. Small objects may stay single-file. Harness wrapper (`run_bpy.py` +
+ `_census.py`) puts `src/` on sys.path, maps errors to workspace-relative
+ `src/parts/<x>.py:line`, collects census, exports GLB (Y-up) + STL.
+* **cadquery**: `src/model.py` — `import cadquery as cq` (+math) only; module-level
+ `result` = `cq.Assembly` or `Workplane`. A chain ending in a selector exports the
+ parent solid with a warning (ExportError when no solid exists); helper-module
+ errors map to `src/<file>.py:line`.
+* **threejs** (static): `src/parts/<snake>.js` each `export function build<Pascal>(THREE) → THREE.Group`
+ at world pose (Y-up, +Z front, meters); `src/object.js` `export function build(THREE)`.
+ Export is **as authored** (no re-centring; `--normalise` is a dataset-only flag);
+ `InstancedMesh` is baked to plain `<Name>_<i>` meshes (trimesh ignores
+ EXT_mesh_gpu_instancing); an exported `selfcheck(THREE, root)` is called and a
+ throw fails the build as `SelfCheckError`; NaN-geometry errors name mesh + part
+ and route to the part file.
+* **urdf_blender**: `src/model.py` builds one object per link named `<link>` in
+ **WORLD coordinates** at the rest pose (q=0 = authored pose); `src/robot.urdf`
+ hand-written: link frame = its pivot, joint origin = pivot_child − frame_parent,
+ `rpy="0 0 0"`, visual AND collision `<origin xyz>` = −pivot (root `0 0 0`) —
+ verified by the FK-consistency check; URDF limits = plan lower−rest .. upper−rest.
+ Link name `world` is reserved. Harness exports `meshes/<link>.glb` (raw Z-up link
+ frames), sweeps poses for collisions (deterministic; python-fcl), builds
+ hierarchical `object.glb`, and gates motion direction against the plan text.
+* **scene_threejs**: `src/scene.js` `createScene({THREE, renderer, loaders}) → {scene, cameras, update(t,dt)}`;
+ `src/env.js`, `src/zones/*.js`, `src/assets/*.js`, `src/shaders/*.js`; GLBs at
+ `public/assets/<name>.glb`. The harness assembles `scene.js` deterministically.
+* **glsl_shader**: `src/shader.frag` (+ optional `src/common.glsl`,
+ `src/buffer_a.frag` for feedback) — the agent never writes `#version`, uniform
+ declarations or `out vec4`; the harness header provides
+ `u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise/u_buffer_a` (+ Shadertoy
+ `iTime/iResolution/iChannel*` aliases). Feedback shaders are simulated at 30 fps.
+* **opengl_python**: `src/program.py` with `setup(ctx, w, h) -> state` and
+ `render(ctx, state, t, frame, fbo)` — moderngl only, no window libs, no wall
+ clock, no file writes; GLSL may live in `src/*.glsl` or in-string (errors carry
+ both line numbers). Runs in a fresh subprocess per render (contexts are not
+ thread-safe); GPU d3d12 first, llvmpipe fallback.
## 5. Spatial tool registry
-`@tool` registers a python function with a pydantic args model → (a) direct
-call from tracks, (b) MCP server for gemini-cli / claude-code / codex, (c) native
-tool schema for `api-agent`, (d) a prompt card. Observations are structured
-(`{text, numbers, images[]}`); images are small labelled PNGs / contact sheets.
+`@tool(name, ArgsModel, description, *, tracks=(), languages=(), cost_hint)` registers
+`fn(ctx, args) -> Observation` → (a) direct call from tracks, (b) the stdio MCP
+server (name `3dcv`) for gemini-cli / claude-code / codex, (c) native tool schema
+for `api-agent`, (d) a prompt card. Tools: `build`, `measure`, `render_views`,
+`render_sheet`, `isolate`, `cross_section`, `check_connectivity`, `check_contract`,
+`compare_silhouette`, `joint_sweep` (articulated), `shader_probe`, `scene_probe`,
+`scene_views` (scene), `gl_probe`, `gl_frames` (graphics), `texture_pass`,
+`texture_preview` (object tracks), `read_cookbook`.
-Core tools: `build`, `measure`, `render_views`, `render_sheet`, `isolate`,
-`cross_section`, `check_connectivity`, `check_contract`, `compare_silhouette`,
-`joint_sweep`, `shader_probe`, `scene_probe`, `read_cookbook`.
+## 6. Judging (protocol v2)
-## 6. Judging
+`VlmJudge(rubric, model_id, n_samples)` sends **montages, not loose views**: ≤ 3
+labelled 2×2 montages (shaded / geometry-only clay-or-normals / poses) + ≤ 2 detail
+crops at ≤ 1024 px, shuffled per sample. The wire schema is **observe-then-score**
+(summary, strengths, issues, **defect checklist**, acceptance *before* criteria) —
+criteria-first measurably compressed flash to 0.6–0.7. Every rubric carries binary
+`defects` (id/text/penalty/cap); defect votes are majority (ties → present) and
+`overall = caps(weighted_mean − Σ penalties)`. Floors, deterministic caps from gate
+findings (`data["kind"]`), console errors, missing must-acceptance and
+`missing_views` rules apply on top; degraded verdicts are glitches, not scores.
+`PairwiseJudge` (position-swapped, tie on disagreement) also ranks N candidates via
+`compare_many`; `ReferenceJudge` for image-conditioned specs.
+Rubrics: `static_object_v1` (0.72), `articulated_v1` (requires pose sheet),
+`scene_v1` (frame-gate caps), `asset_v1`, `reference_v1`, `shader_v1` (0.70).
-`VlmJudge(rubric)`: contact sheet + labelled views + measurement table +
-acceptance checklist → JSON (criterion scores, issues, improvement plan,
-acceptance verdicts). Score is **computed in code** from rubric weights with
-hard floors; n-sample (view-order shuffled) mean/std; deterministic caps from
-gate findings are listed in the verdict. Rubrics: `static_object_v1`,
-`articulated_v1`, `scene_v1`, `asset_v1`, `reference_v1`. `PairwiseJudge`
-(position-swapped) for best-of-N and preference data.
+**Calibration (2026-08-23, `judges/calibration.py`, n=3 on the e2e rounds):**
+flash `gemini-3.7-flash` mean overall std 0.083, pearson(gate errors, score) −0.33;
+pro `gemini-3.1-pro-preview` std 0.030, pearson +0.63, and separation on a
+crafted-vs-crude-vs-wrong triplet 0.60 / 0.00 / 0.25 (flash 0.91 / 0.00 / 0.20 —
+its range is carried by the defect checklist). Hence **default judge =
+`gemini-3.1-pro-preview`** (`Settings.default_judge`); flash stays the cheap
+in-loop option with `n_samples ≥ 2` for decisions.
## 7. Round loop (all tracks)
```
-baseline → build/gates/measure/render/judge (the "raw model" delta)
-repeat ≤ max_rounds:
- plan = judge.improvement_plan ∪ gate.errors ∪ failed acceptance
- dispatch targeted tasks (per part / zone / asset; parallel when file-disjoint)
- build → repair loop on build errors (≤ max_repair_attempts, error-focused)
- gates → measure → render → judge
- keep best (score, then fewer errors); stop on pass / plateau / budget
-finalise: restore best commit, export, caption, record
+plan (structured output, one re-ask) → skeleton (buildable placeholder) → materialise workspace
+[scene only] assets (parallel; blender_glb assets get a sub-workspace + asset_v1 judge + one fix pass)
+ → env → zones (parallel) → assemble (deterministic scene.js)
+round 0 "baseline": generate → build_with_repair → measure → gates → render → post-render gates → judge
+ (--candidates N: N parallel baselines in <ws>/_cand/c<k>, quick 4-view judge, crashed candidate retried once,
+ selection build_ok → quick score → fewer gate errors with pairwise tie-break; winner copied back, normal r00 follows)
+repeat while StopPolicy says continue (≤ max_rounds refine rounds, plateau_window=2 / min_delta=0.02,
+ target = rubric threshold, budget ok):
+ refine tasks = gate ERRORS (fix hints, authoring-frame numbers) ∪ failed must-acceptance ∪ judge improvement plan
+ (≤ 6 tasks, ≤ 6 compacted instruction lines each; reference runs add an IoU task when silhouette IoU < 0.6)
+ fan out when ≥ 2 file-disjoint groups AND every task maps to files (threejs/blender parts, scene zones/assets/env)
+ generate → build+repair (error-focused, escalates on identical signatures) → gates → … → judge
+ BestSelector: highest score, tie → fewer gate errors; |Δ| < pairwise_margin (0.03) → position-swapped
+ PairwiseJudge decides (replace only at confidence ≥ 0.6; note persisted in rNN.json)
+stop reasons: pass | plateau | budget | max_rounds | no_change | no_refine_tasks
+finalise: restore best commit, rebuild so artifacts match delivered code, finalize_record → record.json
```
+Track-specific gates: static `connectivity` + `contract` (+ `reference_silhouette`),
+articulated + `joint_sweep` + `motion_direction` (URDF axis vs plan motion text),
+scene `render_console` (the `scene_frames` gate — dark/blown/flat frames, camera in
+geometry/underground, content too small — is built in `spatial/frame_metrics.py`
+and pending its 2-line wire-up in the scene track), graphics `gl_frames`
+(NaN/black/blown/static/flicker).
+
+## 8. Texturing (derived asset pack)
+
+`texturing.run.texture_pass(ws, spec, plan, model_id=…)` — after (or outside) a run:
+one VLM **material plan** (parts → shared texture ids, family, projection,
+`tile_size_m`; cached) → text-to-image tiles (`GeminiImageModel`,
+gemini-3.1-flash-image; mirror cross-fade makes them tileable, `seam_score ≤ 0.08`
+gate) → **world-metre UV unwrap** (planar/box/cylinder per part; texel density
+identical across parts) → `artifacts/object_textured.glb` → before/after judge gate
+(**ship iff** Δoverall ≥ −0.01 AND the materials criterion improved). Results land
+in `record.extra["texturing"]` + `events texture.*`; `object.glb` and `src/` are
+untouched. Scenes get `scene_texture_pack` instead: 6–12 named tiles +
+`public/textures/manifest.json`, injected into zone prompts as an "Available
+textures" block. Chair live check: plan $0.005 + 1 image $0.067 + gate $0.017,
+judge 0.686 → 0.701, materials 0.60 → 0.69, shipped.
+
+## 9. What actually happens in a run (live runs, 2026-08-23)
+
+Wave-1 e2e runs (planner/judge `gemini-3.7-flash`, n=1, budget $2.5–3 / 45–60 min):
+
+| run | track / language / generator | scores | wall | cost |
+|---|---|---|---|---|
+| `e2e_chair_blender` | static / blender / api-agent | 0.674 → 0.744 (pass) | 11.8 min | $0.84 |
+| `e2e_cabinet_urdf` | articulated / urdf_blender / api-agent | 0.677 → 0.930 (pass) | 12.5 min | $0.84 |
+| `e2e_bench_threejs` | static / threejs / gemini-cli | 0.642 → 0.885 (pass) | 35.7 min | $0.68 |
+| `e2e_garden_scene` | scene / scene_threejs / api-agent | 0.556 → 0.578 (budget) | 45.3 min | $2.90 |
+
+Wave-2/3 live checks: best-of-2 blender stool (single-shot flash) — candidates ran
+in parallel, one crashed on a 503 storm and was retried, scores within the 0.03
+margin so pairwise picked the winner at 0.915 confidence; r00 0.563 → r01 0.612,
+total $0.24 / 7.6 min. Graphics `neon_rain` (single-shot flash, glsl_shader):
+plan → 328-line shader compiled first try, `gl_frames` clean, judged 0.786 →
+stop=pass after round 0, $0.045. Per-stage timings: plan 7–60 s; Blender build
+0.1–0.6 s; GL build + 12 frames ~2–5 s; 8-view GPU render ~1.5 s; judge verdict
+$0.02–0.03 (flash) / ~$0.2 (pro); api-agent generation 3–6 min per object round.
+
+## 10. Known limits (as of 2026-08-23)
+
+* Judge: flash is lenient/noisy on fine distinctions (overall std ≈ 0.08–0.12 at
+ n=3); its dynamic range comes from the defect checklist. Use pro (default) or
+ `n_samples ≥ 3` for decisions. Detail crops are position-heuristic (no 2D part
+ boxes yet).
+* `scene_frames` gate + judge-view subset are built (renders side) but not yet
+ wired into the scene track; `conventions.LANGUAGE_FRAME` lacks
+ glsl_shader/opengl_python entries (stopgap `setdefault` in `tracks/graphics.py`);
+ `3dcv judge` lacks a GRAPHICS → shader_v1 mapping; `flywheel export` lacks
+ graphics entry-file mappings.
+* Articulated: candidate selection uses the quick 4-view sheet (not pose views);
+ mimic joints ignored; sweep is O(links² × poses).
+* Scenes: fps is a relative cost; camera-in-geometry can miss open-back enclosures.
+* threejs: textures are stripped on GLB export (the texture pass re-adds them as a
+ derived pack); `userData.tick` cannot survive export.
+* Trajectory repair mining only understands api-agent transcripts; CLI backends
+ produce raw stdout. agy exposes no per-workspace MCP, cost or served model.
+* Anthropic / OpenAI backends are mock-tested only (no keys on this box).
+* Budget checks run between steps: a refine round that finishes its judge and then
+ trips the budget is not promoted to best — give scenes `--max-minutes 60 --max-usd 4`.
+* Gemini flash 503 storms happen; dead keys and 429s rotate freely now, but a
+ sustained outage can still fail a round (`3dcv resume` re-uses cached stages).
+* `ffmpeg` absent here → turntables fall back to GIF. A few single-file wrappers
+ exceed the ~400-line guideline by design.
-## 8. Flywheel
+## 11. Flywheel
-`record.json` per run + git history; `c3v flywheel export` writes sample
-folders (`code.<ext>` / multi-file, `meta.json`, `captions.json`, `renders/`)
-compatible with the owner's STORAGE_RULES, a parquet index, preference pairs
-(round i < round j by judge Δ ≥ τ), repair pairs (error → fix diff), and
-cross-backend best-of pairs.
+`record.json` per run + git history; `3dcv flywheel export` writes sample folders
+(`<out>/<track>/<language>/<slug>/{code.<ext>, src/**, robot.urdf, meta.json,
+captions.json, renders/}`) with **quality tiers** (A passed & 0 gate errors, B
+passed, C best ≥ 0.6, D else), acceptance checklists, gate summaries and
+`(code fingerprint, prompt)` dedupe (`--drop-duplicates`; side-car captions via
+`--captions-dir`); `metadata.parquet`/`.jsonl` + sqlite index carry tier, gate
+errors, cost, fingerprints, `duplicate_of`; `--pack` tars with byte-range locators.
+`flywheel pairs` emits preference pairs (round i < j by judge Δ ≥ τ), round-level
+repair pairs and **in-session repair pairs mined from api-agent transcripts**
+(replay-verified against the git snapshots); `flywheel caption` adds
+{detailed, instruction, factory} captions (image-grounded, brand-free, `--out` for
+side-car mode); `flywheel gallery` renders a self-contained HTML gallery (tier
+badges, thumbnails, filter/sort) that `bench/report.py` reuses.
diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.md
new file mode 100644
index 00000000..994a995a
--- /dev/null
+++ b/harness/docs/DECISIONS.md
@@ -0,0 +1,180 @@
+# Decisions (ADR-style)
+
+Each entry: context → decision → consequence. All dated 2026-08-23 unless noted;
+"Δ" entries are deviations from the first-wave plan (`INTERFACES.md` as originally
+written) that were accepted because the code works that way and the tests pin it.
+
+## Laws (standing, from CLAUDE.md)
+
+* **L1 Raw code only.** Generated code never imports an SDK/helper; the harness owns
+ wrappers and exporters (`languages/*/wrappers`, `runtime_js/`). Consequence: every
+ language needs a standalone wrapper that cannot import `codeverse` (Blender's python
+ cannot see the package anyway).
+* **L2 One contracts package, one conventions module.** `contracts/` is data-only;
+ `conventions.py` is the only place stating frames/units/naming. Consequence: plan
+ frames are the language's native frame (Z-up for blender/cadquery/urdf) and
+ `check_contract` converts to the GLB frame (Y-up) using `LANGUAGE_FRAME`.
+* **L3 Deterministic first, VLM for perception only.** Score is computed in code
+ from rubric weights; floors and caps are explicit; degraded verdicts are glitches.
+* **L4 Typed, no regex-on-id, no god files.** Files ≤ ~400 lines; two wrappers
+ exceed it by design (`run_bpy.py` 418, `scene_host.mjs` 426).
+* **L5 Cheap first.** Lint → build → gates → montaged views → VLM. `build` tool
+ skips the build when lint has ERRORs.
+* **L6 Every round = a git commit; every call = a Usage; every run = record.json.**
+
+## Architecture decisions
+
+* **D1 Single-shot lives in tracks, not agents (Δ).** `single-shot:<provider>:<model>`
+ ids are dispatched by `tracks/generation.generate()`; the agents registry only knows
+ real agentic kinds. Consequence: `Spec.backends.generator` accepts three id shapes;
+ `is_single_shot()` is the only test.
+* **D2 generate() writes code, build_with_repair() builds (Δ).** The original
+ `generate_files` import still exists, but generation never builds; `run_round`
+ composes generate → commit → build+repair → gates → render → judge. Consequence:
+ repair prompts are error-focused (file:line, traceback tail, lint hints,
+ keyword-matched cookbook section) and escalate temperature/thinking (single-shot)
+ or add a "same error again" notice (agents) on identical error signatures.
+* **D3 `RoundPolicy.max_rounds` counts refine rounds after the baseline.** `3dcv make
+ --rounds 2` = baseline + up to 2 refine rounds. The rubric's `pass_threshold`
+ overrides `RoundPolicy.target` when no explicit policy is injected.
+* **D4 Parallel refine only when it is safe.** Fan out only when ≥ 3 file-disjoint
+ groups exist and every task maps to a file (threejs parts, scene zones/assets/env);
+ single-file languages get one whole-object task. Consequence: `generation.workspace_lock`
+ + retried `git diff` protect the shared git index (Workspace itself has no lock).
+* **D5 A refine round that changes no file is a plateau, not a crash.** Emits
+ `round.no_change` and stops with the best round so far.
+* **D6 Finalise restores the best commit and rebuilds.** Artifacts always match the
+ delivered code; export copies `artifacts/object.glb` trusting that.
+* **D7 Stage cache by input hash.** `StageRunner` stores `stages/<name>.json` keyed by a
+ hash of the inputs, so `3dcv resume` re-runs only what changed; spent budget is
+ restored from `run_state.extra.spent_usage`.
+* **D8 Events carry `event`, not `kind` (Δ).** `EventLog.emit(event, **data)` so payloads
+ may include `kind=` (round kind). `3dcv status` and tests follow.
+* **D9 `materialize_workspace` returns `Materialized` (Δ).** Callers need codex `-c`
+ overrides and the agy fallback text; callers that ignore the return are unaffected.
+ The cookbook is copied to `ws/.3dcv/cookbook.md` (gemini-cli cannot read outside the
+ workspace); MCP argv uses `sys.executable`.
+* **D10 gemini-cli needs a system-settings file (Δ).** api-key auth +
+ `dynamicModelConfiguration` (else silent model substitution) + `folderTrust.enabled=false`
+ (else workspace MCP servers are silently disabled even with `--skip-trust`). Served
+ model is checked; mismatch → `exit_reason=model_substituted`.
+* **D11 AgentJob.extra is the side-channel (Δ).** Keys `round`, `kind`, `language`, `track`
+ (+ `mcp_command`, `max_usd`, `temperature`, `thinking`, `allow_shell` for api-agent)
+ rather than new AgentJob fields, to keep `contracts/agent.py` frozen.
+* **D12 api-agent exposes `build` under its real name; `run_build` is an alias (Δ).**
+* **D13 Node ESM resolution via an import hook (Δ).** `NODE_PATH` cannot resolve bare ESM
+ specifiers; `run_node(three_hook=True)` adds `--import runtime_js/lib/resolve_three.mjs`;
+ browser pages get an import map from `serve.cjs`. `ThreeJsRuntime` writes
+ `src/package.json {"type":"module"}` (idempotent).
+* **D14 render_glb gained keyword-only extras (Δ).** `anim_time, shadow, gpu, timeout_s,
+ use_cache`; all original args/defaults unchanged; renders are cached by
+ sha(glb)+params under `~/.cache/codeverse/renders/`.
+* **D15 `check_contract(measurement, plan, *, language, tol_m)` (Δ).** `language` is
+ required for the Z-up → Y-up plan-box conversion. `cross_section` adds `absolute`,
+ `size`; `compare_silhouette` returns `ref_aspect, render_aspect, reliable` (IoU on
+ bbox-normalised 256² masks).
+* **D16 measure: link-hierarchy rule (Δ, fixed after the cabinet run).** Parts are
+ effective top-level nodes (descending through single geometry-less wrappers) with
+ subtrees merged — except when the scene carries `metadata["links"]`, in which case
+ each link is a part with only its own geometry. Consequence: URDF links are plan parts
+ for `check_contract` / `check_connectivity`; the cabinet run's "plan part missing"
+ errors were an artefact of the pre-fix rule.
+* **D17 URDF meshes are stored in raw Z-up link frames (Δ).** `meshes/<link>.glb` are
+ correct in any URDF loader (verified with yourdfpy); only the canonical `object.glb`
+ is Y-up with joint extras. Build `ok` is flipped only by rest-pose penetration > 5 mm
+ (moved-pose overlaps and floating links are gate findings, not build failures).
+* **D18 Authoring recipe for URDF (corrected in fix batch 1 — this is the ENFORCED
+ recipe).** Link meshes are built/exported in **WORLD coordinates** at q=0 (the
+ authored pose = the plan's rest pose); every non-root link frame = its **pivot**;
+ joint origin = pivot_child − frame_parent; visual AND collision `<origin xyz>` =
+ −pivot (root `0 0 0`), verified by the FK-consistency check; `rpy="0 0 0"`
+ everywhere. Skeleton URDFs shift plan limits by `JointPlan.rest` (URDF limits =
+ plan lower−rest .. upper−rest) so q=0 is the authored rest pose, and annotate the
+ shift inline. Lint accepts PascalCase or snake_case link names (plain
+ identifiers); `world` is a reserved link name (trimesh's glTF reader stomps on it).
+ The old prompts taught "visual origins zero", which the harness rejects — the
+ contract/cookbook examples now all build clean through the real pipeline.
+* **D19 Scene cameras are plain dicts `{name, position, lookAt, fov}`** (matches
+ `scene_host.mjs` validation); `scene.js` is assembled deterministically by the harness
+ from zones/env/assets; log-depth is opt-in; missing `/assets/*.glb` is a WARN, a
+ missing module is an error.
+* **D20 `probe_scene` returns `SceneProbeResult`** that unpacks as `(gate, census)`;
+ use `.model_dump()`, not `dict()`.
+* **D21 Judge wire schema has fixed keys (Δ).** One property per criterion/acceptance id so
+ flash-class models score every criterion; `apply_caps(rubric, overall, gates,
+ acceptance_results, acceptance_items=None, *, console_errors=None) -> CapResult`; rubric
+ caps use `when:` (PyYAML parses bare `on` as `True`). Missing render files raise
+ (pipeline bug), only model/parse failures produce degraded verdicts.
+* **D22 Judge defaults (updated wave 3).** `Settings.default_judge =
+ gemini:gemini-3.1-pro-preview`; tracks construct `VlmJudge(rubric, model_id,
+ n_samples=1)` (`RoundPolicy.judge_samples`). Flash is the cheap in-loop option —
+ use `n_samples ≥ 2` for decisions or re-judge with `3dcv judge --n 3`.
+* **D23 Gemini specifics (Δ).** tools + response_schema are mutually exclusive (schema
+ dropped with a warning); Gemini 3.x cannot disable thinking; provider opaque state
+ (thought signatures / Anthropic thinking blocks) is cached in-process by tool-call id
+ because `ToolCallPart` has no slot.
+* **D24 OpenAI via Chat Completions** (for `OPENAI_BASE_URL` compatibility); Anthropic uses
+ adaptive thinking + `output_config.effort` on 4.6+ models.
+* **D25 Flywheel shapes (Δ).** `caption_sample(ws, record, model_id, *, model=None)`;
+ `export_samples` keeps both `code.<ext>` and full `src/**`; parquet adds
+ track/language/score/passed/generator columns; tar locators filled by `--pack`;
+ `bench/` lives at repo root; `3dcv tools` is one command, not a sub-app; runs whose best
+ round never built are skipped unless `--include-unbuilt`.
+* **D26 Threejs exports strip textures; `userData.tick` cannot survive GLB** — recorded in
+ the census (`tick_present`) for the judge/flywheel rather than faked.
+* **D27 Blender wrapper resets the active layer collection** after clearing the scene (a
+ deleted factory "Collection" leaves `bpy.context.collection == None`, breaking the
+ common `bpy.context.collection.objects.link` pattern) — found live, pinned by tests.
+* **D28 `StopPolicy` "max_rounds" maps to `RunStatus.PLATEAU`** (no dedicated status in
+ contracts); the true reason is in `record.extra["stop_reason"]` / `RunState.stop_reason`.
+* **D29 Best-of-N baseline + pairwise tie-break (second wave).** `--candidates N` runs N
+ baseline candidates in parallel throw-away sub-workspaces (`<ws>/_cand/c<k>`), ranks them
+ by quick 4-view judge score → fewer gate errors, breaks near-ties pairwise, copies the
+ winner back; after each round a score within `pairwise_margin` (0.03) of the best is
+ treated as judge noise and a position-swapped `PairwiseJudge` decides (confidence ≥ 0.6
+ to replace). Every candidate is charged to the run budget.
+* **D30 Judge protocol v2 + pro default (third wave).** The judge sees ≤ 3 labelled
+ 2×2 montages (+ ≤ 2 detail crops, ≤ 1024 px) instead of sheet + 9 views; the wire
+ schema is observe-then-score (defect checklist + acceptance before criteria);
+ every rubric carries binary defects with penalties/caps. Measured on the e2e
+ rounds (`judges/calibration.py`, n=3): flash std 0.083 / pearson(gate errors,
+ score) −0.33; pro std 0.030 / pearson +0.63 — so `default_judge =
+ gemini-3.1-pro-preview` and flash's dynamic range is carried by the checklist.
+ Consequence: `VlmJudge(max_images=)` is gone (`max_montages`, `detail_crops`);
+ `JudgeInput.geometry_views` routes clay/normals views to a geometry-only montage.
+* **D31 Textures are a derived asset pack, never the deliverable.** The texture
+ pass (material plan → tileable tiles → world-metre UVs → `object_textured.glb`)
+ runs after finalise or standalone (`3dcv texture pass`); it never edits `src/` or
+ `object.glb`, ships only when the before/after judge gate agrees (Δoverall ≥
+ −0.01 AND materials criterion improved), and is recorded in
+ `record.extra["texturing"]`. Scenes get a named tile pack under
+ `public/textures/` injected into prompts instead of per-part texturing.
+* **D32 Graphics track = GL, not a 3D pipeline.** `graphics` renders through
+ moderngl in a subprocess per render (contexts are not thread/fork safe), has no
+ GLB/measure step, and gates on frame statistics (`gl_frames`: NaN/black/blown/
+ static/flicker). The harness owns the GLSL header (`#version`, uniforms,
+ `out vec4 fragColor`) — agents write shader bodies only; feedback shaders are
+ simulated at 30 fps. Rubric `shader_v1` (threshold 0.70).
+* **D33 Export as authored (fix batch 1, all languages).** No wrapper re-centres
+ or grounds the object (threejs `--normalise` is an opt-in dataset flag); the
+ build warns (`placement_offset`), the contract/connectivity gates report in the
+ *authoring frame*, and the agent fixes the source. Consequence: exact-per-plan
+ parts always pass `check_contract` even when the union is off-centre.
+* **D34 Key pool outcomes include `dead` (fix batch 1).** Auth/permission errors
+ (401/403, API_KEY_INVALID…) rotate away immediately and bench the key for an
+ hour once another key works; 429s rotate to untried keys without consuming the
+ retry budget. A single dead key no longer fails 1/N of all Gemini calls.
+* **D35 Strict schemas mirror pydantic nullability (fix batch 1).**
+ `to_openai_strict_schema` no longer adds `null` to defaulted fields (defaults
+ become description hints); `pricing.lookup_price` prefix fallback matches only
+ version/date/channel suffixes, so sibling models never inherit a parent's price.
+
+## Rejected / deferred
+
+* Registering `single-shot` as a CodingAgent kind (rejected: it has no tools/session).
+* A free-form `dict` judge schema (rejected: flash skips criteria).
+* Storing URDF meshes Y-up and converting on load (rejected: breaks foreign loaders).
+* Per-asset judging for threejs scene assets (deferred: needs a `render_asset` hook).
+* Proposed and not yet done (owner-level files): `ToolCallPart.extra` for provider
+ state; `Workspace._git` lock + index.lock retry; package-data globs for
+ `languages/**/starter/**` and `languages/**/*.md`; `n_samples` in Settings.
diff --git a/harness/docs/EVAL.md b/harness/docs/EVAL.md
new file mode 100644
index 00000000..19e7634a
--- /dev/null
+++ b/harness/docs/EVAL.md
@@ -0,0 +1,161 @@
+# Evaluation protocol
+
+How we decide whether the harness (plan → generate → gate → render → judge →
+refine) beats raw generation, and whether one backend beats another, without
+fooling ourselves. Tools: `3dcv bench`, `bench/compare_backends.py`,
+`codeverse.judges.{vlm_judge, pairwise, calibration, metrics}`.
+
+## 1. Principles
+
+1. **Fixed judge.** One judge model + rubric + `n_samples` for every arm of a
+ comparison, never the in-loop judge's own score. Default for decisive runs:
+ `gemini:gemini-3.1-pro-preview` (the settings default), `n_samples≥2`;
+ `gemini-3.7-flash` is fine for the loop but is lenient/noisy on fine
+ distinctions (overall std ≈ 0.08–0.12 at n=3) — its dynamic range comes from
+ the rubric defect checklist, not the criteria.
+2. **Same evidence for every arm.** The evaluator rebuilds from code: lint+build →
+ `measure_glb` → connectivity gate → canonical 8-view `render_glb` (`OBJECT_VIEWS`,
+ studio rig) → `VlmJudge`. A failed build scores 0 (error recorded). Acceptance
+ items come from the battery's `must_have` list for *all* arms (no plan-derived
+ items, so harness and one-shot are judged alike).
+3. **Scores are code-computed.** Weighted criteria, floors, caps from gate findings,
+ `passed = overall ≥ threshold ∧ no floor ∧ all must-acceptance`; the ledger is in
+ `Judgment.raw` (ScoreBreakdown). Degraded verdicts (`is_degraded`) are re-run, not
+ counted.
+4. **Stratified batteries.** Prompts are fixed YAML with ids, tiers (easy/medium/hard)
+ and categories; report per tier, never only the mean.
+5. **Pairwise for preferences.** Absolute scores are coarse; `PairwiseJudge` runs
+ both orderings and returns `tie` on disagreement; report win/tie/loss counts with
+ confidence.
+6. **Cost and time are part of the result.** Every cell records `Usage` (USD, tokens)
+ and wall time; compare at equal budget where possible.
+7. **Reproducibility.** `record.prompt_hashes` (contract/cookbook/generate/refine),
+ rubric content hash (`ScoreBreakdown.rubric_hash`), `record.environment` (python,
+ codeverse, blender, node, three, host) are stored per run; keep seeds fixed
+ (`--seed`).
+
+## 2. Batteries (`bench/prompts/`)
+
+| file | track / language | n | strata |
+|---|---|---|---|
+| `static_objects_v1.yaml` | static_object / blender | 24 | 8 categories × easy/medium/hard |
+| `articulated_v1.yaml` | articulated_object / urdf_blender | 12 | tiers |
+| `scenes_v1.yaml` | scene / scene_threejs | 12 | tiers |
+| `compare_v1.yaml` | static_object / blender | 8 | 2 easy / 3 medium / 3 hard; for harness-vs-one-shot |
+
+Each prompt: `{id, tier, category, prompt, must_have[], dimensions_m?}`. `must_have`
+becomes acceptance items (planner-appended in the loop, fixed-judge checklist in
+comparisons); `dimensions_m` becomes `Spec.constraints.dimensions_m` and a
+deterministic contract check.
+
+## 3. Harness battery runs (`3dcv bench run`)
+
+```bash
+3dcv bench run bench/prompts/static_objects_v1.yaml \
+ --generator api-agent:gemini:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \
+ --rounds 2 --max-usd 2.5 --parallel 4 --out bench/out/static_v1_apiagent
+3dcv bench run bench/prompts/static_objects_v1.yaml --generator gemini-cli:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview --out bench/out/static_v1_gemcli
+3dcv bench report bench/out/static_v1_apiagent
+```
+Each item = one full `3dcv make` run (its own workspace under `--out`); `results.jsonl`
+rows carry `score_baseline`, `score_final`, `passed`, `rounds`, `cost_usd`, `minutes`,
+`status`, `generator`, `judge`. `report.md/html` tabulates per tier and category:
+mean baseline → final (the harness delta), pass rate, cost, time. Keep `--judge` fixed
+across arms; vary only `--generator` (and `--planner` if that is the variable).
+Resumable: re-running the same `--out` skips finished ids.
+
+Reading the numbers: *baseline* (round 0) is the raw-model-with-contract result;
+*final − baseline* is what the refine loop buys; the pass rate at the rubric threshold
+(0.72 for `static_object_v1`) is the headline. Observed so far (flash judge,
+n=1, single runs): chair 0.67 → 0.74, bench 0.64 → 0.89, cabinet 0.68 → 0.93,
+scene 0.56 → 0.58 after one refine.
+
+## 4. Harness vs raw one-shot (`bench/compare_backends.py`)
+
+Answers "does the harness beat a strong model writing the file in one go?" —
+including `claude-code` / `codex` one-shot, which cannot run inside the loop as
+cheaply.
+
+```bash
+python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \
+ --arms harness:api-agent:gemini:gemini-3.7-flash,harness:gemini-cli:gemini-3.7-flash,oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \
+ --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1 [--parallel 3] [--limit N] [--ids a,b]
+ [--rounds 3] [--max-usd 2.5] [--loop-judge gemini:gemini-3.7-flash] [--repair-attempts 2] [--gen-timeout 900]
+ [--no-pairwise] [--no-resume] [--report-only]
+```
+Arms:
+* `harness:<generator-id>` — the full static_object track (rounds ≤ `--rounds`, ≤ `--max-usd`);
+ its in-loop judge is `--loop-judge` (default: settings default); the loop's own score
+ is **not** the reported score.
+* `oneshot:<x>` — ONE raw generation from prompt + minimal contract (no tools, cookbook,
+ plan, repair); `x` ∈ `claude-code[:model]` · `codex[:model]` · `gemini|anthropic|openai:<model>`.
+* `oneshot+repair:<x>` — same plus ≤ `--repair-attempts` build-error-feedback retries
+ (labelled; never judge feedback).
+
+Every arm ends with a `src/model.py` copied into a fresh eval workspace and scored by
+the same `FixedEvaluator` (`BlenderRuntime` lint+build → measure → connectivity →
+8-view render → `VlmJudge(static_object_v1, --judge, n_samples=2)`). Then a pairwise
+arena runs every harness arm against every one-shot arm per prompt (both orderings).
+Output under `--out`: `matrix.json`, `results.jsonl` (cells, resume source),
+`pairwise.jsonl`, `cells/<prompt>/<arm>/{run,gen,eval}`, `report.md`, `report.html`.
+
+Report per arm: mean/median score, pass rate, build-failure rate, per-tier breakdown,
+cost and wall time per prompt; arena: wins/ties/losses with mean confidence. Claim a
+harness advantage only when (a) the fixed-judge mean and pass rate are higher **and**
+(b) the pairwise arena agrees, at comparable or lower cost.
+
+Subscription-backed one-shot arms (`claude-code`, `codex`) have estimated or zero USD;
+report token counts alongside. Run them sparingly.
+
+## 5. Comparing backends inside the harness
+
+Same battery, same `--judge`, different `--generator` (`api-agent:*`, `single-shot:*`,
+`gemini-cli:*`, `claude-code:*`, `codex:*`, `agy:*`). Report baseline, final, delta,
+pass rate, cost, time per tier; optionally feed the best rounds of two arms through
+`PairwiseJudge.compare(spec, renders_a, renders_b)` (`flywheel pairs` already emits
+cross-backend candidate pairs keyed by prompt hash).
+
+## 6. Judge calibration
+
+`codeverse.judges.calibration` re-judges recorded rounds without touching the runs:
+
+```bash
+python -m codeverse.judges.calibration runs/e2e_chair_blender runs/e2e_cabinet_urdf \
+ --model gemini:gemini-3.1-pro-preview --n 3 --out out/calib [--geometry clay|normals|none] [--rounds 0,1]
+```
+Output: `calibration_<model>.md/.json` with per-round mean±std (capped and uncapped),
+which caps/defects fired, pearson/spearman(gate errors vs score), correlation with the
+stored in-run scores, per-criterion std and total cost.
+
+**Measured 2026-08-23** (montage prompt + defect checklist + observe-then-score
+schema, n=3, e2e chair/cabinet rounds):
+
+| judge | mean overall std | per-criterion std | pearson(gate errors, score) | cost |
+|---|---|---|---|---|
+| `gemini-3.7-flash` | 0.083 | 0.086 | −0.33 | $0.15 |
+| `gemini-3.1-pro-preview` | 0.030 | 0.057 | +0.63 (cap-driven; the rounds are visually near-identical) | $0.80 |
+
+Dynamic range (static rubric, chair brief, n=2): crafted chair / crude drawing /
+wrong-object primitive → flash 0.91 / 0.00 / 0.20, pro 0.60 / 0.00 / 0.25 — the
+binary defect checklist gives flash the range its raw criteria lack. Hence the
+default judge is pro; flash needs `n_samples ≥ 2` for decisions.
+Notes: the earlier criteria-first schema compressed flash to 0.6–0.7 (std 0.01);
+"images beat gate text for visible facts" in the prompt fixed pro hallucinating
+"nothing moves" from contract-gate text.
+
+* Variance on your own runs: `3dcv judge <slug> --n k` and read `score_std` /
+ `judges.metrics.judge_agreement`.
+* Sanity anchors: a skeleton placeholder should score ≈ 0.3–0.5; a deliberately wrong
+ object should trip the `intent_fidelity` floor / `wrong_object` defect; a floating
+ part should cap via `connectivity` findings with `data["kind"]="floating"`.
+* A better recurring smoke than re-judging e2e rounds: a separation set with
+ deliberately broken variants (exploded / floating / primitive-only).
+* Never tune rubric text against the battery you report on; bump the rubric version
+ (`*_v2`) instead and re-run.
+
+## 7. Reporting checklist
+
+battery name + git sha of prompts; judge id, rubric name + hash, `n_samples`; per-arm
+generator/planner ids; rounds and budget caps; per-tier table (n, mean ± std, pass
+rate, build-fail rate, cost, minutes); pairwise table; number of degraded verdicts
+re-run; links to `record.json` / `report.html` under `bench/out/`.
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index e88f7e3e..88c7ff8e 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -1,121 +1,272 @@
-# Cross-package interfaces (binding for parallel development)
+# Cross-package interfaces (as built)
-All types live in `codeverse/contracts/` (read them first). Protocols live in
-`models/base.py`, `agents/base.py`, `languages/base.py`, `spatial/registry.py`,
-`judges/base.py`, `tracks/base.py`. Do not change those files; if you need a
-field, add it in your own module or propose it in your final report.
+This file lists the signatures other packages may rely on. Types live in
+`codeverse/contracts/`; protocols in `models/base.py`, `agents/base.py`,
+`languages/base.py`, `spatial/registry.py`, `judges/base.py`, `tracks/base.py`.
+Where the build deviated from the original plan the deviation is called out as
+**Δ** — see `docs/DECISIONS.md` for the why. When in doubt the code wins; this
+file was reconciled against it on 2026-08-23 (waves 2–3 + fix batch 1).
-## models/ (package A)
+## Ids
+
+* Chat models: `<provider>:<model>` — `gemini:*` · `anthropic:*` · `openai:*`
+ (`models.registry.parse_model_id`).
+* Coding agents: `<kind>:<model>` — `gemini-cli:*` · `claude-code:*` · `codex:*` ·
+ `agy:*` · `api-agent:<provider>:<model>` (`agents.registry.parse_agent_id`).
+* **Δ** Single-shot generation ids: `single-shot:<provider>:<model>` — handled only
+ inside `tracks/generation.py` (`is_single_shot`, `single_shot_model_id`); never
+ registered in `agents/`. `Spec.backends.generator` accepts any of the three.
+* Image models: `models/gemini_image.py::GeminiImageModel` (default
+ `gemini-3.1-flash-image`, fallback `gemini-2.5-flash-image`) behind the
+ `ImageModel` protocol (`generate`, `generate_with_usage` → `(images, Usage)`).
+
+## models/
```python
-from codeverse.models import get_chat_model # (model_id) -> ChatModel
-m = get_chat_model("gemini:gemini-3.7-flash")
-resp = m.generate(ChatRequest(messages=[ChatMessage.user("...", images=[ImagePart(path=...)])],
- system="...", response_schema=StaticPlan.model_json_schema(),
- temperature=0.4, thinking="medium", label="planner"))
-resp.parsed # dict when response_schema given
-resp.text # always
-resp.tool_calls # when request.tools given
-resp.usage # Usage with cost_usd
-from codeverse.models.keypool import KeyPool # KeyPool(keys, rpm=..) .acquire() -> key, .report(key, ok|429|5xx)
-from codeverse.models.pricing import estimate_cost # (provider, model, usage) -> usd
+from codeverse.models import get_chat_model # (model_id) -> ChatModel, lru-cached, thread-safe
+resp = m.generate(ChatRequest(messages=[...], system=..., response_schema=..., temperature=..., thinking=..., label=...))
+resp.parsed / resp.text / resp.tool_calls / resp.usage # Usage always has cost_usd (models.pricing)
+from codeverse.models.keypool import KeyPool, KeyPoolExhausted
+KeyPool(keys, *, rpm_per_key=900, tpm_per_key=None, cooldown_s=30, dead_cooldown_s=3600)
+pool.acquire(*, tokens_hint=0, exclude=None, timeout_s=120) -> key # raises immediately when every key is dead/cooling past the deadline
+pool.report(key, "ok"|"429"|"5xx"|"error"|"dead", *, tokens=0, retry_after_s=None) # Δ "dead": health 0, benched dead_cooldown_s, re-probed after
+from codeverse.models.pricing import estimate_cost # (provider, model, usage) -> usd (unknown model -> 0.0 + one warning)
+from codeverse.models.schema_utils import to_gemini_schema, to_openai_strict_schema, to_anthropic_schema, parse_json_lenient
```
-Structured output: Gemini via `response_mime_type="application/json"` + `response_schema`
-(strip unsupported keywords: `$defs` → inline, `anyOf` with null → nullable, `const`,
-`title`, `default` removed). Anthropic: force a `submit` tool with `input_schema` or JSON
-prefill; OpenAI: `response_format={"type":"json_schema", ...}` (Responses or Chat API).
-Retries: 429/5xx/timeouts with jittered backoff, rotating Gemini keys via KeyPool. Provider
-exceptions → `ModelError(retryable=...)`. Gemini `thinking` map: off→budget 0 (where allowed),
-low→1024, medium→4096, high→16384 (`ThinkingConfig(thinking_budget=...)`; for models that
-reject the field, omit it and record a warning).
+Backends: `GeminiModel(model, *, keys=None, pool=None, ...)` (one shared KeyPool per
+key list), `AnthropicModel(model, *, json_mode="tool"|"output_config")`,
+`OpenAIModel(model, *, base_url=None)` (Chat Completions; `CV3D_OPENAI_BASE_URL`).
+Rules that callers must know:
+* **Δ** Gemini key handling: auth/permission errors (401/403, or 400 with
+ API_KEY_INVALID / expired / PERMISSION_DENIED / suspended markers) classify as
+ outcome `dead` — the call rotates to the next key at once (no retry budget, no
+ sleep) and the key is benched for an hour once another key succeeds; it raises
+ only when *every* key fails the same way. A 429 while an untried key remains is
+ a **free** rotation (does not consume `max_attempts`); only when all keys are
+ throttled do 429s count against the budget with backoff.
+* **Δ** Gemini: `tools` + `response_schema` together → schema dropped, text parsed
+ leniently into `.parsed`, warning in `resp.raw["warnings"]`. Gemini 3.x cannot
+ disable thinking; keep `max_output_tokens ≥ ~1000` even for one-word answers.
+* Anthropic 4.6+ models use adaptive thinking + `output_config.effort`.
+ Tool-call ids must be echoed unchanged (they key provider caches).
+* **Δ** `to_openai_strict_schema` never adds `null` to defaulted fields: a property
+ is nullable iff the *source* pydantic schema is (`T | None`); non-null defaults
+ are surfaced as a `[default: …]` description hint. Wire contract == pydantic contract.
+* **Δ** `pricing.lookup_price` prefix fallback matches only pure version/date/channel
+ suffixes (`-`/`_`/`@`/`:` + digits/latest/preview/exp/beta/…); sibling models
+ (`-nano`, `-mini`, `-codex`, `-lite`) never inherit the parent's price — they are
+ unknown (0.0 + warning) unless a row exists.
-## agents/ (package B)
+## agents/
```python
-from codeverse.agents import get_coding_agent # (agent_id) -> CodingAgent
-from codeverse.agents.materialize import materialize_workspace
-# materialize_workspace(ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str,
-# spatial_tools: bool, mcp_command: list[str]) -> None
-# writes AGENTS.md + GEMINI.md + CLAUDE.md (same body) and MCP configs:
-# gemini-cli → ws/.gemini/settings.json {"mcpServers": {"c3v": {"command": ..., "args": [...]}}}
-# claude-code → ws/.mcp.json {"mcpServers": {"c3v": {...}}}
-# codex → returned via config overrides (-c mcp_servers.c3v.command=... -c mcp_servers.c3v.args=[...])
-# agy → ~/.gemini/antigravity-cli? (investigate; fall back to no MCP + prompt-described CLI `c3v tools ...`)
-res = agent.run(AgentJob(workspace=str(ws.root), prompt=..., model="gemini-3.7-flash", timeout_s=1200,
- spatial_tools=True, label="baseline"))
-res.files_changed, res.usage, res.transcript_path, res.ok, res.exit_reason
-from codeverse.agents.watchdog import run_with_watchdog # (cmd, cwd, env, soft_timeout_s, idle_grace_s, hard_timeout_s, on_line=...) -> CompletedProc
+from codeverse.agents import get_coding_agent # (agent_id) -> CodingAgent .run(job) .available() .id .kind .model
+from codeverse.agents.materialize import materialize_workspace, Materialized, codex_mcp_overrides
+materialize_workspace(ws, *, agent_kind, contract_md, cookbook_rel, spatial_tools, mcp_command) -> Materialized
+# writes AGENTS.md + GEMINI.md + CLAUDE.md (same body), ws/.3dcv/cookbook.md (Δ copied in: gemini-cli cannot read
+# outside the workspace), .geminiignore/.aiexclude, and MCP wiring:
+# gemini-cli → ws/.gemini/settings.json {"mcpServers": {"3dcv": {...}}} + context.fileFiltering.respectGitIgnore=false
+# claude-code → ws/.mcp.json codex → Materialized.codex_overrides:
+# -c mcp_servers.3dcv.command=… -c mcp_servers.3dcv.args=[…] -c mcp_servers.3dcv.default_tools_approval_mode="approve"
+# (Δ without the approval mode every MCP tool call is elicited and auto-cancelled)
+# agy → no per-workspace MCP; body documents `3dcv tools <name> --json … --workspace .` as the fallback
+res = agent.run(AgentJob(workspace=..., prompt=..., label="baseline", timeout_s=1800, max_turns=60,
+ spatial_tools=True, write_roots=["src","public"], extra={...}))
+res.ok, res.exit_reason # completed | timeout | error | budget | model_substituted
+res.files_changed (git-derived, attributed per session), res.usage, res.transcript_path, res.tool_calls, res.errors
```
-MCP command to expose spatial tools: `["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(ws.root)]`
-(package F implements the server; B just wires the config).
-`api-agent` tool set (ApiAgent): `read_file`, `write_file`, `edit_file` (exact-string replace),
-`list_files`, `run_build` (= spatial tool `build`), plus every `spatial.registry.list_tools()`
-tool; loop until the model stops calling tools or max_turns; writes transcript JSONL.
+`AgentJob.extra` keys honoured by every agent: `round`, `kind`, `language`, `track`,
+`mcp_command` (override), `max_usd` / `temperature` / `thinking` / `allow_shell`
+(api-agent only), **Δ `files_hint`** (list of workspace-relative files/dirs the task
+is expected to touch — used to attribute `files_changed` between concurrent sessions
+in one workspace; harness-owned paths and sibling sessions' hinted files are dropped).
+Trajectories: `ws/trajectories/<label>_rNN/{prompt.md, transcript.jsonl, stdout.json,
+stderr.log, result.json}`; **Δ** a re-run of the same label+round lands in
+`<label>.a2_rNN` (then `.a3` …) — the first attempt is never overwritten; `result.json`
+records `attempt` + `job_label`. Each run makes two git commits (`pre:`/`agent:<label>`).
+gemini-cli specifics: system settings file via `GEMINI_CLI_SYSTEM_SETTINGS_PATH`
+(api-key auth, `dynamicModelConfiguration=true` else silent model substitution →
+`exit_reason="model_substituted"`, `folderTrust.enabled=false` else workspace MCP
+silently dropped). **Δ** `Usage.input_tokens` = `tokens.prompt` (TOTAL prompt incl.
+cached; `tokens.input` is the uncached count) and each served model is priced at its
+own rate. KeyPoolExhausted never escapes `run()` (→ `exit_reason=budget`); retries
+prefer a different key (10 s wait) before re-using the same one.
+api-agent tools: `read_file`, `write_file`, `edit_file`, `list_files`, `run_shell`
++ every spatial tool (`build` keeps its real name; `run_build` is an alias).
+**Δ** `run_shell` is a *policy filter*, not an OS sandbox: allow-listed programs only,
+no inline-code/REPL/loader flags (`-c/-e/-p/-i/--eval/--require/--import/…`),
+`python -m` restricted to a small allow-list, every path-like argument
+realpath-confined to the workspace (and never `.git/`). `FileTools.call` never
+raises — bad arguments / non-UTF-8 files come back as `ToolOutcome(is_error=True)`.
-## languages/ (packages C1, C2, D, E)
+## languages/
```python
-from codeverse.languages import get_runtime # (Language) -> LanguageRuntime
-rt.lint(ws) -> GateReport # gate="lint:<language>"
-rt.build(ws, timeout_s=None) -> BuildResult # glb_path = ws.artifacts/"object.glb" on success
-rt.skeleton(ws, plan) -> list[Path]
-rt.contract_doc() -> str # from prompts/<lang>/contract.md (package K writes it; provide a
- # minimal built-in fallback string if the file is missing)
+from codeverse.languages import get_runtime # (Language | str) -> LanguageRuntime
+rt.language; rt.entry_globs
+rt.lint(ws) -> GateReport # gate = "lint:<language>"
+rt.build(ws, *, timeout_s=None, **per_runtime) -> BuildResult # Δ BuildResult.error_file is WORKSPACE-relative for
+rt.skeleton(ws, plan) -> list[Path] # every runtime ("src/model.py", "src/parts/leg.py", "src/helpers.py")
+rt.contract_doc() -> str ; rt.cookbook_path() -> Path
```
-Build wrappers live in `codeverse/languages/<lang>/wrappers/` and are invoked via
-subprocess; they write `artifacts/build.json` (BuildResult fields) + `artifacts/census.json`.
-Canonical GLB: Y-up, +Z front, meters, named nodes per part (node name = PascalCase part).
+| runtime | entry_globs | notes / artifacts |
+|---|---|---|
+| `BlenderRuntime` | `src/model.py`, `src/parts/*.py` | **Δ multi-file**: `file_for_part(name) -> "src/parts/<snake>.py"` (`def build_<snake>()`), `file_for_target(target) -> list[str]`; lint = `layout.lint_workspace` over every src/*.py; skeleton writes model.py + per-part files; object.glb/stl, build.json, census.json |
+| `CadQueryRuntime` | `src/model.py` | trailing selector on the stack → parent solid exported + warning (ExportError when no solid exists); helper-module errors map to `src/<file>.py:line`; object.glb/stl/step |
+| `ThreeJsRuntime` | `src/object.js`, `src/parts/*.js` | **Δ export as authored** (`--normalise` opt-in, never passed by the runtime; census `placement_offset`/`normalised_offset`); InstancedMesh baked to `<Name>_<i>` meshes (`instanced_meshes_baked`); exported `selfcheck(THREE, root)` is called (throw → SelfCheckError); NaN geometry errors name mesh/part → routed to `src/parts/<snake>.js` |
+| `UrdfBlenderRuntime` | `src/model.py`, `src/robot.urdf` | object.glb (Y-up, node=link, joint extras), meshes/<link>.glb (raw Z-up link frames); link name `world` is reserved (lint ERROR + UrdfError); robot GLB root gets `__root` suffix on name clash |
+| `SceneThreeJsRuntime` | `src/scene.js`, `src/zones/*.js`, `src/assets/*.js`, `src/env.js`, `src/shaders/*.js` | glb_path=None; ok iff `probe_scene` + `check_shaders` pass |
+| `GlslShaderRuntime` | `src/shader.frag`, `src/common.glsl`, `src/buffer_a.frag` | harness owns `#version`/uniforms/`out` (wrap.HEADER: u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise + iTime/iChannel* aliases); build renders judge frames via GlHost; compile errors → GlslCompileError at mapped src file:line; artifacts frames/, frames_sheet.png, preview.gif, metrics.json |
+| `OpenGLPythonRuntime` | `src/program.py`, `src/*.glsl` | `setup(ctx,w,h)->state` + `render(ctx,state,t,frame,fbo)` run in a moderngl subprocess (`wrappers/run_gl.py`); exceptions map to src/program.py:line, in-string GLSL errors carry both line numbers |
-Threejs ESM resolution: agent code does `import * as THREE from 'three'`; the harness provides
-`three` via an import map (browser) or `NODE_PATH=runtime_js/node_modules` (node). Never CDN.
+Wrappers are standalone (never import codeverse): `blender/wrappers/run_bpy.py`
+(+ sibling `_census.py` — copy both), `cadquery/wrappers/run_cq.py`,
+`urdf/wrappers/run_bpy_links.py`, `opengl_python/wrappers/run_gl.py`; threejs/scene
+export+render live in `runtime_js/` (`export_glb.mjs`, `render_glb.mjs`,
+`render_scene.mjs`, `probe_scene.mjs`, `check_shaders.mjs`, `lib/instances.mjs`).
+**Placement policy (all languages)**: nothing re-centres or drops to ground at
+export; the build warns and the contract/connectivity gates report it.
+**Δ Node ESM resolution**: bare `import 'three'` needs
+`run_node(..., three_hook=True)` (`--import runtime_js/lib/resolve_three.mjs`).
-## spatial/ (packages C1 render, E joints, F the rest)
+## spatial/
```python
-from codeverse.spatial.render import render_glb, render_scene
-render_glb(glb: Path, out_dir: Path, *, views: Sequence[ViewPreset] | None = None, mode: str = "shaded",
- width: int = 768, height: int = 768, isolate: list[str] | None = None, explode: float = 0.0,
- sheet: bool = True, background: str = "studio") -> RenderSet
-render_scene(ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None, orbit: bool = True,
- times: Sequence[float] = (0.0, 1.5), width: int = 1024, height: int = 576,
- sheet: bool = True) -> RenderSet # also fills console_errors, fps
-from codeverse.spatial.sheet import contact_sheet # (images: list[tuple[label, path]], out: Path, cols=4, tile=384) -> Path
-from codeverse.spatial.measure import measure_glb # (glb: Path) -> Measurement
-from codeverse.spatial.connectivity import check_connectivity # (glb, gap_m=CONTACT_GAP_M) -> GateReport
-from codeverse.spatial.contract import check_contract # (measurement, plan, tol_m) -> GateReport
-from codeverse.spatial.sections import cross_section # (glb, axis, at, out_png) -> Observation
-from codeverse.spatial.silhouette import compare_silhouette # (render_png, reference_png) -> dict(iou=..., ...)
-from codeverse.spatial.joints import load_urdf, fk, pose_samples, sweep_collisions, urdf_to_glb # package E
-from codeverse.spatial.tools import * # registers @tool: build, measure, render_views, render_sheet, isolate,
- # cross_section, check_connectivity, check_contract, compare_silhouette,
- # joint_sweep, shader_probe, scene_probe, read_cookbook
-python -m codeverse.spatial.mcp_server --workspace <ws> # stdio MCP server over the registry
+from codeverse.spatial.render import render_glb, render_scene, render_turntable
+render_glb(glb, out_dir, *, views=None, mode="shaded|wire|normals|silhouette|clay", width=768, height=768,
+ isolate=None, explode=0.0, sheet=True, background=..., anim_time=None, shadow=True, gpu=None,
+ timeout_s=None, use_cache=True) -> RenderSet
+render_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1024, height=576, sheet=True,
+ bounds=None, sheet_max_views=10) -> RenderSet
+ # Δ bounds default from ws plan.json → orbit rig frustum-fits the CONTENT box (not ground/sky);
+ # contact sheet = judge subset only; views.json entries get judge: true|false
+from codeverse.spatial.render_scene import select_judge_views, JUDGE_MAX_VIEWS, read_metrics, plan_bounds
+select_judge_views(rs, max_n=10) -> RenderSet # priority: authored@t0, 2 overview@t0, 2 authored@t_last, rest
+from codeverse.spatial.frame_metrics import frame_gate_from_renders, frame_findings, frame_summary_text, FRAME_GATE
+frame_gate_from_renders(renders) -> GateReport # gate "scene_frames"; data.kind ∈ dark_frame | blown_frame | flat_frame |
+ # camera_in_geometry | camera_underground | camera_low | camera_high | content_small; authored cameras → ERROR, orbit rig → WARN
+from codeverse.spatial.measure import measure_glb # link-hierarchy rule: metadata["links"] → each link is its own part
+from codeverse.spatial.connectivity import check_connectivity # (glb, *, gap_m=…, …, language="") — Δ language selects the
+from codeverse.spatial.contract import check_contract # frame of fix hints; both gates emit hints in the AUTHORING frame
+ # (labelled "blender frame: Z-up, -Y front" etc.), GLB vectors in data
+from codeverse.spatial.silhouette import compare_silhouette
+from codeverse.spatial.joints import load_urdf, fk, sweep_collisions, urdf_to_glb, render_poses # RESERVED_LINK_NAMES={'world'}
+# joints_collide.py: deterministic penetration (oriented islands + fixed-direction parity ray test; python-fcl is a
+# core dependency, the trimesh fallback is deterministic too)
+from codeverse.spatial.gl_render import GlHost, GlResult, GlHostError, write_contact_sheet, write_gif
+GlHost(gpu="auto|on|off", timeout_s=240, fps=30, max_steps=240)
+ .render_fragment_shader(frag_src, out_dir, *, width=1280, height=720, times=..., buffer_a_src=None, feedback=False)
+ .run_program(program_path, out_dir, *, width, height, times) -> GlResult{ok, stage, frames[GlFrame], renderer, gpu, …}
+from codeverse.spatial.frame_stats import sequence_stats, frame_gate # gate "gl_frames"; data.kind ∈ nan | black | blown |
+ # static | flicker | low_detail | duplicate | no_frames
+from codeverse.spatial.registry import tool, get_tool, list_tools, tool_cards, ToolContext, Observation
+import codeverse.spatial.tools # registers: build, measure, render_views, render_sheet, isolate, cross_section,
+ # check_connectivity, check_contract, compare_silhouette, joint_sweep [articulated], shader_probe, scene_probe,
+ # scene_views [scene], read_cookbook, gl_probe + gl_frames [graphics], texture_pass + texture_preview [object tracks]
+python -m codeverse.spatial.mcp_server --workspace <ws> [--track X] [--language Y] [--round N] [--list] # MCP name: 3dcv
```
-`build` tool = `get_runtime(ctx.language).lint+build` then `measure_glb`; returns a compact
-Observation (errors first, with file:line + traceback tail; on success the key numbers).
-## judges/ (package G)
+## judges/
```python
-from codeverse.judges.vlm_judge import VlmJudge # VlmJudge(rubric="static_object_v1", model_id=..., n_samples=1)
-j = VlmJudge(...); verdict: Judgment = j.judge(JudgeInput(...))
-from codeverse.judges.pairwise import PairwiseJudge # .compare(spec, renders_a, renders_b) -> PairwiseResult{winner, confidence, reasons}
-from codeverse.judges.reference import ReferenceJudge
-from codeverse.judges.rubrics import load_rubric # (name) -> Rubric{name, criteria[{id, weight, description, floor}], pass_threshold}
+from codeverse.judges.rubrics import load_rubric, Rubric # Rubric{…, defects: [DefectItem{id, text, penalty, cap}], caps[{…, when:, kinds}]}
+from codeverse.judges.vlm_judge import VlmJudge
+VlmJudge(rubric="static_object_v1", model_id=None (settings.default_judge = gemini-3.1-pro-preview), n_samples=1,
+ temperature=0.2, *, thinking="low", max_attempts=3, max_montages=3, detail_crops=2, max_px=1024,
+ chat_model=None, cache_dir=None, label="judge") # Δ max_images is GONE → montage budget
+VlmJudge.judge(inp, *, geometry_views: RenderSet | None = None) -> Judgment # also reads inp.geometry_views
+from codeverse.judges.base import JudgeInput # (spec, renders, measurement=None, gates=[], acceptance=[], plan_summary="",
+ # round_index=0, previous=None, extra_context="", geometry_views=None)
+from codeverse.judges.montage import plan_montages, render_montage, Montage # ≤3 2×2 montages (shaded/geometry/poses) + ≤2 detail
+ # crops @≤1024px replace sheet+9 views; clay/normals views (RenderView.mode) auto-route to the GEOMETRY montage
+from codeverse.judges.scoring import is_degraded, aggregate_samples # ScoreBreakdown adds defects, defect_votes (majority,
+ # ties→present), defect_penalty, overall_after_defects; overall = caps(weighted_mean − Σpenalty)
+from codeverse.judges.caps import apply_caps # (rubric, overall, gates, acceptance_results, acceptance_items=None, *,
+ # console_errors=None, views=None, defects_present=None) -> CapResult;
+ # cap rules add when="missing_views" and ledger lines "defect:<id>"
+from codeverse.judges.pairwise import PairwiseJudge # .compare(spec, renders_a, renders_b, *, rubric=…) -> PairwiseResult
+PairwiseJudge.compare_many(spec, candidates: list[RenderSet], *, rubric) -> RankingResult{order, points, confidence, pairs, usage, .best}
+from codeverse.judges.calibration import calibrate, CalibrationTable # (run_dirs, *, model_id, n_samples=3, out_dir, geometry_mode,
+ # rounds, …) -> rows + pearson/spearman(errors vs score), mean_std, cost; CLI: python -m codeverse.judges.calibration RUN… --n 3
+from codeverse.judges.reference import ReferenceJudge # image-conditioned specs
+from codeverse.judges.metrics import judge_agreement, plateau, best_index
```
-Rubric YAMLs: `static_object_v1`, `articulated_v1`, `scene_v1`, `asset_v1`, `reference_v1`.
+Rubrics: `static_object_v1` (0.72), `articulated_v1` (requires pose views via
+`missing_pose_sheet` cap), `scene_v1` (frame-gate caps dark/blown/flat/content_small),
+`asset_v1`, `reference_v1`, `shader_v1` (0.70; gl_frames caps). Wire schema order is
+observe-then-score (summary/issues/defects/acceptance before criteria) — measured to
+restore flash's dynamic range. `passed = overall ≥ threshold ∧ no floor ∧ all
+must-acceptance`; gate authors set `GateFinding.data["kind"]` so caps match precisely.
-## orchestrator/ + tracks/ (package H)
+## orchestrator/ + tracks/
```python
from codeverse.tracks import get_track
-rec = get_track(spec.track).run(spec, ws, resume=False) # RunRecord
-from codeverse.orchestrator.runner import StageRunner # .stage(name, fn, inputs_hash) with run_state.json cache
-from codeverse.orchestrator.rounds import RoundPolicy, StopPolicy, BestSelector
-from codeverse.orchestrator.fanout import fan_out # (items, fn, max_workers) -> list[result | Exception]
-from codeverse.orchestrator.budget import BudgetGuard # .charge(usage) raises BudgetExceeded
-from codeverse.tracks.generation import generate_files, SINGLE_SHOT_FORMAT, parse_multifile # API single-shot codegen
+rec = get_track(spec.track, **options).run(spec, ws, resume=False) -> RunRecord # Δ kwargs forwarded to the constructor:
+# services=, judge=, agent=, model=, runtime=, policy=RoundPolicy, settings=, planner_model=, n_candidates=
+# (CLI --candidates > run_state.extra > settings.default_candidates); StaticObject | Articulated | Scene | Graphics
+from codeverse.orchestrator.rounds import RoundPolicy, StopPolicy, BestSelector, build_refine_instructions, compact_instructions
+RoundPolicy(max_rounds=4, plateau_window=2, min_delta=0.02, target=0.8, judge_on_gate_errors=True, max_refine_tasks=6,
+ max_instructions_per_task=6, parallel_min_tasks=2, n_candidates=1, pairwise_margin=0.03,
+ pairwise_min_confidence=0.6, judge_samples=1).with_candidates(n)
+from codeverse.orchestrator.candidates import CandidateRecord, rank_candidates, decide_best # pure decision logic
+from codeverse.tracks.candidates import run_best_of_n, choose_best_round # N parallel baselines in <ws>/_cand/c<k>
+# (quick 4-view judge, crashed candidate retried once; selection by build_ok → quick score → fewer gate errors, pairwise
+# within margin); winner copied back, normal r00 pipeline follows; rounds/candidates.json + record.extra["candidates"]
+from codeverse.tracks.motion import default_motion_checks, expected_direction # gate "motion_direction" (articulated)
+from codeverse.tracks.reference import silhouette_gate, reference_refine_tasks # gate "reference_silhouette" (IoU<0.6 → WARN + refine task)
+from codeverse.tracks.prompting import base_prompt_context, reference_images, file_for_target_factory # Δ split out of
+from codeverse.tracks.common import RunContext, Services # common.py (lazy re-exports keep old imports working)
+from codeverse.tracks.generation import generate, run_agent_task, parse_multifile, is_single_shot
+from codeverse.tracks.repair import build_with_repair
+from codeverse.tracks.steps import run_round
+from codeverse.tracks.planner import plan, plan_model_for, ensure_acceptance # graphics uses tracks/graphics_steps.plan_graphics
+```
+`run_round` = generate → commit → `build_with_repair` → measure → gates → render →
+post-render gates → judge → commit. Post-render gates: static `reference_silhouette`
+(when references), articulated `joint_sweep` + `motion_direction`, scene
+`render_console` (`scene_frames` via `frame_gate_from_renders` is built but not yet
+wired into `ScenePipeline.post_render_gates`), graphics `gl_frames`. Reference specs get a
+`ReferenceJudge` (rubric `reference_v1` for static_object) and images attached to
+generation prompts.
+
+## texturing/ (derived asset pack; code stays truth — object.glb is never touched)
+```python
+from codeverse.texturing.run import texture_pass, load_report
+texture_pass(ws, spec, plan, *, model_id, image_model=None, judge=True, judge_model_id=None, rubric=None,
+ glb_in=None, views=OBJECT_VIEWS_QUICK, size=1024, ..., events=None, update_record=True) -> TextureReport
+# 1 vision call material plan (cacheable) → tileable textures (mirror cross-fade, seam_score ≤ 0.08) → world-metre UV
+# unwrap (planar/box/cylinder per part, tile_size_m) → artifacts/object_textured.glb → seam gate + before/after judge
+# gate (ship iff Δoverall ≥ −0.01 AND materials criterion improved); record.extra["texturing"], events texture.*
+from codeverse.texturing.plan import material_plan, default_plan, TexturePlan
+from codeverse.texturing.generate import generate_textures, FakeImageModel
+from codeverse.texturing.scene_pack import scene_texture_pack, texture_pack_prompt # 6–12 named tiles + manifest.json
+# under public/textures/ for scene prompts (URL /public/textures/<name>.png)
```
-## flywheel/ + cli/ (package I)
+## flywheel/ + cli/
```python
-from codeverse.flywheel.record import finalize_record # (ws, RunRecord) -> writes record.json
-from codeverse.flywheel.export import export_samples # (runs_dir, out_dir, min_score) -> ExportReport
-from codeverse.flywheel.pairs import build_pairs # (runs_dir, out_jsonl, min_delta) -> n
-from codeverse.flywheel.captions import caption_sample # (ws, model_id) -> Captions{detailed, instruction, factory}
-c3v make|resume|status|render|judge|tools|mcp|flywheel|bench|doctor
+from codeverse.flywheel.record import finalize_record, load_record, iter_runs, best_round_index
+from codeverse.flywheel.export import export_samples # (runs_dir, out_dir, *, min_score=None, only_passed=False, best_round=True,
+ # overwrite=True, include_unbuilt=False, captions_dir=None, drop_duplicates=False) -> ExportReport{…, n_duplicates, duplicates, tiers}
+from codeverse.flywheel.quality import quality_tier, prompt_hash, find_duplicates # tiers: A passed & 0 gate errors, B passed,
+ # C best ≥ 0.6, D else; dedupe = (code fingerprint, prompt)
+from codeverse.flywheel.pairs import build_pairs # (runs_dir, out_jsonl, *, min_delta=0.05, trajectories=True) -> n
+from codeverse.flywheel.trajectories import mine_run # in-session repair pairs from api-agent transcripts (replay-verified)
+from codeverse.flywheel.captions import caption_sample # Δ (ws, record, model_id, *, model=None, out_dir=None) -> Captions;
+ # out_dir → side-car <out_dir>/<slug>.json, run untouched
+from codeverse.flywheel.gallery import write_gallery, gallery_items, render_gallery # self-contained HTML gallery (tier badges,
+ # thumbs); bench/report.py reuses it
+from codeverse.flywheel.index import build_index, query, summary # sqlite + parquet: adds quality_tier, gate_errors, cost_usd,
+ # rounds, status, code_fingerprint, prompt_hash, duplicate_of, has_captions
+3dcodeverse make|resume|status|render|judge|tools|mcp|texture {pass,scene-pack,show}
+ |flywheel {export,pairs,caption,index,dedupe,gallery}|bench {run,report}|doctor # alias: 3dcv
```
+
+## Events and records
+`EventLog.emit(event, **data)` writes `{"t", "event", ...}` (**Δ** key is `event`).
+Event names: `run.start`, `stage.start/done`, `plan.done`, `workspace.materialized`,
+`round.start`, `generate.done`, `build.done`, `gates.done`, `judge.done`,
+`round.done`, `best.updated`, `refine.planned`, `asset.judged`, `assets.done`,
+`zones.done`, `assemble.done`, `round.no_change`, `candidates.start`,
+`candidate.start/done/failed/retry/selected`, `pairwise.done`,
+`texture.start/plan/generated/applied/gate/done`, `budget.exceeded`,
+`finalise.rebuild`, `stop`, `run.done` / `run.failed`.
+`RunRecord` (record.json): spec, plan, workspace, status, rounds[RoundRecord],
+best_round, baseline_score, final_score, total_usage, environment,
+prompt_hashes{contract, cookbook, generate, refine}, error, extra{stop_reason,
+rubric, budget, rounds_summary, n_candidates?, candidates?, texturing?, captions?}.
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
new file mode 100644
index 00000000..dcfd244e
--- /dev/null
+++ b/harness/docs/RUNBOOK.md
@@ -0,0 +1,187 @@
+# Runbook — operating the harness
+
+Everything here was exercised on this machine (WSL2, RTX 5090, Blender 5.0.1,
+node 24, gemini-cli 0.53, claude 2.1, codex 0.147+, agy 1.1) on 2026-08-23. Paths
+are relative to `/home/yipeng/3dcodeverse/harness` unless absolute. The CLI is
+`3dcodeverse` with short alias `3dcv` (used below).
+
+## 1. Install and check
+
+```bash
+pip install -e /home/yipeng/3dcodeverse/harness # once; entry points 3dcodeverse and 3dcv
+cd /home/yipeng/3dcodeverse/harness/runtime_js && npm install # [email protected], puppeteer (chrome cached)
+3dcv doctor # python deps (incl. python-fcl, moderngl), blender, node/three/puppeteer, chrome WebGL, keys, CLIs, git, ffmpeg, mcp
+3dcv doctor --live # + one tiny Gemini call ("pong", ~$0.00001)
+python -m pytest tests -q -m "not live" # ~860 offline tests (blender/node/GL tests run when the binaries exist)
+python -m pytest tests -q -m "not live and not blender and not node" # pure-python subset
+```
+
+### Keys and settings
+* Gemini keys, in precedence order: `GEMINI_API_KEYS` (comma-separated) → `GEMINI_API_KEY`
+ / `GOOGLE_API_KEY` → legacy `~/.config/astra3d/gemini_keys.env` (22 keys here).
+ All `gemini:*` models share one `KeyPool` (900 rpm/key, 30 s cooldown on 429; dead
+ keys benched 1 h and re-probed; 429s rotate to fresh keys for free).
+ `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `CV3D_OPENAI_BASE_URL` for the other
+ providers (not set on this box → `anthropic:*` / `openai:*` unavailable).
+* Settings: `~/.config/codeverse/config.yaml` or `./codeverse.yaml`, overridden by env
+ with prefix `CV3D_` and `__` nesting — e.g. `CV3D_RUNS_DIR=/data/runs`,
+ `CV3D_RENDER__GPU=off`, `CV3D_BINARIES__BLENDER=/opt/blender/blender`,
+ `CV3D_LIMITS__AGENT_TIMEOUT_S=900`, `CV3D_DEFAULT_CANDIDATES=2`.
+ Defaults: runs_dir `runs/`, cache_dir `~/.cache/codeverse`, build/render timeout 300 s,
+ agent timeout 1800 s, bpy RLIMIT 12 GB, 6 parallel agents, 3 parallel builds,
+ `default_judge gemini:gemini-3.1-pro-preview`, `default_candidates 1`.
+* Blender: `settings.binaries.blender` else first `blender-5.0`/`blender`/… on PATH.
+ Always `-b --factory-startup`; the child env strips `PYTHONPATH`/`PYTHONHOME`.
+* GPU rendering: `runtime_js/gpu_launch.cjs` tries Chrome with `--use-angle=gl-egl` +
+ Mesa d3d12 env and falls back to SwiftShader; probe cached in
+ `~/.cache/codeverse/gpu_probe.json`. Force with `CV3D_RENDER_GPU=on|off|auto` or
+ `settings.render.gpu`. The graphics track uses moderngl the same way (d3d12 GPU
+ context first, llvmpipe fallback; no probe needed — `GlHost` decides per process).
+
+## 2. Running each track
+
+```bash
+# static object — Blender (default language, multi-file src/model.py + src/parts/*.py)
+3dcv make "a mid-century wooden dining chair" --track static_object --language blender
+3dcv make "a brass desk lamp" --track static_object --language cadquery
+3dcv make "a classic park bench" --track static_object --language threejs --generator gemini-cli:gemini-3.7-flash
+# articulated object — bpy links + URDF
+3dcv make "a bedside cabinet with one hinged door and one drawer" --track articulated_object --language urdf_blender
+# scene — multi-file three.js + GLSL (+ optional bpy GLB assets chosen by the planner)
+3dcv make "a small japanese garden at dusk with a koi pond" --track scene --language scene_threejs --rounds 2 --max-usd 3 --max-minutes 60
+# graphics — animated shader / raw OpenGL program
+3dcv make "neon cyberpunk rain on a window with bokeh city lights" --track graphics --language glsl_shader
+3dcv make "instanced pastel cubes with bloom" --track graphics --language opengl_python
+```
+Useful flags (`3dcv make --help`): `--generator`, `--planner`, `--judge`, `--captioner`
+(backend ids, §3), `--image <png>` (repeatable; reference images → `ReferenceJudge` +
+silhouette gate + IoU refine tasks), `--rounds N` (refine rounds after the baseline),
+`--candidates N` (best-of-N baseline: N parallel candidates in `<ws>/_cand/`,
+quick-judged, pairwise tie-break, winner kept; multiplies baseline cost ≈ N;
+default from `settings.default_candidates`), `--texture` (run the texture pass after
+finalise; see §6), `--max-usd`, `--max-minutes`, `--dim height=0.45`, `--must`,
+`--must-not`, `--style`, `--tag`, `--seed`, `--slug`, `--runs-dir`, `--force`,
+`--no-run`.
+
+Expected cost/time with gemini-3.7-flash: object tracks ≈ $0.7–0.9 and 12–36 min for
+baseline + 1 refine; best-of-2 single-shot ≈ $0.25 / 8 min; graphics single-shot
+≈ $0.05 / 2 min per judged round; scenes ≈ $2.3 and 30 min before the first judged
+round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60 --max-usd 4`).
+
+## 3. Backends
+
+| id | what runs | notes |
+|---|---|---|
+| `api-agent:gemini:gemini-3.7-flash` (default) | in-process tool loop with file tools + every spatial tool | cheapest agentic path; the only backend whose transcripts feed repair-pair mining |
+| `single-shot:gemini:gemini-3.7-flash` | one structured-output call → multi-file envelope, no tools | fastest/cheapest; baseline for "raw model" deltas |
+| `gemini-cli:gemini-3.7-flash` | `gemini -p … --approval-mode yolo --skip-trust --output-format json` | see gotchas below |
+| `claude-code:<model>` | `claude -p … --dangerously-skip-permissions --mcp-config ws/.mcp.json …` | local subscription — test lightly |
+| `codex:<model>` | `codex exec --json -C ws --sandbox workspace-write … -c mcp_servers.3dcv.…` | subscription; MCP tools need `default_tools_approval_mode="approve"` (harness passes it) |
+| `agy:<model>` | `agy --print … --add-dir ws` | no per-workspace MCP: tools via `3dcv tools <name> --json … --workspace .`; no served-model or cost reporting |
+| `gemini:* / anthropic:* / openai:*` | ChatModel for planner / judge / captioner / single-shot | Anthropic/OpenAI untested live here |
+
+### gemini-cli gotchas (handled by `agents/gemini_cli.py`; do not undo)
+* System settings file via `GEMINI_CLI_SYSTEM_SETTINGS_PATH`: api-key auth,
+ `experimental.dynamicModelConfiguration=true` (else unknown models are silently
+ substituted → checked, `exit_reason=model_substituted`), `security.folderTrust.enabled=false`
+ (else workspace MCP servers are silently ignored even with `--skip-trust`).
+* Workspace `.gemini/settings.json` sets `context.fileFiltering.respectGitIgnore=false`
+ so the fine-grained `.geminiignore` (not the git ignore) decides what the agent can
+ read: build/census/measurement JSON and its own `task_prompt.md` stay readable,
+ renders/judge output/transcripts stay hidden.
+* One pool key injected as `GEMINI_API_KEY`; other credential env stripped; retries
+ prefer a different key (never raise KeyPoolExhausted out of a session).
+* Cost accounting: `tokens.prompt` (total, incl. cached) is the input count; each
+ served model priced at its own rate.
+* Cookbook copied to `ws/.3dcv/cookbook.md` (gemini-cli cannot read outside the ws).
+* MCP server argv is `[sys.executable, -m, codeverse.spatial.mcp_server, --workspace, ws]`;
+ server name `3dcv` → tools appear as `mcp_3dcv_<name>` (gemini) / `mcp__3dcv__<name>`
+ (claude). `3dcv mcp --workspace runs/<slug>` execs the same server;
+ `python -m codeverse.spatial.mcp_server --workspace ws --list` prints the tools.
+
+## 4. Where outputs land
+
+`runs/<slug>/` (ARCHITECTURE §3). Code in `src/` (git; one commit per round), built
+artifacts in `artifacts/` (`object.glb`, `robot.urdf` + `meshes/`, scene
+`public/assets/*.glb`, graphics `frames/` + `frames_sheet.png` + `preview.gif` +
+`metrics.json`, texturing `object_textured.glb` + `textures/`), per-round renders in
+`artifacts/renders/rNN/`, gate JSON in `artifacts/gates/rNN/`, verdicts in
+`artifacts/judge/rNN.json`, transcripts in `trajectories/<label>_rNN/` (retries in
+`<label>.a2_rNN`), events in `events.jsonl`, the flywheel record in `record.json`.
+`3dcv status <slug>` prints the rounds table (best round starred), cost and the last
+events.
+
+## 5. Resume, re-render, re-judge, texture, export
+
+```bash
+3dcv resume <slug> [--candidates N] # continues from run_state + stages/*.json (input-hash cached; budget restored)
+3dcv render <slug> [--round N] [--mode shaded|wire|normals|clay|silhouette] [--out dir]
+3dcv judge <slug> [--round N] [--rubric static_object_v1] [--model gemini:gemini-3.1-pro-preview] [--n 3]
+ # re-judges a round's recorded renders → artifacts/judge/rNN_cli.json
+3dcv texture pass <slug> [--no-judge] [--model …] [--judge-model …] [--image-model …] [--size 1024]
+3dcv texture scene-pack <slug> [--n 10] · 3dcv texture show <slug>
+3dcv tools list [--cards] · 3dcv tools measure --workspace runs/<slug> · 3dcv tools gl_frames --workspace … --json '{"times":[0,1,2.5]}'
+3dcv flywheel export runs/ dataset/ [--min-score 0.7] [--only-passed] [--pack] [--include-unbuilt]
+ [--captions-dir caps/] [--drop-duplicates]
+3dcv flywheel pairs runs/ pairs.jsonl [--min-delta 0.05] [--no-trajectories]
+3dcv flywheel caption <slug> [--model …] [--out caps/] # --out = side-car mode, run untouched
+3dcv flywheel gallery runs/ gallery.html [--title …] # self-contained HTML gallery (tiers, thumbs)
+3dcv flywheel index runs/ runs_index.sqlite · 3dcv flywheel dedupe dataset/
+python -m codeverse.judges.calibration runs/<slug> [runs/<slug2> …] --model gemini:gemini-3.1-pro-preview --n 3 --out out/
+ # re-judges recorded rounds; writes calibration_<model>.md/.json (never touches runs/)
+```
+A run that crashed outside its own handling leaves `record.json` with `status=failed`;
+`3dcv resume` retries from the last completed stage/round (cached plan/skeleton/scene
+stages are reused — this also recovers from Gemini 503 storms). Ctrl-C is safe.
+
+## 6. Texture pass
+
+`3dcv texture pass <slug>` (or `--texture` on `make`): one VLM material plan →
+tileable texture images (gemini-3.1-flash-image, ~$0.07/tile, cached by prompt) →
+world-metre UVs → `artifacts/object_textured.glb` → seam gate + before/after judge
+gate (ships only when the score does not drop and the materials criterion improves).
+`record.extra["texturing"]` holds shipped/delta/cost; `3dcv texture show <slug>`
+prints it. Scenes: `3dcv texture scene-pack <slug>` writes 6–12 named tiles +
+manifest under `public/textures/` for zone prompts. Object tracks' agents can also
+call the `texture_pass` / `texture_preview` tools mid-session.
+
+## 7. Benchmarks
+
+```bash
+3dcv bench run bench/prompts/static_objects_v1.yaml --generator single-shot:gemini:gemini-3.7-flash \
+ --judge gemini:gemini-3.1-pro-preview --rounds 2 --parallel 4 [--tier easy] [--id furn_easy_stool] [--limit 6] [--out bench/out/x]
+3dcv bench report bench/out/static_objects_v1 # report.md + self-contained report.html (gallery)
+python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \
+ --arms harness:api-agent:gemini:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1
+```
+Results stream to `results.jsonl` (resumable). Batteries: `static_objects_v1` (24),
+`articulated_v1` (12), `scenes_v1` (12), `compare_v1` (8, harness-vs-one-shot).
+Protocol and judge calibration: `docs/EVAL.md`.
+
+## 8. Extending (plugin paths)
+
+* **New language**: enum in `contracts/common.py::Language` (+ `TRACK_LANGUAGES`),
+ frame in `conventions.LANGUAGE_FRAME`; `languages/<lang>/{runtime.py, lint.py,
+ skeleton.py, CONTRACT.md, wrappers/}` implementing `LanguageRuntime`; branch in
+ `languages/base.py::get_runtime`; `prompts/<lang>/contract.md` + `cookbook.md`
+ (every snippet must run — `tests/prompts` executes them); entry-file mappings in
+ `flywheel/sample.py`; part→file mapping via `runtime.file_for_part` (blender and
+ threejs have it; `tracks/prompting.file_for_target_factory` picks it up).
+* **New spatial tool**: pydantic args + `@tool("name", Args, "…", tracks=(…),
+ languages=(…), cost_hint=…)` in `spatial/tools*.py` (imported from
+ `spatial/tools.py`); available to tracks, MCP, api-agent and prompt cards at once.
+ Update `tests/spatial_tools` EXPECTED_TOOLS.
+* **New rubric**: `judges/rubrics/<name>.yaml` with `pass_threshold`,
+ `criteria[{id, weight, floor, title, description, anchors, kind}]`,
+ `caps[{id, cap, when: gate|acceptance|console|missing_views, gate, severity, kinds}]`,
+ `defects[{id, text, penalty, cap}]`. Tracks pick rubrics in `tracks/*.py`;
+ `3dcv judge` maps track → rubric in `cli/main.py`.
+* **New backend**: ChatModel → `models/<provider>.py` + registry + prices;
+ CodingAgent → `agents/<kind>.py` using `cli_common` + registry + `materialize.py`.
+* **New track**: subclass `tracks/lifecycle.py::BaseTrack` (hooks: `make_pipeline`,
+ `prepare`, `baseline_tasks`, `refine_tasks`, `round_files_hint`), a `RoundPipeline`,
+ plan model in `contracts/plan.py`, `.j2` prompts, branch in `tracks/base.py`
+ (`get_track` forwards `**options` to constructors). `tracks/graphics.py` is the
+ template for a track with its own planner and no GLB.
+* **New bench battery**: `bench/prompts/<name>.yaml` with `name, track, language,
+ prompts[{id, tier, category, prompt, must_have, dimensions_m}]`.
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
index 17aa2d7b..9c5a1ede 100644
--- a/harness/pyproject.toml
+++ b/harness/pyproject.toml
@@ -18,6 +18,7 @@ dependencies = [
"pyyaml>=6",
"numpy>=1.26",
"trimesh>=4.4",
+ "python-fcl>=0.7",
"pillow>=10",
"google-genai>=1.0",
"anthropic>=0.40",
@@ -31,7 +32,7 @@ urdf = ["yourdfpy>=0.0.56", "scipy>=1.11"]
dev = ["pytest>=8", "pytest-timeout>=2.3", "ruff>=0.5"]
[project.scripts]
-c3v = "codeverse.cli.main:app"
+3dcv = "codeverse.cli.main:app"
3dcodeverse = "codeverse.cli.main:app"
[tool.setuptools.packages.find]
diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.md
index 99b9aa6b..47bb46c1 100644
--- a/harness/runtime_js/README.md
+++ b/harness/runtime_js/README.md
@@ -13,9 +13,14 @@ serve.cjs serveDirs({root, mounts, routes}) loopback static server (
'three/addons/' onto it — nothing is ever fetched from the internet
export_glb.mjs node --import lib/resolve_three.mjs export_glb.mjs --ws <ws> [--entry src/object.js]
[--out artifacts/object.glb] [--census artifacts/census.json]
- imports the agent module, build(THREE) (awaits promises), validates, normalises
- (stands on y=0, xz-centred; offset recorded), strips textures (warning), writes GLB
- + census.json; on failure export_error.json + {ok:false,error:{type,message,file,line,frames}}
+ [--normalise 0|1] imports the agent module, build(THREE) (awaits promises), validates
+ (NaN/empty-bbox errors name the mesh + part), runs an exported selfcheck(THREE, root)
+ if any (throw → SelfCheckError), bakes InstancedMesh copies into named meshes
+ (lib/instances.mjs — trimesh ignores EXT_mesh_gpu_instancing), keeps the source
+ placement (off-ground/off-centre → warning + census.placement_offset; --normalise 1
+ translates instead, for dataset canonicalisation only), strips textures (warning),
+ writes GLB + census.json; on failure export_error.json +
+ {ok:false,error:{type,message,file,line,frames,part?}}
render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode shaded|wire|normals|silhouette|clay]
[--width --height] [--isolate A,B] [--explode 0.3] [--background studio|white|transparent]
[--anim-time t] [--gpu auto|on|off] [--shadow 0|1] [--fill 0.85]
@@ -23,7 +28,8 @@ render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode s
lib/resolve_three.mjs node --import hook: bare 'three' / 'three/addons/*' (and three-mesh-bvh) resolve
from runtime_js/node_modules for modules anywhere on disk (NODE_PATH is CJS-only)
lib/node_polyfills.mjs FileReader/Blob/self shims so GLTFExporter writes binary GLB without a DOM
-lib/census.mjs per-part tri counts, world bboxes, materials, NaN check (node + browser)
+lib/census.mjs per-part tri counts, world bboxes, materials, NaN check naming mesh + part (node + browser)
+lib/instances.mjs bakeInstancedMeshes(THREE, root): InstancedMesh → Group of named plain meshes
lib/stack.mjs Error → {type,message,file,line,frames} with workspace-relative src/ paths
lib/syntax_check.mjs `node --input-type=module --check` per file to locate ESM SyntaxErrors
lib/browser/*.js page-side ESM (served through /__runtime/): camera_fit.js (azimuth/elevation →
diff --git a/harness/runtime_js/check_shaders.mjs b/harness/runtime_js/check_shaders.mjs
index a4342af3..5abe1a47 100644
--- a/harness/runtime_js/check_shaders.mjs
+++ b/harness/runtime_js/check_shaders.mjs
@@ -22,7 +22,7 @@ import { auditFile, fixHintFor, hasGlsl, locateSourceLine } from './lib/glsl_aud
import { errorSummary, openHost } from './lib/host_page.mjs';
const args = parseCli({
- ws: {}, module: {}, out: {}, gpu: { default: process.env.C3V_RENDER_GPU || 'auto' },
+ ws: {}, module: {}, out: {}, gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' },
'timeout-ms': { default: '90000' }, 'no-compile': { type: 'boolean', default: false },
});
diff --git a/harness/runtime_js/export_glb.mjs b/harness/runtime_js/export_glb.mjs
index 450bd0cd..d7a35eae 100644
--- a/harness/runtime_js/export_glb.mjs
+++ b/harness/runtime_js/export_glb.mjs
@@ -5,10 +5,18 @@
// --ws <workspace> [--entry src/object.js] [--out artifacts/object.glb] [--census artifacts/census.json]
//
// Runs in plain node (no browser). The agent module must `export function build(THREE)`
-// returning a THREE.Group (or a Promise of one). Last stdout line is a JSON record:
+// returning a THREE.Group (or a Promise of one); an optional `export function
+// selfcheck(THREE, root)` is called on the built group and fails the build when it
+// throws. InstancedMesh objects are baked into named plain meshes (lib/instances.mjs)
+// so trimesh-based gates see every copy. The object is exported exactly where the
+// source put it: an off-ground / off-centre build only WARNS (census.placement_offset),
+// like the Blender/CadQuery wrappers, so plan-frame gates stay valid; `--normalise 1`
+// (dataset canonicalisation only — never passed by ThreeJsRuntime) translates instead.
+// Last stdout line is a JSON record:
// ok:true -> {ok, glb, census, duration_ms}
-// ok:false -> {ok:false, error:{type,message,file,line,frames,stack}, warnings}
-// and the same error record is written next to the census as export_error.json.
+// ok:false -> {ok:false, error:{type,message,file,line,frames,stack,part?}, warnings}
+// (`part` = the plan part holding the offending mesh, for file routing on the python
+// side) and the same error record is written next to the census as export_error.json.
import fs from 'node:fs';
import path from 'node:path';
@@ -16,14 +24,16 @@ import { parseArgs } from 'node:util';
import { pathToFileURL } from 'node:url';
import { installExporterPolyfills } from './lib/node_polyfills.mjs';
-import { objectCensus, hasNonFinitePositions } from './lib/census.mjs';
+import { objectCensus, findNonFinitePositions, worldBox } from './lib/census.mjs';
+import { bakeInstancedMeshes, expandInstancedMesh } from './lib/instances.mjs';
import { errorRecord } from './lib/stack.mjs';
import { findSyntaxError } from './lib/syntax_check.mjs';
const TEXTURE_SLOTS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap',
'bumpMap', 'displacementMap', 'alphaMap', 'envMap', 'lightMap', 'specularMap', 'clearcoatMap',
'clearcoatNormalMap', 'clearcoatRoughnessMap', 'sheenColorMap', 'transmissionMap', 'thicknessMap'];
-const NORMALISE_THRESHOLD_M = 0.01;
+//: placement offsets below this are not worth a warning (1 cm)
+const PLACEMENT_THRESHOLD_M = 0.01;
function cli() {
const { values } = parseArgs({
@@ -32,7 +42,7 @@ function cli() {
entry: { type: 'string', default: 'src/object.js' },
out: { type: 'string', default: 'artifacts/object.glb' },
census: { type: 'string', default: 'artifacts/census.json' },
- normalise: { type: 'string', default: '1' },
+ normalise: { type: 'string', default: '0' },
},
});
if (!values.ws) throw new Error('--ws <workspace dir> is required');
@@ -43,7 +53,7 @@ function cli() {
entry: abs(values.entry),
out: abs(values.out),
census: abs(values.census),
- normalise: values.normalise !== '0',
+ normalise: values.normalise === '1',
};
}
@@ -77,36 +87,79 @@ async function loadBuild(entry) {
e.name = 'ContractError';
throw e;
}
- return mod.build;
+ return mod;
+}
+
+/** Throw a ContractError; `part` (plan part name) lets the python side route it to src/parts/<snake>.js. */
+function fail(msg, part = '') {
+ const e = new Error(msg);
+ e.name = 'ContractError';
+ if (part) e.part = part;
+ throw e;
+}
+
+function describeMesh(hit) {
+ const where = hit.ancestor && hit.ancestor !== hit.name ? ` (in part '${hit.ancestor}')` : '';
+ return `${hit.type} '${hit.name || '<unnamed>'}'${where}`;
+}
+
+/** First direct child of `group` with an empty / non-finite world box, or null. */
+function firstBadBoxPart(THREE, group) {
+ for (const child of group.children) {
+ const box = worldBox(THREE, child);
+ if (!box || !box.flat().every(Number.isFinite)) return child;
+ }
+ return null;
}
function validateGroup(THREE, group, entry) {
- const fail = (msg) => {
- const e = new Error(msg);
- e.name = 'ContractError';
- throw e;
- };
if (!group || !group.isObject3D) fail(`build(THREE) must return a THREE.Group (got ${group && group.constructor ? group.constructor.name : typeof group})`);
let meshes = 0;
group.traverse((o) => {
- if (o.isMesh || o.isInstancedMesh || o.isSkinnedMesh) meshes += 1;
+ if (o.isInstancedMesh) meshes += o.count > 0 ? 1 : 0; // (isMesh is true for InstancedMesh too)
+ else if (o.isMesh || o.isSkinnedMesh) meshes += 1;
});
if (meshes === 0) fail('build(THREE) returned a group with no meshes');
- if (hasNonFinitePositions(group)) fail('geometry contains NaN/Infinity vertex positions (check divisions by zero, radius 0, empty shapes)');
+ const nan = findNonFinitePositions(group);
+ if (nan) fail(`${describeMesh(nan)} has NaN/Infinity vertex positions (check divisions by zero, radius 0, empty shapes)`, nan.part);
const box = new THREE.Box3().setFromObject(group, true);
- if (box.isEmpty() || !Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) fail('object has an empty or non-finite bounding box');
+ if (box.isEmpty() || !Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
+ const bad = firstBadBoxPart(THREE, group);
+ const who = bad ? `part '${bad.name || '<unnamed>'}' (${bad.type}) has` : 'object has';
+ fail(`${who} an empty or non-finite bounding box (NaN position/scale/matrix or no geometry)`, bad ? bad.name : '');
+ }
if (!group.name) group.name = path.basename(path.dirname(entry)) === 'src' ? 'Object' : path.basename(entry, '.js');
}
-/** Shift the group so it stands on y=0 centred on the Y axis; returns the applied offset or null. */
-function normalise(THREE, group, enabled) {
+/** Run the module's optional `selfcheck(THREE, root)`; a throw fails the build with the agent's message. */
+async function runSelfcheck(mod, THREE, group) {
+ if (typeof mod.selfcheck !== 'function') return false;
+ try {
+ await mod.selfcheck(THREE, group);
+ } catch (err) {
+ const e = err instanceof Error ? err : new Error(String(err));
+ e.message = `selfcheck(THREE, root) threw: ${e.message}`;
+ if (!e.name || e.name === 'Error') e.name = 'SelfCheckError';
+ throw e;
+ }
+ return true;
+}
+
+/**
+ * Offset that WOULD stand the object on y=0 centred on the Y axis (null when within
+ * PLACEMENT_THRESHOLD_M). Only applied when `--normalise 1` was given: by default the
+ * GLB keeps the source placement so check_contract compares in the plan's frame.
+ */
+function placement(THREE, group, apply) {
const box = new THREE.Box3().setFromObject(group, true);
const c = box.getCenter(new THREE.Vector3());
const offset = new THREE.Vector3(-c.x, -box.min.y, -c.z);
- if (!enabled || offset.length() <= NORMALISE_THRESHOLD_M) return null;
+ if (offset.length() <= PLACEMENT_THRESHOLD_M) return { offset: null, applied: null };
+ const rounded = offset.toArray().map((v) => +v.toFixed(5));
+ if (!apply) return { offset: rounded, applied: null };
group.position.add(offset);
group.updateWorldMatrix(true, true);
- return offset.toArray().map((v) => +v.toFixed(5));
+ return { offset: rounded, applied: rounded };
}
function stripTextures(group, warnings) {
@@ -138,20 +191,31 @@ async function main() {
const THREE = await import('three');
const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
- const build = await loadBuild(args.entry);
- let group = build(THREE);
+ const mod = await loadBuild(args.entry);
+ let group = mod.build(THREE);
if (group && typeof group.then === 'function') group = await group;
validateGroup(THREE, group, args.entry);
+ const selfchecked = await runSelfcheck(mod, THREE, group);
+ let bakedInstances = 0;
+ if (group.isInstancedMesh) {
+ group = expandInstancedMesh(THREE, group); // a bare InstancedMesh root has no parent to swap it in
+ bakedInstances += 1;
+ }
+ bakedInstances += bakeInstancedMeshes(THREE, group);
const tickPresent = typeof (group.userData && group.userData.tick) === 'function';
if (tickPresent) delete group.userData.tick; // functions cannot be serialised into glTF extras
- const normalisedOffset = normalise(THREE, group, args.normalise);
- if (normalisedOffset) warnings.push(`object was off ground/centre by ${JSON.stringify(normalisedOffset)} m; translated so min.y=0 and xz-centre=0 (fix the source: the object must stand on y=0 centred on the Y axis)`);
+ const place = placement(THREE, group, args.normalise);
+ if (place.applied) warnings.push(`object was off ground/centre by ${JSON.stringify(place.applied)} m; translated so min.y=0 and xz-centre=0 (--normalise 1)`);
+ else if (place.offset) warnings.push(`object is off ground/centre: it needs a translation of ${JSON.stringify(place.offset)} m to stand on y=0 centred on the Y axis; exported as authored — fix the source (the contract gate reports this too)`);
stripTextures(group, warnings);
const census = objectCensus(THREE, group);
- census.normalised_offset = normalisedOffset;
+ census.placement_offset = place.offset;
+ census.normalised_offset = place.applied;
+ census.instanced_meshes_baked = bakedInstances;
+ census.selfcheck_ran = selfchecked;
census.tick_present = tickPresent;
let unnamed = 0;
group.traverse((o) => {
@@ -183,6 +247,7 @@ async function main() {
main().catch((err) => {
const ws = ARGS ? ARGS.ws : '';
const record = { ok: false, error: errorRecord(err, ws) };
+ if (err && typeof err.part === 'string' && err.part) record.error.part = err.part;
// ESM SyntaxErrors from import() carry no location: find the offending file ourselves.
if (record.error.type === 'SyntaxError' && !record.error.file && ARGS) {
const hit = findSyntaxError(path.dirname(ARGS.entry));
diff --git a/harness/runtime_js/gpu_launch.cjs b/harness/runtime_js/gpu_launch.cjs
index 87ae60ba..77aa0b0c 100644
--- a/harness/runtime_js/gpu_launch.cjs
+++ b/harness/runtime_js/gpu_launch.cjs
@@ -16,7 +16,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
-const CACHE_DIR = process.env.C3V_CACHE_DIR || path.join(os.homedir(), '.cache', 'codeverse');
+const CACHE_DIR = process.env.CV3D_CACHE_DIR || path.join(os.homedir(), '.cache', 'codeverse');
const CACHE_PATH = path.join(CACHE_DIR, 'gpu_probe.json');
const NEGATIVE_TTL_MS = 20 * 60 * 1000; // how long a "no GPU" verdict is trusted
const PROTOCOL_TIMEOUT_MS = 15 * 60 * 1000; // big frame batches exceed puppeteer's 180 s default
@@ -117,7 +117,7 @@ async function tryGpu(puppeteer) {
* @returns {Promise<{browser: object, gpu: boolean, renderer: string}>}
*/
async function launchBrowser(opts = {}) {
- const mode = String(opts.gpu || process.env.C3V_RENDER_GPU || 'auto').toLowerCase();
+ const mode = String(opts.gpu || process.env.CV3D_RENDER_GPU || 'auto').toLowerCase();
const puppeteer = loadPuppeteer(opts.puppeteer);
if (!['auto', 'on', 'off'].includes(mode)) throw new Error(`gpu must be auto|on|off, got ${mode}`);
diff --git a/harness/runtime_js/lib/census.mjs b/harness/runtime_js/lib/census.mjs
index 8fd7d30e..c2756238 100644
--- a/harness/runtime_js/lib/census.mjs
+++ b/harness/runtime_js/lib/census.mjs
@@ -1,5 +1,5 @@
// Census of a THREE.Object3D tree: per-part triangle counts, world bboxes,
-// materials, NaN checks. Pure three.js math — usable in node and browser.
+// materials, NaN checks (with the offending mesh/part named). Pure three.js math — usable in node and browser.
//
// import { objectCensus, triangleCount, worldBox } from './census.mjs';
@@ -35,20 +35,45 @@ export function worldBox(THREE, root) {
return [box.min.toArray().map(r), box.max.toArray().map(r)];
}
+function geometryHasNonFinite(geometry) {
+ if (!geometry || !geometry.attributes || !geometry.attributes.position) return false;
+ const a = geometry.attributes.position.array;
+ for (let i = 0; i < a.length; i++) {
+ if (!Number.isFinite(a[i])) return true;
+ }
+ return false;
+}
+
+/**
+ * First mesh under `root` whose position attribute holds NaN/Infinity, or null.
+ * `part` is the root's direct child on the path to the mesh (the plan part it
+ * belongs to — the mesh itself when it is a direct child, '' when it is the
+ * root); `ancestor` is the nearest named ancestor below the root.
+ * @returns {{name: string, type: string, part: string, ancestor: string} | null}
+ */
+export function findNonFinitePositions(root) {
+ const visit = (o, path) => {
+ if (isMeshLike(o) && geometryHasNonFinite(o.geometry)) {
+ const below = path.slice(1); // ancestors strictly below root, nearest last
+ const named = below.filter((a) => a.name);
+ return {
+ name: o.name || '', type: o.type,
+ part: path.length === 0 ? '' : (below.length ? below[0] : o).name || '',
+ ancestor: named.length ? named[named.length - 1].name : '',
+ };
+ }
+ for (const c of o.children) {
+ const hit = visit(c, [...path, o]);
+ if (hit) return hit;
+ }
+ return null;
+ };
+ return visit(root, []);
+}
+
/** True when any position attribute contains a non-finite value. */
export function hasNonFinitePositions(root) {
- let bad = false;
- root.traverse((o) => {
- if (bad || !isMeshLike(o) || !o.geometry || !o.geometry.attributes.position) return;
- const a = o.geometry.attributes.position.array;
- for (let i = 0; i < a.length; i++) {
- if (!Number.isFinite(a[i])) {
- bad = true;
- return;
- }
- }
- });
- return bad;
+ return findNonFinitePositions(root) !== null;
}
function materialSummary(m) {
diff --git a/harness/runtime_js/lib/glsl_audit.mjs b/harness/runtime_js/lib/glsl_audit.mjs
index 8f26b0c6..94eb50e4 100644
--- a/harness/runtime_js/lib/glsl_audit.mjs
+++ b/harness/runtime_js/lib/glsl_audit.mjs
@@ -95,7 +95,7 @@ export function auditFile(file, source, { sceneUsesFog = false } = {}) {
}
}
// Full ShaderMaterial fragment without fog chunks while the scene uses fog
- const fogOptOut = /fog\s*:\s*false|c3v:\s*no-fog|\bsky\b/i.test(source);
+ const fogOptOut = /fog\s*:\s*false|3dcv:\s*no-fog|\bsky\b/i.test(source);
if (sceneUsesFog && /ShaderMaterial/.test(source) && !isRaw && !fogOptOut) {
for (const s of strings) {
if (/void\s+main/.test(s.text) && /gl_FragColor|fragColor/.test(s.text) && !/fog_fragment|USE_FOG|fogColor/.test(s.text)) {
diff --git a/harness/runtime_js/lib/host_coverage.mjs b/harness/runtime_js/lib/host_coverage.mjs
new file mode 100644
index 00000000..f02c5f68
--- /dev/null
+++ b/harness/runtime_js/lib/host_coverage.mjs
@@ -0,0 +1,105 @@
+/**
+ * Page-side frame coverage instrument: what fraction of a camera's frame is
+ * CONTENT (meshes that are neither the sky dome nor the ground plane), and
+ * what fraction is ground. Implemented as two mask renders — backdrop hidden,
+ * fog/background off, a flat white override material on everything left —
+ * followed by a downscaled readback. `sky_frac` is the remainder.
+ *
+ * The backdrop classifier mirrors the census rules (name + world-bbox size) so
+ * "content" here means the same thing as `census.content_bbox`; a mesh is also
+ * backdrop when its footprint is far larger than the content bbox (scatter
+ * across the whole ground).
+ */
+
+const SAMPLE_W = 96;
+const SAMPLE_H = 54;
+const SKY_NAME_RE = /\b(sky|skydome|skybox|stars|clouds?|sun|moon|atmosphere)\b/i;
+const GROUND_NAME_RE = /\b(ground|terrain|floor|water|ocean|sea|lake|river|plane|sand|grass|land)\b/i;
+
+/** 'sky' | 'ground' | 'content' for one drawable with world box `box`. */
+export function classifyBackdrop(obj, box, contentSpan) {
+ const name = obj.name || (obj.parent && obj.parent.name) || '';
+ const sx = box.max.x - box.min.x, sy = box.max.y - box.min.y, sz = box.max.z - box.min.z;
+ const span = Math.max(sx, sz);
+ if (SKY_NAME_RE.test(name) && span > 50) return 'sky';
+ if (span > 2000 || (sy > 300 && span > 300)) return 'sky';
+ if (obj.isInstancedMesh) return 'content';
+ if (span > 20 && sy < 0.06 * span && GROUND_NAME_RE.test(name)) return 'ground';
+ if (span > 40 && sy < 0.02 * span) return 'ground';
+ if (contentSpan > 0 && span > 2.5 * contentSpan && sy < 0.1 * span) return 'ground';
+ return 'content';
+}
+
+function collectDrawables(scene, THREE, contentSpan) {
+ const out = [];
+ const box = new THREE.Box3();
+ scene.traverse((o) => {
+ if (!o.visible) return;
+ if (!(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;
+ if (!o.geometry) return;
+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
+ const gb = o.geometry.boundingBox;
+ if (!gb || gb.isEmpty()) return;
+ box.copy(gb).applyMatrix4(o.matrixWorld);
+ out.push({ obj: o, kind: classifyBackdrop(o, box, contentSpan) });
+ });
+ return out;
+}
+
+function brightFraction(canvas) {
+ const small = document.createElement('canvas');
+ small.width = SAMPLE_W;
+ small.height = SAMPLE_H;
+ const ctx = small.getContext('2d', { willReadFrequently: true });
+ ctx.drawImage(canvas, 0, 0, SAMPLE_W, SAMPLE_H);
+ const { data } = ctx.getImageData(0, 0, SAMPLE_W, SAMPLE_H);
+ const n = SAMPLE_W * SAMPLE_H;
+ let bright = 0;
+ for (let i = 0; i < n; i++) {
+ if (data[i * 4] + data[i * 4 + 1] + data[i * 4 + 2] > 3 * 64) bright += 1;
+ }
+ return bright / n;
+}
+
+/**
+ * Coverage of `camera`'s frame: {content_frac, ground_frac, sky_frac}.
+ * Restores every scene/renderer setting it touches.
+ */
+export function frameCoverage(renderer, scene, camera, canvas, THREE, contentBox) {
+ const contentSpan = contentBox ? Math.max(contentBox.size[0], contentBox.size[2]) : 0;
+ const drawables = collectDrawables(scene, THREE, contentSpan);
+ const saved = {
+ background: scene.background, fog: scene.fog, override: scene.overrideMaterial,
+ clear: renderer.getClearColor(new THREE.Color()), alpha: renderer.getClearAlpha(),
+ toneMapping: renderer.toneMapping,
+ };
+ const mask = new THREE.MeshBasicMaterial({ color: 0xffffff, fog: false, side: THREE.DoubleSide });
+ const pass = (keep) => {
+ for (const d of drawables) d.obj.visible = keep.includes(d.kind);
+ renderer.render(scene, camera);
+ return brightFraction(canvas);
+ };
+ let content = 0, covered = 0;
+ try {
+ scene.background = null;
+ scene.fog = null;
+ scene.overrideMaterial = mask;
+ renderer.setClearColor(0x000000, 1);
+ renderer.toneMapping = THREE.NoToneMapping;
+ content = pass(['content']);
+ covered = pass(['content', 'ground']); // ground pass includes content so hidden ground is not counted
+ } finally {
+ for (const d of drawables) d.obj.visible = true;
+ scene.background = saved.background;
+ scene.fog = saved.fog;
+ scene.overrideMaterial = saved.override;
+ renderer.setClearColor(saved.clear, saved.alpha);
+ renderer.toneMapping = saved.toneMapping;
+ mask.dispose();
+ }
+ return {
+ content_frac: +content.toFixed(4),
+ ground_frac: +Math.max(0, covered - content).toFixed(4),
+ sky_frac: +Math.max(0, 1 - covered).toFixed(4),
+ };
+}
diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjs
index 66f2a843..9b60ec30 100644
--- a/harness/runtime_js/lib/host_page.mjs
+++ b/harness/runtime_js/lib/host_page.mjs
@@ -14,7 +14,7 @@ const CONTROL_RE = new RegExp('[\\u0000-\\u001f]+', 'g');
function hostHtml() {
return [
- '<!doctype html><html><head><meta charset="utf-8"><title>c3v scene host</title>',
+ '<!doctype html><html><head><meta charset="utf-8"><title>3dcv scene host</title>',
importMapHtml(),
'<style>html,body{margin:0;background:#000;overflow:hidden}</style></head><body>',
`<script type="module" src="${runtimeMount()}lib/scene_host.mjs"></script></body></html>`,
@@ -25,11 +25,37 @@ function clean(s) {
return String(s).replace(CONTROL_RE, ' ').trim();
}
+/**
+ * createScene() boot timeout for a driver: an explicit --create-timeout-ms
+ * wins, else 60% of the driver budget capped at 20 s — always below the
+ * watchdog so a hung boot is an agent-attributed scene failure (exit 1 with
+ * boot.stage = 'createScene'), never a watchdog kill (exit 3).
+ */
+export function createTimeoutMs(flagValue, driverTimeoutMs) {
+ const flag = parseInt(flagValue || '', 10);
+ if (Number.isFinite(flag) && flag > 0) return flag;
+ return Math.min(20000, Math.max(1000, Math.round(0.6 * driverTimeoutMs)));
+}
+
+/**
+ * Error line for a puppeteer 'requestfailed' event, or null when it must be
+ * ignored. Chrome intermittently fires requestfailed with net::ERR_ABORTED
+ * for a same-origin fetch that already received a 200 and was fully consumed
+ * (three's FileLoader stream wrapper) — a phantom failure that used to fail
+ * the render_console / scene_probe gates ~10% of rounds. Real load failures
+ * are still reported by the 404 'response' handler and LoadingManager.onError.
+ */
+export function requestFailureLine(url, base, hasResponse, errorText) {
+ if (!url.startsWith(base)) return null;
+ if (hasResponse || errorText === 'net::ERR_ABORTED') return null;
+ return `request failed: ${url.slice(base.length)} (${errorText || '?'})`;
+}
+
/**
* Open the host for workspace `wsRoot`.
* @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}
*/
-export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js' } = {}) {
+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0 } = {}) {
wsRoot = path.resolve(wsRoot);
if (!fs.existsSync(path.join(wsRoot, sceneRel))) {
throw new Error(`missing ${sceneRel} in workspace ${wsRoot}`);
@@ -58,8 +84,8 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto
if (errors.page.length < MAX_CONSOLE) errors.page.push(text.slice(0, 800));
});
page.on('requestfailed', (req) => {
- const url = req.url();
- if (url.startsWith(srv.base)) errors.console.push(`request failed: ${url.slice(srv.base.length)} (${req.failure()?.errorText || '?'})`);
+ const line = requestFailureLine(req.url(), srv.base, !!req.response(), req.failure()?.errorText || '?');
+ if (line) errors.console.push(line);
});
page.on('response', (res) => {
if (res.status() === 404 && res.url().startsWith(srv.base)) {
@@ -74,7 +100,7 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto
await page.waitForFunction('window.__c3v_ready === true', { timeout: 60000 });
const boot = await page.evaluate(
(o) => window.__c3v.boot(o),
- { sceneUrl: `/${sceneRel}`, width, height, logDepth },
+ { sceneUrl: `/${sceneRel}`, width, height, logDepth, createSceneTimeoutMs },
);
const close = async () => {
try { await launched.browser.close(); } catch (e) { /* ignore */ }
diff --git a/harness/runtime_js/lib/instances.mjs b/harness/runtime_js/lib/instances.mjs
new file mode 100644
index 00000000..ead71193
--- /dev/null
+++ b/harness/runtime_js/lib/instances.mjs
@@ -0,0 +1,85 @@
+// Bake THREE.InstancedMesh objects into plain meshes before GLTF export.
+//
+// three's GLTFExporter writes an InstancedMesh as ONE mesh node + the
+// EXT_mesh_gpu_instancing extension. Browser loaders understand that, but the
+// python side (trimesh: measure / connectivity / contract / cross-sections) does
+// not and sees a single copy at the node origin. Baking every instance into a
+// named child mesh keeps the GLB, the census and every gate consistent.
+//
+// import { bakeInstancedMeshes } from './instances.mjs';
+// const baked = bakeInstancedMeshes(THREE, root); // -> number of InstancedMesh objects replaced
+//
+// Each `InstancedMesh` named `Posts` becomes a `Group` named `Posts` (same local
+// transform, userData, visibility) holding meshes `Posts_0 .. Posts_{n-1}` that
+// share the source geometry (the exporter dedupes it) and material; per-instance
+// colours (`instanceColor`) become per-colour material clones.
+
+function instanceMaterial(THREE, source, color, cache) {
+ if (!color) return source;
+ const key = color.getHexString();
+ let m = cache.get(key);
+ if (!m) {
+ m = Array.isArray(source) ? source.map((s) => s.clone()) : source.clone();
+ for (const mat of Array.isArray(m) ? m : [m]) {
+ if (mat.color && mat.color.isColor) mat.color.copy(color);
+ }
+ cache.set(key, m);
+ }
+ return m;
+}
+
+/** Replace one InstancedMesh by a Group of plain meshes; returns the Group. */
+export function expandInstancedMesh(THREE, inst) {
+ const group = new THREE.Group();
+ group.name = inst.name || '';
+ if (inst.matrixAutoUpdate) inst.updateMatrix();
+ group.matrix.copy(inst.matrix);
+ group.matrix.decompose(group.position, group.quaternion, group.scale);
+ group.visible = inst.visible;
+ group.userData = inst.userData;
+ group.renderOrder = inst.renderOrder;
+ const count = Math.max(0, Number(inst.count) || 0);
+ const m4 = new THREE.Matrix4();
+ const color = new THREE.Color();
+ const matCache = new Map();
+ for (let i = 0; i < count; i++) {
+ inst.getMatrixAt(i, m4);
+ let mat = inst.material;
+ if (inst.instanceColor) {
+ inst.getColorAt(i, color);
+ mat = instanceMaterial(THREE, inst.material, color, matCache);
+ }
+ const mesh = new THREE.Mesh(inst.geometry, mat);
+ mesh.name = group.name ? `${group.name}_${i}` : '';
+ mesh.matrix.copy(m4);
+ mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale);
+ mesh.castShadow = inst.castShadow;
+ mesh.receiveShadow = inst.receiveShadow;
+ group.add(mesh);
+ }
+ // nested children (rare) ride along unchanged
+ for (const child of [...inst.children]) group.add(child);
+ return group;
+}
+
+/**
+ * Bake every InstancedMesh under `root` (root itself included) in place, keeping
+ * child order so census part order is unchanged. Returns how many were baked.
+ */
+export function bakeInstancedMeshes(THREE, root) {
+ const found = [];
+ root.traverse((o) => {
+ if (o.isInstancedMesh) found.push(o);
+ });
+ for (const inst of found) {
+ const parent = inst.parent;
+ const group = expandInstancedMesh(THREE, inst);
+ if (!parent) continue; // a bare InstancedMesh root cannot be swapped; caller wraps it
+ const idx = parent.children.indexOf(inst);
+ parent.children[idx] = group;
+ group.parent = parent;
+ inst.parent = null;
+ }
+ root.updateWorldMatrix(true, true);
+ return found.length;
+}
diff --git a/harness/runtime_js/lib/orbit.mjs b/harness/runtime_js/lib/orbit.mjs
index bbe2acf7..cc86c1ae 100644
--- a/harness/runtime_js/lib/orbit.mjs
+++ b/harness/runtime_js/lib/orbit.mjs
@@ -1,11 +1,21 @@
/**
- * Overview orbit rig fitted to a census bbox (pure). Scenes sit on ground,
- * so the rig is ground-aware: eyes never go below ground, low "eye level"
- * views are lifted to ~1.6 m above ground. Azimuth 0 = front (+Z), CCW from
- * above; elevation in degrees above the horizon (see codeverse/conventions.py).
+ * Overview orbit rig fitted to the CONTENT of a scene (pure).
+ *
+ * `framingBox(census, bounds)` picks what to frame: the union of the census's
+ * content groups (sky dome and ground plane are never content), dropping any
+ * group that sprawls past the plan bounds (scatter across the whole ground) and
+ * clamping the result to the bounds — never the ground plane, never the sky.
+ * `fitOrbitCameras(bbox, views, opts)` then fits each view so the box's eight
+ * corners fill the frame (exact per-corner frustum fit with a margin, not a
+ * bounding-sphere fit). Scenes sit on ground, so the rig is ground-aware: eyes
+ * never go below ground, low "eye level" views stand just outside the footprint
+ * ~1.6 m above ground and look at the content centre. Azimuth 0 = front (+Z),
+ * CCW from above; elevation in degrees above the horizon (conventions.py).
*/
const DEG = Math.PI / 180;
+const BOUNDS_SPRAWL = 1.1; // a content group wider than 110 % of the plan bounds is scatter, not a zone
+const BOUNDS_CLAMP = 1.1; // framing box is clamped to the plan bounds grown by 10 %
/** Unit direction from azimuth/elevation (Y-up, +Z front). */
export function orbitDirection(azimuthDeg, elevationDeg) {
@@ -13,18 +23,81 @@ export function orbitDirection(azimuthDeg, elevationDeg) {
return [Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)];
}
+function unionBox(boxes) {
+ if (!boxes.length) return null;
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
+ for (const b of boxes) for (let i = 0; i < 3; i++) { min[i] = Math.min(min[i], b.min[i]); max[i] = Math.max(max[i], b.max[i]); }
+ return { min, max, size: max.map((v, i) => v - min[i]) };
+}
+
+function span(box) {
+ return Math.max(box.max[0] - box.min[0], box.max[2] - box.min[2]);
+}
+
+/**
+ * The box the overview rig should frame.
+ * @param {object|null} census host census (`groups[]`, `content_bbox`, `bbox`)
+ * @param {{min:number[],max:number[]}|null} bounds plan bounds (optional)
+ */
+export function framingBox(census, bounds = null) {
+ if (!census) return null;
+ let groups = (census.groups || []).filter((g) => g.kind === 'content' && g.bbox && g.bbox.min && g.bbox.max);
+ if (bounds && bounds.min && bounds.max && groups.length > 1) {
+ const limit = span(bounds) * BOUNDS_SPRAWL;
+ const kept = groups.filter((g) => span(g.bbox) <= limit);
+ if (kept.length) groups = kept;
+ }
+ let box = unionBox(groups.map((g) => g.bbox)) || census.content_bbox || census.bbox || null;
+ if (box && bounds && bounds.min && bounds.max) {
+ const c = bounds.min.map((v, i) => (v + bounds.max[i]) / 2);
+ const h = bounds.max.map((v, i) => ((v - bounds.min[i]) / 2) * BOUNDS_CLAMP);
+ const min = box.min.map((v, i) => Math.max(v, c[i] - h[i]));
+ const max = box.max.map((v, i) => Math.min(v, c[i] + h[i]));
+ if (min.every((v, i) => v < max[i])) box = { min, max, size: max.map((v, i) => v - min[i]) };
+ }
+ return box;
+}
+
+function corners(bbox) {
+ const out = [];
+ for (const x of [bbox.min[0], bbox.max[0]]) for (const y of [bbox.min[1], bbox.max[1]]) for (const z of [bbox.min[2], bbox.max[2]]) out.push([x, y, z]);
+ return out;
+}
+
+/**
+ * Smallest distance along `dir` (unit, from `center`) at which every corner sits
+ * inside a camera looking back at `center` with the given half-angle tangents.
+ */
+export function fitDistance(bbox, center, dir, tanH, tanV, margin) {
+ // same roll as THREE's lookAt (world up = +Y unless the view is exactly vertical)
+ const up0 = Math.abs(dir[1]) > 0.9999 ? [0, 0, -1] : [0, 1, 0];
+ const f = dir.map((v) => -v); // forward; right = forward × up0; up = right × forward
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+ const norm = (v) => { const l = Math.hypot(...v) || 1; return v.map((x) => x / l); };
+ const right = norm(cross(f, up0));
+ const up = norm(cross(right, f));
+ let dist = 0;
+ for (const c of corners(bbox)) {
+ const rel = c.map((v, i) => v - center[i]);
+ const depthOffset = rel[0] * dir[0] + rel[1] * dir[1] + rel[2] * dir[2]; // + toward the eye
+ const x = Math.abs(rel[0] * right[0] + rel[1] * right[1] + rel[2] * right[2]);
+ const y = Math.abs(rel[0] * up[0] + rel[1] * up[1] + rel[2] * up[2]);
+ dist = Math.max(dist, depthOffset + (x * margin) / tanH, depthOffset + (y * margin) / tanV);
+ }
+ return dist;
+}
+
/**
* Build camera specs for `views` around `bbox` ({min:[..], max:[..]}).
* @returns {Array<{name, position, lookAt, fov, kind:'orbit'}>}
*/
-export function fitOrbitCameras(bbox, views, { fov = 50, aspect = 16 / 9, groundY = null, margin = 1.15, noFog = true } = {}) {
+export function fitOrbitCameras(bbox, views, { fov = 50, aspect = 16 / 9, groundY = null, margin = 1.05, noFog = true } = {}) {
if (!bbox || !bbox.min || !bbox.max) return [];
const size = bbox.max.map((v, i) => v - bbox.min[i]);
const center = bbox.min.map((v, i) => v + size[i] / 2);
- const radius = Math.max(0.5, Math.hypot(size[0], size[1], size[2]) / 2);
- const fovV = fov * DEG;
- const fovH = 2 * Math.atan(Math.tan(fovV / 2) * aspect);
- const dist = (radius / Math.sin(Math.min(fovV, fovH) / 2)) * margin;
+ const tanV = Math.tan((fov * DEG) / 2);
+ const tanH = tanV * aspect;
+ const minDist = Math.max(1.5, 0.35 * Math.hypot(size[0], size[1], size[2]));
const floor = groundY === null || groundY === undefined ? bbox.min[1] : groundY;
const out = [];
const horizDist = (dx, dz) => {
@@ -47,6 +120,7 @@ export function fitOrbitCameras(bbox, views, { fov = 50, aspect = 16 / 9, ground
eye = [center[0] + dh[0] * back, eyeH, center[2] + dh[2] * back];
lookAt = [center[0], Math.min(center[1], floor + 0.35 * size[1] + 0.5), center[2]];
} else {
+ const dist = Math.max(minDist, fitDistance(bbox, center, d, tanH, tanV, margin));
eye = center.map((c, i) => c + d[i] * dist);
lookAt = center.slice();
}
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index c4ab62d9..9350fbcc 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -6,7 +6,8 @@
* map, calls `createScene({THREE, renderer, loaders})`, validates the returned
* shape and exposes `window.__c3v` with deterministic instruments:
* boot(opts) · renderAt(cameraSpec, t) · census() · fps(seconds)
- * cameraChecks(cameraSpec) · compileAll(cameraSpec) · shaderErrors()
+ * cameraChecks(cameraSpec) (near geometry + luminance + content coverage)
+ * compileAll(cameraSpec) · shaderErrors()
* Node drivers (render_scene / probe_scene / check_shaders) call these via
* page.evaluate. Agent code never imports this file.
*/
@@ -15,11 +16,13 @@ import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { sceneCensus } from './host_census.mjs';
import { frameStats, nearGeometry } from './host_metrics.mjs';
+import { frameCoverage } from './host_coverage.mjs';
import { installShaderErrorHook } from './host_shader_errors.mjs';
import { attributeErrors, captured, captureMaterialSources, materialAudit, stripCustomShaders } from './host_compile.mjs';
const FIXED_DT = 1 / 30;
const LOAD_IDLE_TIMEOUT_MS = 30000;
+const CREATE_SCENE_TIMEOUT_MS = 20000;
const state = {
booted: false,
@@ -28,23 +31,44 @@ const state = {
scene: null,
cameras: [],
update: null,
+ updateBroken: false,
+ updateErrors: [],
simTime: 0,
width: 1024,
height: 576,
rafCalls: 0,
shaderErrors: [],
loadErrors: [],
+ pendingLoads: new Set(),
hostWarnings: [],
bootInfo: null,
contentBox: null,
fullBox: null,
};
+/**
+ * Call the agent's update(t, dt), catching exceptions: the first throw is
+ * recorded (state.updateErrors + console.error so the node driver collects it
+ * as a console error → gate finding) and update() is disabled so the remaining
+ * views still render — an agent bug must never abort the whole render run.
+ */
+function runUpdate(t, dt) {
+ if (!state.update || state.updateBroken) return;
+ try {
+ state.update(t, dt);
+ } catch (e) {
+ state.updateBroken = true;
+ const msg = `update(t=${t.toFixed(2)}) threw: ${formatError(e)} — update() disabled, rendering continues without animation`;
+ state.updateErrors.push(msg);
+ console.error(msg);
+ }
+}
+
function makeRenderer(width, height, opts) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
- canvas.id = 'c3v-canvas';
+ canvas.id = '3dcv-canvas';
document.body.appendChild(canvas);
const renderer = new THREE.WebGLRenderer({
canvas,
@@ -147,9 +171,10 @@ async function boot(opts) {
manager.onStart = () => { manager.__c3vPending = true; };
manager.onLoad = () => { manager.__c3vPending = false; };
manager.onError = (url) => { const m = `failed to load ${url}`; if (!state.loadErrors.includes(m)) state.loadErrors.push(m); };
+ trackPendingLoads(manager);
const loaders = makeLoaders(manager);
const tCs = performance.now();
- const result = await mod.createScene({ THREE, renderer, loaders });
+ const result = await raceCreateScene(mod, { THREE, renderer, loaders }, opts.createSceneTimeoutMs || CREATE_SCENE_TIMEOUT_MS);
info.timings_ms.create_scene = Math.round(performance.now() - tCs);
if (!result || typeof result !== 'object') throw new Error('createScene() must return {scene, cameras, update}');
info.shape = {
@@ -173,7 +198,7 @@ async function boot(opts) {
if (info.load_wait === 'timeout') state.hostWarnings.push('asset loads still pending after timeout');
info.stage = 'first_update';
- if (state.update) state.update(0, 0);
+ runUpdate(0, 0);
state.simTime = 0;
state.scene.updateMatrixWorld(true);
state.booted = true;
@@ -196,6 +221,39 @@ function formatError(e) {
return stack && stack.includes(msg) ? stack : `${msg}\n${stack}`;
}
+/** Track which loader URLs are in flight so a boot timeout can name them. */
+function trackPendingLoads(manager) {
+ const start = manager.itemStart.bind(manager);
+ const end = manager.itemEnd.bind(manager);
+ manager.itemStart = (url) => { state.pendingLoads.add(url); start(url); };
+ manager.itemEnd = (url) => { state.pendingLoads.delete(url); end(url); };
+}
+
+/**
+ * Await the agent's createScene() with a hard timeout: a classic
+ * `await new Promise(r => loaders.texture.load(url, r))` on a missing asset
+ * never settles (three's loaders skip onLoad on 404) and would otherwise hang
+ * the whole driver into its watchdog (exit 3, blamed on the harness). On
+ * expiry the boot fails at stage 'createScene' with an error naming the
+ * pending loader URLs — an agent-fixable scene failure, not a driver one.
+ */
+function raceCreateScene(mod, ctx, timeoutMs) {
+ const createScenePromise = Promise.resolve().then(() => mod.createScene(ctx));
+ createScenePromise.catch(() => {}); // no unhandled rejection if the timeout wins
+ let timer = null;
+ const timeout = new Promise((resolve, reject) => {
+ timer = setTimeout(() => {
+ const pending = [...state.pendingLoads].slice(0, 5);
+ let msg = `createScene() did not resolve within ${Math.round(timeoutMs / 1000)} s — an awaited promise never settled `
+ + '(loader.load(...) without an onError handler on a missing/broken asset? prefer await loaders.gltf.loadAsync(url) in try/catch)';
+ if (pending.length) msg += `; pending loads: ${pending.join(', ')}`;
+ if (state.loadErrors.length) msg += `; load errors: ${state.loadErrors.slice(0, 5).join('; ')}`;
+ reject(new Error(msg));
+ }, timeoutMs);
+ });
+ return Promise.race([createScenePromise, timeout]).finally(() => clearTimeout(timer));
+}
+
function buildCamera(spec) {
const aspect = state.width / state.height;
if (!state.fullBox) { const c = sceneCensus(state.scene, THREE); state.fullBox = c.bbox; state.contentBox = c.content_bbox; }
@@ -217,21 +275,22 @@ function buildCamera(spec) {
return cam;
}
-/** Advance the simulation deterministically to time t (fixed steps). */
+/** Advance the simulation deterministically to time t (fixed steps).
+ * Agent update() exceptions are recorded (runUpdate) and never propagate. */
function advanceTo(t) {
if (!state.update) return;
if (t < state.simTime - 1e-9) throw new Error(`cannot rewind time: at ${state.simTime}, asked ${t}`);
let steps = 0;
while (state.simTime + FIXED_DT <= t + 1e-9) {
state.simTime += FIXED_DT;
- state.update(state.simTime, FIXED_DT);
+ runUpdate(state.simTime, FIXED_DT);
steps += 1;
if (steps > 100000) throw new Error('too many update steps');
}
const rem = t - state.simTime;
if (rem > 1e-6) {
state.simTime = t;
- state.update(t, rem);
+ runUpdate(t, rem);
}
}
@@ -260,14 +319,23 @@ function renderAt(spec, t, opts = {}) {
return { dataUrl: state.canvas.toDataURL('image/png'), ms, sim_time: state.simTime };
}
-/** Camera instruments: near geometry + frame luminance stats (renders). */
+/**
+ * Camera instruments (renders): near geometry, frame luminance stats and
+ * coverage (content / ground / sky fractions of the frame, via mask passes).
+ */
function cameraChecks(spec) {
const cam = buildCamera(spec);
state.scene.updateMatrixWorld(true);
const near = nearGeometry(state.scene, cam, THREE);
renderOnce(cam);
const stats = frameStats(state.canvas);
- return { name: spec.name, ...near, ...stats };
+ let coverage = {};
+ try {
+ coverage = frameCoverage(state.renderer, state.scene, cam, state.canvas, THREE, state.contentBox);
+ } catch (e) {
+ state.hostWarnings.push(`coverage failed for ${spec.name}: ${e.message}`);
+ }
+ return { name: spec.name, ...near, ...stats, ...coverage };
}
/** Force-compile every material as seen from spec (or the first camera). */
@@ -293,7 +361,7 @@ function fps(seconds, spec) {
const t0 = performance.now();
while (performance.now() < deadline) {
state.simTime += FIXED_DT;
- if (state.update) state.update(state.simTime, FIXED_DT);
+ runUpdate(state.simTime, FIXED_DT);
state.renderer.render(state.scene, cam);
frames += 1;
}
@@ -322,6 +390,7 @@ window.__c3v = {
setViewport(w, h) { state.width = w; state.height = h; state.renderer.setSize(w, h, false); },
shaderErrors: () => state.shaderErrors.slice(),
loadErrors: () => state.loadErrors.slice(),
+ updateErrors: () => state.updateErrors.slice(),
cameras: () => state.cameras.slice(),
simTime: () => state.simTime,
THREE,
diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjs
index dd8655d5..3da3ea74 100644
--- a/harness/runtime_js/probe_scene.mjs
+++ b/harness/runtime_js/probe_scene.mjs
@@ -11,20 +11,24 @@
import path from 'node:path';
import { armWatchdog, fail, finish, parseCli, writeJson } from './lib/cli.mjs';
-import { errorSummary, openHost } from './lib/host_page.mjs';
+import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';
const args = parseCli({
- ws: {}, out: {}, gpu: { default: process.env.C3V_RENDER_GPU || 'auto' }, 'timeout-ms': { default: '60000' },
- 'update-steps': { default: '10' }, scene: { default: 'src/scene.js' },
+ ws: {}, out: {}, gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' }, 'timeout-ms': { default: '60000' },
+ 'create-timeout-ms': { default: '' }, 'update-steps': { default: '10' }, scene: { default: 'src/scene.js' },
});
async function main() {
if (!args.ws) throw new Error('--ws is required');
- const watchdog = armWatchdog(parseInt(args['timeout-ms'], 10));
+ const timeoutMs = parseInt(args['timeout-ms'], 10);
+ const watchdog = armWatchdog(timeoutMs);
const t0 = Date.now();
let host;
try {
- host = await openHost(args.ws, { width: 320, height: 180, gpu: args.gpu, sceneRel: args.scene.replace(/^\.?\//, '') });
+ host = await openHost(args.ws, {
+ width: 320, height: 180, gpu: args.gpu, sceneRel: args.scene.replace(/^\.?\//, ''),
+ createSceneTimeoutMs: createTimeoutMs(args['create-timeout-ms'], timeoutMs),
+ });
} catch (e) {
return fail(`host failed: ${e.message}`);
}
@@ -47,6 +51,12 @@ async function main() {
result.update_ok = upd.ok;
result.update_error = upd.error || '';
result.first_render_ms = upd.ms;
+ // update() exceptions are caught page-side (rendering continues); still a probe failure
+ const updateErrors = await page.evaluate(() => window.__c3v.updateErrors());
+ if (upd.ok && updateErrors.length) {
+ result.update_ok = false;
+ result.update_error = updateErrors[0].slice(0, 800);
+ }
const frame = await page.evaluate(() => { const c = window.__c3v.cameras()[0]; return window.__c3v.cameraChecks(c); });
result.first_camera = frame;
}
diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjs
index 0ae94953..451c213b 100644
--- a/harness/runtime_js/render_scene.mjs
+++ b/harness/runtime_js/render_scene.mjs
@@ -5,6 +5,7 @@
*
* node render_scene.mjs --ws <ws> --out <dir> [--cameras authored|<json>]
* [--orbit-views '<json list of {name,azimuth,elevation}>'|none]
+ * [--bounds '{"min":[x,y,z],"max":[x,y,z]}'|none] (plan bounds: orbit framing guard)
* [--times 0,1.5] [--width 1024] [--height 576] [--gpu auto|on|off]
* [--fps-seconds 2] [--timeout-ms 240000]
*
@@ -15,14 +16,14 @@
import path from 'node:path';
import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, writeJson } from './lib/cli.mjs';
-import { errorSummary, openHost } from './lib/host_page.mjs';
-import { fitOrbitCameras } from './lib/orbit.mjs';
+import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';
+import { fitOrbitCameras, framingBox } from './lib/orbit.mjs';
const args = parseCli({
- ws: {}, out: {}, cameras: { default: 'authored' }, 'orbit-views': { default: 'none' },
+ ws: {}, out: {}, cameras: { default: 'authored' }, 'orbit-views': { default: 'none' }, bounds: { default: 'none' },
times: { default: '0,1.5' }, width: { default: '1024' }, height: { default: '576' },
- gpu: { default: process.env.C3V_RENDER_GPU || 'auto' }, 'fps-seconds': { default: '2' },
- 'timeout-ms': { default: '240000' }, 'log-depth': { type: 'boolean', default: false },
+ gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' }, 'fps-seconds': { default: '2' },
+ 'timeout-ms': { default: '240000' }, 'create-timeout-ms': { default: '' }, 'log-depth': { type: 'boolean', default: false },
'orbit-fog': { type: 'boolean', default: false }, counterfactual: { type: 'boolean', default: false },
});
@@ -36,12 +37,16 @@ async function main() {
const times = String(args.times).split(',').map((s) => parseFloat(s)).filter((x) => Number.isFinite(x) && x >= 0).sort((a, b) => a - b);
if (!times.length) throw new Error('--times must list non-negative numbers');
const outDir = ensureDir(path.resolve(args.out));
- const watchdog = armWatchdog(parseInt(args['timeout-ms'], 10));
+ const timeoutMs = parseInt(args['timeout-ms'], 10);
+ const watchdog = armWatchdog(timeoutMs);
const t0 = Date.now();
let host;
try {
- host = await openHost(args.ws, { width, height, gpu: args.gpu, logDepth: args['log-depth'] });
+ host = await openHost(args.ws, {
+ width, height, gpu: args.gpu, logDepth: args['log-depth'],
+ createSceneTimeoutMs: createTimeoutMs(args['create-timeout-ms'], timeoutMs),
+ });
} catch (e) {
return fail(`host failed: ${e.message}`);
}
@@ -62,37 +67,53 @@ async function main() {
else if (args.cameras !== 'none') cams = (readJsonArg(args.cameras, 'cameras') || []).map((c) => ({ ...c, kind: c.kind || 'authored' }));
if (args['orbit-views'] !== 'none') {
const views = readJsonArg(args['orbit-views'], 'orbit-views') || [];
- const bbox = metrics.census.content_bbox || metrics.census.bbox;
+ const bounds = args.bounds && args.bounds !== 'none' ? readJsonArg(args.bounds, 'bounds') : null;
+ const bbox = framingBox(metrics.census, bounds); // content only: never the ground plane / sky dome
+ metrics.framing_bbox = bbox;
cams.push(...fitOrbitCameras(bbox, views, { aspect: width / height, groundY: metrics.census.ground_y, noFog: !args['orbit-fog'] }));
}
const seen = new Set();
cams = cams.filter((c) => { const k = c.name; if (seen.has(k)) return false; seen.add(k); return true; });
if (!cams.length) throw new Error('no cameras to render (authored list empty and no orbit views)');
+ // agent exceptions inside a single view (update() is already guarded page-side;
+ // this catches e.g. an onBeforeRender that throws) must not abort the other
+ // views: record them as scene errors → console_errors → gate finding, exit 1.
+ const sceneErrors = [];
+ const sceneErr = (what, e) => sceneErrors.push(`${what}: ${String(e.message || e).slice(0, 600)}`);
// instruments per camera (at t=0, before any stepping)
for (const c of cams) {
- const chk = await page.evaluate((spec) => window.__c3v.cameraChecks(spec), c);
- metrics.camera_checks.push({ kind: c.kind, ...chk });
+ try {
+ const chk = await page.evaluate((spec) => window.__c3v.cameraChecks(spec), c);
+ metrics.camera_checks.push({ kind: c.kind, ...chk });
+ } catch (e) { sceneErr(`camera checks failed for '${c.name}'`, e); }
}
// renders: times ascending (sim time cannot rewind)
for (const t of times) {
for (const c of cams) {
- const r = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt), c, t);
- const file = `${c.name}_${tag(t)}.png`;
- dataUrlToPng(r.dataUrl, path.join(outDir, file));
- metrics.views.push({ name: c.name, kind: c.kind, path: file, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: r.ms });
- if (args.counterfactual) {
- const cf = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt, { stripCustom: true }), c, t);
- const cfFile = `${c.name}_${tag(t)}_nocustom.png`;
- dataUrlToPng(cf.dataUrl, path.join(outDir, cfFile));
- metrics.views.push({ name: `${c.name}_nocustom`, kind: 'counterfactual', path: cfFile, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: cf.ms, counterfactual_of: file });
- }
+ try {
+ const r = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt), c, t);
+ const file = `${c.name}_${tag(t)}.png`;
+ dataUrlToPng(r.dataUrl, path.join(outDir, file));
+ metrics.views.push({ name: c.name, kind: c.kind, path: file, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: r.ms });
+ if (args.counterfactual) {
+ const cf = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt, { stripCustom: true }), c, t);
+ const cfFile = `${c.name}_${tag(t)}_nocustom.png`;
+ dataUrlToPng(cf.dataUrl, path.join(outDir, cfFile));
+ metrics.views.push({ name: `${c.name}_nocustom`, kind: 'counterfactual', path: cfFile, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: cf.ms, counterfactual_of: file });
+ }
+ } catch (e) { sceneErr(`render failed for '${c.name}' at t=${t}`, e); }
}
}
const fpsSec = parseFloat(args['fps-seconds']);
- if (fpsSec > 0) metrics.fps = await page.evaluate((s) => window.__c3v.fps(s), fpsSec);
+ if (fpsSec > 0) {
+ try { metrics.fps = await page.evaluate((s) => window.__c3v.fps(s), fpsSec); }
+ catch (e) { sceneErr('fps measurement failed', e); }
+ }
metrics.shader_errors = (await page.evaluate(() => window.__c3v.shaderErrors())).map(({ _key, ...e }) => e);
+ metrics.update_errors = await page.evaluate(() => window.__c3v.updateErrors());
Object.assign(metrics, errorSummary(host.errors, boot));
+ for (const e of sceneErrors) if (!metrics.console_errors.includes(e)) metrics.console_errors.push(e);
metrics.ok = metrics.console_errors.length === 0 && metrics.shader_errors.length === 0;
metrics.duration_ms = Date.now() - t0;
writeJson(path.join(outDir, 'metrics.json'), metrics);
diff --git a/harness/tests/agents/test_api_tools.py b/harness/tests/agents/test_api_tools.py
index 5457740a..db782706 100644
--- a/harness/tests/agents/test_api_tools.py
+++ b/harness/tests/agents/test_api_tools.py
@@ -1,4 +1,4 @@
-"""FileTools sandbox + run_shell allowlist."""
+"""FileTools confinement + run_shell policy (allow-list, no inline code, workspace-only paths, never raises)."""
from __future__ import annotations
@@ -50,12 +50,78 @@ def test_run_shell_allowlist(tmp_ws: Workspace):
assert t.call("run_shell", {"cmd": "rm -rf src"}).is_error
assert t.call("run_shell", {"cmd": "ls src | cat"}).is_error
assert t.call("run_shell", {"cmd": "cat /etc/passwd"}).is_error
- bad = t.call("run_shell", {"cmd": "python -c 'import sys; sys.exit(3)'"})
+ (tmp_ws.src / "exit3.py").write_text("import sys; sys.exit(3)\n")
+ bad = t.call("run_shell", {"cmd": "python src/exit3.py"})
assert bad.is_error and "rc=3" in bad.text
- slow = t.call("run_shell", {"cmd": "python -c 'import time; time.sleep(30)'", "timeout_s": 5})
+ (tmp_ws.src / "slow.py").write_text("import time; time.sleep(30)\n")
+ slow = t.call("run_shell", {"cmd": "python src/slow.py", "timeout_s": 5})
assert slow.is_error and "timeout" in slow.text
+def test_run_shell_rejects_inline_code_and_escaping_paths(tmp_ws: Workspace):
+ """Regression: `python -c` / `node -e` / `..` paths used to bypass write_roots and the path check entirely."""
+ t = _tools(tmp_ws)
+ outside = tmp_ws.root.parent / "outside.txt"
+ denied = [
+ f"python -c \"open('{outside}','w').write('x')\"",
+ "python3 -c 'import subprocess; subprocess.run([\"id\"])'",
+ "python -Bc 'print(1)'", # combined short flags
+ "python -i",
+ "python -",
+ "python -m http.server",
+ "python -mhttp.server",
+ "python -cm py_compile", # = python -c "m"
+ "python -mc py_compile",
+ "node -e \"require('fs').writeFileSync('../outside2.txt','y')\"",
+ "node -pe 1",
+ "node --eval 1",
+ "node --eval=1",
+ "node --require=../x.js src/a.js",
+ "node -r ../x.js src/a.js",
+ "cat ../../../../../../etc/hostname",
+ "cat /etc/hostname",
+ "cat .git/HEAD",
+ "ls ~",
+ "find src -exec rm {} ;",
+ "find src -delete",
+ ]
+ for cmd in denied:
+ out = t.call("run_shell", {"cmd": cmd})
+ assert out.is_error and "rc=" not in out.text, (cmd, out.text)
+ assert not outside.exists() and not (tmp_ws.root.parent / "outside2.txt").exists()
+ # allowed shapes keep working
+ (tmp_ws.src / "a.js").write_text("const x = 1;\n")
+ (tmp_ws.src / "m.py").write_text("y = 2\n")
+ for cmd in ("node --check src/a.js", "python -m py_compile src/m.py", "python3 -m json.tool --help",
+ "grep -rn const src", "find src -name '*.js'", "ls -la src", "wc -l src/a.js", "head -n 1 src/a.js",
+ f"cat {tmp_ws.root}/src/a.js"):
+ out = t.call("run_shell", {"cmd": cmd})
+ assert "rc=0" in out.text, (cmd, out.text)
+ # symlink inside the workspace that points outside is resolved and refused
+ os.symlink("/etc", tmp_ws.src / "etc_link")
+ assert t.call("run_shell", {"cmd": "cat src/etc_link/hostname"}).is_error
+
+
+def test_call_never_raises(tmp_ws: Workspace):
+ """ValueError / UnicodeDecodeError used to escape call() and crash ApiAgent.run."""
+ t = _tools(tmp_ws)
+ (tmp_ws.src / "b.bin").write_bytes(b"a\xffb")
+ (tmp_ws.src / "a.js").write_text("hello")
+ for name, args in [("run_shell", {"cmd": "ls src", "timeout_s": "soon"}),
+ ("run_shell", {"cmd": "ls src", "timeout_s": "60.0"}),
+ ("run_shell", {"cmd": "ls src", "timeout_s": None}),
+ ("edit_file", {"path": "src/b.bin", "old": "a", "new": "b"}),
+ ("edit_file", {"path": "src/a.js", "old": "hello", "new": None}),
+ ("write_file", {"path": "src/c.js", "content": None}),
+ ("list_files", {"glob": None}),
+ ("read_file", {"path": 7})]:
+ out = t.call(name, args) # must not raise
+ assert isinstance(out.text, str)
+ assert not t.call("run_shell", {"cmd": "ls src", "timeout_s": "soon"}).is_error
+ e = t.call("edit_file", {"path": "src/b.bin", "old": "a", "new": "b"})
+ assert e.is_error and "UTF-8" in e.text and (tmp_ws.src / "b.bin").read_bytes() == b"a\xffb"
+
+
def test_unknown_tool_and_bad_args(tmp_ws: Workspace):
t = _tools(tmp_ws)
assert t.call("nope", {}).is_error
diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.py
index bdbe018c..da608e57 100644
--- a/harness/tests/agents/test_cli_common.py
+++ b/harness/tests/agents/test_cli_common.py
@@ -4,8 +4,10 @@ from __future__ import annotations
import json
import os
+import threading
from codeverse.agents.cli_common import (
+ attribute_changes,
begin_session,
deliver_prompt,
finish_session,
@@ -15,7 +17,7 @@ from codeverse.agents.cli_common import (
is_transient_failure,
)
from codeverse.agents.transcript import Trajectory
-from codeverse.contracts.agent import AgentJob
+from codeverse.contracts.agent import AgentJob, FileChange
from codeverse.contracts.common import Usage
from codeverse.workspace import Workspace
@@ -33,7 +35,7 @@ def test_hardened_env_strips_secrets_and_adds_guards(tmp_ws: Workspace, monkeypa
env = hardened_env(tmp_ws, job, keep={"ANTHROPIC_API_KEY"})
assert "OPENAI_API_KEY" not in env and "FAKE_SERVICE_API_KEY" not in env
assert env["ANTHROPIC_API_KEY"] == "sk-y" and env["KEEPME"] == "1" and env["EXTRA"] == "2"
- assert env["C3V_AGENT_CONTEXT"] == "1" and env["GIT_CEILING_DIRECTORIES"] == str(tmp_ws.root.parent)
+ assert env["CV3D_AGENT_CONTEXT"] == "1" and env["GIT_CEILING_DIRECTORIES"] == str(tmp_ws.root.parent)
def test_session_roundtrip_tracks_files_and_writes_result(tmp_ws: Workspace):
@@ -49,6 +51,69 @@ def test_session_roundtrip_tracks_files_and_writes_result(tmp_ws: Workspace):
assert tmp_ws.head() == data["head_after"]
+def test_retry_same_label_round_keeps_first_attempt_trajectory(tmp_ws: Workspace):
+ """run_agent_task re-runs a silently-bailing job with the same label+round: attempt 1's files must survive."""
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="first", label="baseline", extra={"round": 0})
+ s1 = begin_session(job, "fake")
+ s1.traj.write_text("stdout.json", "attempt 1 stdout")
+ r1 = finish_session(s1, ok=False, exit_reason="error", text="", usage=Usage(cost_usd=0.5), errors=["bailed"])
+ s2 = begin_session(job.model_copy(update={"prompt": "second"}), "fake")
+ assert s2.traj.dir != s1.traj.dir and s2.traj.dir.name == "baseline.a2_r00" and s2.attempt == 2
+ (tmp_ws.src / "a.py").write_text("x = 1\n")
+ r2 = finish_session(s2, ok=True, exit_reason="completed", text="done", usage=Usage(cost_usd=0.01))
+ d1 = json.loads(s1.traj.result_path.read_text())
+ assert d1["exit_reason"] == "error" and d1["errors"] == ["bailed"] and d1["usage"]["cost_usd"] == 0.5 and d1["attempt"] == 1
+ assert (s1.traj.dir / "stdout.json").read_text() == "attempt 1 stdout" and s1.traj.prompt_path.read_text() == "first"
+ d2 = json.loads(s2.traj.result_path.read_text())
+ assert d2["attempt"] == 2 and d2["job_label"] == "baseline" and d2["label"] == "baseline.a2" and d2["ok"]
+ assert [f.path for f in r2.files_changed] == ["src/a.py"] and r1.files_changed == []
+ log = tmp_ws._git("log", "--oneline").stdout
+ assert "agent:baseline.a2" in log and "pre:baseline" in log
+
+
+def test_attribute_changes_pure():
+ files = [FileChange(path=p, status="modified") for p in (
+ "src/zones/a.js", "src/zones/b.js", "src/assets/x.js", "events.jsonl", "artifacts/census.json",
+ "trajectories/zone_a_r00/result.json", "public/assets/y.glb", "README.md", "AGENTS.md")]
+ got = attribute_changes(files, write_roots=["src", "public"])
+ assert [f.path for f in got] == ["src/zones/a.js", "src/zones/b.js", "src/assets/x.js", "public/assets/y.glb"]
+ got = attribute_changes(files, write_roots=["src", "public"], own_hints=frozenset({"src/zones/a.js"}),
+ sibling_hints=frozenset({"src/zones/b.js", "src/assets/"}))
+ assert [f.path for f in got] == ["src/zones/a.js", "public/assets/y.glb"]
+ # a file both sessions declared stays attributed to both
+ got = attribute_changes(files, write_roots=["src"], own_hints=frozenset({"src/zones/b.js"}), sibling_hints=frozenset({"src/zones/b.js"}))
+ assert "src/zones/b.js" in [f.path for f in got]
+
+
+def test_concurrent_sessions_in_one_workspace_attribute_their_own_files(tmp_ws: Workspace):
+ """Scene fan-out: zone sessions run in parallel in ONE workspace; each result must list only its own work
+ and a session that wrote nothing must report no changes even though siblings wrote files."""
+ (tmp_ws.src / "zones").mkdir(parents=True)
+ barrier = threading.Barrier(3)
+ results = {}
+
+ def session(name: str, write: bool):
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="p", label=f"zone_{name}",
+ extra={"round": 0, "files_hint": [f"src/zones/{name}.js"]})
+ s = begin_session(job, "fake")
+ barrier.wait(timeout=30) # every session has started before anyone writes
+ if write:
+ (tmp_ws.src / "zones" / f"{name}.js").write_text(f"// {name}\n")
+ (tmp_ws.root / "events.jsonl").open("a").write(f"{name}\n")
+ barrier.wait(timeout=30) # every write landed before anyone finishes
+ results[name] = finish_session(s, ok=True, exit_reason="completed", text="", usage=Usage())
+
+ threads = [threading.Thread(target=session, args=("koi", True)), threading.Thread(target=session, args=("gravel", True)),
+ threading.Thread(target=session, args=("lantern", False))]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=60)
+ assert [f.path for f in results["koi"].files_changed] == ["src/zones/koi.js"]
+ assert [f.path for f in results["gravel"].files_changed] == ["src/zones/gravel.js"]
+ assert results["lantern"].files_changed == [] # bailed agent: siblings' files are not its work
+
+
def test_deliver_prompt_uses_file_when_long(tmp_ws: Workspace):
job = AgentJob(workspace=str(tmp_ws.root), prompt="x")
s = begin_session(job, "fake")
diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.py
index 8a9206dc..9027bcd9 100644
--- a/harness/tests/agents/test_codex.py
+++ b/harness/tests/agents/test_codex.py
@@ -56,7 +56,9 @@ def test_argv_with_mcp_overrides(tmp_ws: Workspace):
assert argv[:3] == ["codex", "exec", "--json"] and argv[argv.index("-C") + 1] == str(tmp_ws.root)
assert argv[argv.index("--sandbox") + 1] == "workspace-write" and "--skip-git-repo-check" in argv
joined = " ".join(argv)
- assert 'mcp_servers.c3v.command="' in joined and "mcp_servers.c3v.args=[" in joined and argv[-1] == "p"
+ assert 'mcp_servers.3dcv.command="' in joined and "mcp_servers.3dcv.args=[" in joined and argv[-1] == "p"
+ # codex exec has nobody to answer the per-tool approval elicitation → every MCP call would be cancelled
+ assert 'mcp_servers.3dcv.default_tools_approval_mode="approve"' in argv
assert argv[argv.index("--model") + 1] == "gpt-5.6-sol"
s2 = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "codex")
assert "mcp_servers" not in " ".join(a.build_argv(s2, None)) and a.build_argv(s2, None)[-1] == "-"
@@ -81,6 +83,27 @@ def test_long_prompt_goes_via_stdin(tmp_ws: Workspace, fake_bin, monkeypatch):
assert res.ok and (tmp_ws.src / "hello.txt").read_text() == "hello"
+def test_live_codex_mcp_tool_call_is_not_cancelled(tmp_ws: Workspace):
+ """Regression: without default_tools_approval_mode=approve codex auto-cancels every 3dcv MCP call."""
+ if not shutil.which("codex"):
+ pytest.skip("codex not installed")
+ from codeverse.agents.cli_common import default_mcp_command
+ from codeverse.agents.materialize import materialize_workspace
+
+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="threejs/cookbook.md", spatial_tools=True,
+ mcp_command=default_mcp_command(tmp_ws, language="threejs"))
+ a = CodexAgent("")
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Call the 3dcv MCP tool `read_cookbook` once and reply with its first "
+ "five words, then DONE. Do not edit files.", timeout_s=300, label="mcpt", spatial_tools=True,
+ extra={"language": "threejs"}))
+ assert res.ok, res.errors
+ events = [json.loads(ln) for ln in (Path(res.transcript_path).parent / "stdout.jsonl").read_text().splitlines()
+ if ln.startswith("{")]
+ calls = [e["item"] for e in events if e.get("type") == "item.completed" and (e.get("item") or {}).get("type") == "mcp_tool_call"]
+ assert calls and all(c.get("status") != "failed" for c in calls), calls
+
+
@pytest.mark.live
def test_live_codex_tiny(tmp_ws: Workspace):
if not shutil.which("codex"):
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index 2268e892..7a48ab99 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -21,11 +21,14 @@ assert os.environ.get("GEMINI_API_KEY"), "no key in env"
assert "GEMINI_API_KEYS" not in os.environ
assert "FAKE_SERVICE_API_KEY" not in os.environ, "secret leaked"
assert os.path.isfile(os.environ["GEMINI_CLI_SYSTEM_SETTINGS_PATH"])
-if mode == "fail_once":
+if mode in ("fail_once", "fail_once_503", "fail_always"):
marker = "attempts.txt"
n = int(open(marker).read()) if os.path.exists(marker) else 0
open(marker, "w").write(str(n + 1))
- if n == 0:
+ if n == 0 or mode == "fail_always":
+ if mode == "fail_once_503":
+ print("Error when talking to Gemini API: got status: UNAVAILABLE 503", file=sys.stderr)
+ sys.exit(247)
print("Error: 429 RESOURCE_EXHAUSTED quota", file=sys.stderr)
sys.exit(1)
if mode == "hang":
@@ -34,7 +37,7 @@ served = "gemini-9-pro" if mode == "substitute" else model
os.makedirs("src", exist_ok=True)
open("src/hello.txt", "w").write(prompt[:20])
out = {"session_id": "s1", "response": "DONE: " + prompt[:10],
- "stats": {"models": {served: {"tokens": {"input": 100, "candidates": 20, "cached": 5, "thoughts": 7}}},
+ "stats": {"models": {served: {"tokens": {"input": 95, "prompt": 100, "candidates": 20, "cached": 5, "thoughts": 7}}},
"tools": {"totalCalls": 1}}}
print(json.dumps(out, indent=2))
'''
@@ -90,6 +93,51 @@ def test_transient_failure_retries_once_with_other_key(tmp_ws: Workspace, agent:
assert keys == ["k1", "k2"]
+def test_single_key_transient_failure_retries_same_key_and_never_raises(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ """Settings with ONE key: the retry must reuse it (no KeyPoolExhausted out of run())."""
+ from codeverse.agents import gemini_cli as gc
+
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", ["only"])
+ gc._POOLS.pop(("only",), None)
+ monkeypatch.setenv("FAKE_MODE", "fail_once_503")
+ res = agent.run(_job(tmp_ws))
+ assert res.ok, res.errors
+ assert (tmp_ws.root / "attempts.txt").read_text() == "2"
+ lines = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
+ assert [ln["key_tail"] for ln in lines if ln["kind"] == "invoke"] == ["only", "only"]
+
+
+def test_single_key_quota_failure_returns_budget_without_retry(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ """429 puts the only key into cooldown: no alternative → return the failed outcome (ok=False), do not raise."""
+ from codeverse.agents import gemini_cli as gc
+
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", ["solo"])
+ monkeypatch.setattr(gc, "RETRY_KEY_WAIT_S", 0.2)
+ gc._POOLS.pop(("solo",), None)
+ monkeypatch.setenv("FAKE_MODE", "fail_always")
+ res = agent.run(_job(tmp_ws))
+ assert not res.ok and res.exit_reason == "budget"
+ assert (tmp_ws.root / "attempts.txt").read_text() == "1"
+ rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
+ assert rec["attempts"] == 1 and any("no usable key" in n for n in rec["notes"])
+
+
+def test_pool_exhausted_before_first_attempt_is_a_budget_result(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ from codeverse.agents import gemini_cli as gc
+ from codeverse.models.keypool import KeyPoolExhausted
+
+ class Dead:
+ def acquire(self, **kw):
+ raise KeyPoolExhausted("all 2 keys throttled; waited 120s")
+
+ def report(self, *a, **k):
+ return None
+
+ monkeypatch.setattr(gc, "_key_pool", lambda keys: Dead())
+ res = agent.run(_job(tmp_ws))
+ assert not res.ok and res.exit_reason == "budget" and "exhausted" in res.errors[0]
+
+
def test_timeout_is_reported(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
monkeypatch.setenv("FAKE_MODE", "hang")
monkeypatch.setattr("codeverse.agents.gemini_cli.IDLE_GRACE_S", 1.0)
@@ -108,9 +156,42 @@ def test_unavailable_when_no_keys(tmp_ws: Workspace, agent: GeminiCliAgent, monk
def test_parse_helpers():
assert parse_gemini_json("noise\n{\"response\": \"x\"}") == {"response": "x"}
assert parse_gemini_json("") is None
+ # no `prompt` key: total prompt = uncached input + cached
u = usage_from_stats({"models": {"m": {"tokens": {"input": 1, "candidates": 2, "cached": 3, "thoughts": 4}}},
"tools": {"totalCalls": 9}}, "m")
- assert (u.input_tokens, u.output_tokens, u.cached_tokens, u.thoughts_tokens, u.tool_calls) == (1, 2, 3, 4, 9)
+ assert (u.input_tokens, u.output_tokens, u.cached_tokens, u.thoughts_tokens, u.tool_calls) == (4, 2, 3, 4, 9)
+
+
+def test_usage_input_is_total_prompt_and_cost_reprices_cache():
+ """gemini-cli reports tokens.input = prompt - cached; pricing wants the TOTAL prompt (regression: ~4x under-billing)."""
+ from codeverse.models.pricing import estimate_cost, lookup_price
+
+ tok = {"input": 720_753, "prompt": 14_190_170, "cached": 13_469_417, "candidates": 62_012, "thoughts": 66_809}
+ u = usage_from_stats({"models": {"gemini-3.7-flash": {"tokens": tok}}}, "gemini-3.7-flash")
+ assert u.input_tokens == tok["prompt"] and u.cached_tokens == tok["cached"]
+ price = lookup_price("gemini", "gemini-3.7-flash")
+ assert price is not None
+ m = 1_000_000
+ want = ((tok["prompt"] - tok["cached"]) * price.input + tok["cached"] * price.cached
+ + (tok["candidates"] + tok["thoughts"]) * price.output) / m
+ assert u.cost_usd == pytest.approx(want, rel=1e-9)
+ assert u.cost_usd == pytest.approx(estimate_cost("gemini", "gemini-3.7-flash", u), rel=1e-9)
+ assert u.cost_usd > 3 * estimate_cost("gemini", "gemini-3.7-flash", u.model_copy(update={"input_tokens": tok["input"]}))
+
+
+def test_usage_prices_each_served_model_at_its_own_rate():
+ from codeverse.contracts.common import Usage
+ from codeverse.models.pricing import estimate_cost
+
+ stats = {"models": {"gemini-3.7-flash": {"tokens": {"prompt": 1_000_000, "cached": 0, "candidates": 1000}},
+ "gemini-3-flash-preview": {"tokens": {"prompt": 1_000_000, "cached": 0, "candidates": 1000}},
+ "unknown-utility-model-x": {"tokens": {"prompt": 1_000_000, "cached": 0, "candidates": 1000}}}}
+ u = usage_from_stats(stats, "gemini-3.7-flash")
+ assert u.input_tokens == 3_000_000 and u.output_tokens == 3000
+ one = Usage(input_tokens=1_000_000, output_tokens=1000)
+ want = (estimate_cost("gemini", "gemini-3.7-flash", one) + estimate_cost("gemini", "gemini-3-flash-preview", one)
+ + estimate_cost("gemini", "gemini-3.7-flash", one)) # unknown model falls back to the requested rate
+ assert u.cost_usd == pytest.approx(want, rel=1e-9)
def test_system_append_is_prepended(tmp_ws: Workspace, agent: GeminiCliAgent):
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
index 69d13818..21443380 100644
--- a/harness/tests/agents/test_materialize.py
+++ b/harness/tests/agents/test_materialize.py
@@ -7,7 +7,7 @@ import json
import pytest
from codeverse.agents.cli_common import default_mcp_command
-from codeverse.agents.materialize import C3V_DIR, codex_mcp_overrides, materialize_workspace
+from codeverse.agents.materialize import CV3D_DIR, codex_mcp_overrides, materialize_workspace
from codeverse.workspace import Workspace
CONTRACT = "## blender contract\nWrite pure bpy into src/model.py."
@@ -26,7 +26,7 @@ def test_writes_three_bodies_same_content(tmp_ws: Workspace):
assert "ONLY under `src/` and `public/`" in body
assert "never import from `codeverse`" in body.lower() or "Never import from `codeverse`" in body
assert CONTRACT.splitlines()[0] in body
- assert "Spatial tools (c3v)" in body
+ assert "Spatial tools (3dcv)" in body
assert len(res.body_files) == 3
@@ -37,23 +37,53 @@ def test_mcp_configs_written_and_merged(tmp_ws: Workspace):
res = _mat(tmp_ws)
data = json.loads(gs.read_text())
assert data["ui"]["theme"] == "dark" and "other" in data["mcpServers"]
- c3v = data["mcpServers"]["c3v"]
- assert c3v["command"] == default_mcp_command(tmp_ws)[0]
- assert c3v["args"][:2] == ["-m", "codeverse.spatial.mcp_server"] and c3v["timeout"] == 600000
+ server = data["mcpServers"]["3dcv"]
+ assert server["command"] == default_mcp_command(tmp_ws)[0]
+ assert server["args"][:2] == ["-m", "codeverse.spatial.mcp_server"] and server["timeout"] == 600000
mcp = json.loads((tmp_ws.root / ".mcp.json").read_text())
- assert mcp["mcpServers"]["c3v"]["type"] == "stdio"
- assert res.codex_overrides[1].startswith("mcp_servers.c3v.command=")
- assert "mcp_servers.c3v.args=[" in res.codex_overrides[3]
+ assert mcp["mcpServers"]["3dcv"]["type"] == "stdio"
+ assert res.codex_overrides[1].startswith("mcp_servers.3dcv.command=")
+ assert "mcp_servers.3dcv.args=[" in res.codex_overrides[3]
assert "global" in res.agy_mcp.lower()
+ assert data["context"]["fileFiltering"]["respectGitIgnore"] is False # .gitignore hides artifacts/ + trajectories/
+
+
+def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):
+ """gemini-cli refuses read_file on ignored paths: the build census, tool renders and the
+ long-prompt file (trajectories/<label>_rNN/task_prompt.md) must NOT be ignored."""
+ import fnmatch
+
+ from codeverse.agents.materialize import IGNORE_LINES
+
+ res = _mat(tmp_ws)
+
+ def ignored(rel: str, lines: tuple[str, ...]) -> bool:
+ for pat in lines:
+ if pat.endswith("/"):
+ if rel.startswith(pat) or f"/{pat}" in f"/{rel}":
+ return True
+ elif fnmatch.fnmatch(rel, pat):
+ return True
+ return False
+
for f in (".geminiignore", ".aiexclude"):
- assert "artifacts/" in (tmp_ws.root / f).read_text()
+ lines = tuple(ln for ln in (tmp_ws.root / f).read_text().splitlines() if ln.strip())
+ assert lines == IGNORE_LINES and str(tmp_ws.root / f) in res.ignore_files
+ assert "artifacts/" not in lines and "trajectories/" not in lines
+ for readable in ("artifacts/census.json", "artifacts/build_last.json", "artifacts/measurement.json",
+ "artifacts/gates/r00/contract_tool.json", "artifacts/tool_renders/r00_ab/sheet.png",
+ "trajectories/baseline_r00/task_prompt.md", "src/model.py", ".3dcv/cookbook.md"):
+ assert not ignored(readable, lines), readable
+ for hidden in ("artifacts/renders/r00/sheet.png", "trajectories/baseline_r00/stdout.json",
+ "trajectories/baseline_r00/stderr.log", "node_modules/three/x.js", ".git/HEAD"):
+ assert ignored(hidden, lines), hidden
def test_spatial_disabled_drops_server_and_documents_absence(tmp_ws: Workspace):
_mat(tmp_ws)
res = _mat(tmp_ws, spatial=False)
assert res.mcp_files == []
- assert "c3v" not in json.loads((tmp_ws.root / ".gemini" / "settings.json").read_text())["mcpServers"]
+ assert "3dcv" not in json.loads((tmp_ws.root / ".gemini" / "settings.json").read_text())["mcpServers"]
assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()
@@ -61,9 +91,9 @@ def test_cookbook_copied_when_found(tmp_ws: Workspace, tmp_path):
cb = tmp_path / "cookbook.md"
cb.write_text("# cookbook\nsnippet")
res = _mat(tmp_ws, cookbook=str(cb))
- assert res.cookbook_path.endswith(f"{C3V_DIR}/cookbook.md")
- assert (tmp_ws.root / C3V_DIR / "cookbook.md").read_text().startswith("# cookbook")
- assert f"{C3V_DIR}/cookbook.md" in (tmp_ws.root / "AGENTS.md").read_text()
+ assert res.cookbook_path.endswith(f"{CV3D_DIR}/cookbook.md")
+ assert (tmp_ws.root / CV3D_DIR / "cookbook.md").read_text().startswith("# cookbook")
+ assert f"{CV3D_DIR}/cookbook.md" in (tmp_ws.root / "AGENTS.md").read_text()
assert not res.warnings
@@ -81,8 +111,12 @@ def test_kind_specific_tool_hint(tmp_ws: Workspace):
def test_codex_overrides_are_valid_toml_fragments():
ov = codex_mcp_overrides(["python", "-m", "x", "--workspace", "/a b/c"])
- assert ov[0] == "-c" and ov[1] == 'mcp_servers.c3v.command="python"'
- assert ov[3] == 'mcp_servers.c3v.args=["-m", "x", "--workspace", "/a b/c"]'
+ assert ov[0] == "-c" and ov[1] == 'mcp_servers.3dcv.command="python"'
+ assert ov[3] == 'mcp_servers.3dcv.args=["-m", "x", "--workspace", "/a b/c"]'
+ assert ov[::2] == ["-c"] * (len(ov) // 2)
+ keys = {kv.split("=", 1)[0]: kv.split("=", 1)[1] for kv in ov[1::2]}
+ # codex exec cannot answer the per-tool approval elicitation: without this every 3dcv call is cancelled
+ assert keys["mcp_servers.3dcv.default_tools_approval_mode"] == '"approve"'
def test_spatial_requires_mcp_command(tmp_ws: Workspace):
diff --git a/harness/tests/blender_cadquery/test_blender_layout.py b/harness/tests/blender_cadquery/test_blender_layout.py
new file mode 100644
index 00000000..104c6792
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_blender_layout.py
@@ -0,0 +1,150 @@
+"""Offline tests for the multi-file layout: part-file mapping, workspace lint rules, and the
+wrapper's error→file:line mapping (the wrapper is importable from host python; no bpy needed)."""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+from codeverse.languages.blender.layout import (
+ build_fn_name,
+ lint_workspace,
+ part_file_rel,
+ part_files,
+ source_files,
+)
+from codeverse.languages.blender.runtime import WRAPPER
+
+SEAT = '''import bpy, bmesh
+
+def build_seat():
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=0.3)
+ me = bpy.data.meshes.new("Seat"); bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new("Seat", me)
+ bpy.context.scene.collection.objects.link(obj)
+ return obj
+'''
+MODEL = '''import bpy
+from parts.seat import build_seat
+import parts.leg
+
+def main():
+ build_seat()
+ parts.leg.build_leg()
+
+main()
+'''
+LEG = SEAT.replace("build_seat", "build_leg").replace("Seat", "Leg")
+
+
+def _write(ws, rel: str, text: str) -> Path:
+ p = ws.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text)
+ return p
+
+
+def test_part_file_mapping_uses_the_name_normaliser() -> None:
+ assert part_file_rel("Seat Cushion") == "src/parts/seat_cushion.py"
+ assert part_file_rel("LeftFrontLeg") == "src/parts/left_front_leg.py"
+ assert build_fn_name("SeatCushion") == "build_seat_cushion"
+
+
+def test_file_listing_excludes_helpers_and_orders_entry_first(tmp_ws) -> None:
+ _write(tmp_ws, "src/model.py", MODEL)
+ _write(tmp_ws, "src/parts/seat.py", SEAT)
+ _write(tmp_ws, "src/parts/leg.py", LEG)
+ _write(tmp_ws, "src/parts/_common.py", "def helper():\n return 1\n")
+ assert [p.name for p in part_files(tmp_ws)] == ["leg.py", "seat.py"]
+ rel = [p.relative_to(tmp_ws.root).as_posix() for p in source_files(tmp_ws)]
+ assert rel == ["src/model.py", "src/parts/_common.py", "src/parts/leg.py", "src/parts/seat.py"]
+
+
+def test_lint_workspace_passes_clean_multi_file_layout(tmp_ws) -> None:
+ _write(tmp_ws, "src/model.py", MODEL)
+ _write(tmp_ws, "src/parts/seat.py", SEAT)
+ _write(tmp_ws, "src/parts/leg.py", LEG)
+ _write(tmp_ws, "src/parts/_common.py", "def helper():\n return 1\n") # no bpy import is fine for helpers
+ rep = lint_workspace(tmp_ws)
+ assert rep.passed, [(f.target, f.message) for f in rep.errors]
+ # the entry only imports + calls → no PascalCase-name warning for it
+ assert not [f for f in rep.findings if f.target == "src/model.py" and f.severity.value == "warn"]
+ assert {f.target for f in rep.findings} <= {"src/model.py", "src/parts/seat.py", "src/parts/leg.py", "src/parts/_common.py"}
+
+
+def test_lint_workspace_layout_rules(tmp_ws) -> None:
+ _write(tmp_ws, "src/model.py", MODEL)
+ _write(tmp_ws, "src/parts/seat.py", SEAT.replace("def build_seat", "def build_seat_cushion")) # wrong export
+ _write(tmp_ws, "src/parts/leg.py", LEG + "\nbuild_leg()\n") # builds at import time
+ _write(tmp_ws, "src/parts/back_rest.py", SEAT.replace("build_seat", "build_back_rest")) # never imported
+ _write(tmp_ws, "src/parts/ArmRest.py", SEAT.replace("build_seat", "build_arm_rest")) # not snake_case
+ _write(tmp_ws, "src/parts/bad.py", "import bpy\ndef build_bad(:\n") # syntax error
+ rep = lint_workspace(tmp_ws)
+ errors = {(f.target, f.message) for f in rep.errors}
+ assert not rep.passed
+ assert ("src/parts/seat.py", "src/parts/seat.py does not define `def build_seat()`") in errors
+ assert any(t == "src/parts/ArmRest.py" and "snake_case" in m for t, m in errors)
+ assert any(t == "src/parts/bad.py" and "SyntaxError" in m for t, m in errors)
+ warns = {(f.target, f.message) for f in rep.findings if f.severity.value == "warn"}
+ assert any(t == "src/parts/leg.py" and "import time" in m for t, m in warns)
+ assert any(t == "src/parts/back_rest.py" and "never imported" in m for t, m in warns)
+ assert all(f.fix_hint for f in rep.errors)
+
+
+def test_lint_workspace_forbidden_calls_in_part_files_and_missing_entry(tmp_ws) -> None:
+ assert not lint_workspace(tmp_ws).passed # no model.py at all
+ _write(tmp_ws, "src/model.py", MODEL)
+ _write(tmp_ws, "src/parts/seat.py", SEAT + "\nbpy.ops.render.render()\n")
+ _write(tmp_ws, "src/parts/leg.py", LEG)
+ rep = lint_workspace(tmp_ws)
+ assert any(f.target == "src/parts/seat.py" and "bpy.ops.render.render" in f.message for f in rep.errors)
+
+
+def test_lint_workspace_single_file_still_valid(tmp_ws) -> None:
+ _write(tmp_ws, "src/model.py", SEAT + "\nbuild_seat()\n")
+ rep = lint_workspace(tmp_ws)
+ assert rep.passed, [(f.target, f.message) for f in rep.errors]
+
+
+# --------------------------------------------------------------------------- wrapper error mapping (host python)
+def _load_wrapper():
+ spec = importlib.util.spec_from_file_location("run_bpy_under_test", WRAPPER)
+ mod = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def test_wrapper_maps_errors_to_the_failing_src_file(tmp_path, monkeypatch) -> None:
+ monkeypatch.setattr(sys, "path", list(sys.path)) # run_script edits sys.path; keep the test process clean
+ monkeypatch.setattr(sys, "dont_write_bytecode", sys.dont_write_bytecode)
+ wrapper = _load_wrapper()
+ src = tmp_path / "src"
+ (src / "parts").mkdir(parents=True)
+ (src / "model.py").write_text("from parts.leg import build_leg\nbuild_leg()\n")
+ (src / "parts" / "leg.py").write_text("def build_leg():\n x = {}\n return x['missing']\n")
+ err = wrapper.run_script(str(src / "model.py"))
+ assert err["error_type"] == "KeyError" and err["error_file"] == "src/parts/leg.py" and err["error_line"] == 3
+ assert err["error_source"] == "return x['missing']"
+ # syntax error inside a part file imported by model.py → reported against the part file
+ (src / "parts" / "leg.py").write_text("def build_leg(:\n pass\n")
+ for name in [m for m in sys.modules if m.startswith("parts")]:
+ del sys.modules[name]
+ err = wrapper.run_script(str(src / "model.py"))
+ assert err["error_type"] == "SyntaxError" and err["error_file"] == "src/parts/leg.py" and err["error_line"] == 1
+ # missing builder → hint names the file and the function
+ (src / "parts" / "leg.py").write_text("def build_legs():\n pass\n")
+ err = wrapper.run_script(str(src / "model.py"))
+ assert err["error_type"] == "ImportError" and err["error_file"] == "src/model.py" and err["error_line"] == 1
+ assert "def build_leg()" in err["error_message"] and "parts/leg.py" in err["error_message"]
+ # missing module → hint says to create the file
+ (src / "model.py").write_text("import math\nfrom parts.armrest import build_armrest\n")
+ err = wrapper.run_script(str(src / "model.py"))
+ assert err["error_type"] in ("ModuleNotFoundError", "ImportError")
+ assert err["error_line"] == 2 and "src/parts/armrest.py" in err["error_message"]
+ assert wrapper.src_relative(str(src / "parts" / "x.py"), str(src)) == "src/parts/x.py"
+ assert wrapper.src_relative(str(tmp_path / "other.py"), str(src)) is None
+ for name in [m for m in sys.modules if m == "parts" or m.startswith("parts.")]:
+ del sys.modules[name]
diff --git a/harness/tests/blender_cadquery/test_blender_lint.py b/harness/tests/blender_cadquery/test_blender_lint.py
index 7df02b5b..b4aab894 100644
--- a/harness/tests/blender_cadquery/test_blender_lint.py
+++ b/harness/tests/blender_cadquery/test_blender_lint.py
@@ -63,6 +63,31 @@ def test_bmesh_lookup_table_missing_is_error_even_if_mentioned_in_comment() -> N
assert f and f[0].severity == Severity.ERROR and f[0].data["line"] == 3 and "ensure_lookup_table()" in f[0].fix_hint
+def test_bmesh_lookup_rule_ignores_non_bmesh_bases() -> None:
+ """Finding: e.verts[0] (BMEdge) / me.edges[i] (Mesh) never need ensure_lookup_table."""
+ src = ("import bpy, bmesh\n"
+ "bm = bmesh.new()\n"
+ "side = [e for e in bm.edges if abs(e.verts[0].co.z - e.verts[1].co.z) > 1e-9]\n"
+ "o = bpy.context.object\n"
+ "o.data.edges[0].use_seam = True\n"
+ "me = o.data\n"
+ "me.edges[2].use_seam = True\n"
+ "bm.free()\n")
+ r = lint_blender_source(src)
+ assert not any("ensure_lookup_table" in f.message for f in r.findings), _msgs(r)
+ assert r.passed
+
+
+def test_bmesh_lookup_rule_tracks_bmesh_bindings() -> None:
+ src = "import bpy, bmesh\nmesh_bm = bmesh.new()\nv = mesh_bm.verts[0]\n"
+ r = lint_blender_source(src)
+ f = [x for x in r.findings if "ensure_lookup_table" in x.message]
+ assert f and f[0].severity == Severity.ERROR and f[0].data["line"] == 3
+ src2 = "import bpy, bmesh\nedit_bm = bmesh.from_edit_mesh(bpy.context.object.data)\nx = edit_bm.faces[1]\n"
+ r2 = lint_blender_source(src2)
+ assert any("ensure_lookup_table" in f.message for f in r2.findings)
+
+
def test_vector_without_import() -> None:
r = lint_blender_source("import bpy\nv = Vector((1, 2, 3))\n")
f = [x for x in r.findings if "Vector" in x.message]
@@ -75,6 +100,17 @@ def test_removed_bsdf_inputs() -> None:
assert f and f[0].severity == Severity.ERROR and "Specular IOR Level" in f[0].fix_hint
+def test_valid_bsdf_inputs_not_flagged() -> None:
+ """Finding: 'Anisotropic' and 'Specular Tint' exist in Blender 4.x/5.0.1 — never ERROR."""
+ src = ("import bpy\nm = bpy.data.materials.new('x')\nb = m.node_tree.nodes['Principled BSDF']\n"
+ "b.inputs['Anisotropic'].default_value = 0.6\n"
+ "b.inputs['Specular Tint'].default_value = (1, 1, 1, 1)\n")
+ r = lint_blender_source(src)
+ assert r.passed and not _msgs(r, Severity.ERROR), _msgs(r)
+ tint = [f for f in r.findings if "Specular Tint" in f.message]
+ assert tint and tint[0].severity == Severity.INFO and "4-tuple" in tint[0].fix_hint
+
+
def test_camera_light_and_render_settings_warn() -> None:
src = "import bpy\nbpy.ops.object.light_add(type='SUN')\ncam = bpy.data.cameras.new('c')\nbpy.context.scene.render.engine = 'CYCLES'\nbpy.context.scene.camera = None\n"
r = lint_blender_source(src)
diff --git a/harness/tests/blender_cadquery/test_blender_live_gates.py b/harness/tests/blender_cadquery/test_blender_live_gates.py
new file mode 100644
index 00000000..23dbcb7a
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_blender_live_gates.py
@@ -0,0 +1,104 @@
+"""Live Blender regressions for the review findings (skeleton instances, BSDF names, census).
+
+All tests need the real binary (``-m blender``): they verify the harness's own skeleton
+clears its own contract gate, that the lint's Principled BSDF table matches Blender 5.x,
+and that the census counts exactly what the exporter exports.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+
+import pytest
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.blender.lint import REMOVED_BSDF_INPUTS
+from codeverse.languages.blender.runtime import BlenderRuntime, blender_env
+
+pytestmark = pytest.mark.blender
+
+
+def test_skeleton_with_instances_passes_contract_gate(tmp_ws, table_plan, blender_bin) -> None:
+ """Finding: instances under an Empty merged into one GLB part → 'plan part missing' ERROR."""
+ from codeverse.spatial.contract import check_contract
+ from codeverse.spatial.measure import measure_glb
+
+ rt = BlenderRuntime(blender=blender_bin)
+ rt.skeleton(tmp_ws, table_plan) # multi-file: src/model.py + src/parts/*.py
+ assert (tmp_ws.src / "parts" / "leg.py").is_file()
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ m = measure_glb(r.glb_path)
+ names = {p.name for p in m.parts}
+ assert {"Leg_0", "Leg_1", "Leg_2", "Leg_3"} <= names # one measured part per instance
+ assert "Legs" not in names
+ rep = check_contract(m, table_plan, language="blender")
+ missing = [f for f in rep.findings if f.severity == Severity.ERROR and "missing" in f.message]
+ assert not missing, [(f.target, f.message) for f in missing]
+ assert rep.passed, [(f.severity, f.message) for f in rep.findings]
+
+
+BSDF_PROBE = (
+ "import bpy, json\n"
+ "m = bpy.data.materials.new('probe')\n"
+ "b = m.node_tree.nodes['Principled BSDF']\n"
+ "print('BSDF_INPUTS=' + json.dumps([i.name for i in b.inputs]))\n"
+)
+
+
+def test_lint_bsdf_table_matches_real_principled_inputs(blender_bin) -> None:
+ """Finding: 'Anisotropic'/'Specular Tint' are REAL inputs in Blender 5.0.1 — lint must agree."""
+ proc = subprocess.run([blender_bin, "-b", "--factory-startup", "--python-expr", BSDF_PROBE],
+ capture_output=True, text=True, timeout=120, env=blender_env())
+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("BSDF_INPUTS="))
+ real = set(json.loads(line[len("BSDF_INPUTS="):]))
+ # every key the lint calls removed must actually be absent (no false 'KeyError at runtime')
+ still_there = {k for k in REMOVED_BSDF_INPUTS if k in real}
+ assert not still_there, f"lint flags valid Principled BSDF inputs: {sorted(still_there)}"
+ # the names the lint (and the contract docs) steer agents toward must all exist
+ expected = {"Anisotropic", "Specular Tint", "Specular IOR Level", "Subsurface Weight",
+ "Transmission Weight", "Coat Weight", "Coat Roughness", "Sheen Weight",
+ "Emission Color", "Emission Strength", "Base Color", "Roughness", "Metallic"}
+ assert expected <= real, f"missing from Blender: {sorted(expected - real)}"
+
+
+EXCLUDED_MODEL = '''import bpy
+
+bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5))
+main = bpy.context.object
+main.name = "Main"
+mat = bpy.data.materials.new("MainMat")
+main.data.materials.append(mat)
+
+bpy.ops.mesh.primitive_cube_add(size=1, location=(10, 10, 10))
+extra = bpy.context.object
+extra.name = "InColl"
+coll = bpy.data.collections.new("Extra")
+bpy.context.scene.collection.children.link(coll)
+for c in list(extra.users_collection):
+ c.objects.unlink(extra)
+coll.objects.link(extra)
+bpy.context.view_layer.layer_collection.children["Extra"].exclude = True
+'''
+
+
+def test_census_matches_export_for_excluded_collections(tmp_ws, blender_bin) -> None:
+ """Finding: excluded-collection objects were counted in tri_count/bbox but never exported."""
+ trimesh = pytest.importorskip("trimesh")
+ rt = BlenderRuntime(blender=blender_bin)
+ (tmp_ws.src / "model.py").write_text(EXCLUDED_MODEL)
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ c = r.census
+ rec = {o["name"]: o for o in c["objects"]}
+ assert rec["InColl"]["in_scene"] and not rec["InColl"]["in_view_layer"] and rec["InColl"]["hidden"]
+ assert c["tri_count"] == 12 and c["n_mesh_objects"] == 1 # Main only
+ assert c["scene_bbox_max"][2] <= 1.0 + 1e-4 # bbox not stretched to (10,10,10)
+ assert any("excluded from the view layer" in w and "InColl" in w for w in c["warnings"])
+ assert not any("no material" in w for w in c["warnings"]) # no spurious warning for InColl
+ scene = trimesh.load(r.glb_path)
+ assert set(scene.graph.nodes_geometry) == {"Main"} # census now matches the export
diff --git a/harness/tests/blender_cadquery/test_blender_multifile.py b/harness/tests/blender_cadquery/test_blender_multifile.py
new file mode 100644
index 00000000..45c3cefc
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_blender_multifile.py
@@ -0,0 +1,178 @@
+"""Multi-file blender models on the real binary: the 4-part skeleton builds; a hand-written
+2-part model builds and its errors map to the failing PART file + line; the prompt
+examples (contract.md example A, cookbook "File layout") build and export."""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.languages.blender.runtime import BlenderRuntime
+from codeverse.prompts import PROMPTS_DIR
+from codeverse.workspace import Workspace
+
+_LABELLED_PY = re.compile(r"`((?:src|public)/[^`]+)`\n```py\n(.*?)```", re.DOTALL)
+
+
+def labelled_py_files(rel: str) -> dict[str, str]:
+ """``src/...`` labelled ```py blocks of a prompt file → {path: content} (multi-file examples)."""
+ return dict(_LABELLED_PY.findall((PROMPTS_DIR / rel).read_text()))
+
+
+def _write_files(ws: Workspace, files: dict[str, str]) -> None:
+ for rel, body in files.items():
+ p = ws.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body)
+
+
+SEAT = '''import bpy, bmesh
+
+SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45
+
+def build_seat():
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=SEAT_D / 2, radius2=SEAT_D / 2, depth=SEAT_T)
+ me = bpy.data.meshes.new("Seat"); bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new("Seat", me)
+ obj.location = (0, 0, SEAT_Z - SEAT_T / 2)
+ bpy.context.scene.collection.objects.link(obj)
+ return obj
+'''
+LEG = '''import bpy, bmesh, math
+
+LEG_R, LEG_N, LEG_RING, LEG_H = 0.02, 3, 0.12, 0.414
+
+def build_leg():
+ parent = bpy.data.objects.new("Legs", None)
+ bpy.context.scene.collection.objects.link(parent)
+ for i in range(LEG_N):
+ a = 2 * math.pi * i / LEG_N
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=LEG_R, radius2=LEG_R, depth=LEG_H)
+ me = bpy.data.meshes.new(f"Leg_{i}"); bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new(f"Leg_{i}", me)
+ obj.location = (LEG_RING * math.cos(a), LEG_RING * math.sin(a), LEG_H / 2)
+ bpy.context.scene.collection.objects.link(obj)
+ obj.parent = parent
+ return parent
+'''
+MODEL = '''import bpy
+from parts.seat import build_seat
+import parts.leg
+
+def main():
+ build_seat()
+ parts.leg.build_leg()
+
+main()
+'''
+
+
+def four_part_plan() -> StaticPlan:
+ return StaticPlan(
+ object_name="Stool", summary="A bar stool with a round seat, a ring footrest and four legs.",
+ overall_bbox=BBox(center=(0, 0, 0.375), extents=(0.4, 0.4, 0.75)),
+ parts=[
+ PartPlan(name="Seat", role="seat", description="round padded seat", material="brown leather",
+ bbox=BBox(center=(0, 0, 0.73), extents=(0.36, 0.36, 0.04))),
+ PartPlan(name="Leg", role="support", description="steel tube leg", material="chrome steel",
+ bbox=BBox(center=(0.15, 0.15, 0.355), extents=(0.025, 0.025, 0.71)), attach_to="Seat",
+ instances=4, symmetry="mirror_x"),
+ PartPlan(name="FootRing", role="footrest", description="ring connecting the legs", material="chrome steel",
+ bbox=BBox(center=(0, 0, 0.25), extents=(0.33, 0.33, 0.02)), attach_to="Leg"),
+ PartPlan(name="SeatPlate", role="mount", description="plate under the seat", material="black steel",
+ bbox=BBox(center=(0, 0, 0.705), extents=(0.3, 0.3, 0.01)), attach_to="Seat"),
+ ],
+ )
+
+
+def test_live_four_part_multifile_skeleton_builds(tmp_ws, four_part_plan, blender_bin) -> None:
+ trimesh = pytest.importorskip("trimesh")
+ rt = BlenderRuntime(blender=blender_bin)
+ paths = rt.skeleton(tmp_ws, four_part_plan)
+ assert [p.relative_to(tmp_ws.root).as_posix() for p in paths] == [
+ "src/model.py", "src/parts/seat.py", "src/parts/leg.py", "src/parts/foot_ring.py", "src/parts/seat_plate.py"]
+ assert rt.file_for_part("FootRing") == "src/parts/foot_ring.py"
+ lint = rt.lint(tmp_ws)
+ assert lint.passed, [(f.target, f.message) for f in lint.errors]
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message, r.error_file, r.error_line, r.stderr_tail)
+ scene = trimesh.load(r.glb_path)
+ assert set(scene.graph.nodes_geometry) == {"Seat", "Leg_0", "Leg_1", "Leg_2", "Leg_3", "FootRing", "SeatPlate"}
+ lo, hi = scene.bounds
+ assert abs(lo[1]) < 1e-4 and abs(hi[1] - 0.75) < 1e-3
+ assert "[selfcheck]" in r.stdout_tail
+
+
+def test_live_multifile_errors_map_to_part_file_and_line(tmp_ws, blender_bin) -> None:
+ rt = BlenderRuntime(blender=blender_bin)
+ _write_files(tmp_ws, {"src/model.py": MODEL, "src/parts/seat.py": SEAT, "src/parts/leg.py": LEG})
+ assert rt.lint(tmp_ws).passed
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ assert {o["name"] for o in r.census["objects"]} == {"Seat", "Legs", "Leg_0", "Leg_1", "Leg_2"}
+
+ leg = tmp_ws.src / "parts" / "leg.py"
+ # (a) syntax error in the part file → src/parts/leg.py:8
+ leg.write_text(LEG.replace(" for i in range(LEG_N):", " for i in range(LEG_N)"))
+ lint = rt.lint(tmp_ws)
+ assert not lint.passed and any(f.target == "src/parts/leg.py" and "SyntaxError" in f.message for f in lint.errors)
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "SyntaxError" and r.error_file == "src/parts/leg.py" and r.error_line == 8
+ bj = json.loads((tmp_ws.artifacts / "build.json").read_text())
+ assert (bj["error_file"], bj["error_line"], bj["error_source"]) == ("src/parts/leg.py", 8, "for i in range(LEG_N)")
+
+ # (b) runtime error deep in the part file → that frame, not model.py's import/call line
+ leg.write_text(LEG.replace(" obj.parent = parent", " obj.parent = parent\n obj.data.materials.append(None).foo"))
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "AttributeError" and r.error_file == "src/parts/leg.py" and r.error_line == 17
+ assert r.census["build_report"]["error_source"] == "obj.data.materials.append(None).foo"
+ bj = json.loads((tmp_ws.artifacts / "build.json").read_text())
+ assert bj["error_file"] == "src/parts/leg.py" and bj["error_line"] == 17 and "leg.py" in bj["traceback"]
+
+ # (c) missing builder → lint error; build reports model.py's import line with a hint
+ leg.write_text(LEG.replace("def build_leg", "def build_legs"))
+ (tmp_ws.src / "model.py").write_text(MODEL.replace("import parts.leg", "from parts.leg import build_leg").replace("parts.leg.build_leg()", "build_leg()"))
+ lint = rt.lint(tmp_ws)
+ assert any(f.target == "src/parts/leg.py" and "does not define `def build_leg()`" in f.message for f in lint.errors)
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "ImportError" and r.error_file == "src/model.py" and r.error_line == 3
+ assert "def build_leg()" in r.error_message
+
+
+def test_live_contract_multifile_example_builds(tmp_ws, blender_bin) -> None:
+ trimesh = pytest.importorskip("trimesh")
+ files = labelled_py_files("blender/contract.md")
+ assert set(files) == {"src/parts/seat.py", "src/parts/leg.py", "src/model.py"}
+ _write_files(tmp_ws, files)
+ rt = BlenderRuntime(blender=blender_bin)
+ lint = rt.lint(tmp_ws)
+ assert lint.passed, [(f.target, f.message) for f in lint.errors]
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message, r.error_file, r.error_line)
+ scene = trimesh.load(r.glb_path)
+ assert set(scene.graph.nodes_geometry) == {"Seat", "Leg_0", "Leg_1", "Leg_2"}
+ lo, hi = scene.bounds
+ assert abs(lo[1]) < 1e-3 and abs(hi[1] - 0.45) < 1e-3 # Y-up GLB, on the ground, seat top at 0.45
+
+
+def test_live_cookbook_layout_example_builds(tmp_ws, blender_bin) -> None:
+ files = labelled_py_files("blender/cookbook.md")
+ assert set(files) == {"src/parts/mug_body.py", "src/model.py"}
+ _write_files(tmp_ws, files)
+ rt = BlenderRuntime(blender=blender_bin)
+ assert rt.lint(tmp_ws).passed
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message, r.error_file, r.error_line)
+ assert {o["name"] for o in r.census["objects"] if o["type"] == "MESH"} == {"MugBody"}
+ assert Path(r.glb_path).stat().st_size > 500
diff --git a/harness/tests/blender_cadquery/test_blender_runtime.py b/harness/tests/blender_cadquery/test_blender_runtime.py
index 24e2bac2..cfa59384 100644
--- a/harness/tests/blender_cadquery/test_blender_runtime.py
+++ b/harness/tests/blender_cadquery/test_blender_runtime.py
@@ -43,7 +43,8 @@ def _fake_blender(tmp_path: Path) -> str:
def test_protocol_and_registry() -> None:
rt = get_runtime("blender")
assert isinstance(rt, BlenderRuntime) and isinstance(rt, LanguageRuntime)
- assert rt.entry_globs == ("src/model.py",) and rt.language.value == "blender"
+ assert rt.entry_globs == ("src/model.py", "src/parts/*.py") and rt.language.value == "blender"
+ assert rt.file_for_part("Seat Cushion") == "src/parts/seat_cushion.py" # tracks call this via getattr
assert "bpy" in rt.contract_doc() and "Z is up" in rt.contract_doc()
assert rt.cookbook_path().name == "cookbook.md"
@@ -96,8 +97,9 @@ def test_live_skeleton_builds_and_exports_canonical_glb(tmp_ws, table_plan, blen
assert Path(r.extra_paths["stl"]).stat().st_size > 0
scene = trimesh.load(r.glb_path)
names = set(scene.graph.nodes_geometry)
+ assert (tmp_ws.src / "parts" / "leg.py").is_file() # multi-file skeleton
assert names == {"TableTop", "Shelf", "Leg_0", "Leg_1", "Leg_2", "Leg_3"}
- assert "Legs" in scene.graph.nodes # parent empty exported as a node
+ assert "Legs" not in scene.graph.nodes # instances are TOP-LEVEL: no parent Empty node
lo, hi = scene.bounds
assert abs(lo[1]) < 1e-4 and abs(hi[1] - 0.6) < 1e-3 # Y-up, ground contact, height 0.6
assert abs(lo[0] + 0.25) < 1e-3 and abs(hi[2] - 0.25) < 1e-3
@@ -131,7 +133,7 @@ def test_live_error_maps_to_line_and_lint_catches_it(tmp_ws, blender_bin) -> Non
lint = lint_blender_file(tmp_ws.src / "model.py")
assert not lint.passed and any("ensure_lookup_table" in f.message and f.data.get("line") == 10 for f in lint.errors)
r = rt.build(tmp_ws, timeout_s=120)
- assert not r.ok and r.error_type == "IndexError" and r.error_file == "model.py" and r.error_line == 10
+ assert not r.ok and r.error_type == "IndexError" and r.error_file == "src/model.py" and r.error_line == 10
assert "ensure_lookup_table" in r.error_message
assert r.census["build_report"]["error_source"] == "v = bm.verts[0]"
assert any("light" in w for w in r.census["warnings"])
diff --git a/harness/tests/blender_cadquery/test_blender_skeleton.py b/harness/tests/blender_cadquery/test_blender_skeleton.py
index 22900dcf..dc1eceb4 100644
--- a/harness/tests/blender_cadquery/test_blender_skeleton.py
+++ b/harness/tests/blender_cadquery/test_blender_skeleton.py
@@ -1,34 +1,75 @@
-"""Offline tests for the bpy skeleton generator."""
+"""Offline tests for the bpy skeleton generator (multi-file default + single-file variant)."""
from __future__ import annotations
import ast
from codeverse.contracts.plan import BBox
+from codeverse.languages.blender.layout import lint_workspace
from codeverse.languages.blender.lint import lint_blender_source
from codeverse.languages.blender.skeleton import (
blender_skeleton_source,
finish_for,
instance_centers,
+ model_file_source,
+ part_file_source,
write_blender_skeleton,
)
-def test_skeleton_parses_lints_and_names_parts(table_plan) -> None:
+def test_single_file_skeleton_parses_lints_and_names_parts(table_plan) -> None:
src = blender_skeleton_source(table_plan)
ast.parse(src)
- assert "import codeverse" not in src and "from codeverse" not in src
- for fn in ("def build_table_top(", "def build_leg(", "def build_shelf(", "def main():"):
+ assert "import codeverse" not in src and "from codeverse" not in src and "from parts" not in src
+ for fn in ("def build_table_top(", "def build_leg(", "def build_shelf(", "def main():", "def _selfcheck("):
assert fn in src
- assert 'name = "TableTop"' in src and 'name = f"Leg_{index}"' in src and 'add_empty("Legs")' in src
- assert "Z is up, -Y is the FRONT" in src and "[a1]" in src
+ assert 'add_box("TableTop"' in src and 'add_box(f"Leg_{i}"' in src
+ assert "add_empty" not in src and ".parent" not in src # instances stay TOP-LEVEL (measured as parts)
+ assert "Z is up, -Y is the FRONT" in src and "[a1]" in src and "LEG_EXTENTS = (0.040, 0.040, 0.560)" in src
r = lint_blender_source(src)
assert r.passed, [f.message for f in r.findings]
-def test_write_skeleton(tmp_ws, table_plan) -> None:
+def test_part_file_source_is_self_contained(table_plan) -> None:
+ leg = table_plan.parts[1]
+ src = part_file_source(leg)
+ tree = ast.parse(src)
+ assert "def build_leg():" in src and "def make_material(" in src and "def add_box(" in src
+ assert "LEG_CENTER = (0.210, 0.210, 0.280)" in src and "LEG_INSTANCES = 4" in src
+ assert "tapered square leg" in src and "support" in src and "Attaches to: TableTop" in src and "oak" in src
+ assert "(0.550, 0.360, 0.200)" in src # oak colour hint
+ # defines builders only — nothing is built at import time
+ calls = [n.value.func for n in tree.body if isinstance(n, ast.Expr) and isinstance(n.value, ast.Call)]
+ assert [getattr(f, "id", "") for f in calls if isinstance(f, ast.Name)] == [] # only random.seed(0)
+ assert lint_blender_source(src, target="src/parts/leg.py").passed
+
+
+def test_model_file_source_imports_and_calls_in_plan_order(table_plan) -> None:
+ src = model_file_source(table_plan)
+ ast.parse(src)
+ imports = [ln for ln in src.splitlines() if ln.startswith("from parts.")]
+ assert imports == ["from parts.table_top import build_table_top", "from parts.leg import build_leg",
+ "from parts.shelf import build_shelf"]
+ body = src[src.index("def main():"):]
+ assert body.index("build_table_top()") < body.index("build_leg()") < body.index("build_shelf()") < body.index("_selfcheck()")
+ assert "add_box(" not in src # no geometry in the entry
+ assert "[src/parts/leg.py]" in src # parts table points at the files
+
+
+def test_write_skeleton_multi_file_and_workspace_lint(tmp_ws, table_plan) -> None:
paths = write_blender_skeleton(tmp_ws, table_plan)
+ rel = [p.relative_to(tmp_ws.root).as_posix() for p in paths]
+ assert rel == ["src/model.py", "src/parts/table_top.py", "src/parts/leg.py", "src/parts/shelf.py"]
+ assert all(p.is_file() for p in paths)
+ rep = lint_workspace(tmp_ws)
+ assert rep.passed, [(f.target, f.message) for f in rep.errors]
+ assert not [f for f in rep.findings if f.severity.value == "warn"], [f.message for f in rep.findings]
+
+
+def test_write_skeleton_single_file(tmp_ws, table_plan) -> None:
+ paths = write_blender_skeleton(tmp_ws, table_plan, multi_file=False)
assert paths == [tmp_ws.src / "model.py"] and paths[0].is_file()
+ assert lint_workspace(tmp_ws).passed
def test_instance_centers_symmetry() -> None:
@@ -41,6 +82,17 @@ def test_instance_centers_symmetry() -> None:
assert len(rad) == 3 and all(abs((x * x + y * y) ** 0.5 - 0.5) < 1e-9 for x, y, _ in rad)
+def test_instances_are_top_level_no_empty_parent(table_plan) -> None:
+ """Finding: an Empty parent merges instances into ONE measured part → contract 'missing'."""
+ leg = table_plan.parts[1]
+ src = part_file_source(leg)
+ assert "add_empty" not in src and "obj.parent" not in src
+ assert 'add_box(f"Leg_{i}"' in src and "return objs" in src
+ assert "TOP-LEVEL" in src # docstring warns the agent off the Empty pattern
+ single = blender_skeleton_source(table_plan)
+ assert "add_empty" not in single and "obj.parent" not in single
+
+
def test_finish_for_keywords() -> None:
assert finish_for("brushed steel")[2] == 1.0
assert finish_for("oak wood")[0] == (0.55, 0.36, 0.20)
diff --git a/harness/tests/blender_cadquery/test_cadquery_lint.py b/harness/tests/blender_cadquery/test_cadquery_lint.py
index e3119855..f9fee452 100644
--- a/harness/tests/blender_cadquery/test_cadquery_lint.py
+++ b/harness/tests/blender_cadquery/test_cadquery_lint.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import pytest
+
from codeverse.contracts.artifacts import Severity
from codeverse.languages.cadquery.lint import lint_cadquery_source
@@ -53,6 +55,27 @@ def test_pitfalls() -> None:
assert any("not PascalCase" in m and "my_part" in m for m in w)
+def _rotate_src(expr: str, prelude: str = "") -> str:
+ return (f"import cadquery as cq\nimport math\nimport numpy as np\n{prelude}n_pins, pitch_deg, spindles, i, a = 6, 30.0, 5, 2, 0.4\n"
+ f"w = cq.Workplane().box(1, 1, 1).rotate((0, 0, 0), (0, 0, 1), {expr})\nresult = cq.Assembly()\nresult.add(w, name='Part')\n")
+
+
[email protected]("expr", ["i * 360 / n_pins", "i * pitch_deg", "360 / spindles", "math.degrees(a) * 2",
+ "a * 180 / math.pi", "180 / math.pi * a", "360 * a / (2 * math.pi)", "np.rad2deg(a) / 2",
+ "math.degrees(math.pi / 4)", "90", "pitch_deg"])
+def test_rotate_degrees_expressions_are_not_flagged(expr: str) -> None:
+ """Identifiers merely containing the letters 'pi' (n_pins, pitch, spindles) and rad→deg conversions are degrees."""
+ r = lint_cadquery_source(_rotate_src(expr))
+ assert r.passed and not any("DEGREES" in m for m in _msgs(r)), (expr, _msgs(r))
+
+
[email protected]("expr", ["math.pi / 2", "i * 2 * math.pi / n_pins", "math.pi", "math.radians(30) * 2", "math.radians(a)",
+ "math.tau / 4", "a * math.pi / 180", "np.deg2rad(30)", "-math.pi / 2"])
+def test_rotate_radians_expressions_are_flagged(expr: str) -> None:
+ r = lint_cadquery_source(_rotate_src(expr))
+ assert not r.passed and any("DEGREES" in m for m in _msgs(r, Severity.ERROR)), (expr, _msgs(r))
+
+
def test_bare_workplane_warns() -> None:
r = lint_cadquery_source("import cadquery as cq\nresult = cq.Workplane().box(1, 1, 1)\n")
assert r.passed and any("ONE unnamed part" in m for m in _msgs(r, Severity.WARN))
diff --git a/harness/tests/blender_cadquery/test_cadquery_runtime.py b/harness/tests/blender_cadquery/test_cadquery_runtime.py
index 74dd076e..c451550c 100644
--- a/harness/tests/blender_cadquery/test_cadquery_runtime.py
+++ b/harness/tests/blender_cadquery/test_cadquery_runtime.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import ast
+import importlib.util
import json
import stat
import sys
@@ -119,3 +120,91 @@ result.add(pegs, name="Pegs", color=cq.Color(0, 1, 0))
assert any("bare Workplane" in w for w in r.census["build_report"]["warnings"])
build_json = json.loads((tmp_ws.artifacts / "build.json").read_text())
assert build_json["ok"] is True
+
+
+def _wrapper_module():
+ spec = importlib.util.spec_from_file_location("run_cq_under_test", WRAPPER)
+ mod = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def test_wrapper_error_file_is_workspace_relative(tmp_path) -> None:
+ """error_file must be ``src/<file>`` (like every other runtime) and point at the innermost src/ frame."""
+ mod = _wrapper_module()
+ src = tmp_path / "src"
+ src.mkdir()
+ (src / "helpers.py").write_text("def make_part():\n raise RuntimeError('boom') # line 2\n")
+ (src / "model.py").write_text("from helpers import make_part\nresult = make_part()\n")
+ assert mod.src_relative(str(src / "model.py"), str(src)) == "src/model.py"
+ assert mod.src_relative(str(src / "parts" / "leg.py"), str(src)) == "src/parts/leg.py"
+ assert mod.src_relative(str(tmp_path / "other.py"), str(src)) is None
+ assert mod.entry_relative(str(src / "model.py")) == "src/model.py"
+ err, ns = mod.run_script(str(src / "model.py"))
+ assert err is not None and ns == {}
+ assert err["error_type"] == "RuntimeError" and err["error_file"] == "src/helpers.py" and err["error_line"] == 2
+ assert "raise RuntimeError" in err["error_source"] and "helpers.py" in err["traceback"]
+ # an error raised by model.py itself still maps to src/model.py (and so does a SyntaxError)
+ (src / "model.py").write_text("import math\nx = 1 / 0\n")
+ err, _ = mod.run_script(str(src / "model.py"))
+ assert err["error_file"] == "src/model.py" and err["error_line"] == 2
+ (src / "model.py").write_text("result = (\n")
+ err, _ = mod.run_script(str(src / "model.py"))
+ assert err["error_type"] == "SyntaxError" and err["error_file"] == "src/model.py"
+ (src / "model.py").write_text("import sys\nsys.exit(0)\n")
+ err, _ = mod.run_script(str(src / "model.py"))
+ assert err["error_type"] == "SystemExit" and err["error_file"] == "src/model.py"
+
+
+@needs_cq
+def test_helper_module_error_and_missing_result_report_src_paths(tmp_ws) -> None:
+ rt = CadQueryRuntime()
+ (tmp_ws.src / "helpers.py").write_text("import cadquery as cq\n\n\ndef make_part():\n wp = cq.Workplane('XY').box(1, 1, 1)\n"
+ " return wp.edges('|Z').fillet(5.0) # line 6: OCC fail\n")
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nfrom helpers import make_part\n\nassy = cq.Assembly()\n"
+ "assy.add(make_part(), name='Part')\nresult = assy\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "StdFail_NotDone"
+ assert r.error_file == "src/helpers.py" and r.error_line == 6 and (tmp_ws.root / r.error_file).is_file()
+ assert "helpers.py" in r.stderr_tail and "StdFail_NotDone" in r.stderr_tail # traceback reaches the repair report
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nx = cq.Workplane('XY').box(1, 1, 1)\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "MissingResult" and r.error_file == "src/model.py"
+
+
+@needs_cq
+def test_trailing_selector_exports_parent_solid_with_warning(tmp_ws) -> None:
+ """``body.faces('>Z')`` / ``.edges('|Z')`` on the stack must not become a 2-triangle sheet / nothing."""
+ trimesh = pytest.importorskip("trimesh")
+ rt = CadQueryRuntime()
+ src = '''import cadquery as cq
+body = cq.Workplane("XY").box(0.1, 0.1, 0.01).edges("|Z").fillet(0.002)
+result = cq.Assembly()
+result.add(body.faces(">Z"), name="Plate", color=cq.Color("gray"))
+result.add(cq.Workplane("XY").box(0.02, 0.02, 0.02).edges("|Z"), name="Leg")
+'''
+ (tmp_ws.src / "model.py").write_text(src)
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ parts = {p["name"]: p for p in r.census["parts"]}
+ assert parts["Plate"]["n_solids"] == 1 and abs(parts["Plate"]["volume_m3"] - 0.1 * 0.1 * 0.01) < 2e-6
+ assert parts["Leg"]["n_solids"] == 1 and parts["Leg"]["tri_count"] == 12
+ assert set(trimesh.load(r.glb_path).graph.nodes_geometry) == {"Plate", "Leg"}
+ warns = r.census["build_report"]["warnings"]
+ assert any("'Plate'" in w and "Face" in w and "trailing selector" in w for w in warns), warns
+ assert any("'Leg'" in w and "Edge" in w for w in warns), warns
+ # bare-Workplane result with a trailing selector: same fallback
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nresult = cq.Workplane('XY').box(0.1, 0.1, 0.01).faces('>Z')\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok and r.census["parts"][0]["n_solids"] == 1 and r.census["parts"][0]["tri_count"] == 12
+ # no solid anywhere in the chain (2D wires only) → a typed error naming the stack, not a silent sheet
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nresult = cq.Workplane('XY').rect(0.1, 0.1)\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "ExportError" and "Wire" in r.error_message and "not a Solid" in r.error_message
+ # a bare cq.Face added to an assembly stays a face but is flagged (n_solids == 0 surfaced)
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nf = cq.Workplane('XY').box(0.1, 0.1, 0.01).faces('>Z').val()\n"
+ "result = cq.Assembly()\nresult.add(f, name='Sheet')\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok and r.census["parts"][0]["n_solids"] == 0
+ assert any("'Sheet'" in w and "contains no solid" in w for w in r.census["build_report"]["warnings"])
diff --git a/harness/tests/blender_cadquery/test_prompt_block_lint.py b/harness/tests/blender_cadquery/test_prompt_block_lint.py
new file mode 100644
index 00000000..cd8de4c6
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_prompt_block_lint.py
@@ -0,0 +1,55 @@
+"""Every python block in the blender/cadquery prompts must pass its own lint.
+
+Regression for two false positives that blocked the build on code copied verbatim from
+the cookbook: the bmesh ensure_lookup_table rule firing on ``e.verts[0]`` (BMEdge), and
+'Anisotropic' / 'Specular Tint' flagged as removed Principled BSDF inputs. An agent that
+pastes a cookbook snippet into ``src/model.py`` (with the standard imports) must never
+get a lint ERROR for it.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+from codeverse.languages.blender.lint import lint_blender_source
+from codeverse.languages.cadquery.lint import lint_cadquery_source
+
+PROMPTS = Path(__file__).resolve().parents[2] / "codeverse" / "prompts"
+FENCE = re.compile(r"^```(?:py|python)\s*$(.*?)^```\s*$", re.M | re.S)
+
+BLENDER_HEADER = (
+ "import bpy\nimport bmesh\nimport math\nimport random\nfrom mathutils import Vector, Matrix\n"
+)
+CADQUERY_HEADER = "import cadquery as cq\nimport math\nimport random\n"
+
+
+def blocks(rel: str) -> list[tuple[int, str]]:
+ text = (PROMPTS / rel).read_text()
+ out = []
+ for m in FENCE.finditer(text):
+ out.append((text[: m.start()].count("\n") + 2, m.group(1)))
+ assert out, f"{rel}: no python blocks found"
+ return out
+
+
[email protected]("rel", ["blender/cookbook.md", "blender/contract.md"])
+def test_blender_prompt_blocks_lint_clean(rel: str) -> None:
+ for line, code in blocks(rel):
+ src = code if "import bpy" in code else BLENDER_HEADER + code
+ r = lint_blender_source(src, expect_names=False)
+ errs = [(f.data.get("line"), f.message) for f in r.findings if f.severity.value == "error"]
+ assert not errs, f"{rel} block at line {line}: {errs}"
+
+
[email protected]("rel", ["cadquery/cookbook.md", "cadquery/contract.md"])
+def test_cadquery_prompt_blocks_lint_clean(rel: str) -> None:
+ for line, code in blocks(rel):
+ src = code if "import cadquery" in code else CADQUERY_HEADER + code
+ if not re.search(r"^result\s*=", src, re.M):
+ src += "\nresult = cq.Assembly()\n" # fragments: satisfy the structural rule only
+ r = lint_cadquery_source(src)
+ errs = [(f.data.get("line"), f.message) for f in r.findings if f.severity.value == "error"]
+ assert not errs, f"{rel} block at line {line}: {errs}"
diff --git a/harness/tests/compare_bench/__init__.py b/harness/tests/compare_bench/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/compare_bench/conftest.py b/harness/tests/compare_bench/conftest.py
new file mode 100644
index 00000000..af13079b
--- /dev/null
+++ b/harness/tests/compare_bench/conftest.py
@@ -0,0 +1,142 @@
+"""Fakes for the harness-vs-one-shot bench (no models, no Blender, no Chrome)."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+from PIL import Image
+
+REPO = Path(__file__).resolve().parents[2]
+if str(REPO) not in sys.path:
+ sys.path.insert(0, str(REPO))
+
+from bench._fixed_eval import EvalOutcome # noqa: E402
+from bench._oneshot import MODEL_FILE, OneShotResult # noqa: E402
+from codeverse.contracts.artifacts import ( # noqa: E402
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Measurement,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse.contracts.common import Usage # noqa: E402
+from codeverse.contracts.judgment import Judgment # noqa: E402
+from codeverse.contracts.run import RunRecord, RunStatus # noqa: E402
+from codeverse.contracts.spec import Spec # noqa: E402
+from codeverse.workspace import Workspace # noqa: E402
+
+BATTERY = REPO / "bench" / "prompts" / "compare_v1.yaml"
+GOOD = "import bpy\n# score={score}\nbpy.ops.mesh.primitive_cube_add()\nbpy.context.object.name = 'Body'\n"
+BAD = "import bpy\nraise RuntimeError('BOOM')\n"
+
+
+def _png(path: Path) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.new("RGB", (8, 8), (200, 50, 50)).save(path)
+ return path
+
+
+def _score_of(code: str) -> float:
+ for line in code.splitlines():
+ if line.startswith("# score="):
+ return float(line.split("=", 1)[1])
+ return 0.5
+
+
+class FakeEvaluator:
+ """Builds succeed unless the code raises BOOM; score is read from a ``# score=`` comment."""
+
+ def __init__(self) -> None:
+ self.evaluated: list[str] = []
+ self.builds = 0
+
+ def build(self, ws: Workspace) -> tuple[BuildResult, GateReport]:
+ self.builds += 1
+ code = (ws.root / MODEL_FILE).read_text()
+ lint = GateReport(gate="lint:blender", passed=True)
+ if "BOOM" in code:
+ return BuildResult(ok=False, language="blender", error_type="RuntimeError", error_message="BOOM at line 2",
+ error_file=MODEL_FILE, error_line=2), lint
+ glb = ws.artifacts / "object.glb"
+ glb.parent.mkdir(parents=True, exist_ok=True)
+ glb.write_bytes(b"glb")
+ return BuildResult(ok=True, language="blender", glb_path=str(glb)), lint
+
+ def evaluate(self, ws: Workspace, spec: Spec) -> EvalOutcome:
+ self.evaluated.append(f"{spec.id}")
+ build, lint = self.build(ws)
+ out = EvalOutcome(build=build, lint=lint, gates=[lint])
+ if not build.ok:
+ return out
+ code = (ws.root / MODEL_FILE).read_text()
+ score = _score_of(code)
+ sheet = _png(ws.renders_dir(0) / "sheet.png")
+ view = _png(ws.renders_dir(0) / "view_front.png")
+ out.renders = RenderSet(views=[RenderView(name="front", path=str(view))], contact_sheet=str(sheet))
+ out.measurement = Measurement(bbox_min=(0, 0, 0), bbox_max=(1, 1, 1), extents=(1, 1, 1), center=(0.5, 0.5, 0.5),
+ tri_count=int(score * 1000), n_meshes=1, n_islands=1)
+ gate = GateReport(gate="connectivity", passed=score >= 0.4, findings=[] if score >= 0.4 else [
+ GateFinding(gate="connectivity", severity=Severity.ERROR, target="Body", message="floating part")])
+ out.gates.append(gate)
+ out.judgment = Judgment(rubric="static_object_v1", judge_backend="fake", scores={"intent_fidelity": score},
+ overall=score, passed=score >= 0.72, n_samples=2, usage=Usage(cost_usd=0.01))
+ return out
+
+
+class FakeBackend:
+ """One-shot backend: answers from a script of texts (cycled); records prompts."""
+
+ def __init__(self, answers: list[str], *, tool_calls: int = 0):
+ self.answers = answers
+ self.calls: list[str] = []
+ self.tool_calls = tool_calls
+ self.id = "oneshot:fake"
+
+ def generate(self, prompt: str, *, out_dir: Path, timeout_s: float = 0, label: str = "") -> OneShotResult:
+ self.calls.append(prompt)
+ nth = sum(1 for c in self.calls if c.splitlines()[0] == prompt.splitlines()[0]) # per-prompt attempt no.
+ text = self.answers[min(nth - 1, len(self.answers) - 1)]
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / "response.md").write_text(text)
+ return OneShotResult(ok=bool(text), text=text, usage=Usage(cost_usd=0.02), tool_calls=self.tool_calls,
+ notes="" if text else "empty", duration_s=1.0, transcript_dir=str(out_dir))
+
+
+def fake_run_track(score: float = 0.8):
+ calls: list[str] = []
+
+ def run(spec: Spec, ws: Workspace, resume: bool) -> RunRecord:
+ calls.append(spec.id)
+ ws.src.mkdir(parents=True, exist_ok=True)
+ (ws.root / MODEL_FILE).write_text(GOOD.format(score=score))
+ (ws.src / "parts").mkdir(exist_ok=True)
+ (ws.src / "parts" / "legs.py").write_text("LEGS = 3\n")
+ rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.PASSED, final_score=score - 0.1,
+ total_usage=Usage(cost_usd=0.9, tool_calls=12))
+ ws.write_json(ws.record_path, rec)
+ return rec
+
+ run.calls = calls # type: ignore[attr-defined]
+ return run
+
+
+class FakePairwise:
+ def __init__(self, model_id: str):
+ self.model_id = model_id
+ self.calls = 0
+
+ def compare(self, spec: Spec, ra: RenderSet, rb: RenderSet, *, rubric: Any = None):
+ from codeverse.judges.pairwise import PairwiseResult
+
+ self.calls += 1
+ return PairwiseResult(winner="a", confidence=0.8, reasons=["Candidate A is cleaner"], usage=Usage(cost_usd=0.03))
+
+
+def fake_evaluator() -> FakeEvaluator:
+ return FakeEvaluator()
diff --git a/harness/tests/compare_bench/test_compare_matrix.py b/harness/tests/compare_bench/test_compare_matrix.py
new file mode 100644
index 00000000..18191bb0
--- /dev/null
+++ b/harness/tests/compare_bench/test_compare_matrix.py
@@ -0,0 +1,207 @@
+"""Matrix runner: cells, resume, pairwise arena, report (offline, fakes)."""
+
+from __future__ import annotations
+
+import json
+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 CellResult, PairRow, arm_stats, load_jsonl, pair_stats # noqa: E402
+from bench._fixed_eval import acceptance_from_spec # noqa: E402
+from bench.compare_backends import ( # noqa: E402
+ CompareDeps,
+ CompareOptions,
+ main,
+ parse_arm,
+ parse_arms,
+ run_matrix,
+ spec_for,
+)
+from bench.run_bench import Battery # noqa: E402
+from tests.compare_bench.conftest import ( # noqa: E402
+ BAD,
+ BATTERY,
+ GOOD,
+ FakeBackend,
+ FakeEvaluator,
+ FakePairwise,
+ fake_run_track,
+)
+
+ARMS = "harness:api-agent:gemini:gemini-3.7-flash,oneshot:claude-code,oneshot+repair:codex,oneshot:gemini:gemini-3.7-flash"
+
+
+def test_battery_compare_v1_is_valid():
+ b = Battery.load(BATTERY)
+ assert b.name == "compare_v1" and b.track.value == "static_object" and b.language.value == "blender"
+ assert len(b.prompts) == 8 and len({p.id for p in b.prompts}) == 8
+ assert all(len(p.must_have) >= 3 for p in b.prompts)
+ assert {p.tier for p in b.prompts} == {"easy", "medium", "hard"}
+
+
+def test_parse_arms():
+ arms = parse_arms(ARMS)
+ assert [a.kind for a in arms] == ["harness", "oneshot", "oneshot+repair", "oneshot"]
+ assert arms[0].target == "api-agent:gemini:gemini-3.7-flash" and arms[2].target == "codex"
+ assert arms[2].slug == "oneshot_plus_repair_codex"
+ for bad in ("harness", "foo:bar", "oneshot:gemini-cli:x", "oneshot:nope"):
+ with pytest.raises(ValueError):
+ parse_arm(bad)
+ with pytest.raises(ValueError):
+ parse_arms("oneshot:codex,oneshot:codex")
+
+
+def test_spec_for_and_acceptance():
+ b = Battery.load(BATTERY)
+ opts = CompareOptions(judge="gemini:gemini-3.1-pro-preview", loop_judge="gemini:gemini-3.7-flash")
+ harness = spec_for(b, b.prompts[0], parse_arm("harness:gemini-cli:gemini-3.7-flash"), opts)
+ one = spec_for(b, b.prompts[0], parse_arm("oneshot:codex"), opts)
+ assert harness.backends.generator == "gemini-cli:gemini-3.7-flash" and harness.backends.judge == "gemini:gemini-3.7-flash"
+ assert harness.budget.max_rounds == 3 and harness.budget.max_usd == 2.5
+ assert one.backends.generator == "single-shot:codex" and one.constraints.must_have == b.prompts[0].must_have
+ acc = acceptance_from_spec(one)
+ assert [a.id for a in acc] == ["must_1", "must_2", "must_3"] and all(a.priority == "must" for a in acc)
+
+
+def _deps(ev: FakeEvaluator, backends: dict[str, FakeBackend], run_track) -> CompareDeps:
+ pw = {}
+
+ def _pw(model_id: str):
+ pw.setdefault(model_id, FakePairwise(model_id))
+ return pw[model_id]
+
+ deps = CompareDeps(ev, run_track=run_track, oneshot_backend=lambda t: backends[t], pairwise_judge=_pw)
+ deps.pw = pw # type: ignore[attr-defined]
+ return deps
+
+
+def test_matrix_end_to_end_with_fakes(tmp_path: Path):
+ ev = FakeEvaluator()
+ backends = {
+ "claude-code": FakeBackend(["```python\n" + GOOD.format(score=0.6) + "```"]),
+ "codex": FakeBackend([BAD, BAD, GOOD.format(score=0.75)]), # repair arm: 2 retries fix it
+ "gemini:gemini-3.7-flash": FakeBackend(["I refuse."]), # unparseable → score 0
+ }
+ run_track = fake_run_track(0.9)
+ deps = _deps(ev, backends, run_track)
+ out = tmp_path / "cmp"
+ opts = CompareOptions(judge="gemini:fixed", limit=2, parallel=2, repair_attempts=2)
+ rows = run_matrix(BATTERY, out, parse_arms(ARMS), opts, deps)
+ assert len(rows) == 8 and (out / "matrix.json").is_file()
+ by = {(r.prompt_id, r.arm): r for r in rows}
+ h = by[("cmp_easy_stool", "harness:api-agent:gemini:gemini-3.7-flash")]
+ assert h.status == "scored" and h.score == pytest.approx(0.9) and h.passed and h.build_ok
+ assert h.gen_cost_usd == pytest.approx(0.9) and h.harness_status == "passed" and h.harness_loop_score == pytest.approx(0.8)
+ assert h.judge_cost_usd == pytest.approx(0.01) and h.tris == 900 and Path(h.sheet).is_file()
+ assert (Path(h.workspace) / "run" / "src" / "model.py").is_file() and (Path(h.workspace) / "eval" / "eval.json").is_file()
+ assert (Path(h.workspace) / "eval" / "src" / "parts" / "legs.py").is_file() # whole src/ tree is evaluated
+ c = by[("cmp_easy_stool", "oneshot:claude-code")]
+ assert c.status == "scored" and c.score == pytest.approx(0.6) and c.passed is False and c.attempts == 1
+ assert c.gen_cost_usd == pytest.approx(0.02) and c.kind == "oneshot"
+ x = by[("cmp_easy_stool", "oneshot+repair:codex")]
+ assert x.status == "scored" and x.score == pytest.approx(0.75) and x.attempts == 3 and x.gen_cost_usd == pytest.approx(0.06)
+ g = by[("cmp_easy_stool", "oneshot:gemini:gemini-3.7-flash")]
+ assert g.status == "no_code" and g.score == 0.0 and g.passed is False and not g.build_ok and "unparseable" in g.error
+ # the repair prompts carried the error report
+ repairs = [c for c in backends["codex"].calls if "BUILD FAILED" in c]
+ assert len(repairs) == 4 and all("BOOM" in c and "PREVIOUS `src/model.py`" in c for c in repairs)
+ # the fixed evaluator ran once per cell that had code (6 of 8)
+ assert len(ev.evaluated) == 6
+ # pairwise: 1 harness arm × 3 one-shot arms × 2 prompts = 6 rows; the no-code arm is auto-decided
+ pairs = load_jsonl(out / "pairwise.jsonl", PairRow)
+ assert len(pairs) == 6
+ auto = [p for p in pairs if p.arm_b == "oneshot:gemini:gemini-3.7-flash"]
+ assert all(p.winner == "a" and not p.judged for p in auto)
+ judged = [p for p in pairs if p.judged]
+ assert len(judged) == 4 and all(p.winner == "a" and p.cost_usd == pytest.approx(0.03) for p in judged)
+ assert deps.pw["gemini:fixed"].calls == 4
+ # report
+ md = (out / "report.md").read_text()
+ assert "fixed judge: **gemini:fixed**" in md and "| harness:api-agent:gemini:gemini-3.7-flash | harness | 2 | 0.900 |" in md
+ assert "| cmp_easy_stool | easy | 0.90✓ | 0.60 | 0.75✓ | 0.00 ✗build |" in md
+ assert "| harness:api-agent:gemini:gemini-3.7-flash | oneshot:claude-code | 2 | 2 | 0 | 0 | 100% |" in md
+ page = (out / "report.html").read_text()
+ assert "report_assets/cmp_easy_stool__harness_api-agent_gemini_gemini-3.7-flash.png" in page
+ assert len(list((out / "report_assets").glob("*.png"))) == 6
+
+ # ---- resume: nothing re-runs, nothing re-judged, results identical
+ run_track2 = fake_run_track(0.1)
+ deps2 = _deps(FakeEvaluator(), {k: FakeBackend(["x"]) for k in backends}, run_track2)
+ rows2 = run_matrix(BATTERY, out, parse_arms(ARMS), opts, deps2)
+ assert len(rows2) == 8 and not run_track2.calls and deps2.evaluator.evaluated == [] and not deps2.pw
+ assert {(r.prompt_id, r.arm): r.score for r in rows2} == {(r.prompt_id, r.arm): r.score for r in rows}
+ # ---- adding a prompt (limit 3) only runs the new cells
+ rows3 = run_matrix(BATTERY, out, parse_arms(ARMS), opts.model_copy(update={"limit": 3}), deps2)
+ assert len(rows3) == 12 and run_track2.calls == ["compare_v1/cmp_med_dining_chair"]
+ assert len(load_jsonl(out / "pairwise.jsonl", PairRow)) == 9
+
+
+def test_cell_errors_are_recorded_not_raised(tmp_path: Path):
+ class Exploding:
+ def build(self, ws):
+ raise RuntimeError("blender missing")
+
+ def evaluate(self, ws, spec):
+ raise RuntimeError("blender missing")
+
+ def failing_track(spec, ws, resume):
+ raise RuntimeError("planner down")
+
+ deps = CompareDeps(Exploding(), run_track=failing_track, oneshot_backend=lambda t: FakeBackend([GOOD.format(score=0.5)]),
+ pairwise_judge=FakePairwise)
+ rows = run_matrix(BATTERY, tmp_path / "o", parse_arms("harness:api-agent:gemini:x,oneshot:codex"),
+ CompareOptions(limit=1, parallel=1), deps)
+ by = {r.arm: r for r in rows}
+ assert by["harness:api-agent:gemini:x"].status == "error" and "planner down" in by["harness:api-agent:gemini:x"].error
+ assert by["oneshot:codex"].status == "error" and "blender missing" in by["oneshot:codex"].error
+ assert (tmp_path / "o" / "report.md").is_file()
+
+
+def test_stats_math():
+ rows = [CellResult(prompt_id="p1", arm="a", kind="harness", score=0.8, passed=True, build_ok=True, gen_cost_usd=1.0, wall_s=60),
+ CellResult(prompt_id="p2", arm="a", kind="harness", score=0.0, passed=False, build_ok=False, gen_cost_usd=0.5, wall_s=120),
+ CellResult(prompt_id="p1", arm="b", kind="oneshot", score=None, status="judge_error", build_ok=True)]
+ s = {x.arm: x for x in arm_stats(rows)}
+ assert s["a"].mean_score == pytest.approx(0.4) and s["a"].pass_rate == 0.5 and s["a"].build_ok_rate == 0.5
+ assert s["a"].mean_gen_usd == 0.75 and s["a"].mean_minutes == 1.5
+ assert s["b"].mean_score is None and s["b"].errors == 1
+ ps = pair_stats([PairRow(prompt_id="p1", arm_a="a", arm_b="b", winner="a", confidence=0.9),
+ PairRow(prompt_id="p2", arm_a="a", arm_b="b", winner="tie", confidence=0.3),
+ PairRow(prompt_id="p3", arm_a="a", arm_b="b", winner="b", confidence=0.6)])[0]
+ assert (ps.wins_a, ps.wins_b, ps.ties, ps.win_rate_a) == (1, 1, 1, 0.5) and ps.mean_confidence == pytest.approx(0.6)
+
+
+def test_cli_report_only(tmp_path: Path):
+ out = tmp_path / "o"
+ out.mkdir()
+ (out / "results.jsonl").write_text(CellResult(prompt_id="p", arm="oneshot:codex", kind="oneshot", score=0.3,
+ build_ok=True, status="scored").model_dump_json() + "\n")
+ assert main(["--prompts", str(BATTERY), "--arms", "oneshot:codex", "--out", str(out), "--report-only"]) == 0
+ assert "oneshot:codex" in (out / "report.md").read_text()
+ assert json.loads((out / "results.jsonl").read_text().splitlines()[0])["score"] == 0.3
+
+
+def test_redo_status_reuses_recorded_answers(tmp_path: Path):
+ """A redo of failed cells re-evaluates without a second generation call; a failed generation is not cached."""
+ ev = FakeEvaluator()
+ be = FakeBackend([BAD])
+ deps = CompareDeps(ev, run_track=fake_run_track(), oneshot_backend=lambda t: be, pairwise_judge=FakePairwise)
+ out = tmp_path / "o"
+ opts = CompareOptions(limit=1, parallel=1, pairwise=False)
+ rows = run_matrix(BATTERY, out, parse_arms("oneshot:codex"), opts, deps)
+ assert rows[0].status == "build_failed" and len(be.calls) == 1
+ assert (out / "cells" / "cmp_easy_stool" / "oneshot_codex" / "gen" / "attempt0" / "result.json").is_file()
+ rows2 = run_matrix(BATTERY, out, parse_arms("oneshot:codex"), opts.model_copy(update={"redo_status": ["build_failed"]}), deps)
+ assert rows2[0].status == "build_failed" and len(be.calls) == 1 and len(ev.evaluated) == 2 # re-evaluated, not re-generated
+ empty = FakeBackend([""])
+ deps3 = CompareDeps(ev, run_track=fake_run_track(), oneshot_backend=lambda t: empty, pairwise_judge=FakePairwise)
+ rows3 = run_matrix(BATTERY, out, parse_arms("oneshot:claude-code"), opts, deps3)
+ r3 = next(r for r in rows3 if r.arm == "oneshot:claude-code")
+ assert r3.status == "no_code" and "empty" in r3.error
+ assert not (out / "cells" / "cmp_easy_stool" / "oneshot_claude-code" / "gen" / "attempt0" / "result.json").exists()
diff --git a/harness/tests/compare_bench/test_live_compare.py b/harness/tests/compare_bench/test_live_compare.py
new file mode 100644
index 00000000..3f8fb932
--- /dev/null
+++ b/harness/tests/compare_bench/test_live_compare.py
@@ -0,0 +1,33 @@
+"""Live smoke: one prompt, one API one-shot arm, flash judge (cheap; needs keys + Blender + node)."""
+
+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._fixed_eval import FixedEvaluator # noqa: E402
+from bench.compare_backends import CompareDeps, CompareOptions, parse_arms, run_matrix # noqa: E402
+from codeverse.config import get_settings # noqa: E402
+
+pytestmark = [pytest.mark.live, pytest.mark.blender, pytest.mark.node]
+
+
[email protected](not get_settings().gemini_api_keys, reason="no gemini keys")
+def test_oneshot_gemini_cell_scores(tmp_path: Path):
+ opts = CompareOptions(judge="gemini:gemini-3.7-flash", n_samples=1, limit=1, parallel=1, pairwise=False)
+ deps = CompareDeps(FixedEvaluator(opts.judge, n_samples=1))
+ rows = run_matrix(REPO / "bench" / "prompts" / "compare_v1.yaml", tmp_path / "o",
+ parse_arms("oneshot:gemini:gemini-3.7-flash"), opts, deps)
+ assert len(rows) == 1
+ r = rows[0]
+ assert r.status in ("scored", "build_failed"), r.error
+ assert r.gen_cost_usd > 0 and r.attempts == 1 and r.tool_calls == 0
+ if r.status == "scored":
+ assert r.build_ok and 0.0 <= (r.score or 0) <= 1.0 and Path(r.sheet).is_file() and r.tris
+ assert (tmp_path / "o" / "report.md").is_file() and (tmp_path / "o" / "report.html").is_file()
diff --git a/harness/tests/compare_bench/test_oneshot.py b/harness/tests/compare_bench/test_oneshot.py
new file mode 100644
index 00000000..84fb70b7
--- /dev/null
+++ b/harness/tests/compare_bench/test_oneshot.py
@@ -0,0 +1,126 @@
+"""One-shot helpers: prompt, answer parsing, CLI argv, registry (offline)."""
+
+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._oneshot import ( # noqa: E402
+ MODEL_FILE,
+ ApiOneShot,
+ ClaudeOneShot,
+ CodexOneShot,
+ extract_model_file,
+ get_oneshot_backend,
+ minimal_contract,
+ oneshot_prompt,
+ repair_prompt,
+ write_model_file,
+)
+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
+
+
+def _spec() -> Spec:
+ return Spec(id="t/stool", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a three-legged stool",
+ constraints=Constraints(must_have=["round seat", "three legs"], dimensions_m={"height": 0.45}))
+
+
+def test_prompt_is_brief_plus_minimal_contract_only():
+ p = oneshot_prompt(_spec())
+ assert "a three-legged stool" in p and "MUST HAVE: round seat" in p and "height=0.45" in p
+ assert MODEL_FILE in p and "Z is UP" in p and "meters" in p and "bpy.ops.export_*" in p
+ # no harness help: no cookbook snippets, no plan table, no tool cards
+ assert "cookbook" not in p.lower() and "bmesh.ops.create_cone" not in p and "| part |" not in p
+ assert minimal_contract() in p and p.rstrip().endswith("no partial snippets).")
+
+
+def test_repair_prompt_carries_error_and_previous_code():
+ build = BuildResult(ok=False, language="blender", error_type="NameError", error_message="name 'foo' is not defined",
+ error_file=MODEL_FILE, error_line=7)
+ p = repair_prompt(_spec(), "import bpy\nfoo()\n", build, GateReport(gate="lint:blender", passed=True), attempt=1)
+ assert "BUILD FAILED" in p and "NameError" in p and "foo()" in p and "previous attempt (1)" in p
+
+
+ "```python\nimport bpy\nprint(1)\n```",
+ "Here you go:\n```python\nimport bpy\nprint(1)\n```\nDone.",
+ "=== FILE: src/model.py ===\nimport bpy\nprint(1)\n=== END FILE ===",
+ "import bpy\nprint(1)\n",
+])
+def test_extract_model_file_tolerant(text: str):
+ assert extract_model_file(text) == "import bpy\nprint(1)\n"
+
+
+def test_extract_model_file_rejects_prose():
+ with pytest.raises(MultiFileParseError):
+ extract_model_file("Sorry, I cannot do that.")
+
+
+def test_write_model_file(tmp_ws):
+ p = write_model_file(tmp_ws, "```python\nimport bpy\n```")
+ assert p == tmp_ws.root / MODEL_FILE and p.read_text() == "import bpy\n"
+
+
+def test_claude_argv_disables_tools_and_is_single_turn():
+ argv = ClaudeOneShot("", binary="claude").argv("PROMPT")
+ assert argv[:3] == ["claude", "-p", "PROMPT"]
+ assert argv[argv.index("--tools") + 1] == "" and argv[argv.index("--max-turns") + 1] == "1"
+ assert "--strict-mcp-config" in argv and "--no-session-persistence" in argv and "--model" not in argv
+ assert "--mcp-config" not in argv and "--dangerously-skip-permissions" not in argv
+ argv_m = ClaudeOneShot("opus", binary="claude").argv("x")
+ assert argv_m[argv_m.index("--model") + 1] == "opus"
+
+
+def test_codex_argv_is_read_only_and_reads_prompt_from_stdin(tmp_path: Path):
+ argv = CodexOneShot("", binary="codex").argv(tmp_path, tmp_path / "last.md")
+ assert argv[:3] == ["codex", "exec", "--json"]
+ assert argv[argv.index("--sandbox") + 1] == "read-only" and argv[-1] == "-"
+ assert "--ephemeral" in argv and "-o" in argv and "mcp_servers" not in " ".join(argv)
+
+
+def test_registry():
+ assert isinstance(get_oneshot_backend("claude-code"), ClaudeOneShot)
+ assert get_oneshot_backend("claude-code:sonnet").model == "sonnet"
+ assert isinstance(get_oneshot_backend("codex"), CodexOneShot)
+ api = get_oneshot_backend("gemini:gemini-3.7-flash")
+ assert isinstance(api, ApiOneShot) and api.id == "oneshot:gemini:gemini-3.7-flash"
+ for bad in ("gemini", "gemini-cli:x", "", "anthropic:"):
+ with pytest.raises(ValueError):
+ get_oneshot_backend(bad)
+
+
+def test_api_oneshot_uses_injected_chat_model(tmp_path: Path):
+ class M:
+ def generate(self, req):
+ from codeverse.contracts.chat import ChatResponse
+ from codeverse.contracts.common import Usage
+
+ assert req.max_output_tokens == 32000 and "stool" in req.messages[0].text
+ return ChatResponse(text="```python\nimport bpy\n```", usage=Usage(cost_usd=0.004))
+
+ r = ApiOneShot("gemini:x", chat_model=M()).generate(oneshot_prompt(_spec()), out_dir=tmp_path / "g")
+ assert r.ok and r.usage.cost_usd == 0.004 and (tmp_path / "g" / "response.md").is_file() and r.tool_calls == 0
+
+
+def test_api_oneshot_model_error_is_recorded(tmp_path: Path):
+ class Boom:
+ def generate(self, req):
+ raise RuntimeError("quota")
+
+ r = ApiOneShot("gemini:x", chat_model=Boom()).generate("p", out_dir=tmp_path / "g")
+ assert not r.ok and "quota" in r.notes
+
+
+def test_extract_model_file_from_hallucinated_write_tool_xml():
+ text = ('<invoke name="Write">\n<parameter name="file_path">/tmp/x/src/model.py</parameter>\n'
+ '<parameter name="content">import bpy\nprint(2)\n</parameter>\n</invoke>\n\nsyntax ok\n')
+ assert extract_model_file(text) == "import bpy\nprint(2)\n"
diff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.py
index 1a2dd040..e6fb58c5 100644
--- a/harness/tests/flywheel_cli/conftest.py
+++ b/harness/tests/flywheel_cli/conftest.py
@@ -56,11 +56,13 @@ def make_fake_run(
) -> tuple[Workspace, RunRecord]:
ws = Workspace(runs_dir / slug).create()
track = Track.SCENE if language is Language.SCENE_THREEJS else (
- Track.ARTICULATED_OBJECT if language is Language.URDF_BLENDER else Track.STATIC_OBJECT)
+ Track.ARTICULATED_OBJECT if language is Language.URDF_BLENDER else (
+ Track.GRAPHICS if language in (Language.GLSL_SHADER, Language.OPENGL_PYTHON) else Track.STATIC_OBJECT))
spec = Spec(id=slug, track=track, language=language, prompt=prompt, backends=Backends(generator=generator))
ws.write_json(ws.spec_path, spec)
entry = {"blender": "src/model.py", "cadquery": "src/model.py", "urdf_blender": "src/model.py",
- "threejs": "src/object.js", "scene_threejs": "src/scene.js"}[language.value]
+ "threejs": "src/object.js", "scene_threejs": "src/scene.js",
+ "glsl_shader": "src/shader.frag", "opengl_python": "src/program.py"}[language.value]
e = ws.root / entry
e.parent.mkdir(parents=True, exist_ok=True)
e.write_text("# round 0\nimport bpy # comment\n\nbpy.ops.mesh.primitive_cube_add(size=1.0)\n")
diff --git a/harness/tests/flywheel_cli/test_bench.py b/harness/tests/flywheel_cli/test_bench.py
index a6e8f093..2f37e6ce 100644
--- a/harness/tests/flywheel_cli/test_bench.py
+++ b/harness/tests/flywheel_cli/test_bench.py
@@ -30,7 +30,8 @@ def test_batteries_are_valid(path: Path):
assert tiers <= {"easy", "medium", "hard"} and len(tiers) == 3
assert all(p.must_have for p in b.prompts)
expected = {"static_objects_v1": 24, "articulated_v1": 12, "scenes_v1": 12}
- assert len(b.prompts) == expected[b.name]
+ if b.name in expected: # other batteries (e.g. compare_v1) are owned elsewhere; only the schema is checked
+ assert len(b.prompts) == expected[b.name]
def _fake_run_fn(scores_by_id: dict[str, tuple[float, float]], fail_ids: set[str] = frozenset()):
@@ -78,4 +79,6 @@ def test_run_battery_resume_and_report(tmp_path: Path):
assert tiers["easy"].n == 2 and tiers["easy"].final_mean == pytest.approx(0.85) # toy car errored → unscored
assert rep.overall is not None and rep.overall.errors == 1
assert "| furn_easy_stool | easy |" in rep.markdown
- assert (out / "report_assets").is_dir() and any((out / "report_assets").iterdir())
+ page = (out / "report.html").read_text()
+ assert "data:image/jpeg;base64," in page and "furn_easy_stool" in page # self-contained gallery
+ assert "veh_easy_toy_car" in page and "boom" in page # errored prompt still gets a card
diff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.py
index 6502c918..ee2982ca 100644
--- a/harness/tests/flywheel_cli/test_captions.py
+++ b/harness/tests/flywheel_cli/test_captions.py
@@ -85,3 +85,80 @@ def test_caption_live_gemini(fake_run):
ws, rec = fake_run
caps = caption_sample(ws, rec, "gemini:gemini-3.7-flash")
assert len(caps.detailed) > 20 and "blender" in caps.instruction.lower()
+
+
+# --------------------------------------------------------------------------- finding: Three.js phrase vs forbidden THREE.
+GOOD_JS = {
+ "detailed": "A desk lamp with a round base, an arched arm and a conical shade.",
+ "instruction": "Write a Three.js module that builds a desk lamp with a round base and conical shade.",
+ "factory": "Build the base cylinder, sweep the arm along an arc, add the cone shade, then merge the groups.",
+}
+
+
+def test_threejs_instruction_naming_threejs_is_valid():
+ """The required 'Three.js' phrase must NOT trip the forbidden-API check (both js languages)."""
+ from codeverse.contracts.common import Language
+ from codeverse.flywheel.captions import Captions, validate_captions
+
+ c = Captions(**GOOD_JS)
+ assert validate_captions(c, Language.THREEJS) == []
+ assert validate_captions(c, Language.SCENE_THREEJS) == []
+ # the API namespace itself stays forbidden (case-sensitive THREE.<Symbol>)
+ bad = Captions(**dict(GOOD_JS, factory="Build a THREE.Group holding THREE.Mesh boxes for every part."))
+ probs = validate_captions(bad, Language.THREEJS)
+ assert probs and "THREE." in probs[0]
+ # and omitting the platform name still fails the phrase check
+ off = Captions(**dict(GOOD_JS, instruction="Write a module that builds a desk lamp with a round base."))
+ assert any("target language" in p for p in validate_captions(off, Language.THREEJS))
+
+
+def test_caption_sample_threejs_run(tmp_path):
+ """End to end: a threejs run captions successfully with a 'Three.js' instruction."""
+ from codeverse.contracts.common import Language
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ ws, rec = make_fake_run(tmp_path / "runs", "lamp_js", prompt="a desk lamp", language=Language.THREEJS)
+ m = FakeModel([GOOD_JS])
+ caps = caption_sample(ws, rec, "fake:fake", model=m)
+ assert "Three.js" in caps.instruction and len(m.requests) == 1 # no retry needed
+
+
+def test_caption_graphics_and_scene_phrases():
+ """Graphics languages have phrases + phrase words (no KeyError, sane rules)."""
+ from codeverse.contracts.common import Language
+ from codeverse.flywheel.captions import Captions, validate_captions
+
+ shader = Captions(
+ detailed="Neon rain streaks down a dark window while blurred city lights pulse behind the glass.",
+ instruction="Write a GLSL fragment shader showing neon rain running down a window at night.",
+ factory="Layer a bokeh background pass, a grid-cell rain pass with per-cell offsets, then grade with a vignette.",
+ )
+ assert validate_captions(shader, Language.GLSL_SHADER) == []
+ assert any("target language" in p
+ for p in validate_captions(shader.model_copy(update={"instruction": "Write a shader with rain."}),
+ Language.GLSL_SHADER))
+ gl = shader.model_copy(update={"instruction": "Write an OpenGL Python program showing neon rain on a window."})
+ assert validate_captions(gl, Language.OPENGL_PYTHON) == []
+ leaked = shader.model_copy(update={"factory": "Uses moderngl FBOs for the feedback pass."})
+ assert any("moderngl" in p for p in validate_captions(leaked, Language.OPENGL_PYTHON))
+
+
+def test_caption_graphics_run_from_frames(tmp_path):
+ """(f) graphics runs (no GLB) caption from the sheet/frames renders."""
+ from codeverse.contracts.common import Language
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ ws, rec = make_fake_run(tmp_path / "runs", "rain_glsl", prompt="neon rain", language=Language.GLSL_SHADER)
+ reply = {
+ "detailed": "Bright neon streaks slide down a dark pane while soft coloured discs drift behind it.",
+ "instruction": "Write a GLSL fragment shader with neon rain streaking down a dark window.",
+ "factory": "Hash-place bokeh discs in three depth layers, add per-cell rain trails, then tonemap and vignette.",
+ }
+ m = FakeModel([reply])
+ caps = caption_sample(ws, rec, "fake:fake", model=m)
+ assert caps.instruction.lower().count("glsl")
+ req = m.requests[0]
+ from codeverse.contracts.chat import ImagePart as IP
+
+ imgs = [p for p in req.messages[0].parts if isinstance(p, IP)]
+ assert len(imgs) == 3 # sheet + 2 frame views
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index 8112ccf5..7485e6e3 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -19,7 +19,7 @@ def test_help_and_version():
r = runner.invoke(app, ["--help"])
assert r.exit_code == 0 and "flywheel" in r.output and "doctor" in r.output
r = runner.invoke(app, ["--version"])
- assert r.exit_code == 0 and "c3v" in r.output
+ assert r.exit_code == 0 and "3dcv" in r.output
def test_make_no_run_creates_valid_workspace(tmp_path: Path):
@@ -51,6 +51,7 @@ def test_status_on_fake_run(runs_dir: Path):
r = runner.invoke(app, ["status", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir)])
assert r.exit_code == 0, r.output
assert "passed" in r.output and "0.800" in r.output and "rounds" in r.output
+ assert "1*" in r.output # best round marked
r = runner.invoke(app, ["status", "nope", "--runs-dir", str(runs_dir)])
assert r.exit_code == 1
@@ -66,6 +67,9 @@ def test_flywheel_commands(runs_dir: Path, tmp_path: Path):
assert r.exit_code == 0 and "indexed 3 runs" in r.output
r = runner.invoke(app, ["flywheel", "dedupe", str(out), "--no-mesh"])
assert r.exit_code == 0 and "3 samples" in r.output
+ r = runner.invoke(app, ["flywheel", "gallery", str(runs_dir), str(tmp_path / "g.html"), "--title", "batch 1"])
+ assert r.exit_code == 0 and "gallery of 3 runs" in r.output, r.output
+ assert "batch 1" in (tmp_path / "g.html").read_text()
def test_tools_list_and_unknown(tmp_path: Path):
@@ -86,3 +90,153 @@ def test_doctor_json(tmp_path: Path):
rows = json.loads(r.output[r.output.index("["):])
checks = {row["check"] for row in rows}
assert {"python", "python deps", "blender", "node", "three", "gemini keys", "git", "mcp"} <= checks
+
+
+# --------------------------------------------------------------------------- finding: `3dcv judge` inputs (main.py:204)
+class _FakeVlm:
+ captured: dict = {}
+
+ def __init__(self, *, rubric=None, model_id=None, n_samples=1, **kw):
+ _FakeVlm.captured["rubric"] = rubric
+ _FakeVlm.captured["n_samples"] = n_samples
+
+ def judge(self, inp):
+ from tests.flywheel_cli.conftest import _judgment
+
+ _FakeVlm.captured["inp"] = inp
+ return _judgment(0.7, False, ["polish"])
+
+
+def _write_stool_plan(ws):
+ from codeverse.contracts.plan import AcceptanceItem, BBox, PartPlan, StaticPlan
+
+ plan = StaticPlan(object_name="Chair", summary="a chair", overall_bbox=BBox(center=(0, 0, 0.4), extents=(0.5, 0.5, 0.8)),
+ parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.4), extents=(0.4, 0.4, 0.04)))],
+ acceptance=[AcceptanceItem(id="a1", text="four legs", how="visual", priority="must")])
+ ws.write_json(ws.plan_path, plan)
+
+
+def test_judge_rejudges_with_in_run_inputs(runs_dir: Path, monkeypatch):
+ import codeverse.judges.vlm_judge as vj
+ from codeverse.workspace import Workspace
+ from tests.flywheel_cli.conftest import tiny_png
+
+ ws = Workspace(runs_dir / "wooden_chair_ab12cd34")
+ _write_stool_plan(ws)
+ tiny_png(ws.renders_dir(1) / "clay" / "view_top.png", (128, 128, 128))
+ monkeypatch.setattr(vj, "VlmJudge", _FakeVlm)
+ _FakeVlm.captured.clear()
+ r = runner.invoke(app, ["judge", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir)])
+ assert r.exit_code == 0, r.output
+ inp = _FakeVlm.captured["inp"]
+ assert _FakeVlm.captured["rubric"] == "static_object_v1" # the rubric the round was judged with
+ assert inp.round_index == 1 # best round
+ assert "Chair" in inp.plan_summary # plan digest, not empty
+ assert [a.id for a in inp.acceptance] == ["a1"]
+ assert inp.previous is not None and inp.previous.overall == 0.55 # round 0's verdict
+ assert inp.gates and inp.renders.views
+ assert inp.geometry_views is not None and inp.geometry_views.views[0].mode == "clay"
+ assert (ws.artifacts / "judge" / "r01_cli.json").is_file()
+ assert "prompt images" in r.output
+
+
+def test_judge_uses_reference_judge_for_measured_rubrics(runs_dir: Path, monkeypatch):
+ import codeverse.judges.reference as ref
+
+ class _FakeRef(_FakeVlm):
+ pass
+
+ monkeypatch.setattr(ref, "ReferenceJudge", _FakeRef)
+ _FakeRef.captured.clear()
+ r = runner.invoke(app, ["judge", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir),
+ "--rubric", "reference_v1"])
+ assert r.exit_code == 0, r.output # no ValueError traceback any more
+ assert _FakeRef.captured["rubric"] == "reference_v1"
+
+
+def test_judge_wraps_value_error_as_cli_error(runs_dir: Path, monkeypatch):
+ import codeverse.judges.vlm_judge as vj
+
+ class _Boom(_FakeVlm):
+ def judge(self, inp):
+ raise ValueError("rubric has measured criteria but VlmJudge computes none")
+
+ monkeypatch.setattr(vj, "VlmJudge", _Boom)
+ r = runner.invoke(app, ["judge", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir)])
+ assert r.exit_code == 1
+ out = r.output + str(getattr(r, "stderr", "") or "")
+ assert "judge failed" in out and "Traceback" not in r.output
+
+
+def test_judge_rubric_map_includes_graphics():
+ from codeverse.cli._judge import TRACK_RUBRIC, rubric_for
+ from codeverse.contracts.common import Track
+ from codeverse.contracts.run import RoundRecord
+
+ assert TRACK_RUBRIC[Track.GRAPHICS] == "shader_v1"
+
+ class _R: # minimal record stub
+ class spec:
+ track = Track.GRAPHICS
+
+ rnd = RoundRecord(index=0, kind="baseline")
+ assert rubric_for(_R, rnd, None) == "shader_v1"
+ assert rubric_for(_R, rnd, "asset_v1") == "asset_v1"
+
+
+# --------------------------------------------------------------------------- make --texture / status extras / render graphics
+def test_make_texture_flag_adds_tag(tmp_path: Path):
+ runs = tmp_path / "runs"
+ r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--texture"])
+ assert r.exit_code == 0, r.output
+ ws = next(d for d in runs.iterdir() if d.is_dir())
+ spec = Spec.model_validate_json((ws / "spec.json").read_text())
+ assert "texture" in spec.tags
+
+
+def test_status_shows_candidates_and_texturing(runs_dir: Path):
+ import json as _json
+
+ from codeverse.workspace import Workspace
+
+ ws = Workspace(runs_dir / "wooden_chair_ab12cd34")
+ (ws.root / "rounds").mkdir(exist_ok=True)
+ (ws.root / "rounds" / "candidates.json").write_text(_json.dumps({
+ "n": 2, "selected": 1,
+ "candidates": [{"index": 0, "label": "c0", "score": 0.51, "build_ok": True},
+ {"index": 1, "label": "c1", "score": 0.63, "build_ok": True}],
+ "pairwise": {"a": "c0", "b": "c1", "winner": "b", "confidence": 0.8}}))
+ rec = _json.loads(ws.record_path.read_text())
+ rec.setdefault("extra", {})["texturing"] = {"shipped": True, "delta": 0.01, "reason": "", "n_textures": 3,
+ "glb_textured": "artifacts/object_textured.glb"}
+ ws.record_path.write_text(_json.dumps(rec))
+ r = runner.invoke(app, ["status", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir)])
+ assert r.exit_code == 0, r.output
+ assert "candidates" in r.output and "c1" in r.output and "pairwise" in r.output
+ assert "texturing" in r.output and "shipped" in r.output
+
+
+def test_render_graphics_regenerates_frames(tmp_path: Path, monkeypatch):
+ import codeverse.languages as langs
+ from codeverse.contracts.artifacts import BuildResult
+ from codeverse.contracts.common import Language
+ from tests.flywheel_cli.conftest import make_fake_run, tiny_png
+
+ ws, rec = make_fake_run(tmp_path / "runs", "rain_glsl", prompt="neon rain", language=Language.GLSL_SHADER)
+ frames = ws.artifacts / "frames"
+ tiny_png(frames / "f00_t0.00.png")
+ tiny_png(frames / "f01_t1.00.png")
+ sheet = tiny_png(ws.artifacts / "frames_sheet.png", (0, 0, 200))
+
+ class _RT:
+ def build(self, w, **kw):
+ return BuildResult(ok=True, language="glsl_shader", glb_path=None, duration_ms=8,
+ census={"renderer": "fake-gl"},
+ extra_paths={"frames": str(frames), "sheet": str(sheet)})
+
+ monkeypatch.setattr(langs, "get_runtime", lambda language: _RT())
+ out = tmp_path / "out"
+ r = runner.invoke(app, ["render", "rain_glsl", "--runs-dir", str(tmp_path / "runs"), "--out", str(out)])
+ assert r.exit_code == 0, r.output
+ assert (out / "sheet.png").is_file() and len(list(out.glob("f*.png"))) == 2
+ assert "fake-gl" in r.output
diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.py
index 70ab1acd..bd91c48e 100644
--- a/harness/tests/flywheel_cli/test_flywheel.py
+++ b/harness/tests/flywheel_cli/test_flywheel.py
@@ -228,3 +228,144 @@ def test_build_index_and_queries(runs_dir: Path, tmp_path: Path):
assert top_runs(db, 1)[0]["slug"] == "wooden_chair_ab12cd34"
assert [r["score"] for r in round_curve(db, "wooden_chair_ab12cd34")] == [0.55, 0.80]
assert isinstance(load_record(Workspace(runs_dir / "lamp_three")), RunRecord)
+
+
+# --------------------------------------------------------------------------- finding: repair pairs (pairs.py:115)
+def test_repair_pairs_match_structurally_not_by_kind(tmp_path: Path):
+ """Lifecycle labels the fixing round 'refine' — repair pairs must not need kind='repair'."""
+ from codeverse.flywheel.pairs import repair_pairs
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ ws, rec = make_fake_run(tmp_path / "runs", with_repair=True)
+ fixing = rec.rounds[-1]
+ assert fixing.kind == "repair" # fixture legacy label
+ fixing.kind = "refine" # what the tracks actually emit
+ pairs = repair_pairs(ws, rec)
+ assert len(pairs) == 1
+ p = pairs[0]
+ assert p["kind"] == "repair" and p["source"] == "round"
+ assert p["rejected"]["build_ok"] is False and p["chosen"]["build_ok"] is True
+ assert p["error"]["type"] == "SyntaxError"
+ assert "size=3.0" in p["chosen"]["files"]["src/model.py"]
+
+
+def test_in_round_repair_pairs_from_generated_commit(tmp_path: Path):
+ """build_with_repair fixes inside one round: generated commit → final commit."""
+ import json as _json
+
+ from codeverse.flywheel.pairs import in_round_repair_pairs
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ ws, rec = make_fake_run(tmp_path / "runs")
+ entry = ws.src / "model.py"
+ entry.write_text("import bpy\nbpy.ops.mesh.primitive_cube_add(size=\n") # as generated (broken)
+ gen = ws.commit("r01 refine: generated")
+ entry.write_text("import bpy\nbpy.ops.mesh.primitive_cube_add(size=2.0)\n") # after in-round repair
+ fin = ws.commit("r01 refine")
+ rnd = rec.rounds[1]
+ rnd.commit = fin
+ rnd.notes = "repair attempts: 1 (fixed)"
+ with ws.events_path.open("a") as fh:
+ fh.write(_json.dumps({"t": 1.0, "event": "build.done", "round": 1, "ok": False,
+ "error": "SyntaxError: unexpected EOF"}) + "\n")
+ fh.write(_json.dumps({"t": 2.0, "event": "build.done", "round": 1, "ok": True, "error": ""}) + "\n")
+ pairs = in_round_repair_pairs(ws, rec)
+ assert len(pairs) == 1
+ p = pairs[0]
+ assert p["source"] == "in_round" and p["rejected"]["commit"] == gen
+ assert "size=\n" in p["rejected"]["files"]["src/model.py"]
+ assert "size=2.0" in p["chosen"]["files"]["src/model.py"]
+ assert p["error"]["message"] == "SyntaxError: unexpected EOF"
+ # a round whose repair loop never fixed anything yields no pair
+ rnd.notes = "repair attempts: 2 (still failing)"
+ assert in_round_repair_pairs(ws, rec) == []
+
+
+# --------------------------------------------------------------------------- finding: degraded judgments (pairs.py:75)
+def _degrade(judgment):
+ return judgment.model_copy(update={"overall": 0.0, "passed": False, "summary": "judge_error: 429 on all samples",
+ "scores": {k: 0.0 for k in judgment.scores}})
+
+
+def test_degraded_round_is_not_a_zero_score(tmp_path: Path):
+ from codeverse.flywheel.pairs import preference_pairs
+ from codeverse.flywheel.record import effective_judgment, effective_score, round_summary
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ ws, rec = make_fake_run(tmp_path / "runs", scores=(0.62, 0.64))
+ # splice a degraded round between the two judged ones (own commit)
+ (ws.src / "noise.py").write_text("x = 1\n")
+ degraded_commit = ws.commit("degraded round")
+ mid = rec.rounds[1].model_copy(update={"index": 1, "commit": degraded_commit,
+ "judgment": _degrade(rec.rounds[1].judgment)})
+ last = rec.rounds[1].model_copy(update={"index": 2})
+ rec.rounds = [rec.rounds[0], mid, last]
+ rec.best_round = None
+ assert effective_judgment(mid) is None and effective_score(mid) is None
+ assert round_summary(mid)["score"] is None and round_summary(mid)["judge_degraded"] is True
+ assert best_round_index(rec) == 2 # 0.64 beats 0.62; the degraded 0.0 never competes
+ pairs = preference_pairs(ws, rec, min_delta=0.05)
+ # old behaviour: chosen=r2 rejected=r1(degraded) with delta 0.64 — a pure noise pair
+ assert pairs == []
+ pairs = preference_pairs(ws, rec, min_delta=0.01)
+ assert len(pairs) == 1 and pairs[0]["rejected"]["round"] == 0 and pairs[0]["chosen"]["round"] == 2
+
+
+def test_degraded_best_round_exports_unscored(tmp_path: Path):
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ ws, rec = make_fake_run(tmp_path / "runs", scores=(0.5, 0.9))
+ for r in rec.rounds:
+ if r.judgment is not None:
+ r.judgment = _degrade(r.judgment)
+ rec.best_round = 1
+ rec.baseline_score = rec.final_score = None
+ ws.write_json(ws.record_path, rec)
+ out = tmp_path / "ds"
+ rep = export_samples(ws.root.parent, out)
+ assert rep.n_exported == 1
+ meta = json.loads(next(out.rglob("meta.json")).read_text())
+ assert meta["score"] is None and meta["passed"] is None and meta["quality_tier"] == "D"
+ assert meta["acceptance_results"] == {}
+
+
+# --------------------------------------------------------------------------- graphics + textured exports
+def test_export_graphics_sample(tmp_path: Path):
+ from codeverse.contracts.common import Language
+ from tests.flywheel_cli.conftest import make_fake_run, tiny_png
+
+ ws, rec = make_fake_run(tmp_path / "runs", "rain_glsl", prompt="neon rain", language=Language.GLSL_SHADER)
+ tiny_png(ws.artifacts / "preview.gif") # gif magic irrelevant here — copied by name
+ out = tmp_path / "ds"
+ rep = export_samples(ws.root.parent, out)
+ assert rep.n_exported == 1, rep.skipped
+ sdir = out / "graphics" / "glsl_shader" / "rain_glsl"
+ assert (sdir / "code.frag").is_file() and (sdir / "src" / "shader.frag").is_file()
+ meta = json.loads((sdir / "meta.json").read_text())
+ assert meta["entry"] == "code.frag" and meta["type"] == "Procedural Graphics"
+ assert "renders/preview.gif" in meta["renders"]
+
+
+def test_export_includes_textured_assets_when_shipped(fake_run, tmp_path: Path):
+ from tests.flywheel_cli.conftest import tiny_png
+
+ ws, rec = fake_run
+ tex_dir = ws.artifacts / "textures"
+ tiny_png(tex_dir / "wood.png")
+ (ws.artifacts / "object_textured.glb").write_bytes(b"glTF\x02\x00\x00\x00" + b"\0" * 8)
+ rec.extra["texturing"] = {"shipped": True, "glb_textured": "artifacts/object_textured.glb",
+ "textures_dir": "artifacts/textures"}
+ ws.write_json(ws.record_path, rec)
+ out = tmp_path / "ds"
+ export_samples(ws.root.parent, out)
+ sdir = next(out.rglob("meta.json")).parent
+ assert (sdir / "textures" / "wood.png").is_file()
+ assert (sdir / "renders" / "object_textured.glb").is_file()
+ meta = json.loads((sdir / "meta.json").read_text())
+ assert "textures/wood.png" in meta["files"] and "renders/object_textured.glb" in meta["files"]
+ # not shipped → nothing copied
+ rec.extra["texturing"]["shipped"] = False
+ ws.write_json(ws.record_path, rec)
+ export_samples(ws.root.parent, tmp_path / "ds2")
+ sdir2 = next((tmp_path / "ds2").rglob("meta.json")).parent
+ assert not (sdir2 / "textures").exists()
diff --git a/harness/tests/flywheel_cli/test_gemini_image.py b/harness/tests/flywheel_cli/test_gemini_image.py
new file mode 100644
index 00000000..ec4d6d58
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_gemini_image.py
@@ -0,0 +1,95 @@
+"""GeminiImageModel key rotation: dead-key and free-429 semantics adopted from
+``models/gemini.py`` (offline; fake clients + a 2-key pool).
+
+Lives with the flywheel/CLI tests because this group owns
+``codeverse/models/gemini_image.py``'s rotation behaviour.
+"""
+
+from __future__ import annotations
+
+import io
+from types import SimpleNamespace
+
+import pytest
+
+pytest.importorskip("google.genai")
+from PIL import Image
+
+from codeverse.models.base import ModelError
+from codeverse.models.gemini_image import GeminiImageModel
+from codeverse.models.keypool import KeyPool
+
+
+def _png_bytes() -> bytes:
+ buf = io.BytesIO()
+ Image.new("RGB", (4, 4), (200, 30, 30)).save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _image_response() -> SimpleNamespace:
+ part = SimpleNamespace(inline_data=SimpleNamespace(data=_png_bytes()))
+ cand = SimpleNamespace(finish_reason=SimpleNamespace(name="STOP"), content=SimpleNamespace(parts=[part]))
+ return SimpleNamespace(prompt_feedback=None, candidates=[cand], usage_metadata=None)
+
+
+class _Client:
+ """Fake genai client: the shared script decides each call's outcome."""
+
+ def __init__(self, key: str, script: list, used: list[str]):
+ self._key, self._script, self._used = key, script, used
+ self.models = SimpleNamespace(generate_content=self._generate)
+
+ def _generate(self, *, model, contents, config):
+ self._used.append(self._key)
+ step = self._script.pop(0)
+ if isinstance(step, Exception):
+ raise step
+ return step
+
+
+def _model(script: list, used: list[str], sleeps: list[float], *, max_attempts: int) -> tuple[GeminiImageModel, KeyPool]:
+ pool = KeyPool(["key_a", "key_b"])
+ m = GeminiImageModel(
+ "test-image", fallback=None, pool=pool, max_attempts=max_attempts,
+ sleep=sleeps.append, client_factory=lambda key: _Client(key, script, used),
+ )
+ return m, pool
+
+
+def test_dead_key_rotates_free_and_is_benched(monkeypatch: pytest.MonkeyPatch):
+ used: list[str] = []
+ sleeps: list[float] = []
+ script = [ModelError("API key expired", retryable=False, status=403), _image_response()]
+ m, pool = _model(script, used, sleeps, max_attempts=1)
+ reports: list[tuple[str, str]] = []
+ orig = pool.report
+ monkeypatch.setattr(pool, "report", lambda key, outcome, **kw: (reports.append((key, outcome)), orig(key, outcome, **kw))[1])
+ images, usage = m.generate_with_usage("a wooden crate texture")
+ # the 403 did not consume the single attempt: a second key was tried and won
+ assert len(images) == 1 and len(used) == 2 and used[0] != used[1]
+ assert sleeps == [] # dead rotation never sleeps
+ dead_key = used[0]
+ assert (dead_key, "error") in reports # reported at rotation time
+ assert reports[-1] == (dead_key, "dead") # benched once the sibling key succeeded
+ assert (used[1], "ok") in reports
+
+
+def test_429_rotation_is_free_while_untried_keys_remain():
+ used: list[str] = []
+ sleeps: list[float] = []
+ script = [ModelError("quota", retryable=True, status=429), _image_response()]
+ m, _pool = _model(script, used, sleeps, max_attempts=1)
+ images, _ = m.generate_with_usage("mossy stone tiles")
+ assert len(images) == 1 and len(used) == 2 and used[0] != used[1]
+ assert sleeps == [0.5] # courtesy pause only — the attempt budget was not consumed
+
+
+def test_all_keys_dead_raises_the_key_error():
+ used: list[str] = []
+ sleeps: list[float] = []
+ script = [ModelError("PERMISSION_DENIED", retryable=False, status=403),
+ ModelError("PERMISSION_DENIED", retryable=False, status=403)]
+ m, _pool = _model(script, used, sleeps, max_attempts=4)
+ with pytest.raises(ModelError) as ei:
+ m.generate_with_usage("brushed steel")
+ assert ei.value.status == 403 and len(set(used)) == 2
diff --git a/harness/tests/flywheel_cli/test_quality_gallery.py b/harness/tests/flywheel_cli/test_quality_gallery.py
new file mode 100644
index 00000000..eb1bd288
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_quality_gallery.py
@@ -0,0 +1,212 @@
+"""Quality tiers, (code, prompt) dedupe, richer meta.json, captions side-car, gallery, trajectory repair mining."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from codeverse.contracts.common import Language
+from codeverse.flywheel.captions import caption_sample
+from codeverse.flywheel.export import export_samples, load_captions
+from codeverse.flywheel.gallery import GalleryItem, gallery_items, render_gallery, write_gallery
+from codeverse.flywheel.pairs import build_pairs
+from codeverse.flywheel.quality import find_duplicates, mark_duplicates, prompt_hash, quality_tier
+from codeverse.flywheel.record import load_record
+from codeverse.flywheel.trajectories import mine_run, parse_trajectory_name
+from codeverse.workspace import Workspace
+from tests.flywheel_cli.conftest import make_fake_run
+from tests.flywheel_cli.test_captions import GOOD, FakeModel
+
+# --------------------------------------------------------------------------- tiers + dedupe
+
+
+def test_quality_tier_rule():
+ assert quality_tier(passed=True, gate_errors=0, score=0.9) == "A"
+ assert quality_tier(passed=True, gate_errors=3, score=0.9) == "B"
+ assert quality_tier(passed=False, gate_errors=0, score=0.61) == "C"
+ assert quality_tier(passed=None, gate_errors=0, score=0.6) == "C"
+ assert quality_tier(passed=False, gate_errors=0, score=0.59) == "D"
+ assert quality_tier(passed=None, gate_errors=5, score=None) == "D"
+
+
+def test_find_and_mark_duplicates():
+ rows = [
+ {"id": "a", "key": "a", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "B", "score": 0.8},
+ {"id": "b", "key": "b", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8},
+ {"id": "c", "key": "c", "code_fingerprint": "X", "prompt_hash": "q", "quality_tier": "A", "score": 0.9},
+ {"id": "d", "key": "d", "code_fingerprint": "", "prompt_hash": "p", "quality_tier": "A", "score": 0.9},
+ {"id": "e", "key": "e", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8,
+ "has_captions": True},
+ ]
+ groups = find_duplicates(rows)
+ assert len(groups) == 1 and groups[0].canonical == "e" and set(groups[0].duplicates) == {"a", "b"}
+ mark_duplicates(rows)
+ assert {r["id"]: r["duplicate_of"] for r in rows} == {"a": "e", "b": "e", "c": "", "d": "", "e": ""}
+ assert prompt_hash(" a chair ") == prompt_hash("a chair") and len(prompt_hash("x")) == 16
+
+
+# --------------------------------------------------------------------------- export extras
+
+
+def test_export_meta_tiers_duplicates_and_captions_sidecar(runs_dir: Path, tmp_path: Path):
+ # a fourth run = exact duplicate (same code + prompt) of the first, and a urdf run with link meshes
+ make_fake_run(runs_dir, "wooden_chair_again")
+ ws_u, _ = make_fake_run(runs_dir, "cabinet_urdf", prompt="a cabinet", language=Language.URDF_BLENDER)
+ (ws_u.artifacts / "meshes").mkdir()
+ (ws_u.artifacts / "meshes" / "Body.glb").write_bytes(b"glTF" + b"\0" * 8)
+ side = tmp_path / "caps"
+ side.mkdir()
+ (side / "lamp_three.json").write_text(json.dumps({**GOOD, "provenance": {"captioner": "gemini:x"}}))
+
+ out = tmp_path / "ds"
+ rep = export_samples(runs_dir, out, captions_dir=side)
+ # the codex run shares prompt + round-1 code with the chair → also an exact duplicate
+ assert rep.n_exported == 5 and rep.n_indexed == 5 and rep.n_duplicates == 2
+ assert rep.duplicates[0].canonical == "3dcodeverse/static_object/blender/wooden_chair_ab12cd34"
+ assert set(rep.duplicates[0].duplicates) == {"3dcodeverse/static_object/blender/wooden_chair_again",
+ "3dcodeverse/static_object/blender/wooden_chair_codex"}
+ assert rep.tiers == {"A": 3, "C": 2} # codex run 0.6 (not passed) and lamp 0.72 → C
+ meta = json.loads((out / "static_object" / "blender" / "wooden_chair_ab12cd34" / "meta.json").read_text())
+ assert meta["quality_tier"] == "A" and meta["gate_errors"] == 0 and meta["gate_summary"] == {"lint": 0}
+ assert meta["acceptance"] == [{"id": "a1", "text": "", "how": "", "priority": "", "passed": True}]
+ assert len(meta["code_fingerprint"]) == 64 and meta["prompt_hash"] == prompt_hash("a wooden dining chair")
+ assert [r["index"] for r in meta["rounds_summary"]] == [0, 1] and meta["best_round"] == 1
+ u_meta = json.loads((out / "articulated_object" / "urdf_blender" / "cabinet_urdf" / "meta.json").read_text())
+ assert "meshes/Body.glb" in u_meta["files"] and (out / "articulated_object" / "urdf_blender" / "cabinet_urdf" / "meshes" / "Body.glb").is_file()
+ # side-car captions are picked up for lamp_three only
+ rows = {json.loads(line)["key"]: json.loads(line) for line in (out / "metadata.jsonl").read_text().splitlines()}
+ assert rows["lamp_three"]["has_captions"] is True and rows["lamp_three"]["captions"]["factory"] == GOOD["factory"]
+ assert rows["wooden_chair_ab12cd34"]["has_captions"] is False
+ assert rows["wooden_chair_again"]["duplicate_of"] == "3dcodeverse/static_object/blender/wooden_chair_ab12cd34"
+ assert (out / "duplicates.json").is_file()
+ import pyarrow.parquet as pq
+
+ table = pq.read_table(out / "metadata.parquet")
+ assert {"quality_tier", "gate_errors", "cost_usd", "rounds", "status", "code_fingerprint", "prompt_hash",
+ "duplicate_of", "has_captions"} <= set(table.column_names)
+ # drop duplicates from the index (folder stays)
+ rep2 = export_samples(runs_dir, out, captions_dir=side, drop_duplicates=True)
+ assert rep2.n_indexed == 3 and rep2.n_duplicates == 2 and rep2.tiers == {"A": 2, "C": 1}
+ assert (out / "static_object" / "blender" / "wooden_chair_again").is_dir()
+
+
+def test_export_scene_views_repeating_names(fake_run, tmp_path: Path):
+ """Scene renders repeat a camera name per capture time; the sample must keep every file."""
+ from codeverse.contracts.artifacts import RenderView
+ from tests.flywheel_cli.conftest import tiny_png
+
+ ws, rec = fake_run
+ rnd = rec.rounds[1]
+ rd = ws.renders_dir(1)
+ assert rnd.renders is not None
+ rnd.renders.views = [RenderView(name="Establishing", path=str(tiny_png(rd / "Establishing_t0.png"))),
+ RenderView(name="Establishing", path=str(tiny_png(rd / "Establishing_t1p5.png")))]
+ ws.write_json(ws.record_path, rec)
+ out = tmp_path / "ds"
+ export_samples(ws.root.parent, out)
+ meta = json.loads(next(out.rglob("meta.json")).read_text())
+ assert {"renders/view_Establishing_t0.png", "renders/view_Establishing_t1p5.png"} <= set(meta["renders"])
+ assert len(meta["files"]) == len(set(meta["files"]))
+
+
+def test_caption_out_dir_leaves_run_untouched(fake_run, tmp_path: Path):
+ ws, rec = fake_run
+ before = ws.record_path.read_text()
+ side = tmp_path / "caps"
+ caps = caption_sample(ws, rec, "fake:fake", model=FakeModel([GOOD]), out_dir=side)
+ assert caps.factory == GOOD["factory"]
+ assert ws.record_path.read_text() == before and not (ws.root / "captions.json").exists()
+ data = json.loads((side / f"{ws.root.name}.json").read_text())
+ assert data["provenance"]["captioner"] == "fake:fake" and data["provenance"]["images_used"][0].startswith("artifacts/")
+ assert load_captions(ws, load_record(ws), side)["detailed"] == GOOD["detailed"]
+ assert load_captions(ws, load_record(ws), None) == {}
+
+
+# --------------------------------------------------------------------------- gallery
+
+
+def test_gallery_from_runs(runs_dir: Path, tmp_path: Path):
+ items = gallery_items(runs_dir)
+ assert {i.key for i in items} == {"wooden_chair_ab12cd34", "wooden_chair_codex", "lamp_three"}
+ chair = next(i for i in items if i.key == "wooden_chair_ab12cd34")
+ assert chair.score == 0.80 and chair.passed is True and chair.quality_tier == "A" and chair.sheet
+ assert "object.glb" in chair.links and "record.json" in chair.links
+ path, n = write_gallery(runs_dir, tmp_path / "g" / "gallery.html")
+ page = path.read_text()
+ assert n == 3 and page.count("data:image/jpeg;base64,") == 3
+ assert "a desk lamp" in page and "wooden_chair_codex" in page and "file://" in page
+ # items without renders or records still render
+ html = render_gallery([GalleryItem(key="x", error="boom <b>")], "t")
+ assert "no render" in html and "boom &lt;b&gt;" in html
+
+
+# --------------------------------------------------------------------------- trajectory repair pairs
+
+
+def _write_transcript(ws: Workspace, label: str, rnd: int, events: list[dict]) -> Path:
+ d = ws.root / "trajectories" / f"{label}_r{rnd:02d}"
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "transcript.jsonl").write_text("\n".join(json.dumps(e) for e in events) + "\n")
+ return d
+
+
+def _call(turn: int, t: float, cid: str, name: str, **args) -> dict:
+ return {"t": t, "kind": "assistant", "turn": turn, "text": "", "tool_calls": [{"id": cid, "name": name, "arguments": args}]}
+
+
+def _result(turn: int, t: float, cid: str, name: str, ok: bool, content: str) -> dict:
+ return {"t": t, "kind": "tool_result", "turn": turn, "name": name, "call_id": cid, "ok": ok, "content": content}
+
+
+def test_trajectory_repair_mining(fake_run, tmp_path: Path):
+ ws, rec = fake_run
+ assert parse_trajectory_name("zone_koi_pond_r01") == ("zone_koi_pond", 1)
+ # the base state = the `pre:baseline` snapshot the harness takes before the session
+ (ws.src / "model.py").write_text("import bpy\nA = 1\n")
+ ws.commit("pre:baseline")
+ import time
+
+ t0 = time.time() + 5 # transcript starts after the snapshot
+ ev = [
+ {"t": t0, "kind": "system", "text": "rules"},
+ _call(0, t0 + 1, "c1", "edit_file", path="src/model.py", old="A = 1", new="A = 2)"),
+ _result(0, t0 + 1, "c1", "edit_file", True, "edited"),
+ _call(1, t0 + 2, "c2", "build"), _result(1, t0 + 2, "c2", "build", False, "build failed: SyntaxError"),
+ _call(2, t0 + 3, "c3", "write_file", path="src/model.py", content="import bpy\nA = 3\nB = 4\n"),
+ _result(2, t0 + 3, "c3", "write_file", True, "overwrote"),
+ _call(3, t0 + 4, "c4", "build"), _result(3, t0 + 4, "c4", "build", False, "build failed: NameError"),
+ _call(4, t0 + 5, "c5", "edit_file", path="src/model.py", old="B = 4", new="B = A"),
+ _result(4, t0 + 5, "c5", "edit_file", True, "edited"),
+ _call(5, t0 + 6, "c6", "build"), _result(5, t0 + 6, "c6", "build", True, "BUILD OK"),
+ _call(6, t0 + 7, "c7", "build"), _result(6, t0 + 7, "c7", "build", True, "BUILD OK"), # no new pair
+ ]
+ _write_transcript(ws, "baseline", 0, ev)
+ pairs = mine_run(ws)
+ assert len(pairs) == 1
+ p = pairs[0]
+ assert p.trajectory == "baseline_r00" and p.stage == "baseline" and p.round_index == 0
+ assert p.broken_turn == 3 and p.fixed_turn == 5 and p.n_failures == 2 and "NameError" in p.error
+ assert p.rejected["src/model.py"] == "import bpy\nA = 3\nB = 4\n" and p.chosen["src/model.py"] == "import bpy\nA = 3\nB = A\n"
+ assert "src/parts/leg.py" in p.chosen and p.changed_files == ["src/model.py"] # untouched files ride along
+ # a CLI-backend transcript (raw lines) yields nothing
+ _write_transcript(ws, "refine", 0, [{"t": t0, "kind": "invoke", "argv": ["gemini"]}, {"t": t0, "kind": "line", "text": "x"}])
+ assert len(mine_run(ws)) == 1
+ out = tmp_path / "pairs.jsonl"
+ n = build_pairs(ws.root.parent, out)
+ kinds = [(json.loads(line)["kind"], json.loads(line).get("source", "")) for line in out.read_text().splitlines()]
+ assert n == 2 and ("repair", "trajectory") in kinds and ("preference", "") in kinds
+ assert build_pairs(ws.root.parent, tmp_path / "p2.jsonl", trajectories=False) == 1
+
+
+def test_trajectory_inexact_base_is_skipped(fake_run):
+ """An edit on a file we never saw in full (no pre: commit, no write_file) must not produce a pair."""
+ ws, rec = fake_run
+ t0 = 1.0
+ ev = [
+ _call(0, t0, "c1", "edit_file", path="src/model.py", old="zzz", new="y"), _result(0, t0, "c1", "edit_file", True, "ok"),
+ _call(1, t0, "c2", "build"), _result(1, t0, "c2", "build", False, "fail"),
+ _call(2, t0, "c3", "edit_file", path="src/model.py", old="y", new="w"), _result(2, t0, "c3", "edit_file", True, "ok"),
+ _call(3, t0, "c4", "build"), _result(3, t0, "c4", "build", True, "ok"),
+ ]
+ _write_transcript(ws, "baseline", 0, ev)
+ assert mine_run(ws) == []
diff --git a/harness/tests/graphics/__init__.py b/harness/tests/graphics/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/graphics/test_frame_stats.py b/harness/tests/graphics/test_frame_stats.py
new file mode 100644
index 00000000..2d34d453
--- /dev/null
+++ b/harness/tests/graphics/test_frame_stats.py
@@ -0,0 +1,76 @@
+"""Offline: frame statistics + the gl_frames gate on synthetic frames."""
+
+from __future__ import annotations
+
+import numpy as np
+from PIL import Image
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.spatial.frame_stats import frame_gate, sequence_stats
+
+
+def _png(path, arr):
+ Image.fromarray((np.clip(arr, 0, 1) * 255).astype(np.uint8), "RGB").save(path)
+ return path
+
+
+def _gradient(t: float, w=160, h=90, moving=True):
+ x = np.linspace(0, 1, w, dtype=np.float32)[None, :].repeat(h, 0)
+ y = np.linspace(0, 1, h, dtype=np.float32)[:, None].repeat(w, 1)
+ shift = 0.2 * t if moving else 0.0
+ r = 0.5 + 0.5 * np.sin(6.0 * (x + shift))
+ g = y
+ b = 0.5 + 0.5 * np.cos(4.0 * (y - shift))
+ return np.stack([r, g, b], -1)
+
+
+def _kinds(gate):
+ return {f.data["kind"]: f.severity for f in gate.findings}
+
+
+def test_moving_colourful_sequence_passes(tmp_path):
+ frames = [(t, _png(tmp_path / f"f{i}.png", _gradient(t))) for i, t in enumerate((0.0, 1.0, 2.5, 4.0))]
+ seq = sequence_stats(frames)
+ assert len(seq.frames) == 4 and seq.mean_diff > 0.01 and not seq.static and not seq.any_nan
+ assert seq.mean_colourfulness > 0.15 and 0.2 < seq.mean_lum < 0.8
+ gate = frame_gate(seq)
+ assert gate.passed and "static" not in _kinds(gate)
+
+
+def test_static_sequence_warns_only_when_motion_expected(tmp_path):
+ frames = [(t, _png(tmp_path / f"s{i}.png", _gradient(0.0, moving=False))) for i, t in enumerate((0.0, 1.0, 2.5))]
+ seq = sequence_stats(frames)
+ assert seq.static and seq.n_duplicates == 2
+ gate = frame_gate(seq, motion_expected=True)
+ assert gate.passed and _kinds(gate)["static"] == Severity.WARN
+ assert "static" not in _kinds(frame_gate(seq, motion_expected=False))
+
+
+def test_black_and_blown_and_nan_are_errors(tmp_path):
+ black = [(t, _png(tmp_path / f"b{i}.png", np.zeros((90, 160, 3)))) for i, t in enumerate((0.0, 1.0))]
+ g = frame_gate(sequence_stats(black))
+ assert not g.passed and _kinds(g)["black"] == Severity.ERROR
+ white = [(t, _png(tmp_path / f"w{i}.png", np.ones((90, 160, 3)))) for i, t in enumerate((0.0, 1.0))]
+ g = frame_gate(sequence_stats(white))
+ assert not g.passed and _kinds(g)["blown"] == Severity.ERROR
+ ok = [(t, _png(tmp_path / f"n{i}.png", _gradient(t))) for i, t in enumerate((0.0, 1.0))]
+ seq = sequence_stats(ok, nan_counts=[(0, 0), (12, 1)])
+ assert seq.any_nan and seq.frames[1].nan == 12
+ g = frame_gate(seq)
+ assert not g.passed and _kinds(g)["nan"] == Severity.ERROR and "guard divisions" in g.errors[0].fix_hint
+
+
+def test_flicker_and_low_detail_warn(tmp_path):
+ a = _gradient(0.0)
+ b = 1.0 - a
+ frames = [(0.0, _png(tmp_path / "x0.png", a)), (1.0, _png(tmp_path / "x1.png", b)), (2.0, _png(tmp_path / "x2.png", a))]
+ seq = sequence_stats(frames)
+ assert seq.flicker and _kinds(frame_gate(seq))["flicker"] == Severity.WARN
+ flat = [(t, _png(tmp_path / f"l{i}.png", np.full((90, 160, 3), 0.4 + 0.01 * t))) for i, t in enumerate((0.0, 1.0, 2.0))]
+ g = frame_gate(sequence_stats(flat))
+ assert _kinds(g)["low_detail"] == Severity.WARN and g.passed
+
+
+def test_empty_sequence_is_an_error():
+ g = frame_gate(sequence_stats([]))
+ assert not g.passed and g.errors[0].data["kind"] == "no_frames"
diff --git a/harness/tests/graphics/test_gl_host.py b/harness/tests/graphics/test_gl_host.py
new file mode 100644
index 00000000..ad394035
--- /dev/null
+++ b/harness/tests/graphics/test_gl_host.py
@@ -0,0 +1,96 @@
+"""Offline: GlHost subprocess driving with a fake runner (GPU → CPU fallback, timeouts, crashes, gif/sheet)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from codeverse.spatial import gl_render
+from codeverse.spatial.gl_render import (
+ GlFrame,
+ GlHost,
+ GlHostError,
+ gif_times,
+ write_contact_sheet,
+ write_gif,
+)
+
+FAKE_RUNNER = r'''
+import json, os, sys, time
+from pathlib import Path
+job = json.loads(Path(sys.argv[sys.argv.index("--job") + 1]).read_text())
+out = Path(job["out_dir"]); out.mkdir(parents=True, exist_ok=True)
+mode = os.environ.get("FAKE_MODE", "ok")
+if os.environ.get("GALLIUM_DRIVER") == "d3d12" and mode in ("gpu_fail", "ok_cpu_only"):
+ (out / "gl_result.json").write_text(json.dumps({"ok": False, "stage": "context", "error_type": "Error", "error_message": "no d3d12"}))
+ sys.exit(3)
+if mode == "crash":
+ sys.exit(139)
+if mode == "hang":
+ time.sleep(30)
+frames = []
+for i, t in enumerate(sorted(set(job["times"]) | set(job.get("extra_times", [])))):
+ p = out / "frames" / f"f{i:02d}_t{t:06.2f}.png"; p.parent.mkdir(exist_ok=True)
+ from PIL import Image
+ Image.new("RGB", (32, 18), (int(40 * t) % 255, 80, 120)).save(p)
+ frames.append({"index": i, "time": t, "path": str(p), "judge": t in job["times"], "nan": 0, "inf": 0, "mean": 0.3})
+(out / "gl_result.json").write_text(json.dumps({"ok": True, "stage": "render", "renderer": "fake " + os.environ.get("GALLIUM_DRIVER", ""), "frames": frames}))
+'''
+
+
+def fake_runner(tmp_path, monkeypatch):
+ runner = tmp_path / "fake_run_gl.py"
+ runner.write_text(FAKE_RUNNER)
+ monkeypatch.setattr(gl_render, "RUNNER", runner)
+ monkeypatch.setattr(gl_render, "_ENV_PASS", gl_render._ENV_PASS + ("FAKE_MODE",))
+ gl_render._gpu_state["ok"] = None
+ yield runner
+ gl_render._gpu_state["ok"] = None
+
+
+def test_gpu_then_cpu_fallback_is_cached(tmp_path, fake_runner, monkeypatch):
+ monkeypatch.setenv("FAKE_MODE", "gpu_fail")
+ host = GlHost(gpu="auto", timeout_s=20)
+ res = host.render_fragment_shader("src", tmp_path / "o1", width=32, height=18, times=(0.0, 1.0), extra_times=(0.5,))
+ assert res.ok and not res.gpu and res.renderer == "fake llvmpipe"
+ assert [f.time for f in res.judge_frames] == [0.0, 1.0] and len(res.frames) == 3
+ assert gl_render._gpu_state["ok"] is False and gl_render.gpu_preference("auto") == [False]
+ monkeypatch.setenv("FAKE_MODE", "ok")
+ res2 = host.run_program(fake_runner, tmp_path / "o2", width=32, height=18, times=(0.0,))
+ assert res2.ok and not res2.gpu # cached decision: no GPU retry
+ assert (tmp_path / "o2" / gl_render.JOB_NAME).is_file() and json.loads((tmp_path / "o2" / gl_render.JOB_NAME).read_text())["mode"] == "program"
+
+
+def test_gpu_on_failure_raises_and_crash_timeout_are_typed(tmp_path, fake_runner, monkeypatch):
+ monkeypatch.setenv("FAKE_MODE", "gpu_fail")
+ with pytest.raises(GlHostError):
+ GlHost(gpu="on", timeout_s=20).render_fragment_shader("src", tmp_path / "o", width=8, height=8, times=(0.0,))
+ monkeypatch.setenv("FAKE_MODE", "crash")
+ res = GlHost(gpu="off", timeout_s=20).render_fragment_shader("src", tmp_path / "c", width=8, height=8, times=(0.0,))
+ assert not res.ok and res.error_type == "RunnerCrash" and res.stage == "crash"
+ monkeypatch.setenv("FAKE_MODE", "hang")
+ res = GlHost(gpu="off", timeout_s=1.5).render_fragment_shader("src", tmp_path / "h", width=8, height=8, times=(0.0,))
+ assert not res.ok and res.timed_out and res.error_type == "RenderTimeout"
+
+
+def test_sheet_gif_and_gif_times(tmp_path):
+ frames = []
+ for i, t in enumerate((0.0, 1.0, 2.5)):
+ p = tmp_path / f"f{i}.png"
+ Image.fromarray(np.full((18, 32, 3), 60 * i, dtype=np.uint8), "RGB").save(p)
+ frames.append(GlFrame(index=i, time=t, path=str(p)))
+ sheet = write_contact_sheet(frames, tmp_path / "sheet.png", cols=2, tile_w=64)
+ im = Image.open(sheet)
+ assert im.width > 128 and im.height > 2 * 36 # 2 columns × 2 rows of 64×36 tiles + labels
+ gif = write_gif(frames, tmp_path / "p.gif", width=32)
+ assert gif is not None and Image.open(gif).n_frames == 3
+ assert write_gif(frames[:1], tmp_path / "one.gif") is None
+ assert gif_times(8.0, 4) == [0.0, 2.0, 4.0, 6.0] and len(gif_times(0.1, 12)) == 12
+ with pytest.raises(ValueError):
+ write_contact_sheet([], tmp_path / "x.png")
+ assert Path(sheet).is_file()
diff --git a/harness/tests/graphics/test_gl_runtime.py b/harness/tests/graphics/test_gl_runtime.py
new file mode 100644
index 00000000..414b2664
--- /dev/null
+++ b/harness/tests/graphics/test_gl_runtime.py
@@ -0,0 +1,114 @@
+"""Real moderngl rendering (offline; GPU env if usable, llvmpipe otherwise). Skipped when no GL context."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.plan import GraphicsPlan, PassPlan
+from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
+from codeverse.spatial.gl_render import GlHost, GlHostError
+from codeverse.spatial.registry import ToolContext, get_tool
+
+pytest.importorskip("moderngl")
+
+SMALL = dict(width=256, height=144, preview=False)
+PLAN = GraphicsPlan(title="Test", summary="s", style="warm", passes=[PassPlan(name="Sky", description="gradient")],
+ motion="sun moves", key_visuals=["sun"], duration_s=6.0, resolution=(256, 144))
+
+
[email protected](scope="module")
+def host() -> GlHost:
+ h = GlHost(timeout_s=120)
+ try:
+ r = h.render_fragment_shader("#version 330 core\nout vec4 f;\nvoid main(){ f = vec4(1.0); }\n", __import__("tempfile").mkdtemp(),
+ width=16, height=16, times=(0.0,))
+ except GlHostError as e: # pragma: no cover - machine without GL
+ pytest.skip(f"no OpenGL context: {e}")
+ if not r.ok:
+ pytest.skip(f"GL smoke render failed: {r.error_message}")
+ return h
+
+
+def _ws_with_plan(tmp_ws):
+ tmp_ws.write_json(tmp_ws.plan_path, PLAN)
+ return tmp_ws
+
+
+def test_shader_skeleton_builds_and_writes_artifacts(tmp_ws, host):
+ ws = _ws_with_plan(tmp_ws)
+ rt = GlslShaderRuntime(host=host)
+ paths = rt.skeleton(ws, PLAN)
+ assert {p.name for p in paths} == {"common.glsl", "shader.frag"}
+ assert "TODO pass 1: Sky" in (ws.src / "shader.frag").read_text()
+ assert rt.lint(ws).passed
+ br = rt.build(ws, **SMALL)
+ assert br.ok, br.error_message
+ assert br.glb_path is None and br.language == "glsl_shader"
+ for key in ("frames", "sheet", "metrics"):
+ assert key in br.extra_paths
+ frames = sorted((ws.artifacts / "frames").glob("f*_t*.png"))
+ assert len(frames) == 5 # t = 0, 1, 2.5, 4, 6 (duration 6)
+ metrics = json.loads((ws.artifacts / "metrics.json").read_text())
+ assert metrics["stats"]["mean_lum"] > 0.1 and not metrics["stats"]["any_nan"] and not metrics["stats"]["static"]
+ assert br.census["convention"] == "mainImage" and br.census["feedback"] is False
+ assert (ws.artifacts / "build.json").is_file()
+
+
+def test_shader_compile_error_maps_to_agent_line(tmp_ws, host):
+ ws = _ws_with_plan(tmp_ws)
+ (ws.src / "common.glsl").write_text("float twice(float x) { return 2.0 * x; }\n")
+ (ws.src / "shader.frag").write_text(
+ "// line 1\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"
+ " float v = twice(nope);\n fragColor = vec4(uv, v, 1.0);\n}\n")
+ br = GlslShaderRuntime(host=host).build(ws, **SMALL)
+ assert not br.ok and br.error_type == "GlslCompileError"
+ assert br.error_file == "src/shader.frag" and br.error_line == 4
+ assert "src/shader.frag:4" in br.error_message and "nope" in br.error_message
+
+
+def test_feedback_and_nan_detection(tmp_ws, host):
+ ws = _ws_with_plan(tmp_ws)
+ (ws.src / "shader.frag").write_text(
+ "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"
+ " vec3 prev = texture(u_prev, uv).rgb * 0.9;\n float d = smoothstep(0.05, 0.0, length(uv - vec2(0.5 + 0.3*sin(u_time), 0.5)));\n"
+ " float bad = uv.x > 0.9 ? sqrt(-1.0) : 0.0;\n fragColor = vec4(max(prev, vec3(d)) + bad, 1.0);\n}\n")
+ rt = GlslShaderRuntime(host=host)
+ br = rt.build(ws, **SMALL)
+ assert br.ok and br.census["feedback"] is True
+ metrics = json.loads((ws.artifacts / "metrics.json").read_text())
+ assert metrics["stats"]["any_nan"] is True
+ assert any(f["data"]["kind"] == "nan" for f in metrics["gate"]["findings"]) and not metrics["gate"]["passed"]
+
+
+def test_program_skeleton_builds_and_errors_map(tmp_ws, host):
+ ws = _ws_with_plan(tmp_ws)
+ rt = OpenGLPythonRuntime(host=host)
+ rt.skeleton(ws, PLAN)
+ assert rt.lint(ws).passed
+ br = rt.build(ws, **SMALL)
+ assert br.ok, br.error_message
+ assert len(list((ws.artifacts / "frames").glob("*.png"))) == 5 and (ws.artifacts / "frames_sheet.png").is_file()
+ metrics = json.loads((ws.artifacts / "metrics.json").read_text())
+ assert not metrics["stats"]["static"] and metrics["stats"]["mean_lum"] > 0.1
+ src = (ws.src / "program.py").read_text()
+ (ws.src / "program.py").write_text(src.replace("fbo.use()\n ctx.disable", "fbo.use()\n raise ValueError('boom')\n ctx.disable"))
+ br = rt.build(ws, **SMALL)
+ assert not br.ok and br.error_type == "ValueError" and br.error_file == "src/program.py" and br.error_line
+ assert "boom" in br.error_message
+
+
+def test_gl_tools_probe_and_frames(tmp_ws, host, monkeypatch):
+ ws = _ws_with_plan(tmp_ws)
+ GlslShaderRuntime(host=host).skeleton(ws, PLAN)
+ monkeypatch.setattr("codeverse.languages.glsl_shader.runtime.GlslShaderRuntime.host", lambda self, timeout_s=None: host)
+ ctx = ToolContext(workspace=ws, language="glsl_shader", track="graphics")
+ obs = get_tool("gl_probe").call(ctx, {"t": 1.5})
+ assert obs.ok and "PROBE OK" in obs.text and len(obs.images) == 1 and obs.numbers["n_frames"] == 1
+ obs = get_tool("gl_frames").call(ctx, {"times": [0.0, 2.0], "width": 256, "height": 144})
+ assert obs.ok and "FRAMES OK" in obs.text and obs.images and obs.numbers["n_frames"] == 2 and not obs.numbers["static"]
+ (ws.src / "shader.frag").write_text("#version 330 core\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n")
+ obs = get_tool("gl_probe").call(ctx, {})
+ assert not obs.ok and "LINT FAILED" in obs.text and "#version" in obs.text
diff --git a/harness/tests/graphics/test_live.py b/harness/tests/graphics/test_live.py
new file mode 100644
index 00000000..8065603c
--- /dev/null
+++ b/harness/tests/graphics/test_live.py
@@ -0,0 +1,67 @@
+"""Live (network + Gemini keys): graphics planner → single-shot shader → real GL build → VLM judge."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.config import get_settings
+from codeverse.contracts.common import Backends, Budget, Language, Track
+from codeverse.contracts.plan import GraphicsPlan
+from codeverse.contracts.spec import Spec
+from codeverse.judges.base import JudgeInput
+from codeverse.judges.vlm_judge import VlmJudge
+from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+from codeverse.tracks.generation import generate_files
+from codeverse.tracks.graphics import GraphicsTrack
+from codeverse.tracks.graphics_steps import (
+ frames_render_set,
+ graphics_prompt_context,
+ plan_graphics,
+)
+from codeverse.workspace import Workspace
+
+pytestmark = pytest.mark.live
+MODEL = "gemini:gemini-3.7-flash"
+
+
[email protected](scope="module")
+def keys_ok():
+ if not get_settings().gemini_api_keys:
+ pytest.skip("no Gemini keys")
+
+
+def test_live_plan_generate_build_judge(tmp_path, keys_ok):
+ from codeverse.events import EventLog
+ from codeverse.models import get_chat_model
+ from codeverse.orchestrator.state import RunState
+ from codeverse.prompts import render
+
+ spec = Spec(id="live_gfx", track=Track.GRAPHICS, language=Language.GLSL_SHADER,
+ prompt="a calm animated aurora borealis over snowy mountains with twinkling stars",
+ budget=Budget(max_rounds=1, max_usd=0.5), backends=Backends(planner=MODEL, generator=f"single-shot:{MODEL}", judge=MODEL))
+ ws = Workspace(tmp_path / "live_gfx").create()
+ model = get_chat_model(MODEL)
+ plan = plan_graphics(spec, MODEL, ws, model=model)
+ assert isinstance(plan, GraphicsPlan) and plan.passes and plan.key_visuals and plan.motion
+ rt = GlslShaderRuntime()
+ rt.skeleton(ws, plan)
+ track = GraphicsTrack(runtime=rt)
+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState.load_or_new(ws, resume=False))
+ ctx.plan = plan
+ ctx.model = model
+ task = track.baseline_tasks(ctx)[0]
+ res = generate_files(ws, model=model, task=task)
+ assert res.ok and any(c.path.endswith("shader.frag") for c in res.files_changed)
+ lint = rt.lint(ws)
+ build = rt.build(ws, width=640, height=360)
+ assert lint.gate == "lint:glsl_shader"
+ if not build.ok:
+ pytest.skip(f"model wrote a shader that does not compile (repair loop not exercised here): {build.error_message[:200]}")
+ renders = frames_render_set(ws, build, 0)
+ assert len(renders.views) == 5 and renders.contact_sheet
+ judge = VlmJudge(rubric="shader_v1", model_id=MODEL, n_samples=1)
+ j = judge.judge(JudgeInput(spec=spec, renders=renders, gates=[lint], acceptance=plan.acceptance, plan_summary=plan.summary,
+ round_index=0, extra_context=""))
+ assert 0.0 <= j.overall <= 1.0 and set(j.scores) >= {"brief_fidelity", "motion_quality"}
+ assert render("tracks/refine_graphics.j2", **graphics_prompt_context(
+ ctx, round_index=1, tasks=["x"], targets=["overall"], files=["src/shader.frag"], judge_summary="s", frame_notes="f", current_files={}))
diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.py
new file mode 100644
index 00000000..d7c0b37d
--- /dev/null
+++ b/harness/tests/graphics/test_track.py
@@ -0,0 +1,233 @@
+"""Offline: GraphicsTrack end-to-end with fakes (no GL, no network) + planner + prompts + rubric."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from codeverse.config import Settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Backends, Budget, Language, Track
+from codeverse.contracts.plan import GraphicsPlan
+from codeverse.contracts.run import RunStatus
+from codeverse.contracts.spec import Constraints, Spec
+from codeverse.events import EventLog
+from codeverse.judges.rubrics import load_rubric
+from codeverse.languages.glsl_shader.gl_build import finish_build, judge_times, preview_times
+from codeverse.languages.glsl_shader.lint import lint_workspace
+from codeverse.languages.glsl_shader.skeleton import write_skeleton
+from codeverse.prompts import render
+from codeverse.spatial.gl_render import GlFrame, GlResult
+from codeverse.tracks import get_track
+from codeverse.tracks.graphics import GraphicsPipeline, GraphicsTrack
+from codeverse.tracks.graphics_steps import (
+ build_plan_system_prompt,
+ ensure_graphics_acceptance,
+ graphics_prompt_context,
+ plan_example,
+ plan_graphics,
+)
+from codeverse.tracks.planner import PlanningError
+from codeverse.workspace import Workspace
+from tests.orchestrator_tracks.fakes import FakeAgent, FakeChatModel, FakeJudge, FakeServices
+
+FAIL_MARK = "RAISE_BUILD_ERROR"
+STATIC_MARK = "STATIC_FRAMES"
+
+
+def make_spec(language: Language = Language.GLSL_SHADER, *, generator: str = "fake:fake-model", max_rounds: int = 3) -> Spec:
+ return Spec(id="g1", track=Track.GRAPHICS, language=language, prompt="animated neon rain on a window with bokeh city lights",
+ constraints=Constraints(must_have=["bokeh lights"]),
+ budget=Budget(max_rounds=max_rounds, max_usd=5.0, max_minutes=10, max_repair_attempts=2),
+ backends=Backends(planner="fake:planner", generator=generator, judge="fake:judge"))
+
+
+def _frame(path: Path, t: float, static: bool) -> None:
+ x = np.linspace(0, 1, 64, dtype=np.float32)[None, :].repeat(36, 0)
+ shift = 0.0 if static else 0.3 * t
+ rgb = np.stack([0.5 + 0.5 * np.sin(6 * (x + shift)), x * 0.5 + 0.2, 0.6 - 0.4 * x], -1)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.fromarray((rgb * 255).astype(np.uint8), "RGB").save(path)
+
+
+class FakeGlRuntime:
+ """glsl_shader runtime without GL: writes synthetic frames through the real ``finish_build``."""
+
+ language = Language.GLSL_SHADER
+ entry_globs = ("src/shader.frag", "src/common.glsl")
+
+ def __init__(self) -> None:
+ self.builds = 0
+
+ def skeleton(self, ws: Workspace, plan: Any) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, **kw: Any) -> BuildResult:
+ self.builds += 1
+ src = (ws.src / "shader.frag").read_text()
+ if FAIL_MARK in src:
+ res = GlResult(ok=False, mode="shader", stage="compile", error_type="GlslCompileError",
+ error_message="src/shader.frag:3: error: `nope' undeclared")
+ return finish_build(ws, res, language="glsl_shader", error_file="src/shader.frag", error_line=3)
+ frames = []
+ for i, t in enumerate(judge_times(8.0) + preview_times(8.0, 4)):
+ p = ws.artifacts / "frames" / f"f{i:02d}_t{t:06.2f}.png"
+ _frame(p, t, STATIC_MARK in src)
+ frames.append(GlFrame(index=i, time=t, path=str(p), judge=i < 5))
+ res = GlResult(ok=True, mode="shader", stage="render", renderer="fake-gl", frames=frames)
+ return finish_build(ws, res, language="glsl_shader", census={"convention": "mainImage"})
+
+ def contract_doc(self) -> str:
+ return "FAKE GLSL CONTRACT"
+
+ def cookbook_path(self) -> Path:
+ return Path("/dev/null")
+
+
+def _writer(job, ws):
+ body = "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"
+ body += f" // {job.label} r{job.extra.get('round', 0)}\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}}\n"
+ return {"src/shader.frag": body}
+
+
+def settings(tmp_path) -> Settings:
+ return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")
+
+
+def _services(**kw):
+ return FakeServices(runtime_factory=lambda lang: FakeGlRuntime(), **kw)
+
+
+def test_graphics_track_end_to_end(tmp_path, settings):
+ spec = make_spec(max_rounds=3)
+ ws = Workspace(tmp_path / "runs" / "rain")
+ judge = FakeJudge(scores=(0.55, 0.72, 0.9), targets=("RainDrops", "CityBokeh"))
+ agent = FakeAgent(_writer)
+ runtime = FakeGlRuntime()
+ track = GraphicsTrack(services=_services(), judge=judge, agent=agent, planner_model=FakeChatModel(lambda req: plan_example()),
+ settings=settings, runtime=runtime)
+ assert isinstance(get_track(Track.GRAPHICS), GraphicsTrack)
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.PASSED and [r.kind for r in rec.rounds] == ["baseline", "refine", "refine"]
+ assert rec.baseline_score == pytest.approx(0.55) and rec.final_score == pytest.approx(0.9) and rec.best_round == 2
+ assert rec.extra["rubric"] == "shader_v1"
+ plan = GraphicsPlan.model_validate(json.loads(ws.plan_path.read_text()))
+ assert any(a.text.startswith("Includes: bokeh") for a in plan.acceptance)
+ # renders are the frames (views named t=<s>s) + a sheet, per round
+ r0 = rec.rounds[0]
+ assert r0.renders is not None and [v.name for v in r0.renders.views] == ["t=0s", "t=1s", "t=2.5s", "t=4s", "t=6s"]
+ assert r0.renders.views[2].time_s == 2.5 and Path(r0.renders.contact_sheet).is_file()
+ assert (ws.renders_dir(0) / "sheet.png").is_file() and (ws.artifacts / "preview.gif").is_file()
+ # gates: lint + gl_frames; no measurement
+ assert {g.gate for g in r0.gates} == {"lint:glsl_shader", "gl_frames"} and r0.measurement is None
+ assert (ws.gates_dir(0) / "gl_frames.json").is_file()
+ # judge saw frame metrics in the extra context and the plan digest
+ inp = judge.calls[0]
+ assert "FRAME METRICS" in inp.extra_context and "mean_lum" in inp.extra_context and "CityBokeh" in inp.plan_summary
+ # prompts: baseline is concrete (passes table, key visuals, contract, tools), refine carries judge + metrics
+ p0 = agent.jobs[0].prompt
+ assert "| RainDrops |" in p0 and "rain drops with trails" in p0 and "glsl_shader authoring contract" in p0 and "gl_frames" in p0
+ p1 = agent.jobs[1].prompt
+ assert "Refine" in p1 and "Frame metrics" in p1 and "Previous score 0.55" in p1
+ assert rec.rounds[1].instructions and all("[judge/" in i or "[gate/" in i for i in rec.rounds[1].instructions)
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ for k in ("plan.done", "round.start", "build.done", "gates.done", "judge.done", "refine.planned", "stop", "run.done"):
+ assert k in kinds, k
+
+
+def test_static_frames_become_a_gate_warning_and_refine_task(tmp_path, settings):
+ spec = make_spec(max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "static")
+
+ def writer(job, ws_):
+ return {"src/shader.frag": f"// {STATIC_MARK}\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) {{ fragColor = vec4(1.0, 0.5, 0.2, 1.0); }}\n"}
+
+ judge = FakeJudge(scores=(0.5, 0.5), targets=("overall",))
+ track = GraphicsTrack(services=_services(), judge=judge, agent=FakeAgent(writer), planner_model=FakeChatModel(lambda req: plan_example()),
+ settings=settings, runtime=FakeGlRuntime())
+ rec = track.run(spec, ws)
+ gl = next(g for g in rec.rounds[0].gates if g.gate == "gl_frames")
+ assert gl.passed and any(f.data["kind"] == "static" for f in gl.findings)
+ # the gate's warning is visible to the judge input and the refine round carried a task
+ assert "static" in judge.calls[0].extra_context.lower()
+
+
+def test_build_failure_routes_to_rebuild_task(tmp_path, settings):
+ spec = make_spec(max_rounds=2)
+ ws = Workspace(tmp_path / "runs" / "broken")
+ calls = {"n": 0}
+
+ def writer(job, ws_):
+ calls["n"] += 1
+ if calls["n"] <= 3: # baseline + 2 repair attempts keep failing
+ return {"src/shader.frag": f"void mainImage(out vec4 fragColor, in vec2 fragCoord) {{ fragColor = vec4(nope); }} // {FAIL_MARK} {calls['n']}\n"}
+ return _writer(job, ws_)
+
+ agent = FakeAgent(writer)
+ track = GraphicsTrack(services=_services(), judge=FakeJudge(scores=(0.8,)), agent=agent, planner_model=FakeChatModel(lambda req: plan_example()),
+ settings=settings, runtime=FakeGlRuntime())
+ rec = track.run(spec, ws)
+ assert rec.rounds[0].build is not None and not rec.rounds[0].build.ok
+ assert rec.rounds[0].build.error_file == "src/shader.frag" and rec.rounds[0].build.error_line == 3
+ assert rec.rounds[1].kind == "refine" and rec.rounds[1].instructions == ["rebuild: previous round did not build"]
+ assert rec.rounds[1].build is not None and rec.rounds[1].build.ok
+ labels = [j.label for j in agent.jobs]
+ assert labels[0] == "baseline" and any(lb.startswith("r00_baseline_repair") for lb in labels) and "rebuild" in labels
+
+
+def test_planner_reask_and_acceptance(tmp_ws):
+ spec = make_spec()
+ attempts = {"n": 0}
+
+ def responder(req):
+ attempts["n"] += 1
+ if attempts["n"] == 1:
+ return {"title": "x", "summary": "y", "style": "z", "passes": []} # invalid: passes min_length=1
+ return plan_example()
+
+ model = FakeChatModel(responder)
+ plan = plan_graphics(spec, "fake:planner", tmp_ws, model=model)
+ assert attempts["n"] == 2 and plan.title == "Neon rain on a window" and tmp_ws.plan_path.is_file()
+ assert "Fix EXACTLY these problems" in model.requests[1].messages[-1].text
+ ids = [a.id for a in plan.acceptance]
+ assert "must1" in ids and "a3" in ids # spec must_have appended, motion item already present in the example
+ # a plan without a motion acceptance item gets one; no 'ground contact' ever
+ p2 = ensure_graphics_acceptance(GraphicsPlan.model_validate({**plan_example(), "acceptance": []}), spec)
+ assert any(a.id.startswith("motion") for a in p2.acceptance) and not any("ground" in a.text.lower() for a in p2.acceptance)
+ always_bad = FakeChatModel(lambda req: {"title": "x"})
+ with pytest.raises(PlanningError):
+ plan_graphics(spec, "fake:planner", tmp_ws, model=always_bad)
+ sys_prompt = build_plan_system_prompt(spec)
+ assert "ART-DIRECTOR" in sys_prompt and "NeonRainWindow" in sys_prompt
+
+
+def test_templates_render_and_rubric_loads(tmp_path, settings):
+ rubric = load_rubric("shader_v1")
+ assert rubric.track_hint == "graphics" and {c.id for c in rubric.criteria} >= {"brief_fidelity", "motion_quality", "technical_cleanliness"}
+ assert {c.id for c in rubric.caps} >= {"nan_pixels", "static_frames", "black_or_blown", "build_error"}
+ spec = make_spec(language=Language.OPENGL_PYTHON, generator="single-shot:fake:fake-model")
+ ws = Workspace(tmp_path / "runs" / "tpl").create()
+ track = GraphicsTrack(services=_services(), settings=settings, runtime=FakeGlRuntime())
+ from codeverse.orchestrator.state import RunState
+
+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState.load_or_new(ws, resume=False))
+ ctx.plan = GraphicsPlan.model_validate(plan_example())
+ base = graphics_prompt_context(ctx, skeleton_files={"src/program.py": "# x"}, previous_error="")
+ assert base["expected_files"] == ["src/program.py"] and base["single_shot"] and "=== FILE:" in base["output_format"]
+ gen = render("tracks/generate_graphics.j2", **base)
+ assert "src/program.py" in gen and "| CityBokeh |" in gen and "1280x720" in gen
+ ref = render("tracks/refine_graphics.j2", **graphics_prompt_context(
+ ctx, round_index=1, tasks=["[judge/effect] overall: more bokeh"], targets=["overall"], files=["src/program.py"],
+ judge_summary="Previous score 0.5", frame_notes="(no frame metrics)", current_files={"src/program.py": "# y"}))
+ assert "more bokeh" in ref and "--- src/program.py ---" in ref
+ pipe = GraphicsPipeline()
+ assert "CityBokeh" in pipe.plan_summary(ctx)
diff --git a/harness/tests/graphics/test_wrap_lint.py b/harness/tests/graphics/test_wrap_lint.py
new file mode 100644
index 00000000..4c7fa9a8
--- /dev/null
+++ b/harness/tests/graphics/test_wrap_lint.py
@@ -0,0 +1,115 @@
+"""Offline: shader wrapping / line maps / compiler-log parsing and the two lints."""
+
+from __future__ import annotations
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.glsl_shader.lint import lint_text, lint_workspace
+from codeverse.languages.glsl_shader.wrap import (
+ HEADER,
+ compose,
+ detect_convention,
+ first_error,
+ parse_glsl_log,
+)
+from codeverse.languages.opengl_python.lint import lint_source
+from codeverse.languages.opengl_python.lint import lint_workspace as lint_program_ws
+
+SHADER = "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n fragColor = vec4(uv, 0.5 + 0.5*sin(u_time), 1.0);\n}\n"
+COMMON = "float hash(float n) { return fract(sin(n) * 43758.5453); }\n"
+
+
+def test_compose_line_map_with_common_and_trailer():
+ c = compose(SHADER, COMMON)
+ assert c.convention == "mainImage" and not c.uses_feedback
+ header_lines = HEADER.count("\n")
+ assert c.source.startswith("#version 330 core")
+ # common.glsl line 1 sits right after the header; shader.frag line 1 right after common
+ assert c.line_map.locate(header_lines + 1) == ("src/common.glsl", 1)
+ assert c.line_map.locate(header_lines + 2) == ("src/shader.frag", 1)
+ assert c.line_map.locate(header_lines + 4) == ("src/shader.frag", 3)
+ assert c.source.rstrip().endswith("void main() { mainImage(fragColor, gl_FragCoord.xy); }")
+
+
+def test_plain_main_convention_has_no_trailer_and_comments_ignored():
+ src = "// mainImage is mentioned here only in a comment; u_prev too\nvoid main() { fragColor = vec4(1.0); }\n"
+ c = compose(src)
+ assert c.convention == "main" and not c.uses_feedback
+ assert "mainImage(fragColor" not in c.source
+ assert detect_convention("void mainImage(out vec4 c, in vec2 f) {}") == "mainImage"
+ assert compose("void mainImage(out vec4 c, in vec2 f) { c = texture(u_prev, f); }").uses_feedback
+
+
+def test_parse_glsl_log_dialects_map_to_files():
+ c = compose(SHADER, COMMON)
+ off = HEADER.count("\n") + 1 # common.glsl starts here (1 line) → shader.frag starts at off+1
+ mesa = f"0:{off + 2}(12): error: `foo' undeclared\n0:{off}(3): warning: unused\n"
+ nvidia = f"0({off + 2}) : error C1008: undefined variable \"foo\"\n"
+ angle = f"ERROR: 0:{off + 2}: 'foo' : undeclared identifier\n"
+ for log in (mesa, nvidia, angle):
+ msgs = parse_glsl_log(log, c.line_map)
+ err = first_error(msgs)
+ assert err is not None and err.file == "src/shader.frag" and err.file_line == 2, log
+ msgs = parse_glsl_log(mesa, c.line_map)
+ assert [m.kind for m in msgs] == ["error", "warning"] and msgs[1].file == "src/common.glsl"
+ assert parse_glsl_log("GLSL Compiler failed\n\nfragment_shader\n===========\n") == []
+
+
+def test_glsl_lint_rules():
+ bad = (
+ "// comment: uniform float u_time; is provided\n#version 330 core\nuniform float u_time;\nuniform float u_speed;\n"
+ "out vec4 fragColor;\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec3 c = texture(iChannel2, vec2(0)).rgb;\n"
+ " c += texture(u_tex, vec2(0)).rgb;\n float m = 3.0 % 2.0;\n gl_FragColor = vec4(c, 1.0);\n}\n"
+ )
+ kinds = {f.data["kind"] for f in lint_text(bad) if f.severity == Severity.ERROR}
+ assert {"version_line", "redeclared_uniform", "custom_uniform", "redeclared_output", "missing_input", "undeclared_sampler",
+ "float_modulo", "legacy_glsl"} <= kinds
+ # the comment on line 1 must not trigger anything; the #version is reported on line 2
+ ver = next(f for f in lint_text(bad) if f.data["kind"] == "version_line")
+ assert ver.data["line"] == 2
+ assert not [f for f in lint_text(SHADER, COMMON) if f.severity == Severity.ERROR]
+ # common.glsl must not carry an entry point; no entry at all is an error
+ assert any(f.data["kind"] == "entry_in_common" for f in lint_text(SHADER, "void main(){}"))
+ assert any(f.data["kind"] == "no_entry" for f in lint_text("vec3 f() { return vec3(0); }"))
+ assert any(f.data["kind"] == "buffer_self_ref" for f in lint_text(SHADER, None, SHADER.replace("u_resolution", "u_buffer_a") + "\n"))
+
+
+def test_glsl_lint_workspace_missing_and_stray(tmp_ws):
+ rep = lint_workspace(tmp_ws)
+ assert not rep.passed and rep.findings[0].data["kind"] == "missing_entry"
+ (tmp_ws.src / "shader.frag").write_text(SHADER)
+ (tmp_ws.src / "extra.frag").write_text("// stray")
+ rep = lint_workspace(tmp_ws)
+ assert rep.passed and any(f.data["kind"] == "stray_file" for f in rep.findings)
+
+
+PROGRAM_OK = """import math
+import moderngl
+import numpy as np
+def setup(ctx, width, height):
+ return {}
+def render(ctx, state, t, frame, fbo):
+ fbo.use()
+"""
+
+
+def test_program_lint_rules():
+ assert not [f for f in lint_source(PROGRAM_OK) if f.severity == Severity.ERROR]
+ bad = (
+ "import glfw\nimport os\nimport time\nimport moderngl\nimport random\n"
+ "SRC = '''#version 120\\nvoid main(){ gl_FragColor = vec4(1.0); }'''\n"
+ "def setup(ctx, w):\n ctx2 = moderngl.create_standalone_context()\n f = open('x')\n return random.random()\n"
+ "def render(ctx, state, t, frame, fbo):\n now = time.time()\n"
+ )
+ kinds = {f.data["kind"] for f in lint_source(bad)}
+ assert {"window_lib", "forbidden_import", "own_context", "forbidden_call", "wall_clock", "bad_signature", "glsl_version",
+ "legacy_glsl", "unseeded_random"} <= kinds
+ assert any(f.data["kind"] == "syntax" for f in lint_source("def setup(:\n"))
+ assert any(f.data["kind"] == "missing_entry" for f in lint_source("import moderngl\n"))
+
+
+def test_program_lint_workspace(tmp_ws):
+ assert not lint_program_ws(tmp_ws).passed
+ (tmp_ws.src / "program.py").write_text(PROGRAM_OK)
+ (tmp_ws.src / "helpers.py").write_text("x = 1\n")
+ rep = lint_program_ws(tmp_ws)
+ assert rep.passed and any(f.data["kind"] == "stray_file" for f in rep.findings)
diff --git a/harness/tests/judges/test_calibration.py b/harness/tests/judges/test_calibration.py
new file mode 100644
index 00000000..7efa5ac2
--- /dev/null
+++ b/harness/tests/judges/test_calibration.py
@@ -0,0 +1,85 @@
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.run import RoundRecord
+from codeverse.judges.calibration import calibrate, load_run_cases, pearson, plan_digest, spearman
+from codeverse.judges.rubrics import load_rubric
+from tests.judges.conftest import (
+ ACCEPTANCE,
+ FakeChatModel,
+ good_reply,
+ make_measurement,
+ make_renders,
+ make_spec,
+)
+
+R = load_rubric("static_object_v1")
+
+
+def _fake_run(root: Path, name: str) -> Path:
+ run = root / name
+ (run / "rounds").mkdir(parents=True)
+ (run / "spec.json").write_text(make_spec(id=name).model_dump_json())
+ plan = {"object_name": "Chair", "summary": "a chair.", "overall_bbox": {"center": [0, 0, 0.4], "extents": [0.5, 0.5, 0.9]},
+ "parts": [{"name": "Seat", "instances": 1}, {"name": "Leg", "instances": 4}],
+ "acceptance": [a.model_dump() for a in ACCEPTANCE]}
+ (run / "plan.json").write_text(json.dumps(plan))
+ (run / "record.json").write_text(json.dumps({"best_round": 1}))
+ bad = GateReport(gate="connectivity", passed=False, findings=[
+ GateFinding(gate="connectivity", severity=Severity.ERROR, target="Leg", message="part floating 30 mm", data={"kind": "floating"}),
+ GateFinding(gate="connectivity", severity=Severity.WARN, message="sliver")])
+ for i, gates in enumerate(([bad], [GateReport(gate="connectivity", passed=True)])):
+ rec = RoundRecord(index=i, kind="baseline" if i == 0 else "refine", gates=gates, measurement=make_measurement(),
+ renders=make_renders(run / "artifacts" / "renders" / f"r{i:02d}", sheet=False))
+ (run / "rounds" / f"r{i:02d}.json").write_text(rec.model_dump_json())
+ return run
+
+
+def test_plan_digest_and_load_cases(tmp_path):
+ run = _fake_run(tmp_path, "runA")
+ cases = load_run_cases(run)
+ assert [c.round_index for c in cases] == [0, 1] and cases[0].gate_errors == 1 and cases[1].gate_errors == 0
+ assert cases[0].rubric == "static_object_v1" and len(cases[0].inp.acceptance) == 2
+ assert cases[1].is_best and not cases[0].is_best and cases[0].glb is None
+ assert cases[0].inp.plan_summary == "Chair: a chair. Overall 0.50×0.50×0.90 m. Parts: Seat, Leg×4."
+ assert plan_digest({"title": "Harbour", "summary": "s", "zones": [{"name": "quay"}], "cameras": [{"name": "cam_hero"}], "setting": "dusk"}) \
+ == "Harbour: s Zones: quay. Cameras: cam_hero. Setting: dusk."
+ assert load_run_cases(run, rounds=[1])[0].round_index == 1
+
+
+def test_correlations():
+ assert pearson([0, 1, 2], [2, 1, 0]) == -1.0 and spearman([0, 1, 5], [5, 3, 1]) == -1.0
+ assert pearson([1, 1], [0, 1]) is None and spearman([], []) is None
+ assert spearman([1, 1, 2], [1, 2, 3]) == pytest.approx(0.866, abs=1e-3)
+
+
+def test_calibrate_offline(tmp_path):
+ runs = [_fake_run(tmp_path, "runA"), _fake_run(tmp_path, "runB")]
+ ids = ["A1", "A2"]
+ # every round gets 2 samples; gate-error rounds get low scores so the correlation is negative
+ def reply(req):
+ low = "errors (1)" in req.messages[0].parts[0].text
+ return good_reply(R, ids, 0.5 if low else 0.9)
+ model = FakeChatModel(default=reply)
+ table = calibrate(runs, model_id="fake:fake-1", n_samples=2, out_dir=tmp_path / "out", geometry_mode=None,
+ chat_model=model, max_workers=2)
+ assert len(table.rows) == 4 and table.n_samples == 2
+ r0 = next(r for r in table.rows if r.run == "runA" and r.round == 0)
+ assert r0.gate_errors == 1 and r0.caps == ["floating_part"] and r0.mean == 0.5 and r0.uncapped == 0.5
+ r1 = next(r for r in table.rows if r.run == "runA" and r.round == 1)
+ assert r1.mean == pytest.approx(0.9) and r1.passed and r1.n_used == 2
+ assert table.pearson_errors_vs_score == -1.0 and table.spearman_errors_vs_score == -1.0
+ assert table.pearson_stored_vs_new is None # fake rounds carry no stored judgment
+ assert len(model.requests) == 8 and table.total_cost_usd == pytest.approx(0.008)
+ md = (tmp_path / "out" / "calibration_fake_fake-1.md").read_text()
+ assert "| runA | r00 | baseline | 1/1 |" in md and "pearson(gate errors, new score) = -1.000" in md
+ data = json.loads((tmp_path / "out" / "calibration_fake_fake-1.json").read_text())
+ assert data["rows"][0]["per_criterion_std"]
+ empty = tmp_path / "empty"
+ (empty / "rounds").mkdir(parents=True)
+ (empty / "spec.json").write_text(make_spec(id="empty").model_dump_json())
+ with pytest.raises(ValueError, match="no judgeable rounds"):
+ calibrate([empty], model_id="fake:fake-1", out_dir=tmp_path / "out", chat_model=model)
diff --git a/harness/tests/judges/test_defects.py b/harness/tests/judges/test_defects.py
new file mode 100644
index 00000000..21e50f58
--- /dev/null
+++ b/harness/tests/judges/test_defects.py
@@ -0,0 +1,130 @@
+"""Defect checklist: rubric → wire schema → parse → majority vote → penalties/caps in code."""
+
+import json
+
+import pytest
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.judges.caps import apply_caps
+from codeverse.judges.output_schema import JudgeParseError, parse_judge_output, wire_schema
+from codeverse.judges.rubrics import RubricError, load_rubric, rubric_from_dict
+from codeverse.judges.scoring import aggregate_samples
+from codeverse.judges.vlm_judge import VlmJudge
+from tests.judges.conftest import FakeChatModel, good_reply
+
+R = load_rubric("static_object_v1")
+A = load_rubric("articulated_v1")
+IDS = ["A1", "A2"]
+
+
+def _reply(score=0.9, defects=None):
+ rep = good_reply(R, IDS, score)
+ rep["defects"] = {d.id: {"present": d.id in (defects or ()), "evidence": "MONTAGE 1 top-left"} for d in R.defects}
+ return rep
+
+
+def test_rubrics_declare_defects_with_costs():
+ for name in ("static_object_v1", "articulated_v1", "scene_v1", "asset_v1", "reference_v1"):
+ r = load_rubric(name)
+ assert r.defects, name
+ assert all(d.penalty > 0 or d.cap is not None for d in r.defects)
+ assert R.defect("floating_part").penalty == 0.10 and R.defect("floating_part").cap == 0.60
+ assert R.defect("wrong_object").cap == 0.25 and R.defect("wrong_object").penalty == 0.0
+ assert {"no_articulation_visible", "wrong_motion_type", "pivot_misplaced", "pose_clips_body"} <= {d.id for d in A.defects}
+ with pytest.raises(KeyError):
+ R.defect("nope")
+
+
+def test_duplicate_defect_ids_rejected():
+ bad = {"name": "x", "pass_threshold": 0.7, "criteria": [
+ {"id": "a", "weight": 1.0, "description": "d", "anchors": {"1.0": "", "0.7": "", "0.4": "", "0.1": ""}}],
+ "defects": [{"id": "f", "text": "t"}, {"id": "f", "text": "t2"}]}
+ with pytest.raises(RubricError):
+ rubric_from_dict(bad)
+
+
+def test_wire_schema_has_fixed_defect_keys_and_parse_variants():
+ schema = wire_schema(R, IDS)
+ props = schema["$defs"]["Defects"]["properties"]
+ assert set(props) == {d.id for d in R.defects}
+ out = parse_judge_output(_reply(defects=["floating_part"]), R, IDS)
+ assert out.defects["floating_part"] is True and out.defects["primitive_only"] is False
+ assert out.defect_evidence["floating_part"] == "MONTAGE 1 top-left"
+ # bare booleans and list-of-records are accepted; unknown ids dropped; missing ids → absent
+ rep = good_reply(R, IDS, 0.8)
+ rep["defects"] = [{"id": "interpenetration", "present": True}, {"id": "made_up", "present": True}]
+ out2 = parse_judge_output(rep, R, IDS)
+ assert out2.defects["interpenetration"] is True and "made_up" not in out2.defects
+ assert out2.defects["floating_part"] is False and out2.defect_evidence["floating_part"] == "not answered by judge"
+ rep3 = good_reply(R, IDS, 0.8)
+ rep3["defects"] = {"floating_part": True}
+ assert parse_judge_output(rep3, R, IDS).defects["floating_part"] is True
+ rep4 = good_reply(R, IDS, 0.8)
+ rep4["defects"] = {"floating_part": {"present": "yes"}}
+ with pytest.raises(JudgeParseError):
+ parse_judge_output(rep4, R, IDS)
+
+
+def test_penalties_and_caps_computed_in_code(judge_input, cache_dir):
+ # floating_part: -0.10 and cap 0.60; primitive_only: -0.08 no cap
+ model = FakeChatModel([_reply(0.9, ["primitive_only"])])
+ j = VlmJudge("static_object_v1", chat_model=model, cache_dir=cache_dir).judge(judge_input)
+ raw = json.loads(j.raw)
+ assert raw["overall_uncapped"] == pytest.approx(0.9) and raw["defect_penalty"] == pytest.approx(0.08)
+ assert j.overall == pytest.approx(0.82) and j.passed
+ assert raw["defects"]["primitive_only"] is True and raw["caps"]["caps_applied"] == []
+ assert "defects (-0.08): primitive_only" in j.summary
+ model2 = FakeChatModel([_reply(0.9, ["floating_part", "primitive_only"])])
+ j2 = VlmJudge("static_object_v1", chat_model=model2, cache_dir=cache_dir).judge(judge_input)
+ raw2 = json.loads(j2.raw)
+ assert raw2["overall_after_defects"] == pytest.approx(0.72)
+ assert j2.overall == 0.6 and not j2.passed # capped by defect:floating_part
+ assert raw2["caps"]["caps_applied"][0]["rule"] == "defect:floating_part"
+ # the checklist is per-sample data too
+ assert raw2["samples"][0]["defects"]["floating_part"] is True
+
+
+def test_defect_majority_vote_ties_count_as_present(judge_input, cache_dir):
+ model = FakeChatModel([_reply(0.9, ["render_artifacts"]), _reply(0.9), _reply(0.9)])
+ j = VlmJudge("static_object_v1", chat_model=model, n_samples=3, cache_dir=cache_dir).judge(judge_input)
+ raw = json.loads(j.raw)
+ assert raw["defects"]["render_artifacts"] is False and raw["defect_votes"]["render_artifacts"] == [True, False, False]
+ assert j.overall == pytest.approx(0.9)
+ model2 = FakeChatModel([_reply(0.9, ["render_artifacts"]), _reply(0.9)])
+ j2 = VlmJudge("static_object_v1", chat_model=model2, n_samples=2, cache_dir=cache_dir).judge(judge_input)
+ assert json.loads(j2.raw)["defects"]["render_artifacts"] is True and j2.overall == pytest.approx(0.85)
+ # per-criterion std is reported for n-sample runs
+ assert set(json.loads(j2.raw)["per_criterion_std"]) == set(R.weights)
+
+
+def test_missing_views_cap_for_articulated():
+ rest = [RenderView(name=n, path="x") for n in ("front_right_34", "top")]
+ res = apply_caps(A, 0.9, [], {}, [], views=rest)
+ assert res.overall == 0.5 and res.caps_applied[0].rule == "missing_pose_sheet"
+ res2 = apply_caps(A, 0.9, [], {}, [], views=rest + [RenderView(name="articulation_sheet", path="s")])
+ assert res2.overall == 0.9 and not res2.caps_applied
+ res3 = apply_caps(A, 0.9, [], {}, [], views=rest + [RenderView(name="pose_J@upper", path="s")])
+ assert res3.overall == 0.9
+ # the judge pipeline passes the views through
+ samples = [parse_judge_output(good_reply(A, [], 0.9), A, [])]
+ j = aggregate_samples(A, samples, gates=[], acceptance_items=[], views=rest)
+ assert j.overall == 0.5 and "missing_pose_sheet≤0.50" in j.summary
+ j2 = aggregate_samples(A, samples, gates=[], acceptance_items=[], views=list(RenderSet(views=rest + [RenderView(name="pose_rest", path="p")]).views))
+ assert j2.overall == pytest.approx(0.9)
+
+
+def test_interpenetrate_message_matches_penetration_cap():
+ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+ g = GateReport(gate="connectivity", passed=False, findings=[GateFinding(
+ gate="connectivity", severity=Severity.ERROR, target="Leg", message="'Leg' and 'Seat' interpenetrate by ≈15 mm")])
+ assert apply_caps(R, 0.9, [g], {}, []).overall == 0.7
+ assert apply_caps(A, 0.9, [g], {}, [], views=[RenderView(name="pose_rest", path="p")]).overall == 0.7
+
+
+def test_joint_sweep_touches_nothing_caps_articulated():
+ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+ g = GateReport(gate="joint_sweep", passed=False, findings=[GateFinding(
+ gate="joint_sweep", severity=Severity.ERROR, target="DrawerKnob",
+ message="link 'DrawerKnob' touches nothing connected to the root at pose rest (nearest 'Carcass' at 56.4 mm)")])
+ res = apply_caps(A, 0.9, [g], {}, [], views=[RenderView(name="pose_rest", path="p")])
+ assert res.overall == 0.6 and res.caps_applied[0].rule == "floating_part"
diff --git a/harness/tests/judges/test_live.py b/harness/tests/judges/test_live.py
index 46ddc05f..7263ce82 100644
--- a/harness/tests/judges/test_live.py
+++ b/harness/tests/judges/test_live.py
@@ -75,6 +75,26 @@ def test_live_vlm_judge_two_samples(tmp_path):
assert j.n_samples == 2 and raw["sample_errors"] == [] # parsed first try
assert 0.0 < j.overall < 1.0
assert set(j.scores) == {c.id for c in judge.rubric.criteria}
+ assert set(raw["defects"]) == {d.id for d in judge.rubric.defects} # checklist answered
+ print(f"defects={[d for d, on in raw['defects'].items() if on]} penalty={raw['defect_penalty']}")
+
+
+def test_live_judge_separates_crafted_from_crude(tmp_path):
+ """Dynamic range: a real stool render set vs a crude PIL chair drawing, same brief (stool)."""
+ renders, meas, source = _renders_for_test(tmp_path / "stool")
+ if "stool" not in source:
+ pytest.skip("needs real stool renders")
+ spec = make_spec(prompt="A simple three-legged wooden stool, 45 cm tall, round seat 36 cm across.")
+ judge = VlmJudge("static_object_v1", model_id=MODEL, n_samples=1, cache_dir=tmp_path / "cache")
+ good = judge.judge(JudgeInput(spec=spec, renders=renders, measurement=meas, plan_summary="parts: Seat, Leg1, Leg2, Leg3"))
+ crude = judge.judge(JudgeInput(spec=spec, renders=make_renders(tmp_path / "crude"), measurement=make_measurement(),
+ plan_summary="parts: Seat, Leg1, Leg2, Leg3"))
+ gd, cd = json.loads(good.raw), json.loads(crude.raw)
+ print(f"\nLIVE stool overall={good.overall} uncapped={gd['overall_uncapped']} defects={[d for d, o in gd['defects'].items() if o]}"
+ f"\nLIVE crude overall={crude.overall} uncapped={cd['overall_uncapped']} defects={[d for d, o in cd['defects'].items() if o]}")
+ assert not is_degraded(good) and not is_degraded(crude)
+ assert good.overall - crude.overall >= 0.25
+ assert any(cd["defects"].values()) # the crude drawing trips the checklist
def test_live_pairwise_stool_vs_chair(tmp_path):
@@ -90,6 +110,24 @@ def test_live_pairwise_stool_vs_chair(tmp_path):
assert res.winner == "a"
+def test_live_compare_many_ranks_stool_over_crude(tmp_path):
+ from codeverse.judges.pairwise import PairwiseJudge
+
+ renders, _, source = _renders_for_test(tmp_path / "stool")
+ if "stool" not in source:
+ pytest.skip("needs real stool renders")
+ from codeverse.conventions import OBJECT_VIEWS_QUICK
+ from codeverse.spatial.render import render_glb
+
+ clay = render_glb(tmp_path / "stool" / "stool.glb", tmp_path / "clay", views=OBJECT_VIEWS_QUICK, mode="clay", sheet=False)
+ crude = make_renders(tmp_path / "crude")
+ spec = make_spec(prompt="A simple three-legged wooden stool, 45 cm tall, round seat.")
+ rank = PairwiseJudge(MODEL, cache_dir=tmp_path / "cache").compare_many(spec, [crude, renders, clay])
+ print(f"\nLIVE ranking order={rank.order} points={rank.points} errors={rank.errors}\nusage={rank.usage}")
+ assert rank.order[-1] == 0 # the crude drawing ranks last
+ assert len(rank.pairs) == 3
+
+
def test_live_reference_judge(tmp_path):
from codeverse.contracts.spec import ReferenceImage
from codeverse.judges.reference import ReferenceJudge
diff --git a/harness/tests/judges/test_montage.py b/harness/tests/judges/test_montage.py
new file mode 100644
index 00000000..5a566432
--- /dev/null
+++ b/harness/tests/judges/test_montage.py
@@ -0,0 +1,120 @@
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.judges.images import JudgeImageError
+from codeverse.judges.montage import (
+ describe_montages,
+ montage_label,
+ montage_strip,
+ plan_montages,
+ rank_views,
+ render_montage,
+ shuffle_montages,
+)
+from codeverse.spatial.sheet import crop_region, montage_2x2
+from tests.judges.conftest import draw_chair
+
+OBJ = ("front_right_34", "back_left_34", "front", "right", "back", "left", "top", "low_front_left")
+
+
+def _views(tmp: Path, names, *, mode="shaded", prefix="v"):
+ out = []
+ for n in names:
+ p = draw_chair(tmp / f"{prefix}_{n}.png")
+ out.append(RenderView(name=n, path=str(p), mode=mode))
+ return out
+
+
+def test_rank_views_objects_and_scenes():
+ vs = [RenderView(name=n, path="x") for n in ("left", "top", "zzz", "front_right_34")]
+ assert [v.name for v in rank_views(vs, scene=False)] == ["front_right_34", "top", "left", "zzz"]
+ sv = [RenderView(name=n, path="x") for n in ("overview_top", "cam_hero", "eye_front", "other", "cam_b")]
+ assert [v.name for v in rank_views(sv, scene=True)] == ["cam_hero", "cam_b", "eye_front", "overview_top", "other"]
+
+
+def test_plan_montages_object_rig(tmp_path):
+ rs = RenderSet(views=_views(tmp_path, OBJ))
+ ms = plan_montages(rs)
+ kinds = [m.kind for m in ms]
+ assert kinds == ["shaded", "shaded", "detail", "detail"]
+ assert [v.name for v in ms[0].tiles] == ["front_right_34", "back_left_34", "top", "low_front_left"]
+ assert [v.name for v in ms[1].tiles] == ["front", "right", "back", "left"]
+ assert ms[2].crop == (0.25, 0.25, 0.75, 0.75) and ms[3].tiles[0].name == "low_front_left"
+ assert "- image 2: SHADED views (remaining)" in describe_montages(ms)
+
+
+def test_plan_montages_articulated_and_geometry(tmp_path):
+ poses = _views(tmp_path, ["pose_rest", "pose_J@upper", "pose_K@upper"], prefix="p")
+ sheet = _views(tmp_path, ["articulation_sheet"], prefix="s")
+ rs = RenderSet(views=_views(tmp_path, OBJ) + sheet + poses)
+ clay = RenderSet(views=_views(tmp_path, ["front_right_34", "top", "back"], mode="clay", prefix="c"))
+ ms = plan_montages(rs, geometry_views=clay, max_montages=3, detail_crops=0)
+ assert [m.kind for m in ms] == ["shaded", "pose_sheet", "geometry"]
+ assert ms[1].passthrough and ms[1].tiles[0].name == "articulation_sheet"
+ # geometry tiles are matched to the primary montage's views first
+ assert [v.name for v in ms[2].tiles] == ["front_right_34", "top", "back"]
+ assert "GEOMETRY-ONLY views (clay" in ms[2].title
+ # more room: secondary shaded then the pose 2×2 (duplicate of the sheet, lowest priority)
+ ms5 = plan_montages(rs, geometry_views=clay, max_montages=5, detail_crops=0)
+ assert [m.kind for m in ms5] == ["shaded", "pose_sheet", "geometry", "shaded", "poses"]
+ # without a sheet the pose_* views form the pose montage
+ rs2 = RenderSet(views=_views(tmp_path, OBJ[:4]) + poses)
+ ms2 = plan_montages(rs2, detail_crops=0)
+ assert [m.kind for m in ms2] == ["shaded", "poses"] and len(ms2[1].tiles) == 3
+
+
+def test_missing_pose_views_leave_no_pose_montage(tmp_path):
+ rs = RenderSet(views=_views(tmp_path, OBJ[:4]))
+ assert all(m.kind in ("shaded", "detail") for m in plan_montages(rs))
+
+
+def test_shuffle_keeps_sets_and_details_last(tmp_path):
+ rs = RenderSet(views=_views(tmp_path, OBJ))
+ ms = plan_montages(rs)
+ sh = shuffle_montages(ms, 7)
+ assert shuffle_montages(ms, 7) == sh and shuffle_montages(ms, None) == ms
+ assert [m.kind for m in sh[-2:]] == ["detail", "detail"]
+ assert {frozenset(v.name for v in m.tiles) for m in sh[:2]} == {frozenset(v.name for v in m.tiles) for m in ms[:2]}
+ seeds = {tuple((m.kind, tuple(v.name for v in m.tiles)) for m in shuffle_montages(ms, s)) for s in range(6)}
+ assert len(seeds) >= 3
+
+
+def test_labels_and_render(tmp_path):
+ rs = RenderSet(views=_views(tmp_path, OBJ[:3]))
+ m = plan_montages(rs, detail_crops=1)[0]
+ lbl = montage_label(m, 1, 1)
+ assert lbl.startswith("MONTAGE 1/1 — SHADED views: top-left = front_right_34 · az 35° el 22°, top-right = back_left_34")
+ assert "bottom-left = front · az 0° el 8°" in lbl
+ assert montage_strip(m, 1, 1) == "MONTAGE 1/1 — SHADED views"
+ png = render_montage(m, cache_dir=tmp_path / "cache", tile_px=256)
+ assert png.is_file() and render_montage(m, cache_dir=tmp_path / "cache", tile_px=256) == png # cached
+ with Image.open(png) as im:
+ assert im.size[0] == 2 * 256 + 3 * 6 and im.size[1] > 2 * 256 # 2 cols × 2 rows with labels
+ crop = plan_montages(rs, detail_crops=1)[-1]
+ cpng = render_montage(crop, cache_dir=tmp_path / "cache", tile_px=400)
+ with Image.open(cpng) as im:
+ assert max(im.size) >= 400
+ assert "look for bevels" in montage_label(crop, 1, 1)
+
+
+def test_missing_tile_is_judge_image_error(tmp_path):
+ m = plan_montages(RenderSet(views=[RenderView(name="front", path="/nonexistent/x.png")]), detail_crops=0)[0]
+ with pytest.raises(JudgeImageError):
+ render_montage(m, cache_dir=tmp_path / "cache")
+
+
+def test_sheet_helpers(tmp_path):
+ src = draw_chair(tmp_path / "a.png", size=600)
+ with pytest.raises(ValueError):
+ montage_2x2([("a", src)] * 5, tmp_path / "m.png")
+ out = montage_2x2([("one", src)], tmp_path / "m1.png", tile=200)
+ with Image.open(out) as im:
+ assert im.size[0] == 200 + 2 * 6 # single column
+ c = crop_region(src, tmp_path / "c.png", (0.25, 0.25, 0.75, 0.75), min_px=600)
+ with Image.open(c) as im:
+ assert im.size == (600, 600)
+ with pytest.raises(ValueError):
+ crop_region(src, tmp_path / "c2.png", (0.5, 0.5, 0.5, 0.9))
diff --git a/harness/tests/judges/test_pairwise.py b/harness/tests/judges/test_pairwise.py
index c25b7aea..542379c1 100644
--- a/harness/tests/judges/test_pairwise.py
+++ b/harness/tests/judges/test_pairwise.py
@@ -15,7 +15,11 @@ def test_agreement_across_swap(tmp_path, cache_dir):
assert res.winner == "a" and res.confidence == 0.8 and len(res.orderings) == 2
assert res.usage.cost_usd > 0
labels = [p.label for p in image_parts(model.requests[0])]
- assert labels[0].startswith("CANDIDATE A — contact sheet") and labels[1].startswith("CANDIDATE B")
+ assert len(labels) == 2 # one 2×2 montage per side
+ assert labels[0].startswith("CANDIDATE A — MONTAGE 1/1 — SHADED views: top-left = front_right_34") and labels[1].startswith("CANDIDATE B — MONTAGE")
+ # swapped ordering puts rb first as "A"
+ labels2 = [p.label for p in image_parts(model.requests[1])]
+ assert labels2[0].startswith("CANDIDATE A — MONTAGE")
def test_disagreement_is_tie(tmp_path, cache_dir):
@@ -30,7 +34,7 @@ def test_tie_and_errors(tmp_path, cache_dir):
model = FakeChatModel([_reply("tie", 0.6), _reply("tie", 0.6)])
res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)
assert res.winner == "tie" and res.confidence == 0.6
- assert len(image_parts(model.requests[0])) == 8 # 4 views per side without a sheet
+ assert len(image_parts(model.requests[0])) == 2 # still one montage per side without a sheet
model2 = FakeChatModel(default=ModelError("down", retryable=True))
res2 = PairwiseJudge("fake:fake-1", chat_model=model2, cache_dir=cache_dir).compare(make_spec(), ra, rb)
assert res2.winner == "tie" and res2.confidence == 0.0 and "ModelError" in res2.error
@@ -47,3 +51,29 @@ def test_unswap_reasons():
from codeverse.judges.pairwise import _unswap_text
assert _unswap_text("Candidate A beats candidate B", True) == "Candidate B beats candidate A"
assert _unswap_text("Candidate A beats candidate B", False) == "Candidate A beats candidate B"
+
+
+def test_compare_many_round_robin(tmp_path, cache_dir):
+ from codeverse.judges.pairwise import RankingResult
+ cands = [make_renders(tmp_path / f"c{i}") for i in range(3)]
+ # pairs (0,1), (0,2), (1,2); each compare = 2 orderings. Make 2 beat everyone, 0 beat 1.
+ replies = [_reply("A", 0.9), _reply("B", 0.8), # 0 v 1 → a (0 wins)
+ _reply("B", 0.9), _reply("A", 0.9), # 0 v 2 → b (2 wins)
+ _reply("B", 0.7), _reply("A", 0.7)] # 1 v 2 → b (2 wins)
+ model = FakeChatModel(replies)
+ rank: RankingResult = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare_many(make_spec(), cands)
+ assert rank.order == [2, 0, 1] and rank.best == 2
+ assert rank.points == {0: 1.0, 1: 0.0, 2: 2.0}
+ assert len(rank.pairs) == 3 and len(model.requests) == 6
+ assert rank.usage.cost_usd > 0 and rank.errors == []
+ # single candidate → no calls
+ solo = PairwiseJudge("fake:fake-1", chat_model=FakeChatModel(), cache_dir=cache_dir).compare_many(make_spec(), cands[:1])
+ assert solo.order == [0] and solo.points == {0: 0.0}
+
+
+def test_compare_many_ties_and_errors(tmp_path, cache_dir):
+ cands = [make_renders(tmp_path / f"c{i}") for i in range(2)]
+ model = FakeChatModel([_reply("A", 0.9), _reply("A", 0.9)]) # position bias → tie
+ rank = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare_many(make_spec(), cands)
+ assert rank.points == {0: 0.5, 1: 0.5} and rank.order == [0, 1]
+ assert rank.errors and "orderings disagree" in rank.errors[0]
diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.py
index d7bde978..f8a0677c 100644
--- a/harness/tests/judges/test_prompt_builder.py
+++ b/harness/tests/judges/test_prompt_builder.py
@@ -2,7 +2,7 @@ from pathlib import Path
from PIL import Image
-from codeverse.contracts.artifacts import GateFinding, GateReport, RenderView, Severity
+from codeverse.contracts.artifacts import GateFinding, GateReport, RenderSet, RenderView, Severity
from codeverse.contracts.chat import ImagePart, TextPart
from codeverse.contracts.judgment import ImprovementItem, Judgment
from codeverse.judges.images import prepare_image, view_az_el
@@ -10,7 +10,7 @@ from codeverse.judges.prompt_builder import (
TEXT_BUDGET_CHARS,
build_judge_messages,
build_system_prompt,
- select_views,
+ montage_image_parts,
)
from codeverse.judges.rubrics import load_rubric
from tests.judges.conftest import draw_chair, make_renders
@@ -22,12 +22,20 @@ def _parts(msgs):
return msgs[0].parts
-def test_system_has_role_rubric_and_anchors():
+def _images(msgs):
+ return [p for p in _parts(msgs) if isinstance(p, ImagePart)]
+
+
+def test_system_has_role_rubric_anchors_and_defects():
system = build_system_prompt(R)
assert "BLIND JUDGE" in system
for c in R.criteria:
assert c.id in system and c.anchors["0.4"][:30] in system
assert "Do NOT compute an overall" in system
+ assert "DEFECT CHECKLIST" in system
+ for d in R.defects:
+ assert f"- {d.id}:" in system
+ assert "[-0.10, cap 0.60]" in system # floating_part penalty + cap shown
def test_user_message_layout(judge_input, cache_dir):
@@ -39,50 +47,71 @@ def test_user_message_layout(judge_input, cache_dir):
assert section in text, section
assert "A1 [must, via measure]" in text
assert "Seat" in text and "Backrest" in text # measurement table (spatial or local fallback)
- imgs = [p for p in parts if isinstance(p, ImagePart)]
- assert len(imgs) == 5 # sheet + 4 views
- assert imgs[0].label.startswith("CONTACT SHEET")
- assert imgs[1].label.startswith("VIEW 1/4 — ")
- assert "az 35° el 22°" in imgs[1].label
- # labelled text precedes each image
- idx = parts.index(imgs[1])
- assert isinstance(parts[idx - 1], TextPart) and parts[idx - 1].text == imgs[1].label
- # prepared images are cached + downscaled + strip added
+ imgs = _images(msgs)
+ # 4 shaded views → ONE 2×2 montage + centre crop + ground-contact crop
+ assert len(imgs) == 3
+ assert imgs[0].label.startswith("MONTAGE 1/1 — SHADED views: top-left = front_right_34 · az 35° el 22°")
+ assert "bottom-left = top · az 0° el 88°, bottom-right = front · az 0° el 8°" in imgs[0].label
+ assert imgs[1].label.startswith("DETAIL CROP — centre of front_right_34")
+ assert imgs[2].label.startswith("DETAIL CROP — ground-contact band of front") # lowest elevation (8°)
+ # labelled text precedes each image; the rig paragraph lists images in send order
+ idx = parts.index(imgs[0])
+ assert isinstance(parts[idx - 1], TextPart) and parts[idx - 1].text == imgs[0].label
+ assert "- image 1: SHADED views" in text and "- detail crop 2: ground-contact band" in text
+ assert "MONTAGE k <position> (<view name>)" in text
for ip in imgs:
assert Path(ip.path).is_file() and Path(ip.path).parent == cache_dir
with Image.open(imgs[0].path) as im:
- assert max(im.size) <= 1024 + 80
+ assert 900 <= im.size[0] <= 1024 and im.size[1] > im.size[0] # 2×2 grid + strip
-def test_shuffle_is_deterministic_and_changes_order(judge_input, cache_dir):
+def test_shuffle_is_deterministic_and_changes_order(tmp_path, judge_input, cache_dir):
+ rs = make_renders(tmp_path / "eight", n=4)
+ extra = []
+ for name in ("right", "back", "left", "low_front_left"):
+ p = draw_chair(tmp_path / f"v_{name}.png", az_hint=1)
+ extra.append(RenderView(name=name, path=str(p)))
+ judge_input.renders = RenderSet(views=rs.views + extra)
_, a = build_judge_messages(judge_input, R, shuffle_seed=1, cache_dir=cache_dir)
_, b = build_judge_messages(judge_input, R, shuffle_seed=1, cache_dir=cache_dir)
_, c = build_judge_messages(judge_input, R, shuffle_seed=None, cache_dir=cache_dir)
- la = [p.label for p in _parts(a) if isinstance(p, ImagePart)]
- lb = [p.label for p in _parts(b) if isinstance(p, ImagePart)]
- lc = [p.label for p in _parts(c) if isinstance(p, ImagePart)]
+ la, lb, lc = ([p.label for p in _images(m)] for m in (a, b, c))
assert la == lb
- def names(ls):
- return [x.split("— ")[1].split(" ·")[0] for x in ls[1:]]
-
- assert sorted(names(la)) == sorted(names(lc))
- assert names(la) != names(lc) or True # shuffle of 4 may coincide; order set equality is what matters
+ assert len(lc) == 4 # 2 montages + 2 crops
+ assert lc[0].startswith("MONTAGE 1/2 — SHADED views:") and lc[1].startswith("MONTAGE 2/2 — SHADED views (remaining)")
+ # canonical order puts the 3/4 views first; the seeded order differs somewhere (montage or tile order)
+ assert la != lc
+ assert la[-2:] == lc[-2:] # detail crops are never shuffled
+
+
+def test_geometry_views_add_a_montage(tmp_path, judge_input, cache_dir):
+ clay = []
+ for v in judge_input.renders.views:
+ p = draw_chair(tmp_path / f"clay_{v.name}.png", color=(180, 180, 180))
+ clay.append(RenderView(name=v.name, path=str(p), mode="clay"))
+ _, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir, geometry_views=RenderSet(views=clay))
+ labels = [p.label for p in _images(msgs)]
+ assert labels[0].startswith("MONTAGE 1/2 — SHADED views") and labels[1].startswith("MONTAGE 2/2 — GEOMETRY-ONLY views (clay")
+ assert "front_right_34 · az 35° el 22° · clay" in labels[1]
+ text = _parts(msgs)[0].text
+ assert "GEOMETRY-ONLY montage shows the same object without materials" in text
+ # embedded clay views (by RenderView.mode) are routed the same way
+ judge_input.renders = RenderSet(views=judge_input.renders.views + clay)
+ _, msgs2 = build_judge_messages(judge_input, R, cache_dir=cache_dir)
+ assert any(p.label.startswith("MONTAGE 2/2 — GEOMETRY-ONLY") for p in _images(msgs2))
-def test_image_budget_subsamples(tmp_path, judge_input, cache_dir):
- rs = make_renders(tmp_path / "many", n=4)
+def test_montage_cap_and_crop_knobs(tmp_path, judge_input, cache_dir):
views = []
for i in range(14):
p = draw_chair(tmp_path / f"v{i}.png", az_hint=i)
views.append(RenderView(name=f"v{i}", path=str(p), camera_position=(1.0, 0.5, 1.0), look_at=(0, 0.3, 0)))
- rs.views = views
- judge_input.renders = rs
- _, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir, max_images=10)
- imgs = [p for p in _parts(msgs) if isinstance(p, ImagePart)]
- assert len(imgs) == 10
- assert imgs[1].label.startswith("VIEW 1/9")
- assert select_views(views, 9, shuffle_seed=None)[0].name == "v0"
- assert "az 45° el" in imgs[1].label # computed from camera geometry
+ judge_input.renders = RenderSet(views=views)
+ pairs, montages = montage_image_parts(judge_input.renders, cache_dir=cache_dir, max_montages=3, detail_crops=0)
+ assert len(pairs) == 3 and all(m.kind == "shaded" for m in montages)
+ assert "top-left = v0 · az 45° el" in pairs[0][0] # az/el computed from camera geometry
+ pairs2, _ = montage_image_parts(judge_input.renders, cache_dir=cache_dir, max_montages=1, detail_crops=1)
+ assert len(pairs2) == 2 and pairs2[1][0].startswith("DETAIL CROP — centre of v0")
def test_gates_previous_and_budget(judge_input, cache_dir):
@@ -109,6 +138,7 @@ def test_scene_rig_paragraph(judge_input, cache_dir):
_, msgs = build_judge_messages(judge_input, load_rubric("scene_v1"), cache_dir=cache_dir)
text = _parts(msgs)[0].text
assert "overview_*" in text and "console error" in text and "48 fps" in text
+ assert len(_images(msgs)) == 2 # montage + centre crop only (no ground band for scenes)
def test_view_az_el_geometry():
diff --git a/harness/tests/judges/test_reference.py b/harness/tests/judges/test_reference.py
index e9391204..0367e1be 100644
--- a/harness/tests/judges/test_reference.py
+++ b/harness/tests/judges/test_reference.py
@@ -30,7 +30,7 @@ def test_reference_judge_measures_silhouette_and_adds_reference_images(judge_inp
assert j.overall == pytest.approx(round(expected, 4))
req = model.requests[0]
labels = [p.label for p in image_parts(req)]
- assert labels[0].startswith("REFERENCE 1/1 (target) — target chair") and labels[1].startswith("CONTACT SHEET")
+ assert labels[0].startswith("REFERENCE 1/1 (target) — target chair") and labels[1].startswith("MONTAGE 1/1 — SHADED views")
assert "IoU 0.700" in req.messages[0].parts[0].text
assert "silhouette_match" not in req.response_schema["$defs"]["Criteria"]["properties"]
diff --git a/harness/tests/judges/test_vlm_judge.py b/harness/tests/judges/test_vlm_judge.py
index 39766c7c..c2ed9fff 100644
--- a/harness/tests/judges/test_vlm_judge.py
+++ b/harness/tests/judges/test_vlm_judge.py
@@ -32,8 +32,10 @@ def test_full_path_single_sample(judge_input, cache_dir):
req = model.requests[0]
assert req.response_schema is not None and "Criteria" in req.response_schema["$defs"]
assert req.label == "judge:static_object_v1:s0" and req.temperature == 0.2
- assert len(image_parts(req)) == 5
- assert "BLIND JUDGE" in req.system
+ assert len(image_parts(req)) == 3 # 2×2 montage + 2 detail crops
+ assert "BLIND JUDGE" in req.system and "DEFECT CHECKLIST" in req.system
+ assert "Defects" in req.response_schema["$defs"]
+ assert raw["defects"] == {d.id: False for d in R.defects} and raw["defect_penalty"] == 0.0
def test_overall_is_code_computed_weighted_mean(judge_input, cache_dir):
@@ -49,8 +51,8 @@ def test_n_samples_mean_std_and_shuffle(judge_input, cache_dir):
j = _judge(model, n_samples=3, cache_dir=cache_dir).judge(judge_input)
assert j.n_samples == 3 and j.overall == pytest.approx(0.8) and j.score_std == pytest.approx(0.0816, abs=1e-3)
assert j.usage.cost_usd == pytest.approx(0.003) and j.usage.input_tokens == 3000
- orders = [[p.label for p in image_parts(r)][1:] for r in model.requests]
- assert len({tuple(o) for o in orders}) >= 2 # view order differs between samples
+ orders = [[p.label for p in image_parts(r)] for r in model.requests]
+ assert len({tuple(o) for o in orders}) >= 2 # montage tile order differs between samples
raw = json.loads(j.raw)
assert raw["per_sample_overall"] == [0.7, 0.9, 0.8]
# representative sample (closest to mean) supplies the narrative
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
index 0ddc2b5c..5ef24262 100644
--- a/harness/tests/models/test_gemini.py
+++ b/harness/tests/models/test_gemini.py
@@ -20,7 +20,7 @@ from codeverse.contracts.chat import (
)
from codeverse.contracts.plan import StaticPlan
from codeverse.models.base import ModelError
-from codeverse.models.gemini import GeminiModel, classify_exception
+from codeverse.models.gemini import GeminiModel, classify_exception, failure_outcome
from codeverse.models.gemini_convert import SIGNATURES, build_config, to_contents
from codeverse.models.keypool import KeyPool
@@ -81,10 +81,10 @@ class FakeClient:
self.models = FakeModels(script, key, log)
-def make_model(script: list[Any], keys=("k1", "k2", "k3"), **kw):
+def make_model(script: list[Any], keys=("k1", "k2", "k3"), pool: KeyPool | None = None, **kw):
"""Shared script across keys (each call pops the next item); log records which key was used."""
log: list[dict] = []
- pool = KeyPool(list(keys), cooldown_s=30)
+ pool = pool or KeyPool(list(keys), cooldown_s=30)
m = GeminiModel(
"gemini-3.7-flash",
pool=pool,
@@ -177,6 +177,116 @@ def test_429_rotates_keys_and_cools_down():
assert 0 < cooling["…k1"] <= 7.0 # retryDelay honoured
+def _api_error(code: int, message: str, status: str) -> genai_errors.APIError:
+ return genai_errors.APIError(code, {"error": {"message": message, "status": status}})
+
+
+class _KeyedClient:
+ """Client whose behaviour depends on the key: ``fail[key]`` raises, others answer."""
+
+ def __init__(self, key: str, fail: dict[str, BaseException], log: list[dict]):
+ self.key, self.fail, self.log = key, fail, log
+ self.models = self
+
+ def generate_content(self, *, model: str, contents, config):
+ self.log.append({"key": self.key})
+ if self.key in self.fail:
+ raise self.fail[self.key]
+ return text_response(f"ok from {self.key}")
+
+
+def _keyed_model(
+ keys: list[str], fail: dict[str, BaseException], pool: KeyPool | None = None, **kw
+):
+ log: list[dict] = []
+ pool = pool or KeyPool(keys, cooldown_s=30)
+ m = GeminiModel(
+ "gemini-3.7-flash",
+ pool=pool,
+ sleep=lambda s: None,
+ client_factory=lambda key: _KeyedClient(key, fail, log),
+ **kw,
+ )
+ return m, log, pool
+
+
+SUSPENDED = _api_error(
+ 403, "PERMISSION_DENIED: Consumer 'api_key:xxx' has been suspended.", "PERMISSION_DENIED"
+)
+THROTTLED = genai_errors.APIError(
+ 429,
+ {
+ "error": {
+ "message": "quota",
+ "status": "RESOURCE_EXHAUSTED",
+ "details": [{"retryDelay": "7s"}],
+ }
+ },
+)
+
+
+def test_429_rotation_does_not_consume_the_retry_budget():
+ # 8 throttled keys > max_attempts=6, yet fresh keys remain → must still succeed
+ keys = [f"k{i}" for i in range(1, 23)]
+ m, log, pool = _keyed_model(keys, {k: THROTTLED for k in keys[:8]}, max_attempts=6)
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert r.text == "ok from k9" and [e["key"] for e in log] == keys[:9]
+ assert pool.stats()["n_cooling"] == 8
+
+
+def test_429_on_every_key_waits_for_cooldown_then_counts_against_budget():
+ clock = {"t": 1000.0}
+ pool = KeyPool(
+ ["k1", "k2", "k3"],
+ cooldown_s=30,
+ clock=lambda: clock["t"],
+ sleep=lambda s: clock.__setitem__("t", clock["t"] + s),
+ )
+ keys = ["k1", "k2", "k3"]
+ m, log, _ = _keyed_model(keys, {k: THROTTLED for k in keys}, pool=pool, max_attempts=3)
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert ei.value.retryable and ei.value.status == 429
+ # 2 free rotations + 3 budgeted attempts; the pool waited out the cooldowns in between
+ assert len(log) == 5 and clock["t"] >= 1000.0 + 7.0
+
+
+def test_dead_key_is_rotated_past_and_benched():
+ m, log, pool = _keyed_model(["k1", "k2", "k3"], {"k1": SUSPENDED})
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert r.text == "ok from k2" and [e["key"] for e in log] == ["k1", "k2"]
+ st = {k["key"]: k for k in pool.stats()["keys"]}
+ assert st["…k1"]["dead"] == 1 and st["…k1"]["cooldown_s"] > 600 and pool.stats()["n_dead"] == 1
+ # the dead key never comes back round-robin while benched
+ log.clear()
+ for _ in range(10):
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert {e["key"] for e in log} == {"k2", "k3"}
+
+
+def test_api_key_invalid_400_is_treated_as_dead_key():
+ bad = _api_error(400, "API key not valid. Please pass a valid API key.", "INVALID_ARGUMENT")
+ m, log, pool = _keyed_model(["k1", "k2"], {"k1": bad})
+ assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok from k2"
+ assert pool.stats()["dead"] == 1
+ assert failure_outcome(classify_exception(bad)) == "dead"
+ assert failure_outcome(classify_exception(SUSPENDED)) == "dead"
+ assert failure_outcome(classify_exception(THROTTLED)) == "429"
+ assert failure_outcome(ModelError("bad json", retryable=True)) == "ok"
+
+
+def test_every_key_dead_raises_without_benching():
+ keys = ["k1", "k2", "k3"]
+ m, log, pool = _keyed_model(keys, {k: SUSPENDED for k in keys})
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert not ei.value.retryable and ei.value.status == 403
+ assert [e["key"] for e in log] == keys # each tried once, no sleeps, no budget burnt
+ # the request (not the keys) is suspect: nothing benched, next call is not blocked
+ assert pool.stats()["dead"] == 0 and pool.stats()["n_cooling"] == 0
+ assert pool.acquire(timeout_s=0.0) in keys
+
+
def test_5xx_retries_then_gives_up_with_retryable_error():
err = genai_errors.APIError(503, {"error": {"message": "high demand", "status": "UNAVAILABLE"}})
slept: list[float] = []
@@ -364,7 +474,9 @@ def test_truncated_json_is_not_retried():
def test_empty_max_tokens_is_not_retried():
- m, log, _ = make_model([text_response("", finish="MAX_TOKENS", thoughts=49), text_response("never")])
+ m, log, _ = make_model(
+ [text_response("", finish="MAX_TOKENS", thoughts=49), text_response("never")]
+ )
with pytest.raises(ModelError) as ei:
m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_output_tokens=50))
assert not ei.value.retryable and len(log) == 1 and "thinking" in str(ei.value)
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
index d641b61a..d15a940c 100644
--- a/harness/tests/models/test_keypool.py
+++ b/harness/tests/models/test_keypool.py
@@ -131,3 +131,28 @@ def test_token_bucket_math():
assert b.try_take(10, 0.0) and not b.try_take(1, 0.0)
assert b.wait_for(5, 0.0) == 5.0
assert b.try_take(5, 5.0)
+
+
+def test_dead_key_is_benched_for_a_long_time_then_reprobed():
+ pool, clock = make(keys=("dead", "ok"), cooldown_s=30, dead_cooldown_s=3600)
+ pool.report("dead", "dead")
+ # passive health recovery must not bring it back: it stays benched for an hour
+ clock.t += 1800
+ assert [pool.acquire() for _ in range(6)] == ["ok"] * 6
+ st = pool.stats()
+ assert st["n_dead"] == 1 and st["dead"] == 1
+ by = {k["key"]: k for k in st["keys"]}
+ assert by["…dead"]["dead"] == 1 and by["…dead"]["cooldown_s"] > 0
+ clock.t += 1801
+ assert "dead" in [pool.acquire() for _ in range(3)] # re-probed once the bench ends
+ assert pool.stats()["n_dead"] == 0
+
+
+def test_all_keys_dead_raises_immediately_instead_of_waiting_out_the_timeout():
+ pool, clock = make(keys=("a", "b"), dead_cooldown_s=3600)
+ pool.report("a", "dead")
+ pool.report("b", "dead")
+ t0 = clock.t
+ with pytest.raises(KeyPoolExhausted):
+ pool.acquire(timeout_s=120)
+ assert clock.t == t0 # no pointless 120 s wait: availability only moves later
diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.py
index df956017..28f0fb9c 100644
--- a/harness/tests/models/test_openai.py
+++ b/harness/tests/models/test_openai.py
@@ -264,7 +264,7 @@ def test_empty_and_classify():
def test_base_url_from_settings(monkeypatch):
from codeverse.config import get_settings
- monkeypatch.setenv("C3V_OPENAI_BASE_URL", "http://localhost:8000/v1")
+ monkeypatch.setenv("CV3D_OPENAI_BASE_URL", "http://localhost:8000/v1")
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
get_settings.cache_clear()
try:
diff --git a/harness/tests/models/test_pricing.py b/harness/tests/models/test_pricing.py
index 5c362fd6..885d8f99 100644
--- a/harness/tests/models/test_pricing.py
+++ b/harness/tests/models/test_pricing.py
@@ -47,6 +47,46 @@ def test_prefix_match_and_boundary():
)
+def test_sibling_models_are_not_priced_as_their_bigger_prefix(caplog):
+ """``gpt-4.1-nano`` must not resolve to the ``gpt-4.1`` row (20x), nor ``o3-mini``
+ to ``o3``: cheap siblings have their own rows; unknown siblings price 0 + warn."""
+ caplog.set_level(logging.WARNING)
+ assert lookup_price("openai", "gpt-4.1-nano") is PRICES[("openai", "gpt-4.1-nano")]
+ assert lookup_price("openai", "o3-mini") is PRICES[("openai", "o3-mini")]
+ assert lookup_price("openai", "o3-pro") is PRICES[("openai", "o3-pro")]
+ assert lookup_price("openai", "gpt-5-codex") is PRICES[("openai", "gpt-5-codex")]
+ u = Usage(input_tokens=1_000_000, output_tokens=1_000_000)
+ assert abs(estimate_cost("openai", "gpt-4.1-nano", u) - 0.50) < 1e-9
+ # a family name we do not know is reported unknown, not priced as the parent
+ for prov, m in [
+ ("openai", "gpt-5.4-mini"),
+ ("openai", "gpt-5.7"), # ".7" is a different minor version, not a date tag
+ ("gemini", "gemini-3.7-flash-lite"),
+ ("gemini", "gemini-2.5-flash-imagine"),
+ ("anthropic", "claude-opus-5-turbo"),
+ ]:
+ assert lookup_price(prov, m) is None, m
+ assert estimate_cost(prov, m, u) == 0.0, m
+ assert any(m in r.message for r in caplog.records), m
+ # version / date / channel suffixes still fall back to the family row
+ assert lookup_price("openai", "gpt-4o-2024-08-06") is PRICES[("openai", "gpt-4o")]
+ assert (
+ lookup_price("gemini", "gemini-2.5-flash-preview-05-20")
+ is PRICES[("gemini", "gemini-2.5-flash")]
+ )
+ assert (
+ lookup_price("gemini", "gemini-2.5-flash-image-preview")
+ is PRICES[("gemini", "gemini-2.5-flash-image")]
+ )
+ assert (
+ lookup_price("anthropic", "claude-sonnet-5@20260301")
+ is PRICES[("anthropic", "claude-sonnet-5")]
+ )
+ assert (
+ lookup_price("gemini", "gemini-3.7-flash-latest") is PRICES[("gemini", "gemini-3.7-flash")]
+ )
+
+
def test_unknown_model_zero_and_warns_once(caplog):
caplog.set_level(logging.WARNING)
u = Usage(input_tokens=10, output_tokens=10)
diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.py
index 8f3a628a..bf9d4935 100644
--- a/harness/tests/models/test_schema_utils.py
+++ b/harness/tests/models/test_schema_utils.py
@@ -6,7 +6,7 @@ import json
import pytest
from google.genai import types
-from pydantic import BaseModel
+from pydantic import BaseModel, ValidationError
from codeverse.contracts.plan import ArticulatedPlan, ScenePlan, StaticPlan
from codeverse.models.schema_utils import (
@@ -102,10 +102,84 @@ def test_openai_strict_schema_shape():
assert set(n["required"]) == set(n["properties"].keys())
_walk(s, check)
- # optional field became nullable
part = s["properties"]["parts"]["items"]["properties"]
- assert part["material"]["type"] == ["string", "null"]
+ # optional-without-default (``str | None = None``) is nullable on the wire …
assert {"type": "null"} in part["attach_to"]["anyOf"]
+ # … but defaulted fields stay non-null (pydantic rejects null there) with a hint
+ assert (
+ part["material"]["type"] == "string" and '[default: ""]' in part["material"]["description"]
+ )
+ assert (
+ part["instances"]["type"] == "integer"
+ and "[default: 1]" in part["instances"]["description"]
+ )
+ assert part["symmetry"]["type"] == "string" and "null" not in json.dumps(part["symmetry"])
+ assert s["properties"]["style_notes"]["type"] == "string"
+
+
[email protected]("model", [StaticPlan, ArticulatedPlan, ScenePlan])
+def test_openai_strict_schema_never_adds_null(model):
+ """Wire contract == pydantic contract: a field accepts null on the wire iff the
+ source schema does (``x: T | None``) — never because it merely has a default /
+ default_factory, else the model's nulls fail ``model_validate``."""
+ original = inline_refs(model.model_json_schema())
+ strict = to_openai_strict_schema(model.model_json_schema())
+
+ def pairs(o, st):
+ if isinstance(o, dict) and "properties" in o and isinstance(st, dict):
+ for name, sub in o["properties"].items():
+ yield sub, st["properties"][name]
+ yield from pairs(sub, st["properties"][name])
+ if isinstance(o, dict) and "items" in o and isinstance(st, dict):
+ yield from pairs(o["items"], st["items"])
+ if isinstance(o, dict) and "anyOf" in o and isinstance(st, dict):
+ for a, b in zip(o["anyOf"], st["anyOf"], strict=True):
+ yield from pairs(a, b)
+
+ n_defaulted = 0
+ for orig, strict_sub in pairs(original, strict):
+ if not isinstance(orig, dict):
+ continue
+ n_defaulted += orig.get("default") is not None
+ assert _accepts_null(strict_sub) == _accepts_null(orig), (orig, strict_sub)
+ assert n_defaulted > 0
+
+
+def _accepts_null(sub) -> bool:
+ return "null" in json.dumps(sub.get("type")) or any(
+ isinstance(v, dict) and v.get("type") == "null" for v in sub.get("anyOf", [])
+ )
+
+
+def test_openai_strict_schema_rejects_nulls_that_pydantic_rejects():
+ jsonschema = pytest.importorskip("jsonschema")
+ strict = to_openai_strict_schema(StaticPlan.model_json_schema())
+ bbox = {"center": [0, 0, 0.5], "extents": [1, 1, 1]}
+ part = {
+ "name": "Seat",
+ "role": "r",
+ "description": "d",
+ "bbox": bbox,
+ "material": "",
+ "attach_to": None,
+ "symmetry": "none",
+ "instances": 1,
+ }
+ good = {
+ "object_name": "Chair",
+ "summary": "x",
+ "overall_bbox": bbox,
+ "style_notes": "",
+ "parts": [part],
+ "acceptance": [],
+ }
+ jsonschema.validate(good, strict)
+ StaticPlan.model_validate(good)
+ bad = {**good, "style_notes": None, "parts": [{**part, "material": None, "instances": None}]}
+ with pytest.raises(jsonschema.ValidationError):
+ jsonschema.validate(bad, strict) # the model is not allowed to answer like this
+ with pytest.raises(ValidationError):
+ StaticPlan.model_validate(bad) # … because the contract would reject it
def test_anthropic_schema_shape():
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index ed6e8da5..89d2f12a 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -208,6 +208,23 @@ class FakeJudge:
improvement_plan=plan, acceptance_results=acc, usage=Usage(backend="fake", cost_usd=self.cost))
+class FakePairwise:
+ """Scripted pairwise verdicts: ``verdicts`` is consumed in order (last one repeats)."""
+
+ def __init__(self, verdicts: Sequence[tuple[str, float]] = (("tie", 0.3),), cost: float = 0.004):
+ self.verdicts = list(verdicts)
+ self.cost = cost
+ self.calls: list[tuple[Any, Any, Any, str]] = []
+
+ def compare(self, spec: Any, renders_a: Any, renders_b: Any, *, rubric: str = "static_object_v1") -> Any:
+ from codeverse.judges.pairwise import PairwiseResult
+
+ i = min(len(self.calls), len(self.verdicts) - 1)
+ self.calls.append((spec, renders_a, renders_b, rubric))
+ winner, conf = self.verdicts[i]
+ return PairwiseResult(winner=winner, confidence=conf, reasons=[f"scripted verdict {i}"], usage=Usage(backend="fake", cost_usd=self.cost))
+
+
# ----------------------------------------------------------------------------- services
def _png(path: Path, size: int = 32) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
@@ -216,14 +233,22 @@ def _png(path: Path, size: int = 32) -> None:
class FakeServices(Services):
def __init__(self, *, runtime_factory: Callable[[Language], Any] | None = None, judge: Any | None = None,
- contract_errors: int = 0, assemble: bool = False, sweep_errors: int = 0):
+ contract_errors: int = 0, assemble: bool = False, sweep_errors: int = 0, pairwise: Any | None = None,
+ silhouette_iou: float | None = None, motion_errors: int = 0):
self.runtime_factory = runtime_factory or (lambda lang: FakeRuntime(lang))
self._judge = judge
self.contract_errors = contract_errors
self.assemble = assemble
self.sweep_errors = sweep_errors
+ self._pairwise = pairwise
+ self.silhouette_iou = silhouette_iou
+ self.motion_errors = motion_errors
self.materialized: list[str] = []
self.records: list[RunRecord] = []
+ self.reference_judges: list[tuple[str, int, str]] = []
+ self.silhouette_calls: list[tuple[str, str]] = []
+ self.connectivity_languages: list[str] = []
+ self.geometry_renders: list[str] = []
def chat_model(self, model_id: str) -> Any:
raise ServiceUnavailable("no chat model in tests")
@@ -234,6 +259,31 @@ class FakeServices(Services):
def judge(self, rubric: str, model_id: str, n_samples: int = 1) -> Any:
return self._judge if self._judge is not None else FakeJudge()
+ def reference_judge(self, model_id: str, n_samples: int = 1, rubric: str = "reference_v1") -> Any:
+ self.reference_judges.append((model_id, n_samples, rubric))
+ return self._judge if self._judge is not None else FakeJudge()
+
+ def pairwise(self, model_id: str) -> Any:
+ if self._pairwise is None:
+ raise ServiceUnavailable("no pairwise judge in tests")
+ return self._pairwise
+
+ def silhouette(self, render_png, reference_png) -> dict[str, Any]:
+ self.silhouette_calls.append((str(render_png), str(reference_png)))
+ if self.silhouette_iou is None:
+ raise ServiceUnavailable("no silhouette tool in tests")
+ return {"iou": self.silhouette_iou, "reliable": True, "ref_aspect": 1.2, "render_aspect": 0.8, "aspect_ratio_err": 0.4}
+
+ def motion_checks(self, ws: Workspace, plan: Plan) -> GateReport | None:
+ joints = list(getattr(plan, "joints", []) or [])
+ if not joints:
+ return None
+ findings = [GateFinding(gate="motion_direction", severity=Severity.ERROR, target=j.name,
+ message=f"{j.name}: child '{j.child}' moves (0, 1, 0); expected front (WRONG)",
+ fix_hint=f"negate the axis of joint '{j.name}' in src/robot.urdf")
+ for j in joints[: self.motion_errors]]
+ return GateReport(gate="motion_direction", passed=not findings, findings=findings)
+
def runtime(self, language: Language) -> Any:
return self.runtime_factory(language)
@@ -254,7 +304,8 @@ class FakeServices(Services):
center=tuple(cen), tri_count=sum(p.tri_count for p in parts), n_meshes=len(parts), n_islands=len(parts),
parts=parts, ground_gap_m=float(bounds[0][1]), footprint_offset_m=float(np.hypot(cen[0], cen[2])))
- def connectivity(self, glb: Path) -> GateReport:
+ def connectivity(self, glb: Path, language: str = "") -> GateReport:
+ self.connectivity_languages.append(language)
return GateReport(gate="connectivity", passed=True)
def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
@@ -272,6 +323,15 @@ class FakeServices(Services):
_png(sheet)
return RenderSet(views=vs, contact_sheet=str(sheet), renderer="fake")
+ def render_geometry(self, glb: Path, out_dir: Path, *, views) -> RenderSet:
+ self.geometry_renders.append(str(glb))
+ vs = []
+ for v in views:
+ p = out_dir / f"clay_{v.name}.png"
+ _png(p)
+ vs.append(RenderView(name=v.name, path=str(p), mode="clay", width=32, height=32))
+ return RenderSet(views=vs, renderer="fake")
+
def render_scene(self, ws: Workspace, out_dir: Path, *, cameras, times, width: int, height: int) -> RenderSet:
vs = []
for c in cameras or []:
diff --git a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
new file mode 100644
index 00000000..f6435ed0
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
@@ -0,0 +1,382 @@
+"""Best-of-N candidates, pairwise tie-breaks, reference images, motion checks, instruction compaction."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from PIL import Image
+
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import ArticulatedPlan
+from codeverse.contracts.run import RunStatus
+from codeverse.contracts.spec import ReferenceImage
+from codeverse.events import EventLog
+from codeverse.orchestrator.candidates import CandidateRecord, decide_best, rank_candidates
+from codeverse.orchestrator.rounds import (
+ RefineTask,
+ RoundPolicy,
+ build_refine_instructions,
+ compact_instructions,
+)
+from codeverse.tracks import get_track
+from codeverse.tracks.articulated_object import ArticulatedObjectTrack
+from codeverse.tracks.motion import expected_direction
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.static_object import StaticObjectTrack
+from codeverse.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeChatModel,
+ FakeJudge,
+ FakePairwise,
+ FakeRuntime,
+ FakeServices,
+)
+
+
+def _planner(plan_dict):
+ return FakeChatModel(lambda req: plan_dict)
+
+
+# ----------------------------------------------------------------------------- pure logic
+def test_round_policy_candidates_and_compaction():
+ pol = RoundPolicy()
+ assert pol.n_candidates == 1 and pol.with_candidates(None) is pol and pol.with_candidates(3).n_candidates == 3
+ assert pol.with_candidates(0).n_candidates == 1 and pol.parallel_min_tasks == 2
+ tasks = [RefineTask(target=f"BackLeg_{i}", kind="gate:connectivity", instruction=f"leg {i} floats", priority=0, source="gate") for i in range(4)]
+ tasks += [RefineTask(target="Seat", kind="geometry", instruction="thicker", priority=2)]
+ tasks += [RefineTask(target=f"Spindle_{i}", kind="gate:contract", instruction="off", priority=0, source="gate") for i in range(3)]
+ lines = compact_instructions(tasks, max_lines=6)
+ assert len(lines) == 3 and lines[0].startswith("BackLeg: (a) [BackLeg_0]") and "(d) [BackLeg_3]" in lines[0]
+ assert lines[1].startswith("Spindle:") and lines[2] == "[judge/geometry] Seat: thicker"
+ many = [RefineTask(target=f"P{i}", kind="geometry", instruction="x", priority=i % 3) for i in range(10)]
+ assert len(compact_instructions(many, max_lines=6)) == 6
+ assert compact_instructions([]) == []
+
+
+def test_build_refine_instructions_extra_and_instance_targets(chair_plan):
+ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+
+ gate = GateReport(gate="connectivity", passed=False, findings=[
+ GateFinding(gate="connectivity", severity=Severity.ERROR, target="back_leg_1", message="floats", fix_hint="lower it")])
+ extra = [RefineTask(target="overall", kind="reference", instruction="IoU 0.4", priority=1, source="gate")]
+ tasks = build_refine_instructions(None, [gate], [], chair_plan, extra=extra)
+ assert [t.target for t in tasks] == ["BackLeg_1", "overall"] and tasks[1].kind == "reference"
+
+
+def test_rank_candidates_and_decide_best():
+ recs = [CandidateRecord(index=0, label="c0", build_ok=True, score=0.62, gate_errors=2),
+ CandidateRecord(index=1, label="c1", build_ok=True, score=0.62, gate_errors=0),
+ CandidateRecord(index=2, label="c2", build_ok=False),
+ CandidateRecord(index=3, label="c3", build_ok=True, score=0.70, gate_errors=5)]
+ assert rank_candidates(recs) == [3, 1, 0, 2]
+ # clear delta → ordinary ranking
+ assert decide_best(0.60, 0.70, margin=0.03, min_confidence=0.6, compare=None) == ("score", None)
+ # within noise, no comparator → keep
+ d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=None, labels=("r00", "r01"))
+ assert d == "keep" and note is not None and not note.accepted and "keep" in note.line()
+
+ class R:
+ def __init__(self, w, c):
+ self.winner, self.confidence, self.reasons, self.usage, self.error = w, c, ["x"], None, ""
+
+ d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=lambda: R("b", 0.8))
+ assert d == "pairwise" and note.accepted and note.winner == "b"
+ d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=lambda: R("b", 0.5))
+ assert d == "keep" and not note.accepted
+ d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=lambda: R("a", 0.9))
+ assert d == "keep"
+
+ def boom():
+ raise RuntimeError("judge down")
+
+ d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=boom)
+ assert d == "keep" and "judge down" in note.error
+ assert decide_best(None, 0.5, margin=0.03, min_confidence=0.6, compare=None) == ("score", None)
+
+
[email protected]("text,expected", [
+ ("drawer pulls out towards -Y", "-y"), ("lid opens upward", "up"), ("door swings to the left", "left"),
+ ("drawer slides out", "front"), ("opens to the front", "front"), ("seat folds down", "down"),
+ ("drawer pushes in", "back"), ("lid hinges up and out", None), ("spins around its axis", None),
+ ("", None), ("handle turns", None), ("does not move up", None), ("lower drawer pulls out", "front"),
+])
+def test_expected_direction(text, expected):
+ assert expected_direction(text) == expected
+
+
+# ----------------------------------------------------------------------------- best-of-N track run
+class _CandidateJudge(FakeJudge):
+ """Scores by which candidate workspace the renders come from; the main round gets 0.6."""
+
+ def __init__(self, by_candidate: dict[str, float]):
+ super().__init__(scores=(0.6,))
+ self.by_candidate = by_candidate
+
+ def judge(self, inp):
+ path = inp.renders.views[0].path if inp.renders.views else ""
+ for key, score in self.by_candidate.items():
+ if f"/_cand/{key}/" in path:
+ self.scores = [score]
+ self.calls = []
+ return super().judge(inp)
+ self.scores, self.calls = [0.6], []
+ return super().judge(inp)
+
+
+def _writer_by_candidate(job, ws):
+ tag = ws.root.parent.name + "/" + ws.root.name if ws.root.parent.name == "_cand" else "main"
+ return {"src/model.py": f"import bpy # {job.label} in {tag}\n"}
+
+
+def test_best_of_two_baseline_selects_highest_quick_score(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "stool")
+ agent = FakeAgent(_writer_by_candidate)
+ judge = _CandidateJudge({"c0": 0.55, "c1": 0.72})
+ services = FakeServices(pairwise=FakePairwise())
+ track = StaticObjectTrack(services=services, judge=judge, agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.BLENDER), n_candidates=2)
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.PLATEAU and len(rec.rounds) == 1
+ r0 = rec.rounds[0]
+ assert "best-of-2: selected c1" in r0.notes and r0.score == pytest.approx(0.6)
+ assert "_cand/c1" in (ws.src / "model.py").read_text()
+ cands = json.loads((ws.root / "rounds" / "candidates.json").read_text())
+ assert cands["selected"] == 1 and [c["score"] for c in cands["candidates"]] == [0.55, 0.72]
+ assert cands["candidates"][1]["selected"] and cands["candidates"][0]["build_ok"]
+ labels = sorted(j.label for j in agent.jobs)
+ assert labels == ["baseline_c0", "baseline_c1"]
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert kinds.count("candidate.done") == 2 and "candidate.selected" in kinds and "candidates.start" in kinds
+ # both candidates charged: round usage > one generation + one judge
+ assert r0.usage.cost_usd > 2 * agent.cost and rec.extra["n_candidates"] == 2 and rec.extra["candidates"]["selected"] == 1
+ # the sub-workspaces are git-ignored and self-contained
+ assert (ws.root / "_cand" / "c0" / "spec.json").is_file() and "_cand/" in (ws.root / ".gitignore").read_text()
+ assert (ws.root / "_cand" / "c1" / "AGENTS.md").is_file()
+ # the winner's trajectory was kept under the run workspace
+ assert any(p.name.startswith("baseline_c1") for p in ws.trajectories.iterdir())
+ # pairwise not consulted: scores differ by more than the margin
+ assert services._pairwise.calls == []
+
+
+def test_best_of_two_pairwise_tiebreak_overrides_ranking(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "stool2")
+ judge = _CandidateJudge({"c0": 0.61, "c1": 0.60})
+ pw = FakePairwise(verdicts=[("b", 0.9)])
+ track = StaticObjectTrack(services=FakeServices(pairwise=pw), judge=judge, agent=FakeAgent(_writer_by_candidate),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.BLENDER), n_candidates=2)
+ rec = track.run(spec, ws)
+ assert len(pw.calls) == 1 and "pairwise c0 vs c1: c1 wins" in rec.rounds[0].notes
+ assert "_cand/c1" in (ws.src / "model.py").read_text()
+ ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "pairwise.done"]
+ assert ev and ev[0]["stage"] == "candidates" and ev[0]["accepted"] is True
+
+
+def test_candidate_count_persists_for_resume_and_settings_default(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "stool3")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5,)), agent=FakeAgent(_writer_by_candidate),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.BLENDER), n_candidates=2)
+ track.run(spec, ws)
+ state = json.loads(ws.state_path.read_text())
+ assert state["extra"]["n_candidates"] == 2
+ # a resume without the flag reads the persisted width
+ t2 = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5,)), agent=FakeAgent(_writer_by_candidate),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER))
+ from codeverse.orchestrator.state import RunState
+
+ ctx = t2.build_context(spec, ws, EventLog(ws.events_path), RunState.load(ws))
+ assert ctx.policy.n_candidates == 2
+ # settings default is honoured when nothing else says
+ settings2 = settings.model_copy()
+ object.__setattr__(settings2, "default_candidates", 3)
+ t3 = StaticObjectTrack(services=FakeServices(), settings=settings2, runtime=FakeRuntime(Language.BLENDER))
+ ctx3 = t3.build_context(spec, Workspace(tmp_path / "runs" / "fresh").create(), EventLog(tmp_path / "e.jsonl"), RunState())
+ assert ctx3.policy.n_candidates == 3
+ assert get_track("static_object", n_candidates=4)._n_candidates == 4
+
+
+# ----------------------------------------------------------------------------- refine pairwise tie-break
+def test_refine_round_within_margin_needs_pairwise_win(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER, max_rounds=2)
+ ws = Workspace(tmp_path / "runs" / "tie")
+ agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label} {job.extra.get('round')}\n"})
+ pw = FakePairwise(verdicts=[("a", 0.8), ("b", 0.9)])
+ # r01 scores +0.01 (noise) → pairwise says incumbent wins → best stays r00; r02 +0.02 → pairwise b wins → best r02
+ judge = FakeJudge(scores=(0.60, 0.61, 0.62))
+ track = StaticObjectTrack(services=FakeServices(pairwise=pw), judge=judge, agent=agent,
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER),
+ policy=RoundPolicy(max_rounds=2, target=0.9, plateau_window=5))
+ rec = track.run(spec, ws)
+ assert [r.score for r in rec.rounds] == pytest.approx([0.60, 0.61, 0.62])
+ assert len(pw.calls) == 2 and rec.best_round == 2
+ assert "pairwise r00 vs r01: r00 wins" in rec.rounds[1].notes and "→ keep" in rec.rounds[1].notes
+ assert "pairwise r00 vs r02: r02 wins" in rec.rounds[2].notes and "→ replace" in rec.rounds[2].notes
+ events = EventLog(ws.events_path).read()
+ best_updates = [e["round"] for e in events if e["event"] == "best.updated"]
+ assert best_updates == [0, 2]
+ assert sum(1 for e in events if e["event"] == "pairwise.done") == 2
+ # persisted round record carries the note + pairwise cost
+ saved = json.loads((ws.root / "rounds" / "r01.json").read_text())
+ assert "pairwise" in saved["notes"] and saved["usage"]["cost_usd"] > 0
+
+
+def test_refine_round_clear_delta_skips_pairwise(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER, max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "clear")
+ pw = FakePairwise()
+ track = StaticObjectTrack(services=FakeServices(pairwise=pw), judge=FakeJudge(scores=(0.50, 0.70)),
+ agent=FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n"}),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER))
+ rec = track.run(spec, ws)
+ assert rec.best_round == 1 and pw.calls == []
+
+
+# ----------------------------------------------------------------------------- reference images
+def test_reference_images_wire_judge_prompts_and_silhouette(tmp_path, chair_plan, settings):
+ ref = tmp_path / "ref.png"
+ Image.new("RGB", (64, 48), (10, 10, 10)).save(ref)
+ spec = make_spec(language=Language.BLENDER, max_rounds=1, generator="single-shot:gemini:fake",
+ references=[ReferenceImage(path=str(ref), role="target", note="side view photo")])
+ ws = Workspace(tmp_path / "runs" / "ref")
+ model = FakeChatModel(lambda req: "=== FILE: src/model.py ===\nimport bpy\n=== END FILE ===")
+ services = FakeServices(silhouette_iou=0.42)
+ track = StaticObjectTrack(services=services, model=model, planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.BLENDER))
+ rec = track.run(spec, ws)
+ # reference judge + rubric
+ assert services.reference_judges and services.reference_judges[0][2] == "reference_v1" and rec.extra["rubric"] == "reference_v1"
+ # prompts mention the references; single-shot attaches the image
+ from codeverse.contracts.chat import ImagePart
+
+ p0 = model.requests[0]
+ imgs = [pt for pt in p0.messages[0].parts if isinstance(pt, ImagePart)]
+ assert "REFERENCE IMAGES (1)" in p0.messages[0].text and imgs and imgs[0].path == str(ref)
+ # silhouette gate recorded with the IoU, and the refine round got the reference task
+ gate = next(g for g in rec.rounds[0].gates if g.gate == "reference_silhouette")
+ assert gate.passed and gate.findings[0].data["iou"] == pytest.approx(0.42) and services.silhouette_calls
+ assert any("silhouette IoU vs the reference image is 0.42" in i for i in rec.rounds[1].instructions)
+ assert any("wider relative to its height" in i for i in rec.rounds[1].instructions)
+ refine_prompt = model.requests[-1].messages[0].text
+ assert "## Reference images" in refine_prompt and "compare_silhouette" not in refine_prompt # single-shot: no tools
+
+
+def test_reference_note_mentions_silhouette_tool_for_agents(tmp_path, chair_plan, settings):
+ ref = tmp_path / "ref.png"
+ Image.new("RGB", (64, 48)).save(ref)
+ spec = make_spec(language=Language.BLENDER, max_rounds=0, references=[ReferenceImage(path=str(ref))])
+ ws = Workspace(tmp_path / "runs" / "ref2")
+ agent = FakeAgent(lambda job, ws: {"src/model.py": "import bpy\n"})
+ track = StaticObjectTrack(services=FakeServices(silhouette_iou=0.8), agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.BLENDER))
+ rec = track.run(spec, ws)
+ assert "compare_silhouette" in agent.jobs[0].prompt and str(ref) in agent.jobs[0].prompt
+ gate = next(g for g in rec.rounds[0].gates if g.gate == "reference_silhouette")
+ assert gate.findings[0].severity.value == "info" # IoU 0.8 is fine → no refine task
+
+
+# ----------------------------------------------------------------------------- articulated motion gate
+def test_articulated_motion_direction_gate_feeds_refine_and_judge(tmp_path, settings):
+ spec = make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER, max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "drawer2")
+ plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))
+ agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n", "src/robot.urdf": "<robot name='x'/>\n"})
+ judge = FakeJudge(scores=(0.6, 0.9), targets=("Drawer",))
+ track = ArticulatedObjectTrack(services=FakeServices(motion_errors=1), judge=judge, agent=agent,
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.URDF_BLENDER))
+ rec = track.run(spec, ws)
+ motion = next(g for g in rec.rounds[0].gates if g.gate == "motion_direction")
+ assert not motion.passed and motion.errors[0].target == "DrawerSlide"
+ assert any(i.startswith("[gate/gate:motion_direction] DrawerSlide") and "negate the axis" in i for i in rec.rounds[1].instructions)
+ assert "Motion direction (harness FK check): 1 WRONG" in judge.calls[0].extra_context
+ assert any(v.name == "pose_DrawerSlide_upper" for v in rec.rounds[0].renders.views)
+
+
+# ----------------------------------------------------------------------------- per-part files via runtime.file_for_part
+def test_expected_files_and_targets_follow_runtime_file_for_part(tmp_path, chair_plan, settings):
+ from codeverse.conventions import to_snake
+ from codeverse.tracks.prompting import file_for_target_factory
+ from codeverse.tracks.static_object import expected_files
+
+ class PartsRuntime(FakeRuntime):
+ @staticmethod
+ def file_for_part(name: str) -> str:
+ return f"src/parts/{to_snake(name)}.py"
+
+ spec = make_spec(language=Language.BLENDER, max_rounds=0)
+ track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=PartsRuntime(Language.BLENDER))
+ from codeverse.orchestrator.state import RunState
+
+ ctx = track.build_context(spec, Workspace(tmp_path / "ws").create(), EventLog(tmp_path / "e.jsonl"), RunState())
+ ctx.plan = chair_plan
+ assert expected_files(ctx)[:3] == ["src/model.py", "src/parts/seat.py", "src/parts/front_leg.py"]
+ fft = file_for_target_factory(ctx)
+ assert fft("Seat") == ["src/parts/seat.py"] and fft("overall") == ["src/model.py"] and fft("BackLeg_1") == []
+
+
+def test_crashed_candidate_is_retried_once(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "retry")
+ seen: dict[str, int] = {}
+
+ def writer(job, ws_):
+ seen[job.label] = seen.get(job.label, 0) + 1
+ if job.label == "baseline_c0" and seen[job.label] == 1:
+ raise RuntimeError("503 high demand")
+ return _writer_by_candidate(job, ws_)
+
+ judge = _CandidateJudge({"c0": 0.75, "c1": 0.55})
+ track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(writer), planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.BLENDER), n_candidates=2)
+ rec = track.run(spec, ws)
+ assert seen == {"baseline_c0": 2, "baseline_c1": 1}
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "candidate.retry" in kinds and "candidate.failed" not in kinds
+ assert "best-of-2: selected c0" in rec.rounds[0].notes and "_cand/c0" in (ws.src / "model.py").read_text()
+
+
+def test_default_motion_checks_on_real_urdf(tmp_path):
+ """Hinged door: axis -z opens to the front (ok); axis +z → WRONG with the negated-axis fix."""
+ import trimesh
+
+ from codeverse.contracts.plan import BBox, JointPlan, PartPlan
+ from codeverse.tracks.motion import default_motion_checks
+
+ def robot(root, axis_z):
+ ws = Workspace(root).create()
+ meshes = ws.artifacts / "meshes"
+ for name, c, e in (("Body", (0, 0, 0.4), (0.6, 0.4, 0.8)), ("Door", (0, -0.21, 0.4), (0.58, 0.02, 0.78))):
+ m = trimesh.creation.box(e)
+ m.apply_translation(c)
+ meshes.mkdir(parents=True, exist_ok=True)
+ (meshes / f"{name}.glb").write_bytes(m.export(file_type="glb"))
+ (ws.artifacts / "robot.urdf").write_text(f"""<robot name="cab">
+<link name="Body"><visual><origin xyz="0 0 0"/><geometry><mesh filename="meshes/Body.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0"/><geometry><mesh filename="meshes/Body.glb"/></geometry></collision></link>
+<link name="Door"><visual><origin xyz="0.29 0.2 0"/><geometry><mesh filename="meshes/Door.glb"/></geometry></visual>
+ <collision><origin xyz="0.29 0.2 0"/><geometry><mesh filename="meshes/Door.glb"/></geometry></collision></link>
+<joint name="door_hinge" type="revolute"><parent link="Body"/><child link="Door"/>
+ <origin xyz="-0.29 -0.2 0"/><axis xyz="0 0 {axis_z}"/><limit lower="0" upper="1.57" effort="10" velocity="1"/></joint>
+</robot>""")
+ return ws
+
+ bbox = BBox(center=(0, 0, 0.4), extents=(0.6, 0.4, 0.8))
+ plan = ArticulatedPlan(object_name="Cabinet", summary="s", overall_bbox=bbox, root_link="Body",
+ parts=[PartPlan(name="Body", role="r", description="d", bbox=bbox),
+ PartPlan(name="Door", role="r", description="d", bbox=bbox, attach_to="Body")],
+ joints=[JointPlan(name="DoorHinge", type="revolute", parent="Body", child="Door", axis=(0, 0, 1),
+ pivot=(-0.29, -0.2, 0.4), lower=0, upper=1.57, motion="door swings open to the front")],
+ acceptance=[])
+ good = default_motion_checks(robot(tmp_path / "good", -1), plan)
+ assert good is not None and good.passed and good.findings[0].severity.value == "info"
+ bad = default_motion_checks(robot(tmp_path / "bad", 1), plan)
+ assert bad is not None and not bad.passed and bad.errors[0].target == "DoorHinge"
+ assert "WRONG" in bad.errors[0].message and '<axis xyz="-0 -0 -1"/>' in bad.errors[0].fix_hint
+ plan.joints[0].motion = "rotates" # ambiguous → no gate
+ assert default_motion_checks(robot(tmp_path / "none", 1), plan) is None
diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.py
new file mode 100644
index 00000000..ef405174
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py
@@ -0,0 +1,283 @@
+"""Regression tests for review fix batch 2 (orchestrator / lifecycle findings)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import Language, Track, Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import BBox, PartPlan, ScenePlan, StaticPlan
+from codeverse.contracts.run import RoundRecord, RunStatus
+from codeverse.events import EventLog
+from codeverse.orchestrator.rounds import RoundPolicy
+from codeverse.orchestrator.state import RunState
+from codeverse.prompts import load_text
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.scene import SceneTrack
+from codeverse.tracks.static_object import ObjectPipeline, StaticObjectTrack
+from codeverse.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeChatModel,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+)
+
+
+def _planner(plan_dict):
+ return FakeChatModel(lambda req: plan_dict)
+
+
+def _writer(job, ws):
+ return {"src/object.js": f"// {job.label} r{job.extra.get('round', 0)}\nexport function build(THREE) {{ return new THREE.Group(); }}\n"}
+
+
+def degraded_verdict(cost: float = 0.003) -> Judgment:
+ return Judgment(rubric="fake_v1", judge_backend="fake", scores={}, overall=0.0, passed=False,
+ summary="judge_error: 503 UNAVAILABLE", usage=Usage(backend="fake", cost_usd=cost),
+ raw=json.dumps({"status": "degraded"}))
+
+
+class ScriptedJudge(FakeJudge):
+ """``script[i]`` is either a float (good verdict) or "degraded"."""
+
+ def __init__(self, script):
+ super().__init__(scores=tuple(s for s in script if not isinstance(s, str)) or (0.5,), targets=("Seat",))
+ self.script = list(script)
+ self.all_calls = []
+
+ def judge(self, inp):
+ i = min(len(self.all_calls), len(self.script) - 1)
+ self.all_calls.append(inp)
+ if self.script[i] == "degraded":
+ return degraded_verdict()
+ self.calls = self.all_calls[: i] # FakeJudge indexes by len(calls)
+ out = super().judge(inp)
+ out = out.model_copy(update={"overall": float(self.script[i]), "passed": float(self.script[i]) >= 0.8,
+ "scores": {"geometry": float(self.script[i])}})
+ return out
+
+
+# --------------------------------------------------------------------- finding: judge charge after persist (+ best BEFORE budget check)
+def test_judged_round_survives_budget_ceiling_crossed_by_judge(tmp_path, chair_plan, settings):
+ """steps.py:148 — the judge's own charge used to raise BudgetExceeded BEFORE the round
+ was committed/recorded, throwing away a complete judged round (scene r2 case)."""
+ spec = make_spec(max_rounds=3, max_usd=0.02)
+ ws = Workspace(tmp_path / "runs" / "r")
+ judge = FakeJudge(scores=(0.55,), cost=0.05) # this single verdict crosses max_usd
+ track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.BUDGET and rec.extra["stop_reason"] == "budget"
+ assert len(rec.rounds) == 1 and rec.rounds[0].judgment is not None
+ assert rec.best_round == 0 and rec.final_score == pytest.approx(0.55) # promoted BEFORE the budget stop
+ assert (ws.root / "rounds" / "r00.json").is_file() and ws.judge_path(0).is_file()
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "best.updated" in kinds and kinds.index("best.updated") < kinds.index("stop")
+ # the judge cost is still in the totals
+ assert rec.total_usage.cost_usd > 0.05
+
+
+# --------------------------------------------------------------------- finding: finalise with a dirty tree at the best commit
+def test_finalise_restores_best_when_aborted_round_dirtied_src(tmp_path, chair_plan, settings):
+ """lifecycle.py:263 — a refine round that wrote files but died on the generation charge
+ left HEAD at the best commit with foreign src/: the run then shipped unjudged code."""
+ spec = make_spec(max_rounds=3, max_usd=0.02)
+ ws = Workspace(tmp_path / "runs" / "r")
+ # planner 0.002 + baseline agent 0.01 + judge 0.003 = 0.015 < 0.02; the refine agent's
+ # 0.01 charge crosses the ceiling AFTER its files hit the disk.
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.55, 0.7), targets=("Seat",)), agent=FakeAgent(_writer),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.BUDGET and rec.best_round == 0 and len(rec.rounds) == 1
+ text = (ws.src / "object.js").read_text()
+ assert "baseline r0" in text and "refine" not in text # restored, not the aborted round's edits
+ assert ws.changed_files() == [] # tree clean at the delivered commit
+ # finding lifecycle.py:256 — the aborted round's charges survive into run_state for resume
+ spent = RunState.load(ws).extra["spent_usage"]
+ assert spent["cost_usd"] == pytest.approx(0.025, abs=1e-6)
+
+
+# --------------------------------------------------------------------- finding: spent usage persisted on crash paths
+def test_spent_usage_saved_when_a_round_crashes(tmp_path, chair_plan, settings):
+ class BoomServices(FakeServices):
+ def __init__(self):
+ super().__init__()
+ self.n = 0
+
+ def contract(self, measurement, plan, tol_m, language=""):
+ self.n += 1
+ if self.n >= 2:
+ raise RuntimeError("gate exploded")
+ return super().contract(measurement, plan, tol_m, language)
+
+ spec = make_spec(max_rounds=3)
+ ws = Workspace(tmp_path / "runs" / "r")
+ track = StaticObjectTrack(services=BoomServices(), judge=FakeJudge(scores=(0.55,), targets=("Seat",)), agent=FakeAgent(_writer),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ with pytest.raises(RuntimeError, match="gate exploded"):
+ track.run(spec, ws)
+ spent = RunState.load(ws).extra["spent_usage"]
+ # planner 0.002 + r0 agent 0.01 + r0 judge 0.003 + r1 agent 0.01 — the r1 charge must not vanish
+ assert spent["cost_usd"] == pytest.approx(0.025, abs=1e-6)
+
+
+# --------------------------------------------------------------------- finding: degraded judge verdicts are glitches, not scores
+def test_degraded_verdict_never_scores_and_run_stops_as_judge_unavailable(tmp_path, chair_plan, settings):
+ spec = make_spec(max_rounds=3)
+ ws = Workspace(tmp_path / "runs" / "r")
+ judge = ScriptedJudge([0.65, "degraded", "degraded"]) # r0 good; r1 degraded, re-judge degraded too
+ track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.rounds[1].judgment is None and rec.rounds[1].score is None # never 0.0
+ assert rec.best_round == 0 and rec.final_score == pytest.approx(0.65)
+ assert rec.extra["stop_reason"] == "judge_unavailable" and rec.status is RunStatus.PLATEAU
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "judge.degraded" in kinds and "judge.retry" in kinds
+ # the degraded summary never reaches a refine prompt
+ assert len(judge.all_calls) == 3
+
+
+def test_degraded_verdict_recovers_via_rejudge_of_same_commit(tmp_path, chair_plan, settings):
+ spec = make_spec(max_rounds=3)
+ ws = Workspace(tmp_path / "runs" / "r")
+ judge = ScriptedJudge([0.55, "degraded", 0.85]) # re-judge of r1 succeeds and passes
+ agent = FakeAgent(_writer)
+ track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=agent,
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.PASSED and rec.best_round == 1
+ assert rec.rounds[1].score == pytest.approx(0.85)
+ # the recovery re-judged the SAME commit: exactly 2 generation rounds ran
+ assert [j.extra.get("round") for j in agent.jobs] == [0, 1]
+ saved = RoundRecord.model_validate(json.loads((ws.root / "rounds" / "r01.json").read_text()))
+ assert saved.judgment is not None and saved.judgment.overall == pytest.approx(0.85)
+
+
+# --------------------------------------------------------------------- finding: plan stage hash covers the whole Spec
+def test_resume_with_raised_budget_does_not_replan_or_reskeleton(tmp_path, chair_plan, settings):
+ spec = make_spec(max_rounds=1, max_usd=5.0)
+ ws = Workspace(tmp_path / "runs" / "r")
+ planner = _planner(chair_plan.model_dump(mode="json"))
+ services = FakeServices()
+ mk = lambda: StaticObjectTrack(services=services, judge=FakeJudge(scores=(0.5, 0.6, 0.9)), agent=FakeAgent(_writer), # noqa: E731
+ planner_model=planner, settings=settings, runtime=FakeRuntime(Language.THREEJS),
+ policy=RoundPolicy(max_rounds=1, target=0.8))
+ mk().run(spec, ws)
+ n_plan_calls = len(planner.requests)
+ src_before = (ws.src / "object.js").read_text()
+ # the only way to continue a BUDGET-stopped run: raise the budget in the spec
+ spec2 = make_spec(max_rounds=1, max_usd=50.0)
+ rec2 = mk().run(spec2, ws, resume=True)
+ assert len(planner.requests) == n_plan_calls # plan stage still cached
+ assert (ws.src / "object.js").read_text() == src_before or "r0" in (ws.src / "object.js").read_text()
+ assert rec2.rounds[0].commit # prior rounds still loaded
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert kinds.count("stage.cached") >= 2
+
+
+def test_skeleton_never_reruns_over_existing_rounds(tmp_path, chair_plan, settings):
+ class CountingRuntime(FakeRuntime):
+ def __init__(self, language):
+ super().__init__(language)
+ self.skeletons = 0
+
+ def skeleton(self, ws, plan):
+ self.skeletons += 1
+ return super().skeleton(ws, plan)
+
+ spec = make_spec(max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "r")
+ rt = CountingRuntime(Language.THREEJS)
+ planner = _planner(chair_plan.model_dump(mode="json"))
+ mk = lambda: StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5, 0.6)), agent=FakeAgent(_writer), # noqa: E731
+ planner_model=planner, settings=settings, runtime=rt)
+ mk().run(spec, ws)
+ assert rt.skeletons == 1
+ src_before = (ws.src / "object.js").read_text()
+ # simulate a skeleton-stage hash change on resume (the failure mode the guard closes)
+ state = json.loads(ws.state_path.read_text())
+ state["stages"].pop("skeleton")
+ ws.state_path.write_text(json.dumps(state))
+ mk().run(spec, ws, resume=True)
+ assert rt.skeletons == 1, "skeleton must not overwrite agent-authored src/ once rounds exist"
+ assert (ws.src / "object.js").read_text() == src_before
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "skeleton.skipped" in kinds
+
+
+# --------------------------------------------------------------------- finding: scene track rebuild path
+def test_scene_refine_emits_rebuild_task_when_build_failed(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)
+ ws = Workspace(tmp_path / "runs" / "r")
+ ws.create()
+ track = SceneTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))
+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState())
+ ctx.plan = plan
+ (ws.src / "zones").mkdir(parents=True, exist_ok=True)
+ (ws.src / "zones" / "quay.js").write_text("// broken\n")
+ last = RoundRecord(index=0, kind="baseline",
+ build=BuildResult(ok=False, language="scene_threejs", error_type="ProbeError",
+ error_message="Cannot read properties of undefined (reading 'update')",
+ error_file="src/zones/quay.js"),
+ gates=[GateReport(gate="lint:scene_threejs", passed=True)])
+ tasks, instructions = track.refine_tasks(ctx, last, [last])
+ assert len(tasks) == 1 and tasks[0].kind == "rebuild"
+ assert tasks[0].files_hint == ["src/zones/quay.js"]
+ assert "ProbeError" in tasks[0].prompt and "Cannot read properties" in tasks[0].prompt
+ assert instructions and "rebuild" in instructions[0]
+
+
+# --------------------------------------------------------------------- finding: plan digest frame order
+def test_plan_digest_is_labelled_w_h_d_in_the_measurement_frame():
+ plan = StaticPlan(object_name="Cabinet", summary="A cabinet.",
+ overall_bbox=BBox(center=(0, 0, 0.4), extents=(0.48, 0.52, 0.80)), # Z-up plan: W×D×H
+ parts=[PartPlan(name="Body", role="body", description="box",
+ bbox=BBox(center=(0, 0, 0.4), extents=(0.48, 0.52, 0.80)))])
+ zup = ObjectPipeline().plan_summary(SimpleNamespace(plan=plan, language=Language.BLENDER))
+ assert "Overall 0.48×0.80×0.52 m (W×H×D)" in zup # H and D swapped into the GLB/measurement order
+ yup = ObjectPipeline().plan_summary(SimpleNamespace(plan=plan, language=Language.THREEJS))
+ assert "Overall 0.48×0.52×0.80 m (W×H×D)" in yup # identity for Y-up plans
+
+
+# --------------------------------------------------------------------- finding: articulated prompt origin rule
+def test_articulated_prompt_states_negated_pivot_visual_origin():
+ text = load_text("tracks/generate_articulated.j2")
+ assert "child mesh offset relative to P" not in text
+ assert "NEGATED world pivot" in text and "WORLD coordinates" in text
+ assert "visual AND collision" in text
+
+
+# --------------------------------------------------------------------- integration: scene_frames errors reach refine
+def test_scene_frames_gate_errors_flow_into_refine_instructions(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)
+ ws = Workspace(tmp_path / "runs" / "r")
+ ws.create()
+ track = SceneTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))
+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState())
+ ctx.plan = plan
+ frames = GateReport(gate="scene_frames", passed=False, findings=[
+ GateFinding(gate="scene_frames", severity=Severity.ERROR, target=plan.cameras[0].name,
+ message="frame is 78% dark (mean luminance 0.04)",
+ fix_hint="raise ambient/hemisphere light intensity or move the camera out of shadow",
+ data={"kind": "dark_frame"})])
+ last = RoundRecord(index=0, kind="baseline", build=BuildResult(ok=True, language="scene_threejs"),
+ gates=[GateReport(gate="lint:scene_threejs", passed=True), frames])
+ tasks, instructions = track.refine_tasks(ctx, last, [last])
+ assert tasks, "a scene_frames ERROR must produce a refine task"
+ joined = "\n".join(instructions)
+ assert "dark" in joined and "FIX: raise ambient" in joined
diff --git a/harness/tests/orchestrator_tracks/test_fix_generation.py b/harness/tests/orchestrator_tracks/test_fix_generation.py
new file mode 100644
index 00000000..d72480c9
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_fix_generation.py
@@ -0,0 +1,147 @@
+"""Regression tests for review fix batch 2 — tracks/generation.py findings."""
+
+from __future__ import annotations
+
+from codeverse.contracts.agent import AgentResult
+from codeverse.contracts.chat import ChatResponse
+from codeverse.contracts.common import Usage
+from codeverse.events import EventLog
+from codeverse.tracks.generation import (
+ GenerationTask,
+ generate_files,
+ parse_multifile,
+ run_agent_task,
+)
+from codeverse.workspace import Workspace
+
+FULL = "=== FILE: src/model.py ===\nimport bpy\nprint('ok')\n=== END FILE ==="
+TRUNCATED = "=== FILE: src/model.py ===\nimport bpy\nbpy.ops.mesh.primitive_cube_add(size=0.4, location=(0, 0,"
+
+
+class ScriptedModel:
+ """Yields ``(text, finish_reason)`` pairs in order."""
+
+ def __init__(self, answers):
+ self.answers = list(answers)
+ self.requests = []
+
+ def generate(self, req):
+ self.requests.append(req)
+ text, fr = self.answers.pop(0)
+ return ChatResponse(text=text, usage=Usage(backend="fake", cost_usd=0.001), finish_reason=fr)
+
+
+# --------------------------------------------------------------------- finding: truncated single-shot answer written verbatim
+def test_parse_multifile_strips_header_from_unterminated_block():
+ files = parse_multifile(TRUNCATED, expected_files=["src/model.py"])
+ body = files["src/model.py"]
+ assert body.startswith("import bpy"), body # NOT the '=== FILE:' header line
+ assert "=== FILE:" not in body
+
+
+def test_generate_files_retries_once_on_max_tokens_then_succeeds(tmp_path):
+ ws = Workspace(tmp_path / "ws").create()
+ model = ScriptedModel([(TRUNCATED, "MAX_TOKENS"), (FULL, "STOP")])
+ events = EventLog(tmp_path / "e.jsonl")
+ task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"], max_output_tokens=32000)
+ res = generate_files(ws, model=model, task=task, events=events)
+ assert res.ok and (ws.root / "src" / "model.py").read_text().startswith("import bpy")
+ assert len(model.requests) == 2 and model.requests[1].max_output_tokens == 64000
+ kinds = [e["event"] for e in events.read()]
+ assert "generate.truncated" in kinds
+
+
+def test_generate_files_still_truncated_after_retry_fails_cleanly(tmp_path):
+ ws = Workspace(tmp_path / "ws").create()
+ model = ScriptedModel([(TRUNCATED, "MAX_TOKENS"), (TRUNCATED, "length")])
+ task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"])
+ res = generate_files(ws, model=model, task=task, events=EventLog(tmp_path / "e.jsonl"))
+ assert not res.ok and res.notes.startswith("truncated")
+ assert not (ws.root / "src" / "model.py").exists() # never write a half-file
+
+
+# --------------------------------------------------------------------- finding: out-of-root path aborted the whole write
+def test_out_of_root_paths_are_skipped_not_fatal(tmp_path):
+ ws = Workspace(tmp_path / "ws").create()
+ answer = (
+ "=== FILE: src/model.py ===\nimport bpy\n=== END FILE ===\n"
+ "=== FILE: README.md ===\n# notes\n=== END FILE ===\n"
+ "=== FILE: ../evil.py ===\nx = 1\n=== END FILE ==="
+ )
+ events = EventLog(tmp_path / "e.jsonl")
+ task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"])
+ res = generate_files(ws, model=ScriptedModel([(answer, "STOP")]), task=task, events=events)
+ assert res.ok, res.notes # the good file was paid for — never abort the round on a README
+ assert (ws.root / "src" / "model.py").is_file()
+ assert not (ws.root / "README.md").exists() and not (tmp_path / "evil.py").exists()
+ assert [c.path for c in res.files_changed] == ["src/model.py"]
+ assert "README.md" in res.notes
+ skipped = [e for e in events.read() if e["event"] == "generate.skipped_path"]
+ assert {e["path"] for e in skipped} == {"README.md", "../evil.py"}
+
+
+# --------------------------------------------------------------------- finding: whole-workspace diff claimed sibling tasks' files
+class NonReportingAgent:
+ """An agent that writes its own file but reports no files_changed (fallback path)."""
+
+ kind = "fake"
+ model = "m"
+
+ def __init__(self, files):
+ self.files = files
+ self.jobs = []
+
+ def run(self, job):
+ self.jobs.append(job)
+ ws = Workspace(job.workspace)
+ for rel, content in self.files.items():
+ p = ws.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content)
+ return AgentResult(ok=True, exit_reason="completed", files_changed=[], usage=Usage(backend="fake", cost_usd=0.001))
+
+
+def test_run_agent_task_passes_files_hint_and_attributes_fallback_diff(tmp_path):
+ ws = Workspace(tmp_path / "ws").create()
+ ws.commit("init")
+ # noise a fallback whole-tree diff used to claim as the task's own work
+ (ws.root / "events.jsonl").write_text("{}\n")
+ (ws.root / "notes.md").write_text("scratch\n")
+ (ws.root / "artifacts").mkdir(exist_ok=True)
+ (ws.root / "artifacts" / "x.json").write_text("{}")
+ agent = NonReportingAgent({"src/parts/seat.js": "export function buildSeat(){}\n"})
+ task = GenerationTask(label="refine_seat", prompt="p", files_hint=["src/parts/seat.js"], round=1, kind="refine")
+ res = run_agent_task(ws, agent=agent, task=task)
+ assert agent.jobs[0].extra["files_hint"] == ["src/parts/seat.js"] # per-session attribution key
+ assert res.ok and [c.path for c in res.files_changed] == ["src/parts/seat.js"]
+
+
+def test_run_agent_task_that_wrote_nothing_is_not_ok(tmp_path):
+ ws = Workspace(tmp_path / "ws").create()
+ ws.commit("init")
+ (ws.root / "events.jsonl").write_text("{}\n") # harness noise only
+ agent = NonReportingAgent({})
+ task = GenerationTask(label="asset_stone_lantern", prompt="p", files_hint=["src/assets/stone_lantern.js"])
+ res = run_agent_task(ws, agent=agent, task=task, retry_silent_bail=False)
+ assert not res.ok and res.files_changed == []
+
+
+# --------------------------------------------------------------------- guard: envelope round-trip still intact
+def test_parse_multifile_normal_envelope_unchanged():
+ text = ("=== FILE: src/object.js ===\nexport function build() {}\n=== END FILE ===\n"
+ "=== FILE: src/parts/leg.js ===\nexport function buildLeg() {}\n=== END FILE ===")
+ files = parse_multifile(text)
+ assert set(files) == {"src/object.js", "src/parts/leg.js"}
+ assert files["src/object.js"] == "export function build() {}"
+
+
+def test_generation_result_records_skip_in_events_payload(tmp_path):
+ """generate.done files list contains only the files actually written."""
+ ws = Workspace(tmp_path / "ws").create()
+ answer = "=== FILE: src/model.py ===\nimport bpy\n=== END FILE ===\n=== FILE: package.json ===\n{}\n=== END FILE ==="
+ events = EventLog(tmp_path / "e.jsonl")
+ res = generate_files(ws, model=ScriptedModel([(answer, "STOP")]),
+ task=GenerationTask(label="baseline", prompt="p"), events=events)
+ done = next(e for e in events.read() if e["event"] == "generate.done")
+ assert done["files"] == ["src/model.py"] and res.ok
+ assert (ws.root / "src" / "model.py").read_text() == "import bpy\n"
diff --git a/harness/tests/orchestrator_tracks/test_integrations2.py b/harness/tests/orchestrator_tracks/test_integrations2.py
new file mode 100644
index 00000000..283c9464
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_integrations2.py
@@ -0,0 +1,184 @@
+"""Integration wiring from the other packages into the tracks (fix batch 2):
+clay geometry views for the judge, scene frame gate + judge view selection,
+connectivity language, blender multi-file targets, texture hook."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.contracts.common import Language, Track, Usage
+from codeverse.contracts.plan import ScenePlan
+from codeverse.contracts.run import RunStatus
+from codeverse.events import EventLog
+from codeverse.orchestrator.state import RunState
+from codeverse.tracks import get_track
+from codeverse.tracks.graphics import GraphicsTrack
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.prompting import file_for_target_factory
+from codeverse.tracks.scene import JUDGE_MAX_VIEWS, ScenePipeline, SceneTrack
+from codeverse.tracks.static_object import StaticObjectTrack, expected_files
+from codeverse.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeChatModel,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+)
+from tests.orchestrator_tracks.test_tracks import _agent_writer, _scene_writer
+
+
+def _planner(plan_dict):
+ return FakeChatModel(lambda req: plan_dict)
+
+
+def _static_run(tmp_path, chair_plan, settings, **spec_kw):
+ spec = make_spec(max_rounds=0, **spec_kw)
+ ws = Workspace(tmp_path / "runs" / "obj")
+ judge = FakeJudge(scores=(0.6,))
+ services = FakeServices()
+ track = StaticObjectTrack(services=services, judge=judge, agent=FakeAgent(_agent_writer),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ return rec, ws, judge, services
+
+
+# --------------------------------------------------------------------- (b) clay geometry views reach the judge
+def test_object_judge_receives_clay_geometry_views(tmp_path, chair_plan, settings):
+ rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings)
+ inp = judge.calls[0]
+ assert inp.geometry_views is not None and len(inp.geometry_views.views) == 4
+ assert {v.name for v in inp.geometry_views.views} == {"front_right_34", "back_left_34", "top", "low_front_left"}
+ assert all(v.mode == "clay" for v in inp.geometry_views.views)
+ assert services.geometry_renders # rendered from the round's GLB
+ assert (ws.renders_dir(0) / "clay").is_dir()
+
+
+def test_scene_judge_gets_no_geometry_views(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan.assets = [a for a in plan.assets if a.kind == "threejs"]
+ for z in plan.zones:
+ z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "scene")
+ judge = FakeJudge(scores=(0.6,))
+ services = FakeServices(assemble=True)
+ track = SceneTrack(services=services, judge=judge, agent=FakeAgent(_scene_writer),
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_THREEJS))
+ rec = track.run(spec, ws)
+ assert judge.calls and judge.calls[0].geometry_views is None
+ # (a) the scene_frames gate ran (passing empty report without metrics.json)
+ frames = [g for g in rec.rounds[0].gates if g.gate == "scene_frames"]
+ assert len(frames) == 1 and frames[0].passed
+ assert services.geometry_renders == []
+
+
+# --------------------------------------------------------------------- (a) judge view selection for scenes
+def test_scene_pipeline_selects_at_most_ten_judge_views():
+ views = [RenderView(name=f"cam{i}", path=f"/tmp/x{i}_{t}.png", time_s=t)
+ for i in range(7) for t in (0.0, 1.5)]
+ rs = RenderSet(views=views, renderer="fake")
+ ctx = SimpleNamespace(services=FakeServices())
+ out = ScenePipeline().judge_views(ctx, rs)
+ assert len(out.views) == JUDGE_MAX_VIEWS == 10
+ # authored views at t=0 all survive
+ kept_t0 = [v.name for v in out.views if v.time_s == 0.0]
+ assert set(kept_t0) >= {f"cam{i}" for i in range(7)}
+
+
+# --------------------------------------------------------------------- (d) connectivity hints in the author's frame
+def test_connectivity_gate_receives_spec_language(tmp_path, chair_plan, settings):
+ rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings)
+ assert services.connectivity_languages == ["threejs"]
+
+
+# --------------------------------------------------------------------- (e) blender multi-file expected files / targets
+class BlenderishRuntime(FakeRuntime):
+ def __init__(self):
+ super().__init__(Language.BLENDER)
+
+ @staticmethod
+ def file_for_part(part_name: str) -> str:
+ from codeverse.conventions import to_snake
+
+ return f"src/parts/{to_snake(part_name)}.py"
+
+ @staticmethod
+ def file_for_target(target: str) -> list[str]:
+ from codeverse.conventions import to_snake
+
+ if target.strip().lower() in ("", "overall", "assembly", "object", "model"):
+ return ["src/model.py"]
+ return [f"src/parts/{to_snake(target)}.py"]
+
+
+def test_blender_expected_files_and_whole_object_targets(tmp_path, chair_plan, settings):
+ spec = make_spec(language=Language.BLENDER)
+ ws = Workspace(tmp_path / "runs" / "b")
+ ws.create()
+ track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=BlenderishRuntime())
+ ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState())
+ ctx.plan = chair_plan
+ files = expected_files(ctx)
+ assert files[0] == "src/model.py" and "src/parts/seat.py" in files and "src/parts/front_leg.py" in files
+ fft = file_for_target_factory(ctx)
+ assert fft is not None
+ assert fft("overall") == ["src/model.py"] # via runtime.file_for_target, never src/object.js
+ assert fft("assembly") == ["src/model.py"] and fft("object") == ["src/model.py"]
+ assert fft("Seat") == ["src/parts/seat.py"]
+
+
+# --------------------------------------------------------------------- (f) texture hook in finalise
+def test_texture_tag_runs_texture_pass_and_records_summary(tmp_path, chair_plan, settings, monkeypatch):
+ calls = {}
+
+ def fake_texture_pass(ws, spec, plan, **kw):
+ calls["kw"] = kw
+ calls["ws"] = str(ws.root)
+ return SimpleNamespace(usage=Usage(backend="fake", cost_usd=0.02),
+ summary=lambda: {"shipped": True, "n_textures": 3})
+
+ import codeverse.texturing.run as trun
+
+ monkeypatch.setattr(trun, "texture_pass", fake_texture_pass)
+ rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])
+ assert rec.extra["texturing"] == {"shipped": True, "n_textures": 3}
+ assert calls["kw"]["judge"] is True and calls["kw"]["update_record"] is False
+ assert calls["kw"]["rubric"] == "static_object_v1" and calls["kw"]["judge_model_id"] == "fake:judge"
+ assert rec.total_usage.cost_usd >= 0.02 # texture usage charged into the totals
+
+
+def test_texture_pass_failure_is_additive_not_fatal(tmp_path, chair_plan, settings, monkeypatch):
+ import codeverse.texturing.run as trun
+
+ def boom(*a, **kw):
+ raise RuntimeError("image model down")
+
+ monkeypatch.setattr(trun, "texture_pass", boom)
+ rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])
+ assert rec.status in (RunStatus.PLATEAU, RunStatus.PASSED, RunStatus.BUDGET)
+ assert "texturing" not in rec.extra
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "texture.failed" in kinds
+
+
+def test_untagged_run_never_calls_texture_pass(tmp_path, chair_plan, settings, monkeypatch):
+ import codeverse.texturing.run as trun
+
+ def boom(*a, **kw):
+ raise AssertionError("texture_pass must not run without the tag")
+
+ monkeypatch.setattr(trun, "texture_pass", boom)
+ rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings)
+ assert "texturing" not in rec.extra
+
+
+# --------------------------------------------------------------------- (i) graphics track still constructs through get_track
+def test_get_track_graphics_accepts_options(settings):
+ t = get_track("graphics", settings=settings, n_candidates=2)
+ assert isinstance(t, GraphicsTrack) and t._n_candidates == 2
+ assert isinstance(get_track(Track.GRAPHICS), GraphicsTrack)
diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.py
index 16ca9e1f..3b42bed8 100644
--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py
+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py
@@ -9,9 +9,10 @@ from codeverse.orchestrator.budget import BudgetGuard
from codeverse.orchestrator.rounds import RoundPolicy
from codeverse.orchestrator.state import RunState
from codeverse.prompts import list_prompts, render
-from codeverse.tracks.common import RunContext, base_prompt_context
+from codeverse.tracks.common import RunContext
from codeverse.tracks.generation import SINGLE_SHOT_FORMAT
from codeverse.tracks.planner import plan_example
+from codeverse.tracks.prompting import base_prompt_context
from codeverse.tracks.scene_assets import asset_api_summary, asset_plan, run_asset_stage
from tests.orchestrator_tracks.conftest import make_spec
from tests.orchestrator_tracks.fakes import FakeAgent, FakeJudge, FakeRuntime, FakeServices
diff --git a/harness/tests/prompts/helpers/glsl_compile.mjs b/harness/tests/prompts/helpers/glsl_compile.mjs
index 0b0a878d..3501dd88 100644
--- a/harness/tests/prompts/helpers/glsl_compile.mjs
+++ b/harness/tests/prompts/helpers/glsl_compile.mjs
@@ -7,7 +7,7 @@ import path from 'node:path';
import { createRequire } from 'node:module';
import url from 'node:url';
-const RUNTIME = process.env.C3V_RUNTIME_JS
+const RUNTIME = process.env.CV3D_RUNTIME_JS
|| path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '../../../runtime_js');
const require_ = createRequire(path.join(RUNTIME, 'package.json'));
const puppeteer = require_('puppeteer');
diff --git a/harness/tests/prompts/test_snippets_run.py b/harness/tests/prompts/test_snippets_run.py
index 478f9ff2..2e60733d 100644
--- a/harness/tests/prompts/test_snippets_run.py
+++ b/harness/tests/prompts/test_snippets_run.py
@@ -87,52 +87,51 @@ def test_urdf_cookbook_runs(tmp_path) -> None:
assert "[selfcheck] links" in out
+def _build_urdf_example(tmp_path, tag: str, model_py: str, urdf: str):
+ """Run a doc example through the REAL urdf_blender pipeline (lint → Blender export →
+ FK consistency → collision sweep) — the build the agent's own files go through."""
+ from codeverse.config import get_settings
+ from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+ from codeverse.workspace import Workspace
+
+ if not get_settings().resolve_blender():
+ pytest.skip("no Blender binary configured")
+ ws = Workspace(tmp_path / tag).create()
+ ws.src.mkdir(parents=True, exist_ok=True)
+ (ws.src / "model.py").write_text(model_py)
+ (ws.src / "robot.urdf").write_text(urdf)
+ res = UrdfBlenderRuntime().build(ws)
+ assert res.ok, f"{tag}: {res.error_type}: {res.error_message}"
+ warns = [f["message"] for f in res.census["lint"] if f["severity"] != "info"]
+ assert warns == [], f"{tag}: lint warnings {warns}"
+ summary = res.census["articulation"]["summary"]
+ assert summary["max_penetration_m"] == 0.0 and summary["floating_links"] == [], f"{tag}: {summary}"
+ return ws, res
+
+
@pytest.mark.blender
-def test_urdf_contract_example_fk_and_clearance(tmp_path) -> None:
- """Full pipeline: build in Blender, export per-link meshes in link frames,
- load the URDF with yourdfpy, sweep the lid — it must open upward, no penetration."""
- yourdfpy = pytest.importorskip("yourdfpy")
- trimesh = pytest.importorskip("trimesh")
- pytest.importorskip("fcl")
- code = "\n".join(blocks("urdf/contract.md", "python"))
- meshes = tmp_path / "meshes"
- meshes.mkdir()
- code += (
- "\nimport mathutils, bpy\n"
- "for _o in [o for o in bpy.data.objects if o.type == 'MESH']:\n"
- " bpy.ops.object.select_all(action='DESELECT'); _o.select_set(True)\n"
- " bpy.context.view_layer.objects.active = _o\n"
- " bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)\n"
- " _o.data.transform(mathutils.Matrix.Translation(-PIVOT[_o.name]))\n"
- f" bpy.ops.export_scene.gltf(filepath={str(meshes)!r} + '/' + _o.name + '.glb',\n"
- " export_format='GLB', use_selection=True, export_yup=False, export_apply=True)\n"
- )
- run_blender_script(tmp_path, code)
- urdf_text = blocks("urdf/contract.md", "xml")[0]
- (tmp_path / "robot.urdf").write_text(urdf_text)
- u = yourdfpy.URDF.load(
- str(tmp_path / "robot.urdf"), build_scene_graph=True, load_meshes=True, mesh_dir=str(tmp_path)
- )
- tops = {}
- for q in (0.0, 0.75, 1.5):
- u.update_cfg({"BodyToLid": q})
- s = u.scene
- cm = trimesh.collision.CollisionManager()
- world = {}
- for name, geom in s.geometry.items():
- node = next(n for n in s.graph.nodes_geometry if s.graph[n][1] == name)
- m = geom.copy()
- m.apply_transform(s.graph[node][0])
- world[node] = m
- cm.add_object(node, m)
- _, pairs = cm.in_collision_internal(return_names=True)
- # only the intended weld (Knob into Lid, fixed joint) may touch
- unexpected = {p for p in pairs if set(x.split(".glb")[0] for x in p) != {"Knob", "Lid"}}
- assert not unexpected, f"unexpected penetration at q={q}: {unexpected}"
- tops[q] = world[next(k for k in world if k.startswith("Lid"))].bounds[1][2]
+def test_urdf_contract_example_builds_and_lid_opens_upward(tmp_path) -> None:
+ """The contract's COMPLETE example must pass the harness build exactly as written
+ (FK consistency, no lint warnings, clean sweep) and the lid must open upward."""
+ from codeverse.spatial.joints import link_world_meshes, load_urdf
+
+ ws, _ = _build_urdf_example(tmp_path, "pedalbin", "\n".join(blocks("urdf/contract.md", "python")),
+ blocks("urdf/contract.md", "xml")[0])
+ r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")
+ tops = {q: link_world_meshes(r, {"body_to_lid": q})["lid"].bounds[1][2] for q in (0.0, 0.75, 1.5)}
assert tops[1.5] > tops[0.75] > tops[0.0] + 0.05, f"lid does not open upward: {tops}"
[email protected]("index,tag", [(0, "cabinet"), (1, "laptop"), (2, "cart")])
+def test_urdf_cookbook_worked_examples_build(tmp_path, index: int, tag: str) -> None:
+ """Each worked example (prelude + helpers + example block, paired with its URDF) must
+ pass the harness build: world meshes + visual/collision origin = −pivot."""
+ py = blocks("urdf/cookbook.md", "python")
+ xml = blocks("urdf/cookbook.md", "xml")
+ _build_urdf_example(tmp_path, tag, "\n".join(py[:2]) + "\n" + py[2 + index], xml[index])
+
+
# ------------------------------------------------------------------------ node
@pytest.mark.node
def test_threejs_cookbook_runs(tmp_path) -> None:
diff --git a/harness/tests/prompts/test_snippets_static.py b/harness/tests/prompts/test_snippets_static.py
index 85ebcff6..fc708f7d 100644
--- a/harness/tests/prompts/test_snippets_static.py
+++ b/harness/tests/prompts/test_snippets_static.py
@@ -8,6 +8,7 @@ import shutil
import subprocess
import xml.etree.ElementTree as ET
+import numpy as np
import pytest
from tests.prompts.conftest import PROMPT_FILES, blocks, read_prompt
@@ -61,17 +62,55 @@ def test_xml_blocks_are_valid_urdf(rel: str) -> None:
assert abs(sum(a * a for a in v) - 1.0) < 1e-6, f"{rel} block {i}: non-unit axis on {j.get('name')}"
roots = links - children
assert len(roots) == 1, f"{rel} block {i}: expected a single root link, got {roots}"
- for v in root.iter("visual"):
- o = v.find("origin")
- assert o is not None and o.get("xyz") == "0 0 0", f"{rel} block {i}: visual origins must be 0 0 0"
- mesh = v.find("geometry/mesh")
- assert mesh is not None and mesh.get("filename", "").startswith("meshes/"), \
- f"{rel} block {i}: visuals must reference meshes/<link>.glb"
- assert mesh.get("scale") is None, f"{rel} block {i}: mesh scale is forbidden"
+ for ln in root.findall("link"):
+ vis, col = ln.findall("visual"), ln.findall("collision")
+ assert len(vis) == 1 and len(col) == 1, f"{rel} block {i}: link {ln.get('name')} needs one <visual> + one <collision>"
+ vo, co = vis[0].find("origin"), col[0].find("origin")
+ assert vo is not None and co is not None and vo.get("xyz") == co.get("xyz"), \
+ f"{rel} block {i}: link {ln.get('name')}: collision origin must equal the visual origin"
+ for tag in (vis[0], col[0]):
+ mesh = tag.find("geometry/mesh")
+ assert mesh is not None and mesh.get("filename") == f"meshes/{ln.get('name')}.glb", \
+ f"{rel} block {i}: link {ln.get('name')} must reference meshes/<link>.glb"
+ assert mesh.get("scale") is None, f"{rel} block {i}: mesh scale is forbidden"
found += 1
assert found > 0, f"{rel}: expected at least one xml block"
+def _is_template(body: str) -> bool:
+ """Fill-in skeletons carry symbolic origins (``PX PY PZ``) — not FK-checkable."""
+ return any(not _NUM.match(tok) for el in ET.fromstring(body).iter("origin") for tok in el.get("xyz", "0 0 0").split())
+
+
+_NUM = re.compile(r"^-?\d+(\.\d+)?([eE]-?\d+)?$")
+
+
[email protected]("rel", XML_FILES)
+def test_xml_examples_follow_the_enforced_frame_recipe(rel: str, tmp_path) -> None:
+ """Every worked URDF in the agent-facing docs must pass the harness lint AND the FK
+ consistency rule the build enforces: meshes hold WORLD coordinates, so FK(q=0) of a
+ link composed with its visual origin is the identity (visual origin = −link frame).
+ This is the recipe the reviewer found the docs contradicting (visual origin 0 0 0)."""
+ from codeverse.languages.urdf.lint import lint_urdf_text
+ from codeverse.spatial.joints import fk, load_urdf
+
+ checked = 0
+ for i, body in enumerate(blocks(rel, "xml")):
+ if _is_template(body):
+ continue
+ findings, _ = lint_urdf_text(body)
+ assert findings == [], f"{rel} block {i}: lint findings {[f.message for f in findings]}"
+ path = tmp_path / f"block{i}.urdf"
+ path.write_text(body)
+ robot = load_urdf(path, load_meshes=False)
+ T = fk(robot, {})
+ for name, link in robot.links.items():
+ assert np.allclose(T[name] @ link.visual_origin, np.eye(4), atol=1e-6), \
+ f"{rel} block {i}: link {name}: visual origin must be -(link frame world) = {(-T[name][:3, 3]).round(4).tolist()}"
+ checked += 1
+ assert checked > 0, f"{rel}: expected at least one FK-checkable xml block"
+
+
@pytest.mark.node
@pytest.mark.parametrize("rel", [f for f in JS_FILES if f != "system/singleshot_format.md"])
def test_js_blocks_syntax(rel: str, tmp_path) -> None:
diff --git a/harness/tests/scene_gates/__init__.py b/harness/tests/scene_gates/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/scene_gates/conftest.py b/harness/tests/scene_gates/conftest.py
new file mode 100644
index 00000000..f0970f33
--- /dev/null
+++ b/harness/tests/scene_gates/conftest.py
@@ -0,0 +1,18 @@
+"""Fixtures for the scene gate tests (reuse the C2 scene runtime helpers)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.languages.scene_threejs.skeleton import write_example
+from codeverse.workspace import Workspace
+
+
+def starter_ws(tmp_path: Path) -> Workspace:
+ """Workspace with the complete example scene."""
+ w = Workspace(tmp_path / "run").create()
+ write_example(w)
+ return w
diff --git a/harness/tests/scene_gates/test_frame_metrics.py b/harness/tests/scene_gates/test_frame_metrics.py
new file mode 100644
index 00000000..d425fb36
--- /dev/null
+++ b/harness/tests/scene_gates/test_frame_metrics.py
@@ -0,0 +1,141 @@
+"""scene_frames gate: synthetic camera_checks → findings, hints, caps (pure python)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from codeverse.contracts.artifacts import RenderSet, RenderView, Severity
+from codeverse.judges.caps import apply_caps
+from codeverse.judges.rubrics import load_rubric
+from codeverse.spatial.frame_metrics import (
+ FRAME_GATE,
+ frame_findings,
+ frame_gate_from_renders,
+ frame_summary_text,
+)
+
+
+def _chk(name: str, kind: str = "authored", **over):
+ base = {"name": name, "kind": kind, "nearest_hit_m": 6.0, "nearest_hit_name": "Ground", "inside_mesh_bbox": [],
+ "camera_in_geometry": False, "eye_height_m": 1.6, "mean_lum": 0.35, "lum_std": 0.1, "dark_frac": 0.02,
+ "blown_frac": 0.0, "modal_frac": 0.4, "content_frac": 0.45, "ground_frac": 0.3, "sky_frac": 0.25}
+ base.update(over)
+ return base
+
+
+def _metrics(*checks, ground_y=0.0):
+ return {"camera_checks": list(checks), "census": {"ground_y": ground_y}}
+
+
+def _kinds(report):
+ return [(f.data["kind"], f.severity, f.target) for f in report.findings]
+
+
+def test_clean_frames_pass_with_info():
+ rep = frame_findings(_metrics(_chk("Establishing"), _chk("overview_top", "orbit")))
+ assert rep.gate == FRAME_GATE and rep.passed
+ assert [f.data["kind"] for f in rep.findings] == ["frames_ok"]
+
+
+def test_dark_frame_is_error_on_authored_with_concrete_hint():
+ rep = frame_findings(_metrics(_chk("Establishing", mean_lum=0.07, dark_frac=0.41)))
+ assert not rep.passed
+ f = rep.findings[0]
+ assert f.data["kind"] == "dark_frame" and f.severity == Severity.ERROR and f.target == "Establishing"
+ assert "0.07" in f.message and "41%" in f.message
+ assert "DirectionalLight" in f.fix_hint and "HemisphereLight" in f.fix_hint and "NOT black" in f.fix_hint
+ assert f.data["view"] == "Establishing" and f.data["mean_lum"] == 0.07
+
+
+def test_dark_frame_on_orbit_view_only_warns():
+ rep = frame_findings(_metrics(_chk("eye_front", "orbit", mean_lum=0.04, dark_frac=0.77)))
+ assert rep.passed
+ assert _kinds(rep) == [("dark_frame", Severity.WARN, "eye_front")]
+
+
+def test_blown_and_flat_frames():
+ rep = frame_findings(_metrics(_chk("Cam", blown_frac=0.3), _chk("Flat", modal_frac=0.95), _chk("Soft", modal_frac=0.88)))
+ kinds = {(k, s) for k, s, _ in _kinds(rep)}
+ assert ("blown_frame", Severity.ERROR) in kinds
+ assert ("flat_frame", Severity.ERROR) in kinds # > 0.92 on an authored camera
+ assert ("flat_frame", Severity.WARN) in kinds # 0.85-0.92
+ assert not rep.passed
+
+
+def test_flat_is_not_duplicated_on_dark_frames():
+ rep = frame_findings(_metrics(_chk("Night", mean_lum=0.05, dark_frac=0.9, modal_frac=1.0)))
+ assert [k for k, _, _ in _kinds(rep)] == ["dark_frame"]
+
+
+def test_camera_in_geometry_and_near_hit():
+ rep = frame_findings(_metrics(_chk("Buried", camera_in_geometry=True, inside_mesh_bbox=["Tower"], nearest_hit_m=0.1),
+ _chk("Close", nearest_hit_m=0.3)))
+ assert [(k, s) for k, s, _ in _kinds(rep)] == [("camera_in_geometry", Severity.ERROR)] * 2
+ assert "Tower" in rep.findings[0].message and "0.5 m" in rep.findings[0].fix_hint
+
+
+def test_eye_height_sanity_against_ground():
+ rep = frame_findings(_metrics(_chk("Under", eye_height_m=-0.5), _chk("Ant", eye_height_m=0.1), _chk("Sat", eye_height_m=120.0),
+ ground_y=0.0))
+ assert [(k, s) for k, s, _ in _kinds(rep)] == [
+ ("camera_underground", Severity.ERROR), ("camera_low", Severity.WARN), ("camera_high", Severity.WARN)]
+ assert "heightAt" in rep.findings[0].fix_hint
+
+
+def test_content_small_roles():
+ rep = frame_findings(_metrics(
+ _chk("Establishing", content_frac=0.12, sky_frac=0.5, ground_frac=0.38), # first authored = establishing → ERROR
+ _chk("Detail", content_frac=0.05), # other authored → WARN
+ _chk("overview_top", "orbit", content_frac=0.03), # overview rig → WARN
+ _chk("eye_front", "orbit", content_frac=0.01), # eye rig: never
+ ))
+ got = _kinds(rep)
+ assert got == [("content_small", Severity.ERROR, "Establishing"), ("content_small", Severity.WARN, "Detail"),
+ ("content_small", Severity.WARN, "overview_top")]
+ assert "12%" in rep.findings[0].message and "sky 50%" in rep.findings[0].message
+ assert rep.findings[0].data["role"] == "establishing" and not rep.passed
+
+
+def test_missing_coverage_metric_is_tolerated():
+ c = _chk("Establishing")
+ for k in ("content_frac", "ground_frac", "sky_frac"):
+ c.pop(k)
+ assert frame_findings(_metrics(c)).passed
+
+
+def test_frame_gate_from_paths_and_renderset(tmp_path: Path):
+ out = tmp_path / "r00"
+ out.mkdir()
+ (out / "metrics.json").write_text(json.dumps(_metrics(_chk("Establishing", mean_lum=0.05))))
+ (out / "Establishing_t0.png").write_bytes(b"")
+ assert not frame_gate_from_renders(out).passed
+ assert not frame_gate_from_renders(out / "metrics.json").passed
+ rs = RenderSet(views=[RenderView(name="Establishing", path=str(out / "Establishing_t0.png"))])
+ assert not frame_gate_from_renders(rs).passed
+ assert frame_gate_from_renders(tmp_path / "nowhere").passed # no metrics → empty passing report
+ assert frame_gate_from_renders(RenderSet()).passed
+
+
+def test_scene_rubric_caps_fire_on_frame_kinds():
+ rubric = load_rubric("scene_v1")
+ rep = frame_findings(_metrics(_chk("Establishing", mean_lum=0.07, dark_frac=0.41, content_frac=0.1)))
+ res = apply_caps(rubric, 0.9, [rep], {}, [])
+ fired = {c.rule: c.cap for c in res.caps_applied}
+ assert fired == {"dark_frame": 0.55, "content_small": 0.6}
+ assert res.overall == 0.55
+ rep2 = frame_findings(_metrics(_chk("Cam", blown_frac=0.5), _chk("Flat", modal_frac=0.99)))
+ fired2 = {c.rule for c in apply_caps(rubric, 0.9, [rep2], {}, []).caps_applied}
+ assert {"blown_frame", "flat_frame"} <= fired2
+ # orbit-only warnings never cap
+ rep3 = frame_findings(_metrics(_chk("overview_top", "orbit", mean_lum=0.05)))
+ assert apply_caps(rubric, 0.9, [rep3], {}, []).caps_applied == []
+
+
+def test_frame_summary_text_table():
+ txt = frame_summary_text(_metrics(_chk("Establishing", mean_lum=0.07, dark_frac=0.41), _chk("overview_top", "orbit")))
+ lines = txt.splitlines()
+ assert lines[0].startswith("frame checks (FAILED")
+ assert lines[1].startswith("Establishing [authored]: lum 0.07 dark 41%") and lines[1].endswith("— DARK FRAME")
+ assert "content 45%" in lines[2] and "—" not in lines[2]
+ assert frame_summary_text({}) == "frame checks: no camera_checks in metrics"
diff --git a/harness/tests/scene_gates/test_judge_views.py b/harness/tests/scene_gates/test_judge_views.py
new file mode 100644
index 00000000..37189497
--- /dev/null
+++ b/harness/tests/scene_gates/test_judge_views.py
@@ -0,0 +1,65 @@
+"""select_judge_views / metrics_path_for (pure python)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.conventions import SCENE_VIEWS
+from codeverse.spatial.render_scene import JUDGE_MAX_VIEWS, metrics_path_for, select_judge_views
+
+AUTHORED = ["Establishing", "BridgeAndPond", "LanternDetail"]
+
+
+def _rs(times=(0.0, 1.5), authored=AUTHORED, orbit=True) -> RenderSet:
+ names = list(authored) + ([v.name for v in SCENE_VIEWS] if orbit else [])
+ views = [RenderView(name=n, path=f"/x/{n}_t{t:g}.png", time_s=t) for t in times for n in names]
+ return RenderSet(views=views, contact_sheet="/x/sheet.png")
+
+
+def test_default_selection_is_ten_in_priority_order():
+ rs = _rs()
+ assert len(rs.views) == 18
+ sel = select_judge_views(rs)
+ assert len(sel.views) == JUDGE_MAX_VIEWS == 10
+ keys = [(v.name, v.time_s) for v in sel.views]
+ # authored t=0, first two overviews t=0 always in; first two authored at t=1.5 in
+ for n in AUTHORED:
+ assert (n, 0.0) in keys
+ assert ("overview_front_right", 0.0) in keys and ("overview_back_left", 0.0) in keys
+ assert ("Establishing", 1.5) in keys and ("BridgeAndPond", 1.5) in keys
+ assert ("LanternDetail", 1.5) not in keys
+ assert not any(t == 1.5 and n.startswith(("overview", "eye")) for n, t in keys)
+ # disk order preserved; original untouched
+ assert keys == sorted(keys, key=lambda k: (k[1], rs.views.index(next(v for v in rs.views if (v.name, v.time_s) == k))))
+ assert len(rs.views) == 18 and sel.contact_sheet == rs.contact_sheet
+
+
+def test_small_sets_pass_through_and_nocustom_dropped():
+ rs = _rs(times=(0.0,), orbit=False)
+ rs.views.append(RenderView(name="Establishing_nocustom", path="/x/cf.png", time_s=0.0))
+ sel = select_judge_views(rs, max_n=10)
+ assert [v.name for v in sel.views] == AUTHORED
+ assert select_judge_views(RenderSet(), max_n=10).views == []
+ assert select_judge_views(rs, max_n=0).views == []
+
+
+def test_max_n_and_custom_orbit_names():
+ rs = _rs()
+ sel = select_judge_views(rs, max_n=4)
+ assert [(v.name, v.time_s) for v in sel.views] == [(n, 0.0) for n in AUTHORED] + [("overview_front_right", 0.0)]
+ # unknown orbit names → everything counts as authored
+ sel2 = select_judge_views(rs, max_n=12, orbit_names=["nothing"])
+ assert len(sel2.views) == 12 and sum(1 for v in sel2.views if v.time_s == 0.0) == 9
+
+
+def test_metrics_path_for_locates_sibling_file(tmp_path: Path):
+ out = tmp_path / "r01"
+ out.mkdir()
+ (out / "a_t0.png").write_bytes(b"")
+ rs = RenderSet(views=[RenderView(name="a", path=str(out / "a_t0.png"))])
+ assert metrics_path_for(rs) is None
+ (out / "metrics.json").write_text("{}")
+ assert metrics_path_for(rs) == out / "metrics.json"
+ assert metrics_path_for(RenderSet(contact_sheet=str(out / "sheet.png"))) == out / "metrics.json"
+ assert metrics_path_for(RenderSet()) is None
diff --git a/harness/tests/scene_gates/test_live_frames.py b/harness/tests/scene_gates/test_live_frames.py
new file mode 100644
index 00000000..6567ac3d
--- /dev/null
+++ b/harness/tests/scene_gates/test_live_frames.py
@@ -0,0 +1,95 @@
+"""Browser-backed: render_scene → camera_checks coverage, judge subset sheet, scene_frames gate.
+
+The example starter scene must pass; a crushed-dark variant of it must raise
+``dark_frame`` ERRORs with the lighting hint.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.conventions import SCENE_VIEWS
+from codeverse.spatial.frame_metrics import frame_gate_from_renders
+from codeverse.spatial.render_scene import (
+ JUDGE_MAX_VIEWS,
+ read_metrics,
+ render_scene,
+ select_judge_views,
+)
+from codeverse.workspace import Workspace
+from tests.scene_runtime.conftest import needs_browser
+
+pytestmark = [pytest.mark.node, needs_browser]
+
+
+def _darken(ws: Workspace) -> None:
+ env = ws.src / "env.js"
+ text = env.read_text()
+ text = text.replace("new THREE.DirectionalLight(0xfff1d6, 2.6)", "new THREE.DirectionalLight(0xfff1d6, 0.05)")
+ text = text.replace("new THREE.HemisphereLight(0xbcd7ff, 0x4a5a2a, 0.9)", "new THREE.HemisphereLight(0x101018, 0x000000, 0.02)")
+ text = text.replace("scene.background = new THREE.Color(0xcfdcec)", "scene.background = new THREE.Color(0x000000)")
+ assert "0.05" in text and "0x000000" in text
+ env.write_text(text)
+ sky = ws.src / "shaders" / "sky.js"
+ if sky.is_file():
+ sky.write_text(sky.read_text().replace("export function", "export function /*dark*/"))
+
+
+def test_example_scene_passes_frame_gate_and_judge_subset(starter_ws: Workspace):
+ out = starter_ws.renders_dir(0)
+ rs = render_scene(starter_ws, out, times=(0.0, 1.5), width=640, height=360, fps_seconds=0.3)
+ assert rs.console_errors == []
+ assert len(rs.views) == 2 * (3 + len(SCENE_VIEWS)) # full set on disk
+ m = read_metrics(out)
+ chk = {c["name"]: c for c in m["camera_checks"]}
+ for c in chk.values():
+ assert 0.0 <= c["content_frac"] <= 1.0 and abs(c["content_frac"] + c["ground_frac"] + c["sky_frac"] - 1.0) < 0.02
+ assert chk["overview"]["content_frac"] > 0.2 # authored establishing shot shows the grove
+ assert chk["overview_top"]["ground_frac"] > 0.5 # top-down: mostly ground between the trees
+ assert m["framing_bbox"]["size"][0] < m["census"]["bbox"]["size"][0] # content, not the sky dome / ground
+ gate = frame_gate_from_renders(rs)
+ assert gate.gate == "scene_frames" and gate.passed, [f.message for f in gate.findings]
+ # judge subset: ≤ 10 views, marked in views.json, sheet built from them only
+ judge = select_judge_views(rs)
+ assert len(judge.views) == JUDGE_MAX_VIEWS
+ flags = {(v["name"], v["time_s"]) for v in json.loads((out / "views.json").read_text()) if v.get("judge")}
+ assert flags == {(v.name, v.time_s) for v in judge.views}
+ sheet = Image.open(rs.contact_sheet)
+ tile_h = Image.open(rs.views[0].path).size[1]
+ assert sheet.size[1] < 5 * tile_h # 10 tiles in 4 columns → 3 rows, not 5
+
+
+def test_dark_variant_raises_dark_frame_errors(starter_ws: Workspace):
+ _darken(starter_ws)
+ out = starter_ws.renders_dir(1)
+ rs = render_scene(starter_ws, out, times=(0.0,), orbit=False, width=480, height=270, fps_seconds=0)
+ assert rs.views, rs.console_errors
+ gate = frame_gate_from_renders(out)
+ assert not gate.passed
+ dark = [f for f in gate.findings if f.data.get("kind") == "dark_frame"]
+ assert dark and all(f.severity == "error" for f in dark)
+ assert dark[0].target == "overview" and "HemisphereLight" in dark[0].fix_hint and "NOT black" in dark[0].fix_hint
+ assert dark[0].data["mean_lum"] < 0.12 or dark[0].data["dark_frac"] > 0.35
+
+
+def test_plan_bounds_guard_orbit_framing(starter_ws: Workspace, tmp_path: Path):
+ """Plan bounds guard the framing: a zone that sprawls far past the bounds is dropped in
+ favour of the zones inside them; bounds that contain everything change nothing."""
+ from codeverse.contracts.plan import BBox
+
+ def _run(i: int, extents: float) -> tuple[dict, float]:
+ out = starter_ws.renders_dir(i)
+ rs = render_scene(starter_ws, out, times=(0.0,), orbit_views=SCENE_VIEWS[:1], width=320, height=180, fps_seconds=0,
+ bounds=BBox(center=(0, 3, 0), extents=(extents, 10, extents)), sheet=False)
+ ov = next(v for v in rs.views if v.name == SCENE_VIEWS[0].name)
+ return read_metrics(out)["framing_bbox"], ov.camera_position[1]
+
+ wide, y_wide = _run(2, 90.0) # meadow (≈ 84 m) fits → framed as a whole
+ assert wide["size"][0] == pytest.approx(84.4, abs=0.5)
+ tight, y_tight = _run(3, 30.0) # meadow sprawls past 33 m → the pondside zone (16.7 m) is framed
+ assert 10 < tight["size"][0] < 17.5
+ assert y_tight < y_wide / 2
diff --git a/harness/tests/scene_gates/test_orbit_framing.py b/harness/tests/scene_gates/test_orbit_framing.py
new file mode 100644
index 00000000..870246f9
--- /dev/null
+++ b/harness/tests/scene_gates/test_orbit_framing.py
@@ -0,0 +1,112 @@
+"""Orbit rig: content framing box + tight per-corner fit (pure node functions)."""
+
+from __future__ import annotations
+
+import json
+import math
+
+import pytest
+
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+pytestmark = [pytest.mark.node, needs_node]
+
+
+def _call(fn: str, *args):
+ body = f"""
+import {{ fitOrbitCameras, framingBox, fitDistance, orbitDirection }} from './lib/orbit.mjs';
+console.log(JSON.stringify({fn}(...{json.dumps(list(args))})));
+"""
+ return run_node_json(body)
+
+
+def _box(mn, mx):
+ return {"min": mn, "max": mx, "size": [b - a for a, b in zip(mn, mx, strict=True)]}
+
+
+GARDEN = {
+ "bbox": _box([-300, -300, -300], [300, 300, 300]),
+ "content_bbox": _box([-12.3, -0.3, -9.1], [10.4, 5.8, 11.7]),
+ "ground_y": 0.37,
+ "groups": [
+ {"name": "Environment", "kind": "ground", "bbox": _box([-300, -300, -300], [300, 300, 300])},
+ {"name": "MapleGrove", "kind": "content", "bbox": _box([-12.3, 0, -0.1], [10.4, 5.8, 11.7])},
+ {"name": "KoiPond", "kind": "content", "bbox": _box([-3, -0.3, -9.1], [3.5, 1.1, -0.1])},
+ {"name": "Fence", "kind": "content", "bbox": _box([-5, 0, -6], [5, 1.8, 4])},
+ ],
+}
+BOUNDS = {"min": [-13, -1.5, -13], "max": [13, 6.5, 13]}
+
+
+def test_framing_box_is_content_union_not_ground_or_sky():
+ box = _call("framingBox", GARDEN, BOUNDS)
+ assert box["min"] == pytest.approx([-12.3, -0.3, -9.1]) and box["max"] == pytest.approx([10.4, 5.8, 11.7])
+ # without bounds: same union
+ assert _call("framingBox", GARDEN)["size"] == pytest.approx(box["size"])
+
+
+def test_framing_box_drops_scatter_that_sprawls_past_bounds_and_clamps():
+ census = json.loads(json.dumps(GARDEN))
+ census["groups"].append({"name": "GrassScatter", "kind": "content", "bbox": _box([-60, 0, -60], [60, 0.3, 60])})
+ box = _call("framingBox", census, BOUNDS)
+ assert box["max"][0] == pytest.approx(10.4) and box["min"][2] == pytest.approx(-9.1) # scatter ignored
+ # no bounds → nothing to judge sprawl against, but the union is still content only
+ box2 = _call("framingBox", census)
+ assert box2["size"][0] == pytest.approx(120)
+ # a lone sprawling group is kept but clamped to the bounds (×1.1)
+ lone = {"groups": [{"name": "Only", "kind": "content", "bbox": _box([-50, 0, -50], [50, 4, 50])}]}
+ box3 = _call("framingBox", lone, BOUNDS)
+ assert box3["min"][0] == pytest.approx(-13 * 1.1) and box3["max"][2] == pytest.approx(13 * 1.1)
+
+
+def test_framing_box_falls_back_to_content_bbox():
+ assert _call("framingBox", {"content_bbox": GARDEN["content_bbox"], "groups": []})["size"] == pytest.approx(GARDEN["content_bbox"]["size"])
+ assert _call("framingBox", None) is None
+
+
+def _ndc_of_corners(bbox, cam, aspect):
+ """Project bbox corners with a THREE-style lookAt camera (Y-up); returns max |x|,|y| in NDC."""
+ eye, tgt, fov = cam["position"], cam["lookAt"], cam["fov"]
+ f = [t - e for t, e in zip(tgt, eye, strict=True)]
+ fl = math.hypot(*f)
+ f = [v / fl for v in f]
+ up0 = [0, 1, 0]
+ r = [f[1] * up0[2] - f[2] * up0[1], f[2] * up0[0] - f[0] * up0[2], f[0] * up0[1] - f[1] * up0[0]]
+ rl = math.hypot(*r)
+ r = [v / rl for v in r]
+ u = [r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]]
+ tv = math.tan(math.radians(fov) / 2)
+ th = tv * aspect
+ worst = 0.0
+ for x in (bbox["min"][0], bbox["max"][0]):
+ for y in (bbox["min"][1], bbox["max"][1]):
+ for z in (bbox["min"][2], bbox["max"][2]):
+ rel = [x - eye[0], y - eye[1], z - eye[2]]
+ depth = sum(a * b for a, b in zip(rel, f, strict=True))
+ px = sum(a * b for a, b in zip(rel, r, strict=True)) / (depth * th)
+ py = sum(a * b for a, b in zip(rel, u, strict=True)) / (depth * tv)
+ worst = max(worst, abs(px), abs(py))
+ return worst
+
+
[email protected]("bbox", [GARDEN["content_bbox"], _box([-40, -1, -40], [40, 9, 40]), _box([-3, 0, -1], [3, 12, 1])])
+def test_overview_fit_is_tight_every_corner_just_inside_frame(bbox):
+ views = [{"name": "overview_front_right", "azimuth": 40, "elevation": 32},
+ {"name": "overview_back_left", "azimuth": 220, "elevation": 32},
+ {"name": "overview_top", "azimuth": 0, "elevation": 87}]
+ cams = _call("fitOrbitCameras", bbox, views, {"groundY": bbox["min"][1], "aspect": 16 / 9})
+ for cam in cams:
+ worst = _ndc_of_corners(bbox, cam, 16 / 9)
+ assert worst <= 1.0 + 1e-6, (cam["name"], worst) # every corner inside the frame
+ assert worst >= 0.80, (cam["name"], worst) # ...and the box fills it (tight, not a sphere fit)
+
+
+def test_garden_rig_is_much_closer_than_the_sphere_fit():
+ views = [{"name": "overview_front_right", "azimuth": 40, "elevation": 32}, {"name": "overview_top", "azimuth": 0, "elevation": 87},
+ {"name": "eye_front", "azimuth": 0, "elevation": 10}]
+ cams = {c["name"]: c for c in _call("fitOrbitCameras", GARDEN["content_bbox"], views, {"groundY": 0.37, "aspect": 16 / 9})}
+ ov = cams["overview_front_right"]
+ assert math.dist(ov["position"], ov["lookAt"]) < 38 # the sphere fit gave ≈ 42 m
+ assert cams["overview_top"]["position"][1] < 32 # was ≈ 45 m
+ eye = cams["eye_front"]
+ assert 1.5 < eye["position"][1] < 4 and eye["lookAt"][0] == pytest.approx(-0.95, abs=0.1) # looks at the content centre
diff --git a/harness/tests/scene_runtime/test_assemble.py b/harness/tests/scene_runtime/test_assemble.py
index e6d1a42b..acf70f88 100644
--- a/harness/tests/scene_runtime/test_assemble.py
+++ b/harness/tests/scene_runtime/test_assemble.py
@@ -100,3 +100,36 @@ def test_assemble_end_to_end_excludes_broken_zone(starter_ws):
src = (starter_ws.src / "scene.js").read_text()
assert "broken" not in src
assert lint(starter_ws).passed
+
+
+def test_render_scene_js_awaits_async_builds():
+ """Finding: lint + the assembler probe accept `export async function build(ctx)`,
+ so the generated scene.js must await build/buildEnv instead of throwing on the Promise."""
+ cams = [CameraPlan(name="overview", position=(1, 2, 3), look_at=(0, 0, 0), fov=50)]
+ src = render_scene_js(["orchard"], cams, [], env_ok=True)
+ assert "const addZone = async (build, name) => {" in src
+ assert "const g = await build(ctx);" in src
+ assert "await addZone(buildOrchard, 'Orchard');" in src
+ assert "const env = (await buildEnv(ctx)) || {};" in src
+
+
+@needs_browser
+def test_assemble_with_async_zone_boots(starter_ws):
+ (starter_ws.src / "zones" / "orchard.js").write_text(
+ "import * as THREE from 'three';\n"
+ "export async function build(ctx) {\n"
+ " await new Promise((r) => setTimeout(r, 10));\n"
+ " const g = new THREE.Group(); g.name = 'Orchard';\n"
+ " const m = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshStandardMaterial({ color: 0x884400 }));\n"
+ " m.position.y = 1; g.add(m);\n"
+ " return g;\n"
+ "}\n"
+ )
+ res = assemble(starter_ws)
+ assert "orchard" in res.zones_included and res.zones_failed == {}
+ from codeverse.spatial.probes import probe_scene
+
+ probe = probe_scene(starter_ws)
+ assert probe.gate.passed, [(f.target, f.message) for f in probe.gate.findings]
+ assert "Orchard" in {g["name"] for g in probe.census.get("groups", [])}
diff --git a/harness/tests/scene_runtime/test_glsl_audit.py b/harness/tests/scene_runtime/test_glsl_audit.py
index 416c0f39..221a512f 100644
--- a/harness/tests/scene_runtime/test_glsl_audit.py
+++ b/harness/tests/scene_runtime/test_glsl_audit.py
@@ -94,7 +94,7 @@ void main() { gl_FragColor = vec4(1.0); }`;
export const m = new THREE.ShaderMaterial({ fragmentShader: frag });"""
assert "no_fog" not in kinds(audit(src, sceneUsesFog=False))
assert "no_fog" in kinds(audit(src, sceneUsesFog=True))
- assert "no_fog" not in kinds(audit(src + "\n// c3v: no-fog", sceneUsesFog=True))
+ assert "no_fog" not in kinds(audit(src + "\n// 3dcv: no-fog", sceneUsesFog=True))
def test_locate_source_line_maps_to_file_and_line():
diff --git a/harness/tests/scene_runtime/test_probes.py b/harness/tests/scene_runtime/test_probes.py
index 3fd8a083..30edbbc1 100644
--- a/harness/tests/scene_runtime/test_probes.py
+++ b/harness/tests/scene_runtime/test_probes.py
@@ -132,3 +132,57 @@ def test_shader_presence_on_example_and_when_hidden(starter_ws):
e.write_text(e.read_text().replace(" sky.name = 'Sky';", " sky.name = 'Sky';\n sky.visible = false;"))
obs2 = shader_presence(starter_ws)
assert obs2.numbers["max_diff_frac"] == 0.0 and "NOT VISIBLE" in obs2.text
+
+
+def test_probe_scene_hanging_create_scene_times_out_as_agent_finding(starter_ws):
+ """Finding: a createScene that never resolves (loader.load without onError on a
+ missing asset) must time out INSIDE boot with an agent-attributed finding, not
+ hang into the driver watchdog (exit 3 → 'harness failure, not your code')."""
+ (starter_ws.src / "scene.js").write_text(
+ "import * as THREE from 'three';\n"
+ "export async function createScene({ THREE: T, renderer, loaders }) {\n"
+ " const tex = await new Promise((resolve) => loaders.texture.load('/assets/missing.png', resolve));\n"
+ " return { scene: new THREE.Scene(), cameras: [], update() {} };\n"
+ "}\n"
+ )
+ res = probe_scene(starter_ws, timeout_s=10) # createScene timeout = 6 s < watchdog
+ gate = res.gate
+ assert not gate.passed
+ err = next(f for f in gate.errors if f.data.get("stage") == "createScene")
+ assert "did not resolve within" in err.message and "never settled" in err.message
+ assert "failed to load /assets/missing.png" in err.message
+ assert "createScene({THREE, renderer, loaders})" in err.fix_hint
+ assert res.ok and res.errors == [] # the probe TOOL ran fine (agent-fixable failure)
+ assert not any("harness/driver failure" in f.fix_hint for f in gate.findings)
+
+
+def test_probe_result_tool_semantics(starter_ws, monkeypatch):
+ """SceneProbeResult.ok/errors = 'did the tool run' (MCP is_error); agent-fixable
+ gate findings live in .findings and never mark the tool call as failed."""
+ import codeverse.spatial.probes as probes_mod
+ from codeverse.spatial.render_scene import NodeResult, SceneRenderError
+
+ def fake_run_ok(script, args, **kw):
+ return NodeResult(0, "", "", {
+ "ok": False,
+ "boot": {"ok": True, "stage": "ready", "cameras": [{"name": "a"}], "camera_problems": []},
+ "update_ok": True, "census": {"totals": {"meshes": 3, "lights": 1}},
+ "console_errors": ["custom failure 42"], "console_warnings": [], "shader_errors": [],
+ }, 5)
+
+ monkeypatch.setattr(probes_mod, "run_scene_script", fake_run_ok)
+ res = probes_mod.probe_scene(starter_ws)
+ assert not res.gate.passed # gate truth: the scene has an error
+ assert res.ok and res.errors == [] # tool truth: the probe ran
+ assert any("custom failure 42" in line for line in res.findings)
+
+ def fake_run_crash(script, args, **kw):
+ raise SceneRenderError("probe_scene.mjs failed (exit 3): timeout")
+
+ monkeypatch.setattr(probes_mod, "run_scene_script", fake_run_crash)
+ res2 = probes_mod.probe_scene(starter_ws)
+ assert not res2.gate.passed and not res2.ok
+ assert res2.errors and "could not run" in res2.errors[0]
+ assert res2.gate.errors[0].data.get("harness_failure") is True
+ rep = probes_mod.check_shaders(starter_ws)
+ assert not rep.passed and rep.errors[0].data.get("harness_failure") is True
diff --git a/harness/tests/scene_runtime/test_render_scene.py b/harness/tests/scene_runtime/test_render_scene.py
index b6805ec6..433e8de0 100644
--- a/harness/tests/scene_runtime/test_render_scene.py
+++ b/harness/tests/scene_runtime/test_render_scene.py
@@ -127,3 +127,109 @@ def test_camera_in_geometry_is_detected(starter_ws):
m = read_metrics(out)
chk = m["camera_checks"][0]
assert chk["camera_in_geometry"] is True
+
+
+@needs_node
+def test_driver_crash_after_metrics_degrades_to_renderset(fake_runtime, ws, tmp_path):
+ """A driver death AFTER instruments were written must yield a degraded
+ RenderSet (console_errors say why) — never a SceneRenderError that fails the run."""
+ (fake_runtime / "render_scene.mjs").write_text(
+ FAKE_DRIVER.replace(
+ "console.log(JSON.stringify({ ok: true, n_views: views.length, renderer: 'FakeGL' }));",
+ "console.error('error: render failed: Cannot set properties of undefined');\nprocess.exit(2);",
+ )
+ )
+ out = tmp_path / "out"
+ rs = render_scene(ws, out, cameras=[CameraPlan(name="cam_a", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)],
+ orbit=False, times=(0.0,), sheet=False)
+ assert len(rs.views) == 1
+ assert any("render_scene.mjs failed (exit 2)" in e for e in rs.console_errors)
+
+
+@needs_node
+def test_render_scene_clears_stale_metrics(fake_runtime, ws, tmp_path):
+ out = tmp_path / "out"
+ out.mkdir()
+ (out / "metrics.json").write_text('{"views": [{"name": "stale", "path": "x.png", "position": [0,0,0], "lookAt": [0,0,0]}]}')
+ rs = render_scene(ws, out, cameras=[CameraPlan(name="cam_a", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)],
+ orbit=False, times=(0.0,), sheet=False)
+ assert all(v.name != "stale" for v in rs.views)
+
+
+@needs_browser
+def test_update_throw_mid_render_yields_frames_and_console_error(starter_ws):
+ """Finding: an update(t, dt) exception past the probed window must NOT abort the
+ render (SceneRenderError → run FAILED); the remaining views render and the error
+ becomes a console error (→ render_console gate finding)."""
+ scene = starter_ws.src / "scene.js"
+ src = scene.read_text()
+ assert "function update(t, dt) {" in src
+ scene.write_text(src.replace(
+ "function update(t, dt) {",
+ "function update(t, dt) {\n if (t > 1.0) { const lanterns = []; lanterns[0].intensity = Math.sin(t); }",
+ 1,
+ ))
+ out = starter_ws.renders_dir(3)
+ rs = render_scene(starter_ws, out, times=(0.0, 1.5), width=320, height=180, fps_seconds=0.3,
+ orbit_views=SCENE_VIEWS[:1])
+ # every requested view rendered (3 authored + 1 orbit, at 2 times)
+ assert len(rs.views) == 2 * 4, [v.name for v in rs.views]
+ assert all(Path(v.path).is_file() for v in rs.views)
+ assert any(e.startswith("update(t=") and "intensity" in e for e in rs.console_errors), rs.console_errors
+ m = read_metrics(out)
+ assert m["update_errors"] and "update() disabled" in m["update_errors"][0]
+
+
+@needs_browser
+def test_request_failure_line_filters_phantom_aborts():
+ """Finding: Chrome's phantom `requestfailed net::ERR_ABORTED` after a consumed
+ 200 response must never reach console_errors (spurious gate failures)."""
+ from tests.scene_runtime.conftest import run_node_json
+
+ res = run_node_json(
+ "import { requestFailureLine, createTimeoutMs } from './lib/host_page.mjs';\n"
+ "console.log(JSON.stringify({\n"
+ " phantom: requestFailureLine('http://x/assets/a.glb', 'http://x', true, 'net::ERR_ABORTED'),\n"
+ " aborted: requestFailureLine('http://x/assets/a.glb', 'http://x', false, 'net::ERR_ABORTED'),\n"
+ " responded: requestFailureLine('http://x/assets/a.glb', 'http://x', true, 'net::ERR_FAILED'),\n"
+ " real: requestFailureLine('http://x/assets/a.glb', 'http://x', false, 'net::ERR_CONNECTION_REFUSED'),\n"
+ " offsite: requestFailureLine('http://cdn/other.js', 'http://x', false, 'net::ERR_FAILED'),\n"
+ " cs_default: createTimeoutMs('', 240000),\n"
+ " cs_flag: createTimeoutMs('3000', 240000),\n"
+ " cs_small_budget: createTimeoutMs('', 10000),\n"
+ "}));\n"
+ )
+ assert res["phantom"] is None and res["aborted"] is None and res["responded"] is None
+ assert res["real"] == "request failed: /assets/a.glb (net::ERR_CONNECTION_REFUSED)"
+ assert res["offsite"] is None
+ assert res["cs_default"] == 20000 and res["cs_flag"] == 3000 and res["cs_small_budget"] == 6000
+
+
+def test_frame_table_from_metrics_dict():
+ from codeverse.spatial.render_scene import frame_table
+
+ metrics = {"camera_checks": [
+ {"name": "overview", "kind": "authored", "mean_lum": 0.34, "dark_frac": 0.05, "blown_frac": 0.0,
+ "content_frac": 0.48, "camera_in_geometry": False},
+ {"name": "buried", "kind": "orbit", "mean_lum": 0.02, "dark_frac": 0.91, "blown_frac": 0.0,
+ "content_frac": 0.01, "camera_in_geometry": True},
+ ]}
+ table = frame_table(metrics)
+ lines = table.splitlines()
+ assert lines[0].split() == ["view", "mean_lum", "dark%", "blown%", "content%", "cam_in_geom"]
+ assert "overview [authored]" in lines[1] and "0.34" in lines[1] and "48%" in lines[1] and lines[1].endswith("no")
+ assert "buried [orbit]" in lines[2] and "91%" in lines[2] and lines[2].endswith("YES")
+ assert "no camera_checks" in frame_table({})
+
+
+@needs_browser
+def test_frame_table_from_renderset(starter_ws):
+ from codeverse.spatial.render_scene import frame_table
+
+ out = starter_ws.renders_dir(4)
+ rs = render_scene(starter_ws, out, times=(0.0,), width=320, height=180, fps_seconds=0, orbit_views=SCENE_VIEWS[:1], sheet=False)
+ table = frame_table(rs)
+ assert "overview [authored]" in table and "mean_lum" in table
+ assert table == frame_table(out)
diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.py
index 5a95dfb0..5393fa4b 100644
--- a/harness/tests/spatial_tools/test_connectivity.py
+++ b/harness/tests/spatial_tools/test_connectivity.py
@@ -20,7 +20,29 @@ def test_floating_leg_found_with_exact_gap(stool_glb: Path) -> None:
assert d["nearest"] == "Seat"
assert d["gap_m"] == pytest.approx(FLOAT_GAP_M, abs=1e-4)
assert np.allclose(d["gap_vector_m"], (0.0, FLOAT_GAP_M, 0.0), atol=1e-4)
- assert "translate 'Leg_3' by (+0.0000, +0.0050, +0.0000)" in errs[0].fix_hint
+ assert "translate 'Leg_3' by (+0.0000, +0.0050, +0.0000) m (GLB frame: Y-up, +Z front)" in errs[0].fix_hint
+
+
+def test_hints_use_the_authoring_frame(stool_glb: Path) -> None:
+ """The 5 mm gap is along GLB +y (up). A Blender/CadQuery/URDF agent codes in Z-up, so
+ the pasted hint must say +z (a literal '+y' would move the leg towards the back)."""
+ err = check_connectivity(stool_glb, language="blender").errors[0]
+ assert "translate 'Leg_3' by (+0.0000, +0.0000, +0.0050) m (blender frame: Z-up, -Y front)" in err.fix_hint
+ assert np.allclose(err.data["gap_vector_m"], (0.0, 0.0, FLOAT_GAP_M), atol=1e-4)
+ assert np.allclose(err.data["gap_vector_glb_m"], (0.0, FLOAT_GAP_M, 0.0), atol=1e-4)
+ assert err.data["frame"] == "z_up_neg_y_front"
+ err = check_connectivity(stool_glb, language="threejs").errors[0]
+ assert "(+0.0000, +0.0050, +0.0000) m (threejs frame: Y-up, +Z front)" in err.fix_hint
+ # nothing grounded: the ground hint names the language's up axis
+ s = trimesh.Scene()
+ for i, x in enumerate((0.0, 0.3)):
+ m = trimesh.creation.box((0.1, 0.1, 0.1))
+ m.apply_translation((x, 0.5, 0))
+ s.add_geometry(m, node_name=f"P{i}", geom_name=f"P{i}")
+ p = stool_glb.parent / "floating_pair.glb"
+ p.write_bytes(s.export(file_type="glb"))
+ ground = [f for f in check_connectivity(p, language="cadquery").findings if "touches the ground" in f.message]
+ assert ground and "(z=0)" in ground[0].message and "z=0, cadquery frame" in ground[0].fix_hint
def test_solid_stool_passes(solid_stool_glb: Path) -> None:
diff --git a/harness/tests/spatial_tools/test_contract.py b/harness/tests/spatial_tools/test_contract.py
index 2d24dec2..d0b1b77d 100644
--- a/harness/tests/spatial_tools/test_contract.py
+++ b/harness/tests/spatial_tools/test_contract.py
@@ -2,6 +2,8 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
from codeverse.contracts.artifacts import Measurement, PartMeasure, Severity
from codeverse.contracts.plan import BBox, CameraPlan, PartPlan, ScenePlan, StaticPlan, ZonePlan
from codeverse.spatial.contract import check_contract, match_parts, plan_bbox_to_glb
@@ -94,3 +96,31 @@ def test_scene_plan_bounds() -> None:
assert r.passed # scene findings are warnings
assert any("exceeds the planned bounds" in f.message for f in r.findings)
assert not any("zone group" in f.message for f in r.findings)
+
+
+def test_hints_are_written_in_the_authoring_frame() -> None:
+ """Blender plan (Z-up): Leg 5×5 cm footprint, 40 cm tall. The build made the leg 25 cm
+ DEEP (Blender y) — sizes, deltas and centres in the hint must be Z-up so the agent
+ changes the right dimension (in the GLB frame the same error reads as 'z+20cm')."""
+ plan = StaticPlan(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.5, 0.5, 0.45)),
+ parts=[PartPlan(name="Seat", role="seat", description="d", bbox=BBox(center=(0, 0, 0.425), extents=(0.5, 0.5, 0.05))),
+ PartPlan(name="Leg", role="leg", description="d", bbox=BBox(center=(0.2, -0.2, 0.2), extents=(0.05, 0.05, 0.40)))])
+ m = Measurement(bbox_min=(-0.25, 0, -0.25), bbox_max=(0.25, 0.45, 0.25), extents=(0.5, 0.45, 0.5), center=(0.1, 0.225, -0.05),
+ tri_count=24, n_meshes=2, n_islands=2, footprint_offset_m=0.3,
+ parts=[PartMeasure(name="Seat", bbox_min=(-0.25, 0.40, -0.25), bbox_max=(0.25, 0.45, 0.25)),
+ PartMeasure(name="Leg", bbox_min=(0.175, 0.0, 0.075), bbox_max=(0.225, 0.40, 0.325))])
+ r = check_contract(m, plan, language="blender")
+ leg = [f for f in r.findings if f.target == "Leg"][0]
+ assert "size 5.0×25.0×40.0 vs planned 5.0×5.0×40.0 cm (Δ x+0.0cm, y+20.0cm, z+0.0cm)" in leg.fix_hint
+ assert "centre off by (x+0.0cm, y+0.0cm, z+0.0cm)" not in leg.fix_hint
+ assert "planned centre (0.200, -0.200, 0.200) m (blender frame: Z-up, -Y front)" in leg.fix_hint
+ assert leg.data["delta_extents_m"] == pytest.approx([0.0, 0.2, 0.0], abs=1e-9) and leg.data["frame"] == "z_up_neg_y_front"
+ foot = [f for f in r.findings if "footprint" in f.message][0]
+ # GLB offset (+0.1, ·, -0.05) → move by (-0.1, 0, +0.05) GLB = (-0.1, -0.05, 0) in Blender's Z-up frame
+ assert "translate everything by (-0.100, -0.050, +0.000) m (blender frame: Z-up, -Y front)" in foot.fix_hint
+ # Y-up languages keep the GLB numbers verbatim
+ plan_tjs = plan.model_copy(deep=True)
+ plan_tjs.parts[1].bbox = BBox(center=(0.2, 0.2, 0.2), extents=(0.05, 0.40, 0.05))
+ leg = [f for f in check_contract(m, plan_tjs, language="threejs").findings if f.target == "Leg"][0]
+ assert "size 5.0×40.0×25.0 vs planned 5.0×40.0×5.0 cm (Δ x+0.0cm, y+0.0cm, z+20.0cm)" in leg.fix_hint
+ assert "(threejs frame: Y-up, +Z front)" in leg.fix_hint
diff --git a/harness/tests/spatial_tools/test_measure.py b/harness/tests/spatial_tools/test_measure.py
index 683215ee..200b4379 100644
--- a/harness/tests/spatial_tools/test_measure.py
+++ b/harness/tests/spatial_tools/test_measure.py
@@ -64,3 +64,17 @@ def test_unnamed_single_mesh(tmp_path: Path) -> None:
trimesh.creation.box(extents=(1, 1, 1)).export(str(p))
m = measure_glb(p)
assert len(m.parts) == 1 and m.tri_count == 12
+
+
+def test_cyclic_scene_graph_does_not_hang(tmp_path: Path) -> None:
+ """A GLB node named like the loader's base frame ('world') closes a cycle in the
+ scene graph; measuring must terminate (with the geometry still counted once)."""
+ from codeverse.spatial.measure import _subtree_nodes, part_meshes
+
+ box = trimesh.creation.box((0.2, 0.2, 0.2))
+ scene = trimesh.Scene(base_frame="root")
+ scene.graph.update(frame_to="wrapper", frame_from="root")
+ scene.add_geometry(box, node_name="world", geom_name="world", parent_node_name="wrapper")
+ scene.graph.update(frame_to="root", frame_from="world") # cycle: root → wrapper → world → root
+ assert "world" in _subtree_nodes(scene, "root") and len(_subtree_nodes(scene, "root")) == 3
+ assert [k for k, v in part_meshes(scene).items() if v is not None]
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index c12c3b83..9c9fbe0f 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -21,14 +21,30 @@ from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
from codeverse.spatial.registry import ToolContext, get_tool, list_tools
from codeverse.workspace import Workspace
-EXPECTED_TOOLS = {"build", "measure", "render_views", "render_sheet", "isolate", "cross_section", "check_connectivity",
- "check_contract", "compare_silhouette", "joint_sweep", "shader_probe", "scene_probe", "scene_views", "read_cookbook"}
+#: tools every workspace gets (no track/language restriction)
+CORE_TOOLS = {"build", "measure", "render_views", "render_sheet", "isolate", "cross_section", "check_connectivity",
+ "check_contract", "compare_silhouette", "read_cookbook"}
+#: track- / language-scoped tools (documented; keep in sync when registering a new one)
+SCOPED_TOOLS = {
+ "joint_sweep", # articulated_object
+ "shader_probe", "scene_probe", "scene_views", # scene_threejs
+ "gl_probe", "gl_frames", # graphics (glsl_shader / opengl_python)
+ "texture_pass", "texture_preview", # object tracks (texturing)
+}
+EXPECTED_TOOLS = CORE_TOOLS | SCOPED_TOOLS
def test_registry_has_every_tool() -> None:
- assert {t.name for t in list_tools()} == EXPECTED_TOOLS
- assert "joint_sweep" not in {t.name for t in list_tools(track="static_object", language="blender")}
+ registered = {t.name for t in list_tools()}
+ assert registered == EXPECTED_TOOLS, (
+ f"registry drifted: unexpected {sorted(registered - EXPECTED_TOOLS)}, "
+ f"missing {sorted(EXPECTED_TOOLS - registered)} — update CORE_TOOLS/SCOPED_TOOLS above")
+ static_blender = {t.name for t in list_tools(track="static_object", language="blender")}
+ assert "joint_sweep" not in static_blender and "gl_probe" not in static_blender
+ assert "texture_pass" in static_blender
assert "shader_probe" in {t.name for t in list_tools(track="scene", language="scene_threejs")}
+ graphics = {t.name for t in list_tools(track="graphics", language="glsl_shader")}
+ assert {"gl_probe", "gl_frames"} <= graphics and "texture_pass" not in graphics and "scene_probe" not in graphics
for t in list_tools():
assert t.schema()["type"] == "object" and t.description
@@ -51,7 +67,9 @@ def test_tools_without_glb(tmp_ws: Workspace) -> None:
def test_connectivity_and_section_tools(stool_ctx: ToolContext) -> None:
obs = get_tool("check_connectivity").call(stool_ctx, {})
- assert not obs.ok and "Leg_3" in obs.text and "translate 'Leg_3' by (+0.0000, +0.0050, +0.0000)" in obs.text
+ # the 5 mm gap is along GLB +y (up) → written in the Blender frame as +z, labelled
+ assert not obs.ok and "Leg_3" in obs.text
+ assert "translate 'Leg_3' by (+0.0000, +0.0000, +0.0050) m (blender frame: Z-up, -Y front)" in obs.text
assert (stool_ctx.workspace.gates_dir(0) / "connectivity_tool.json").is_file()
obs = get_tool("cross_section").call(stool_ctx, {"axis": "y", "at": 0.5})
assert obs.ok and len(obs.images) == 1 and Path(obs.images[0]).is_file() and obs.numbers["n_loops"] == 4
@@ -286,3 +304,68 @@ def test_scene_tools_with_fake_siblings(stool_ctx: ToolContext, monkeypatch: pyt
assert obs.ok and "meshes=12" in obs.text and obs.numbers["fps"] == 58.0
obs = get_tool("joint_sweep").call(stool_ctx, {"joints": ["hinge"], "n_samples": 5})
assert obs.ok and calls == {"n_random": 5, "joint": "hinge"}
+
+
+# --------------------------------------------------------------------------- build without a GLB (scene / graphics)
+class _NoGlbRuntime(_FakeRuntime):
+ """Build succeeds with glb_path=None (scene_threejs / graphics runtimes)."""
+
+ def __init__(self, language: str, census: dict, extra_paths: dict | None = None):
+ super().__init__()
+ self.language, self.census, self.extra_paths = language, census, extra_paths or {}
+
+ def build(self, ws, *, timeout_s=None):
+ return BuildResult(ok=True, language=self.language, glb_path=None, duration_ms=9,
+ census=self.census, extra_paths=self.extra_paths)
+
+
+def test_build_tool_scene_reports_probe_census(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = ToolContext(workspace=tmp_ws, language="scene_threejs", track="scene")
+ rt = _NoGlbRuntime("scene_threejs", {"meshes": 12, "lights": 2, "fps": 58.0},
+ {"scene_probe": str(tmp_ws.artifacts / "scene_probe.json")})
+ _patch_runtime(monkeypatch, rt)
+ obs = get_tool("build").call(ctx, {})
+ assert obs.ok, obs.text
+ assert "no GLB path" not in obs.text
+ assert "scene probe census" in obs.text and "meshes=12" in obs.text
+ assert obs.numbers["census"]["fps"] == 58.0
+
+
+def test_build_tool_graphics_reports_frames(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.languages.glsl_shader.gl_build as gl_build
+ from codeverse.spatial.frame_stats import FrameStat, SequenceStats
+
+ ctx = ToolContext(workspace=tmp_ws, language="glsl_shader", track="graphics")
+ rt = _NoGlbRuntime("glsl_shader", {"renderer": "moderngl"},
+ {"frames": str(tmp_ws.artifacts / "frames"), "sheet": str(tmp_ws.artifacts / "frames_sheet.png")})
+ _patch_runtime(monkeypatch, rt)
+ def _frame(t: float, path: str) -> FrameStat:
+ return FrameStat(time=t, path=path, mean_lum=0.4, std_lum=0.2, pct_black=0.01, pct_blown=0.01,
+ colourfulness=0.3, edge_density=0.05)
+
+ stats = SequenceStats(frames=[_frame(0.0, "f0.png"), _frame(1.0, "f1.png")], mean_diff=0.1)
+ gate = GateReport(gate="gl_frames", passed=True)
+ monkeypatch.setattr(gl_build, "read_metrics", lambda ws: (stats, gate))
+ obs = get_tool("build").call(ctx, {})
+ assert obs.ok, obs.text
+ assert "no GLB path" not in obs.text
+ assert "frames=2" in obs.text and "sheet:" in obs.text
+ assert obs.numbers["n_frames"] == 2 and obs.numbers["gate_errors"] == 0
+ # a failing gl_frames gate flips ok
+ bad = GateReport(gate="gl_frames", passed=False,
+ findings=[GateFinding(gate="gl_frames", severity=Severity.ERROR, message="static image",
+ data={"kind": "static"})])
+ monkeypatch.setattr(gl_build, "read_metrics", lambda ws: (stats, bad))
+ obs = get_tool("build").call(ctx, {})
+ assert not obs.ok and "static image" in obs.text
+
+
+def test_load_plan_recognises_graphics_plan(tmp_ws: Workspace) -> None:
+ from codeverse.contracts.plan import GraphicsPlan, PassPlan
+ from codeverse.spatial.tool_common import load_plan
+
+ plan = GraphicsPlan(title="Neon rain", summary="s", style="cyberpunk",
+ passes=[PassPlan(name="Rain", description="drops")])
+ tmp_ws.write_json(tmp_ws.plan_path, plan)
+ loaded = load_plan(tmp_ws.plan_path)
+ assert isinstance(loaded, GraphicsPlan) and loaded.title == "Neon rain"
diff --git a/harness/tests/texturing/__init__.py b/harness/tests/texturing/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/texturing/conftest.py b/harness/tests/texturing/conftest.py
new file mode 100644
index 00000000..4b5f4885
--- /dev/null
+++ b/harness/tests/texturing/conftest.py
@@ -0,0 +1,115 @@
+"""Fixtures for the texturing tests: a small chair-like GLB (named nodes, instances),
+its plan + spec, a fake image model, a fake render function and a fake judge."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import pytest
+import trimesh
+from PIL import Image
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.contracts.common import Language, Track, Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.texturing.generate import FakeImageModel
+
+
+
+def _box(ext: tuple[float, float, float], center: tuple[float, float, float]) -> trimesh.Trimesh:
+ m = trimesh.creation.box(extents=ext)
+ m.apply_translation(center)
+ return m
+
+
+def chair_glb(tmp_path: Path) -> Path:
+ """Y-up chair: Seat slab, Back slab, 4 Leg_i cylinders (instances), a tiny glass Knob."""
+ scene = trimesh.Scene()
+ seat = _box((0.44, 0.03, 0.42), (0, 0.45, 0))
+ seat.visual = trimesh.visual.ColorVisuals(seat, face_colors=(150, 100, 60, 255))
+ scene.add_geometry(seat, node_name="Seat", geom_name="Seat")
+ back = _box((0.44, 0.35, 0.03), (0, 0.64, -0.195))
+ back.visual = trimesh.visual.ColorVisuals(back, face_colors=(150, 100, 60, 255))
+ scene.add_geometry(back, node_name="Back", geom_name="Back")
+ leg = trimesh.creation.cylinder(radius=0.02, height=0.45, sections=24)
+ leg.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, (1, 0, 0))) # along Y
+ leg.apply_translation((0, 0.225, 0))
+ leg.visual = trimesh.visual.ColorVisuals(leg, face_colors=(90, 90, 95, 255))
+ for i, (x, z) in enumerate([(-0.2, -0.19), (0.2, -0.19), (-0.2, 0.19), (0.2, 0.19)]):
+ T = trimesh.transformations.translation_matrix((x, 0, z))
+ scene.add_geometry(leg.copy(), node_name=f"Leg_{i}", geom_name=f"Leg_{i}", transform=T)
+ knob = trimesh.creation.icosphere(subdivisions=1, radius=0.01)
+ knob.apply_translation((0.22, 0.47, 0))
+ knob.visual = trimesh.visual.ColorVisuals(knob, face_colors=(200, 220, 255, 255))
+ scene.add_geometry(knob, node_name="Knob", geom_name="Knob")
+ out = tmp_path / "object.glb"
+ scene.export(out)
+ return out
+
+
+def _bbox(c: tuple[float, float, float], e: tuple[float, float, float]) -> BBox:
+ return BBox(center=c, extents=e)
+
+
+def chair_plan() -> StaticPlan:
+ return StaticPlan(
+ object_name="TestChair", summary="a simple wooden chair with steel legs",
+ overall_bbox=_bbox((0, 0, 0.4), (0.44, 0.42, 0.82)),
+ parts=[
+ PartPlan(name="Seat", role="seat", description="slab", bbox=_bbox((0, 0, 0.45), (0.44, 0.42, 0.03)), material="oiled oak wood"),
+ PartPlan(name="Back", role="backrest", description="slab", bbox=_bbox((0, -0.2, 0.64), (0.44, 0.03, 0.35)), material="oiled oak wood"),
+ PartPlan(name="Leg", role="leg", description="round steel tube", bbox=_bbox((0.2, 0.19, 0.225), (0.04, 0.04, 0.45)),
+ material="brushed steel", attach_to="Seat", instances=4),
+ PartPlan(name="Knob", role="decor", description="tiny glass ball", bbox=_bbox((0.22, 0, 0.47), (0.02, 0.02, 0.02)),
+ material="clear glass", attach_to="Seat"),
+ ],
+ )
+
+
+def chair_spec() -> Spec:
+ return Spec(id="t1", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a simple oak chair with brushed steel legs")
+
+
+def fake_image_model() -> FakeImageModel:
+ return FakeImageModel()
+
+
+def fake_render(glb: Path | str, out_dir: Path | str, *, views: Any, width: int = 512, height: int = 512, **_: Any) -> RenderSet:
+ """Writes one flat PNG per view + a sheet; colour keyed by the GLB size (so before/after differ)."""
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ seed = Path(glb).stat().st_size % 200
+ rviews = []
+ for v in views:
+ p = out_dir / f"view_{v.name}.png"
+ Image.new("RGB", (64, 64), (seed + 30, 120, 160)).save(p)
+ rviews.append(RenderView(name=v.name, path=str(p), width=64, height=64))
+ sheet = out_dir / "sheet.png"
+ Image.new("RGB", (128, 64), (seed + 30, 120, 160)).save(sheet)
+ return RenderSet(views=rviews, contact_sheet=str(sheet), renderer="fake")
+
+
+class FakeJudge:
+ """Returns scripted verdicts in order (cycles the last one)."""
+
+ name = "fake"
+
+ def __init__(self, verdicts: list[tuple[float, dict[str, float]]], *, degraded: bool = False):
+ self.verdicts = verdicts
+ self.calls = 0
+ self.degraded = degraded
+
+ def judge(self, inp: Any) -> Judgment:
+ overall, scores = self.verdicts[min(self.calls, len(self.verdicts) - 1)]
+ self.calls += 1
+ summary = "judge_error: boom" if self.degraded else "ok"
+ return Judgment(rubric="static_object_v1", scores=scores, overall=overall, passed=overall >= 0.72, summary=summary,
+ usage=Usage(cost_usd=0.01))
diff --git a/harness/tests/texturing/test_apply.py b/harness/tests/texturing/test_apply.py
new file mode 100644
index 00000000..9dcaaa77
--- /dev/null
+++ b/harness/tests/texturing/test_apply.py
@@ -0,0 +1,52 @@
+"""apply.py: textured GLB keeps names/geometry, shares images, skips parts, reloads."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import numpy as np
+import trimesh
+
+from codeverse.spatial.measure import measure_glb
+from codeverse.texturing.apply import apply_textures, node_part_lookup, textured_summary
+from codeverse.texturing.generate import FakeImageModel, generate_textures
+from codeverse.texturing.plan import default_plan
+
+
+def test_node_part_lookup_instances_and_links(chair_plan):
+ tp = default_plan(chair_plan)
+ lk = node_part_lookup(["Seat", "Leg_0", "Leg_3", "Knob", "Back__1", "Mystery"], tp.by_part())
+ assert lk["Leg_0"].part == "Leg" and lk["Leg_3"].part == "Leg" and lk["Back__1"].part == "Back"
+ assert lk["Mystery"] is None
+
+
+def test_apply_textures_end_to_end(tmp_path: Path, chair_glb: Path, chair_plan):
+ tp = default_plan(chair_plan)
+ ts = generate_textures(tp, tmp_path / "tex", FakeImageModel(), size=64, cache_dir=tmp_path / "c")
+ out = tmp_path / "object_textured.glb"
+ rep = apply_textures(chair_glb, tp, ts.paths(), out)
+ assert out.is_file() and rep.warnings == []
+ assert sorted(rep.parts_textured) == ["Back", "Leg_0", "Leg_1", "Leg_2", "Leg_3", "Seat"]
+ assert rep.parts_skipped == ["Knob"] and rep.parts_unmatched == []
+ assert rep.projections["Leg_0"] == "cylinder" and rep.projections["Seat"] == "box"
+ assert rep.n_materials == 2
+ summ = textured_summary(out)
+ assert summ["textured"] == 6 and summ["geometries"] == 7 and summ["images"] == 2
+ # names + geometry preserved; measurement unchanged
+ a, b = measure_glb(chair_glb), measure_glb(out)
+ assert {p.name for p in a.parts} == {p.name for p in b.parts}
+ assert np.allclose(a.extents, b.extents, atol=1e-6) and a.tri_count == b.tri_count
+ # skipped part keeps its original (untextured) visual
+ s = trimesh.load(out, force="scene", process=False)
+ knob = s.geometry["Knob"]
+ assert getattr(getattr(knob.visual, "material", None), "baseColorTexture", None) is None
+ # UVs present and per-vertex on textured parts
+ seat = s.geometry["Seat"]
+ assert seat.visual.uv is not None and len(seat.visual.uv) == len(seat.vertices)
+
+
+def test_apply_with_missing_texture_file_warns(tmp_path: Path, chair_glb: Path, chair_plan):
+ tp = default_plan(chair_plan)
+ rep = apply_textures(chair_glb, tp, {tp.texture_ids()[0]: tmp_path / "missing.png"}, tmp_path / "o.glb")
+ assert any("missing" in w for w in rep.warnings)
+ assert rep.parts_textured == []
diff --git a/harness/tests/texturing/test_gate.py b/harness/tests/texturing/test_gate.py
new file mode 100644
index 00000000..395b19ca
--- /dev/null
+++ b/harness/tests/texturing/test_gate.py
@@ -0,0 +1,58 @@
+"""gate.py: seam gate + before/after judge gate decisions."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.texturing.gate import judge_gate, material_criterion, seam_gate
+from codeverse.texturing.generate import TextureAsset
+from tests.texturing.conftest import FakeJudge, fake_render
+
+
+def _asset(tid: str, seam: float, ok_path: Path) -> TextureAsset:
+ return TextureAsset(texture_id=tid, path=str(ok_path), prompt="p", prompt_hash="h", seam_score=seam)
+
+
+def test_seam_gate(tmp_path: Path):
+ p = tmp_path / "a.png"
+ p.write_bytes(b"x")
+ res = seam_gate({"a": _asset("a", 0.01, p), "b": _asset("b", 0.5, p), "c": _asset("c", 0.0, tmp_path / "none.png")})
+ assert res.passed == {"a": 0.01} and res.failed == {"b": 0.5}
+
+
+def test_material_criterion_lookup():
+ assert material_criterion({"intent_fidelity": 1, "materials": 0.5}) == "materials"
+ assert material_criterion({"a": 1, "materials_shaders_effects": 0.2}) == "materials_shaders_effects"
+ assert material_criterion({"x": 1}) == ""
+
+
+def _run(tmp_path, chair_spec, chair_plan, chair_glb, verdicts, **kw):
+ judge = FakeJudge(verdicts)
+ after = tmp_path / "after.glb"
+ after.write_bytes(chair_glb.read_bytes() + b"\0" * 7) # different size → different fake render colour
+ res = judge_gate(chair_spec, chair_plan, chair_glb, after, tmp_path / "gate", judge=judge, render=fake_render, **kw)
+ assert judge.calls == 2
+ return res
+
+
+def test_judge_gate_ships_on_material_gain(tmp_path, chair_spec, chair_plan, chair_glb):
+ res = _run(tmp_path, chair_spec, chair_plan, chair_glb,
+ [(0.70, {"materials": 0.6, "x": 0.7}), (0.71, {"materials": 0.7, "x": 0.7})])
+ assert res.shipped and res.delta == 0.01 and res.materials_delta == 0.1 and res.materials_criterion == "materials"
+ assert res.renders_before and res.renders_after and res.usage.cost_usd == 0.02
+ assert Path(res.renders_after.contact_sheet).is_file()
+
+
+def test_judge_gate_rejects_overall_drop_or_flat_materials(tmp_path, chair_spec, chair_plan, chair_glb):
+ res = _run(tmp_path, chair_spec, chair_plan, chair_glb, [(0.70, {"materials": 0.6}), (0.65, {"materials": 0.9})])
+ assert not res.shipped and "Δoverall" in res.reason
+ res = _run(tmp_path, chair_spec, chair_plan, chair_glb, [(0.70, {"materials": 0.6}), (0.72, {"materials": 0.6})])
+ assert not res.shipped and "did not improve" in res.reason
+ res = _run(tmp_path, chair_spec, chair_plan, chair_glb, [(0.70, {"materials": 0.6}), (0.695, {"materials": 0.7})])
+ assert res.shipped # −0.005 is within the −0.01 tolerance
+
+
+def test_judge_gate_degraded_never_ships(tmp_path, chair_spec, chair_plan, chair_glb):
+ judge = FakeJudge([(0.0, {"materials": 0.0})], degraded=True)
+ res = judge_gate(chair_spec, chair_plan, chair_glb, chair_glb, tmp_path / "g", judge=judge, render=fake_render)
+ assert not res.shipped and "degraded" in res.reason
diff --git a/harness/tests/texturing/test_generate.py b/harness/tests/texturing/test_generate.py
new file mode 100644
index 00000000..bcb5ddfd
--- /dev/null
+++ b/harness/tests/texturing/test_generate.py
@@ -0,0 +1,44 @@
+"""generate.py: dedupe, cache, parallel fan-out, per-texture failures, usage."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from PIL import Image
+
+from codeverse.texturing.generate import FakeImageModel, generate_textures, prompt_key
+from codeverse.texturing.tile import SEAM_MAX
+
+
+def test_generate_dedupes_caches_and_accounts(tmp_path: Path):
+ model = FakeImageModel(usd_per_image=0.01)
+ prompts = {"oak": "oak wood grain", "oak_copy": "oak wood grain", "steel": "brushed steel"}
+ ts = generate_textures(prompts, tmp_path / "out", model, size=128, cache_dir=tmp_path / "cache", max_workers=3)
+ assert set(ts.textures) == set(prompts)
+ assert len(model.calls) == 2 # identical prompt generated once
+ assert ts.usage.cost_usd == 0.02 and ts.usage.output_tokens == 2 * 1290
+ for a in ts.textures.values():
+ assert a.ok and Image.open(a.path).size == (128, 128)
+ assert a.seam_score <= SEAM_MAX and a.seam_score < a.seam_score_raw
+ assert ts.textures["oak_copy"].cached and ts.textures["oak_copy"].prompt_hash == ts.textures["oak"].prompt_hash
+ assert (tmp_path / "cache" / "textures" / f"{prompt_key('oak wood grain', model.id, 128)}.png").is_file()
+ # second run: everything from cache, no model calls, zero cost
+ ts2 = generate_textures(prompts, tmp_path / "out2", model, size=128, cache_dir=tmp_path / "cache")
+ assert len(model.calls) == 2 and ts2.usage.cost_usd == 0.0 and all(a.cached for a in ts2.textures.values())
+
+
+def test_generate_records_failures_per_texture(tmp_path: Path):
+ model = FakeImageModel(fail_on=("forbidden",))
+ ts = generate_textures({"ok": "oak", "bad": "forbidden pattern"}, tmp_path, model, size=64, cache_dir=tmp_path / "c")
+ assert ts.textures["ok"].ok and not ts.textures["bad"].ok
+ assert "ModelError" in ts.textures["bad"].error and ts.failed() == {"bad": ts.textures["bad"].error}
+ assert set(ts.paths()) == {"ok"}
+
+
+def test_generate_accepts_texture_plan_and_empty(tmp_path: Path, chair_plan):
+ from codeverse.texturing.plan import default_plan
+
+ tp = default_plan(chair_plan)
+ ts = generate_textures(tp, tmp_path, FakeImageModel(), size=64, cache_dir=tmp_path / "c")
+ assert set(ts.textures) == set(tp.texture_ids())
+ assert generate_textures({}, tmp_path, FakeImageModel(), size=64, cache_dir=tmp_path / "c").textures == {}
diff --git a/harness/tests/texturing/test_live.py b/harness/tests/texturing/test_live.py
new file mode 100644
index 00000000..be41bb6c
--- /dev/null
+++ b/harness/tests/texturing/test_live.py
@@ -0,0 +1,44 @@
+"""Live texturing tests (real Gemini calls; need keys). Run: pytest tests/texturing -m live -s"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.config import get_settings
+from codeverse.contracts.plan import StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.models.gemini_image import GeminiImageModel
+from codeverse.texturing.plan import compose_image_prompt, material_plan
+from codeverse.texturing.tile import seam_score
+
+pytestmark = pytest.mark.live
+RUN = Path(__file__).resolve().parents[2] / "runs" / "e2e_chair_blender"
+
+
[email protected](autouse=True)
+def _keys():
+ if not get_settings().gemini_api_keys:
+ pytest.skip("no Gemini keys")
+
+
+def test_gemini_image_model_generates_a_tile(tmp_path: Path):
+ model = GeminiImageModel()
+ images, usage = model.generate_with_usage(compose_image_prompt("oiled walnut wood grain, warm brown", "wood"), size=1024, seed=1)
+ assert len(images) == 1 and images[0].size == (1024, 1024)
+ assert usage.cost_usd > 0.01 and usage.output_tokens > 0 and usage.backend == "gemini-image"
+ assert 0.0 <= seam_score(images[0]) <= 1.0
+ images[0].save(tmp_path / "walnut.png")
+
+
+def test_material_plan_live_on_chair(tmp_path: Path):
+ if not (RUN / "plan.json").is_file():
+ pytest.skip("reference run missing")
+ spec = Spec.model_validate_json((RUN / "spec.json").read_text())
+ plan = StaticPlan.model_validate_json((RUN / "plan.json").read_text())
+ sheet = RUN / "artifacts" / "renders" / "r01" / "sheet.png"
+ tp = material_plan(spec, plan, sheet if sheet.is_file() else None, "gemini:gemini-3.7-flash", cache_dir=tmp_path, use_cache=False)
+ assert tp.source == "vlm" and len(tp.parts) == len(plan.parts)
+ assert tp.textured() and all("wood" in p.material_family or p.skip for p in tp.parts)
+ assert 1 <= len(tp.texture_ids()) <= 4 and tp.usage.cost_usd > 0
diff --git a/harness/tests/texturing/test_plan.py b/harness/tests/texturing/test_plan.py
new file mode 100644
index 00000000..e60f850e
--- /dev/null
+++ b/harness/tests/texturing/test_plan.py
@@ -0,0 +1,123 @@
+"""plan.py: default heuristics, planner-output finalisation, one vision call + cache."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+from codeverse.contracts.common import Usage
+from codeverse.texturing.plan import (
+ STYLE_SUFFIX,
+ PlannerOutput,
+ PlannerPart,
+ TexturePlan,
+ compose_image_prompt,
+ default_plan,
+ family_from_text,
+ finalize_plan,
+ material_plan,
+ plan_table,
+)
+
+
+def test_family_keywords_are_whole_words():
+ assert family_from_text("satin oiled walnut") == "wood"
+ assert family_from_text("brushed stainless steel") == "metal"
+ assert family_from_text("grey-blue linen upholstery") == "fabric"
+ assert family_from_text("oiled") == "other" # 'led' must not match
+
+
+def test_default_plan_shares_ids_and_skips(chair_plan):
+ tp = default_plan(chair_plan)
+ by = tp.by_part()
+ assert by["seat"].texture_id == by["back"].texture_id # same material → same texture
+ assert by["seat"].material_family == "wood" and by["leg"].material_family == "metal"
+ assert by["leg"].metallic == 1.0 and by["leg"].roughness < 0.5
+ assert by["knob"].skip # tiny + glass
+ assert len(tp.texture_ids()) == 2
+ assert tp.source == "default"
+ assert STYLE_SUFFIX in by["seat"].prompt and "oak" in by["seat"].prompt
+ assert "Seat" in plan_table(tp)
+
+
+def test_finalize_plan_defaults_and_unification(chair_plan):
+ out = PlannerOutput(parts=[
+ PlannerPart(part="Seat", texture_id="oak", material_family="wood", subject="light oak, straight grain"),
+ PlannerPart(part="back", texture_id="oak", material_family="fabric", subject="something else", roughness=0.9),
+ PlannerPart(part="Ghost", texture_id="x", material_family="wood", subject="unknown part is dropped"),
+ # Leg omitted → defaulted from the plan material (brushed steel → metal)
+ ])
+ tp = finalize_plan(out, chair_plan, model_id="m")
+ by = tp.by_part()
+ assert set(by) == {"seat", "back", "leg", "knob"}
+ assert by["back"].prompt == by["seat"].prompt and by["back"].material_family == "wood" # shared id → first wins
+ assert by["back"].roughness == 0.9 # per-part factor kept
+ assert by["leg"].material_family == "metal" and not by["leg"].skip
+ assert by["knob"].skip
+ assert by["seat"].tile_size_m == 0.35 # wood default
+
+
+def test_compose_prompt():
+ p = compose_image_prompt(" red brick wall. ", "stone")
+ assert p.startswith("red brick wall, stone surface") and p.endswith("1:1 square")
+
+
+class _FakeChat:
+ provider = "fake"
+ model = "fake"
+
+ def __init__(self, payload: dict):
+ self.payload = payload
+ self.calls: list[ChatRequest] = []
+
+ @property
+ def id(self):
+ return "fake:fake"
+
+ def supports_vision(self):
+ return True
+
+ def generate(self, req: ChatRequest) -> ChatResponse:
+ self.calls.append(req)
+ return ChatResponse(text=json.dumps(self.payload), parsed=self.payload, usage=Usage(cost_usd=0.002, input_tokens=100))
+
+
+def test_material_plan_one_call_with_sheet_and_cache(tmp_path: Path, chair_plan, chair_spec):
+ sheet = tmp_path / "sheet.png"
+ Image.new("RGB", (32, 32), (1, 2, 3)).save(sheet)
+ payload = {"parts": [
+ {"part": "Seat", "texture_id": "oak_wood", "material_family": "wood", "subject": "light oak", "projection": "planar_y", "tile_size_m": 0.4},
+ {"part": "Back", "texture_id": "oak_wood", "material_family": "wood", "subject": "light oak", "projection": "box"},
+ {"part": "Leg", "texture_id": "steel", "material_family": "metal", "subject": "brushed steel", "projection": "cylinder", "metallic": 1, "roughness": 0.3},
+ {"part": "Knob", "texture_id": "glass", "material_family": "glass", "skip": True, "reason": "glass"},
+ ], "notes": "two materials"}
+ chat = _FakeChat(payload)
+ tp = material_plan(chair_spec, chair_plan, sheet, "fake:fake", model=chat, cache_dir=tmp_path / "cache")
+ assert isinstance(tp, TexturePlan) and tp.source == "vlm" and tp.usage.cost_usd == pytest.approx(0.002)
+ assert len(chat.calls) == 1
+ req = chat.calls[0]
+ assert req.response_schema is not None and any(p.type == "image" for p in req.messages[0].parts)
+ assert "Seat" in req.messages[0].text and chair_spec.prompt in req.messages[0].text
+ assert tp.by_part()["seat"].projection == "planar_y" and tp.by_part()["seat"].tile_size_m == 0.4
+ assert tp.texture_ids() == ["oak_wood", "steel"]
+ # cache hit: no second call
+ tp2 = material_plan(chair_spec, chair_plan, sheet, "fake:fake", model=chat, cache_dir=tmp_path / "cache")
+ assert tp2.source == "cache" and len(chat.calls) == 1 and tp2.texture_ids() == tp.texture_ids()
+ # different sheet → new key → new call
+ Image.new("RGB", (32, 32), (9, 9, 9)).save(sheet)
+ material_plan(chair_spec, chair_plan, sheet, "fake:fake", model=chat, cache_dir=tmp_path / "cache")
+ assert len(chat.calls) == 2
+
+
+def test_material_plan_invalid_payload_fails_loud(tmp_path, chair_plan, chair_spec):
+ chat = _FakeChat({"nope": 1})
+ with pytest.raises(ValueError):
+ material_plan(chair_spec, chair_plan, None, "fake:fake", model=chat, cache_dir=tmp_path, use_cache=False)
+
+
+def test_material_plan_without_model_is_default(chair_plan, chair_spec):
+ assert material_plan(chair_spec, chair_plan, None, "").source == "default"
diff --git a/harness/tests/texturing/test_run.py b/harness/tests/texturing/test_run.py
new file mode 100644
index 00000000..c041c682
--- /dev/null
+++ b/harness/tests/texturing/test_run.py
@@ -0,0 +1,68 @@
+"""run.py: the whole pass offline (fake image model, fake render, fake judge)."""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+from codeverse.contracts.run import RunRecord
+from codeverse.texturing.generate import FakeImageModel
+from codeverse.texturing.run import TextureReport, latest_sheet, load_report, texture_pass
+from codeverse.workspace import Workspace
+from tests.texturing.conftest import FakeJudge, fake_render
+
+
+def _ws(tmp_path: Path, chair_glb: Path, chair_spec, chair_plan) -> Workspace:
+ ws = Workspace(tmp_path / "run").create()
+ ws.write_json(ws.spec_path, chair_spec)
+ ws.write_json(ws.plan_path, chair_plan)
+ shutil.copy(chair_glb, ws.artifacts / "object.glb")
+ rec = RunRecord(spec=chair_spec, plan=chair_plan, workspace=str(ws.root))
+ ws.write_json(ws.record_path, rec)
+ return ws
+
+
+def test_texture_pass_ships_and_records(tmp_path, chair_glb, chair_spec, chair_plan):
+ ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
+ judge = FakeJudge([(0.70, {"materials": 0.6, "intent_fidelity": 0.8}), (0.73, {"materials": 0.75, "intent_fidelity": 0.8})])
+ img = FakeImageModel(usd_per_image=0.05)
+ rep = texture_pass(ws, chair_spec, chair_plan, model_id="", image_model=img, judge=judge, render=fake_render,
+ cache_dir=tmp_path / "cache")
+ assert isinstance(rep, TextureReport) and rep.shipped and rep.delta == 0.03
+ assert rep.plan.source == "default" and len(rep.textures.paths()) == 2
+ assert (ws.artifacts / "object_textured.glb").is_file() and (ws.artifacts / "object.glb").read_bytes() == chair_glb.read_bytes()
+ assert (ws.artifacts / "textures" / "texturing.json").is_file() and (ws.artifacts / "textures" / "texture_plan.json").is_file()
+ assert rep.usage.cost_usd > 0.1 # 2 images + 2 judge calls
+ rec = json.loads(ws.record_path.read_text())
+ tx = rec["extra"]["texturing"]
+ assert tx["shipped"] is True and tx["glb_textured"] == "artifacts/object_textured.glb" and len(tx["textures"]) == 2
+ assert tx["texture_plan"]["Seat"] == tx["texture_plan"]["Back"]
+ # events were emitted
+ events = [json.loads(line)["event"] for line in ws.events_path.read_text().splitlines()]
+ assert events[0] == "texture.start" and "texture.gate" in events and events[-1] == "texture.done"
+ # report reloads
+ assert load_report(ws).shipped
+ # planner quick render was written because there was no sheet
+ assert latest_sheet(ws) is None and (ws.artifacts / "textures" / "planner_views" / "sheet.png").is_file()
+
+
+def test_texture_pass_not_shipped_keeps_report(tmp_path, chair_glb, chair_spec, chair_plan):
+ ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
+ judge = FakeJudge([(0.70, {"materials": 0.6}), (0.60, {"materials": 0.6})])
+ rep = texture_pass(ws, chair_spec, chair_plan, model_id="", image_model=FakeImageModel(), judge=judge, render=fake_render,
+ cache_dir=tmp_path / "cache")
+ assert not rep.shipped and rep.gate is not None and rep.glb_out.endswith("object_textured.glb")
+ assert json.loads(ws.record_path.read_text())["extra"]["texturing"]["shipped"] is False
+
+
+def test_texture_pass_no_judge_and_all_failed(tmp_path, chair_glb, chair_spec, chair_plan):
+ ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
+ rep = texture_pass(ws, chair_spec, chair_plan, model_id="", image_model=FakeImageModel(), judge=False, render=fake_render,
+ cache_dir=tmp_path / "cache")
+ assert rep.shipped and rep.gate is None and any("skipped" in n for n in rep.notes)
+ # every image fails → nothing applied, not shipped, no crash
+ ws2 = _ws(tmp_path / "b", chair_glb, chair_spec, chair_plan)
+ rep2 = texture_pass(ws2, chair_spec, chair_plan, model_id="", image_model=FakeImageModel(fail_on=("seamless",)), judge=False,
+ render=fake_render, cache_dir=tmp_path / "cache2")
+ assert not rep2.shipped and rep2.apply is None and rep2.glb_out == "" and rep2.textures.failed()
diff --git a/harness/tests/texturing/test_scene_pack.py b/harness/tests/texturing/test_scene_pack.py
new file mode 100644
index 00000000..f3c1c051
--- /dev/null
+++ b/harness/tests/texturing/test_scene_pack.py
@@ -0,0 +1,71 @@
+"""scene_pack.py: heuristic + VLM pack plans, generation, manifest, prompt snippet."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
+from codeverse.texturing.generate import FakeImageModel
+from codeverse.texturing.scene_pack import (
+ default_scene_pack_plan,
+ load_manifest,
+ scene_pack_plan,
+ scene_texture_pack,
+ texture_pack_prompt,
+)
+from tests.texturing.test_plan import _FakeChat
+
+
+def garden_plan() -> ScenePlan:
+ bb = BBox(center=(0, 0, 0), extents=(30, 10, 30))
+ return ScenePlan(
+ title="Zen Garden", summary="a small Kyoto garden", setting="Kyoto, autumn dusk", mood="calm",
+ bounds=bb, environment="mossy banks, a koi pond, raked gravel court",
+ zones=[ZonePlan(name="Pond", description="koi pond with stepping stones", bbox=bb, contents=["Bridge"]),
+ ZonePlan(name="GravelCourt", description="raked gravel karesansui with granite rocks", bbox=bb)],
+ assets=[AssetPlan(name="Bridge", kind="blender_glb", description="red lacquered wooden arched bridge", approx_size_m=(4, 2, 1))],
+ cameras=[CameraPlan(name="main", position=(10, 3, 10), look_at=(0, 0, 0))],
+ )
+
+
+def test_default_pack_plan_picks_keywords(garden_plan):
+ entries = default_scene_pack_plan(garden_plan, n_min=6, n_max=12)
+ names = [e.name for e in entries]
+ assert "moss_ground" in names and "fine_gravel" in names and "pond_bed" in names and "weathered_planks" in names
+ assert 6 <= len(entries) <= 12 and len(set(names)) == len(names)
+ assert all(e.prompt.endswith("1:1 square") and e.tile_size_m > 0 for e in entries)
+
+
+def test_scene_pack_plan_with_model_and_cap(garden_plan):
+ payload = {"textures": [
+ {"name": "Moss Ground", "material_family": "other", "subject": "green moss carpet", "tile_size_m": 1.2, "role": "ground"},
+ {"name": "moss_ground", "material_family": "other", "subject": "dup", "tile_size_m": 1.0, "role": "ground"},
+ {"name": "granite_gravel", "material_family": "stone", "subject": "fine grey gravel", "tile_size_m": 0.8, "role": "ground"},
+ ], "notes": "n"}
+ chat = _FakeChat(payload)
+ entries, notes, usage = scene_pack_plan(garden_plan, "fake:fake", model=chat, n_max=2)
+ assert [e.name for e in entries] == ["moss_ground", "granite_gravel"] and notes == "n" and usage.cost_usd > 0
+ assert entries[0].tile_size_m == 1.2 and "green moss carpet, matte natural surface" in entries[0].prompt
+ assert "Zen Garden" in chat.calls[0].messages[0].text and "GravelCourt" in chat.calls[0].messages[0].text
+ with pytest.raises(ValueError):
+ scene_pack_plan(garden_plan, "fake:fake", model=_FakeChat({"textures": []}))
+
+
+def test_scene_texture_pack_writes_manifest_and_prompt(tmp_path: Path, garden_plan):
+ model = FakeImageModel()
+ out = tmp_path / "public" / "textures"
+ pack = scene_texture_pack(garden_plan, out, model, "", size=64, cache_dir=tmp_path / "c", n_min=4, n_max=6)
+ man = load_manifest(out)
+ assert pack.source == "default" and 4 <= len(man) <= 6 and Path(pack.manifest_path).name == "manifest.json"
+ for name, e in man.items():
+ assert (out / e["file"]).is_file() and e["file"] == f"{name}.png" and e["tile_size_m"] > 0 and "family" in e
+ assert json.loads(Path(pack.manifest_path).read_text()) == man
+ snippet = texture_pack_prompt(man)
+ assert "/public/textures/" in snippet and "RepeatWrapping" in snippet and "SRGBColorSpace" in snippet
+ assert "loaders.texture.load" in snippet and "tile =" in snippet
+ assert texture_pack_prompt({}) == ""
+ assert "/textures/x" in texture_pack_prompt({"a": {"file": "a.png", "tile_size_m": 1}}, url_prefix="/textures/x")
diff --git a/harness/tests/texturing/test_tile.py b/harness/tests/texturing/test_tile.py
new file mode 100644
index 00000000..9ea05e5c
--- /dev/null
+++ b/harness/tests/texturing/test_tile.py
@@ -0,0 +1,56 @@
+"""tile.py: seam score, mirror-blend tileability, sizing."""
+
+from __future__ import annotations
+
+import numpy as np
+from PIL import Image
+
+from codeverse.texturing.generate import procedural_texture
+from codeverse.texturing.tile import (
+ SEAM_MAX,
+ fit_size,
+ make_tileable,
+ offset_check,
+ save_texture,
+ seam_score,
+ tile_preview,
+)
+
+
+def _tileable(size: int = 64) -> Image.Image:
+ y, x = np.mgrid[0:size, 0:size] / size
+ a = 0.5 + 0.4 * np.sin(2 * np.pi * 3 * x) * np.cos(2 * np.pi * 2 * y)
+ return Image.fromarray((np.stack([a, a, a], 2) * 255).astype(np.uint8), "RGB")
+
+
+def test_seam_score_tileable_is_low_and_gradient_is_high():
+ assert seam_score(_tileable()) < 0.02
+ bad = procedural_texture("x", size=64) # carries a horizontal gradient → seam
+ assert seam_score(bad) > seam_score(_tileable())
+
+
+def test_make_tileable_makes_wrap_edges_equal_and_lowers_score():
+ bad = procedural_texture("wood", size=128)
+ before = seam_score(bad)
+ fixed = make_tileable(bad, 0.12)
+ after = seam_score(fixed)
+ assert after < before and after <= SEAM_MAX
+ a = np.asarray(fixed).astype(int)
+ assert np.abs(a[:, 0, :] - a[:, -1, :]).mean() < 2.0 # wrap-exact horizontally
+ assert np.abs(a[0, :, :] - a[-1, :, :]).mean() < 2.0
+ # centre untouched
+ b = np.asarray(bad).astype(int)
+ assert np.array_equal(a[40:88, 40:88], b[40:88, 40:88])
+
+
+def test_fit_size_save_and_helpers(tmp_path):
+ img = Image.new("RGB", (300, 200), (10, 20, 30))
+ sq = fit_size(img, 128)
+ assert sq.size == (128, 128)
+ assert fit_size(Image.new("RGB", (64, 64)), 128).size == (64, 64) # never upscales
+ p = save_texture(sq, tmp_path / "t.jpg")
+ assert p.is_file() and Image.open(p).format == "JPEG"
+ p2 = save_texture(sq, tmp_path / "t.png")
+ assert Image.open(p2).format == "PNG"
+ assert offset_check(sq).size == sq.size
+ assert tile_preview(sq, reps=2, size=64).size == (64, 64)
diff --git a/harness/tests/texturing/test_tools_cli.py b/harness/tests/texturing/test_tools_cli.py
new file mode 100644
index 00000000..232bd9a3
--- /dev/null
+++ b/harness/tests/texturing/test_tools_cli.py
@@ -0,0 +1,68 @@
+"""texture tools (registry) + `3dcv texture` CLI, offline."""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+from typer.testing import CliRunner
+
+from codeverse.spatial.registry import ToolContext, get_tool, list_tools
+from codeverse.texturing.generate import FakeImageModel
+from codeverse.workspace import Workspace
+from tests.texturing.conftest import FakeJudge, fake_render
+
+
+def _ws(tmp_path: Path, chair_glb, chair_spec, chair_plan) -> Workspace:
+ ws = Workspace(tmp_path / "run").create()
+ ws.write_json(ws.spec_path, chair_spec)
+ ws.write_json(ws.plan_path, chair_plan)
+ shutil.copy(chair_glb, ws.artifacts / "object.glb")
+ return ws
+
+
+def test_tools_registered_for_object_tracks():
+ names = {t.name for t in list_tools(track="static_object")}
+ assert {"texture_pass", "texture_preview"} <= names
+ assert "texture_pass" not in {t.name for t in list_tools(track="scene")}
+ card = get_tool("texture_pass").card()
+ assert "judge" in card and "texture_pass" in card
+
+
+def test_texture_pass_tool_runs_with_injected_fakes(tmp_path, chair_glb, chair_spec, chair_plan):
+ ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
+ judge = FakeJudge([(0.7, {"materials": 0.5}), (0.72, {"materials": 0.7})])
+ ctx = ToolContext(workspace=ws, track="static_object", language="blender",
+ extra={"image_model": FakeImageModel(), "judge": judge, "render": fake_render, "cache_dir": tmp_path / "c"})
+ obs = get_tool("texture_pass").call(ctx, {"model": ""})
+ assert obs.ok, obs.text
+ assert "SHIPPED" in obs.text and obs.numbers["shipped"] is True and obs.images
+ assert (ws.artifacts / "object_textured.glb").is_file()
+ # preview tool: cached_render_glb needs the real renderer; with a fake we only check the usage error path
+ obs2 = get_tool("texture_preview").call(ToolContext(workspace=Workspace(tmp_path / "empty").create()), {})
+ assert not obs2.ok and "texture_pass" in obs2.text
+
+
+def test_texture_pass_tool_without_glb_is_usage_error(tmp_path, chair_spec, chair_plan):
+ ws = Workspace(tmp_path / "run").create()
+ ws.write_json(ws.spec_path, chair_spec)
+ ws.write_json(ws.plan_path, chair_plan)
+ obs = get_tool("texture_pass").call(ToolContext(workspace=ws), {})
+ assert not obs.ok and "build" in obs.text
+
+
+def test_cli_texture_show_and_help(tmp_path, chair_glb, chair_spec, chair_plan):
+ from codeverse.cli.main import app
+ from codeverse.texturing.run import texture_pass
+
+ ws = _ws(tmp_path, chair_glb, chair_spec, chair_plan)
+ texture_pass(ws, chair_spec, chair_plan, model_id="", image_model=FakeImageModel(), judge=False, render=fake_render,
+ cache_dir=tmp_path / "c")
+ runner = CliRunner()
+ res = runner.invoke(app, ["texture", "show", str(ws.root)])
+ assert res.exit_code == 0, res.output
+ assert "texture pass" in res.output and "wood_oiled_oak" in res.output
+ res = runner.invoke(app, ["texture", "--help"])
+ assert res.exit_code == 0 and "scene-pack" in res.output and "pass" in res.output
+ res = runner.invoke(app, ["texture", "show", str(tmp_path / "nowhere")])
+ assert res.exit_code != 0
diff --git a/harness/tests/texturing/test_uv.py b/harness/tests/texturing/test_uv.py
new file mode 100644
index 00000000..feaedb5a
--- /dev/null
+++ b/harness/tests/texturing/test_uv.py
@@ -0,0 +1,68 @@
+"""uv.py: projections, world-scale texel density, seam splitting."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import trimesh
+
+from codeverse.texturing.uv import choose_projection, split_by_key, unwrap
+
+
+def test_choose_projection_rules():
+ assert choose_projection(np.array([0.04, 0.45, 0.04]), "auto") == ("cylinder", 1)
+ assert choose_projection(np.array([0.44, 0.03, 0.42]), "auto")[0] == "box" # slab
+ assert choose_projection(np.array([0.44, 0.03, 0.08]), "auto")[0] == "box" # elongated slab, not round
+ assert choose_projection(np.array([1, 1, 1]), "planar_y") == ("planar_y", 1)
+ assert choose_projection(np.array([1, 1, 1]), "planar_z") == ("planar_z", 2)
+ assert choose_projection(np.array([0.1, 2.0, 0.1]), "cylinder") == ("cylinder", 1)
+
+
+def test_box_projection_world_scale_and_splits():
+ m = trimesh.creation.box(extents=(0.6, 0.3, 0.3))
+ uw = unwrap(m.vertices, m.faces, np.eye(4), projection="box", tile_size_m=0.3)
+ assert uw.projection == "box"
+ assert len(uw.faces) == len(m.faces)
+ # every box vertex touches 3 axis-groups → 8 vertices × 3 keys = 24
+ assert len(uw.vertices) == 24 and uw.n_split == 16
+ # the 0.6 m faces span 2 tiles along u, 0.3 m span 1 tile
+ spans = []
+ for f in uw.faces:
+ uv = uw.uv[f]
+ spans.append(uv.max(0) - uv.min(0))
+ assert max(s.max() for s in spans) == pytest.approx(2.0, abs=1e-6)
+ # scaling the world transform ×2 doubles the UV range (texel density is world-space)
+ T = np.diag([2.0, 2.0, 2.0, 1.0])
+ uw2 = unwrap(m.vertices, m.faces, T, projection="box", tile_size_m=0.3)
+ assert (uw2.uv.max(0) - uw2.uv.min(0)) == pytest.approx(2 * (uw.uv.max(0) - uw.uv.min(0)), abs=1e-6)
+
+
+def test_cylinder_projection_seam_and_caps():
+ m = trimesh.creation.cylinder(radius=0.05, height=0.5, sections=32) # along z
+ uw = unwrap(m.vertices, m.faces, np.eye(4), projection="auto", tile_size_m=0.1)
+ assert uw.projection == "cylinder" and uw.axis == 2
+ assert uw.n_split > 0 # seam + caps split
+ # side faces: u spread per face must be small (no face stretched across the seam)
+ for f in uw.faces:
+ uv = uw.uv[f]
+ assert (uv[:, 0].max() - uv[:, 0].min()) < 1.0
+ # v covers height / tile = 5 tiles
+ assert (uw.uv[:, 1].max() - uw.uv[:, 1].min()) >= 5.0 - 1e-6
+
+
+def test_split_by_key_preserves_geometry_and_normals():
+ m = trimesh.creation.box()
+ normals = np.asarray(m.vertex_normals)
+ uv_c = np.zeros((len(m.faces), 3, 2))
+ key = np.zeros((len(m.faces), 3), dtype=int)
+ v, f, n, uv, n_split = split_by_key(m.vertices, m.faces, normals, uv_c, key)
+ assert n_split == 0 and len(v) == len(m.vertices) and np.allclose(n, normals)
+ assert np.allclose(v[f], m.vertices[m.faces])
+
+
+def test_unwrap_rejects_bad_input():
+ with pytest.raises(ValueError):
+ unwrap(np.zeros((3, 3)), np.zeros((0, 3), dtype=int), np.eye(4))
+ m = trimesh.creation.box()
+ with pytest.raises(ValueError):
+ unwrap(m.vertices, m.faces, np.eye(4), tile_size_m=0.0)
diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.py
index 76c006ae..628d81d5 100644
--- a/harness/tests/threejs_render/test_build.py
+++ b/harness/tests/threejs_render/test_build.py
@@ -26,7 +26,8 @@ def test_build_stool_glb_and_census(stool_ws: Workspace):
assert [p["name"] for p in c["parts"]] == ["Seat", "Legs", "Stretchers"]
assert c["tri_count"] > 500 and c["n_meshes"] == 9
assert c["tick_present"] is True
- assert c["normalised_offset"] is None
+ assert c["normalised_offset"] is None and c["placement_offset"] is None
+ assert c["instanced_meshes_baked"] == 0 and c["selfcheck_ran"] is False
assert c["unnamed_meshes"] == 0
assert "Leg_LB" in c["parts"][1]["children"]
assert len(c["materials"]) == 3 # seat + legs + stretchers (distinct objects)
@@ -72,16 +73,109 @@ def test_build_missing_build_export(stool_ws: Workspace):
assert not res.ok and res.error_type == "ContractError" and "export function build" in res.error_message
-def test_build_normalises_and_records_offset(stool_ws: Workspace):
+def test_build_keeps_source_placement_and_warns(stool_ws: Workspace):
+ """An off-ground / off-centre object is exported AS AUTHORED (no silent re-centring):
+ the census records the offset it would need and the warning says so."""
p = stool_ws.src / "object.js"
p.write_text(p.read_text().replace("return root;", "root.position.set(0.5, 0.2, 0); return root;"))
res = ThreeJsRuntime().build(stool_ws)
assert res.ok
- off = res.census["normalised_offset"]
+ assert res.census["normalised_offset"] is None
+ off = res.census["placement_offset"]
assert off is not None and abs(off[0] + 0.5) < 1e-4 and abs(off[1] + 0.2) < 1e-4
- assert any("off ground/centre" in w for w in res.census["warnings"])
+ assert any("off ground/centre" in w and "exported as authored" in w for w in res.census["warnings"])
lo, _ = trimesh.load(res.glb_path, force="scene").bounds
- assert abs(lo[1]) < 2e-3 and abs(lo[0] + 0.17) < 2e-3
+ assert abs(lo[1] - 0.2) < 2e-3 and abs(lo[0] - 0.33) < 2e-3
+
+
+def test_build_per_plan_placement_passes_contract_even_when_union_is_off_centre(stool_ws: Workspace):
+ """Plan parts whose union footprint is NOT centred (backrest-style skew): an object
+ built exactly per plan must not be reported as 'centre off' for every part."""
+ from codeverse.contracts.plan import StaticPlan
+ from codeverse.spatial.contract import check_contract
+ from codeverse.spatial.measure import measure_glb
+
+ (stool_ws.src / "object.js").write_text(
+ "import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name = 'Sign';\n"
+ " const base = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.35, 0.3), new THREE.MeshStandardMaterial({color: 0x888888}));\n"
+ " base.name = 'Base'; base.position.set(0, 0.175, 0); g.add(base);\n"
+ " const panel = new THREE.Mesh(new THREE.BoxGeometry(0.5, 0.1, 0.3), new THREE.MeshStandardMaterial({color: 0x884422}));\n"
+ " panel.name = 'Panel'; panel.position.set(0, 0.4, 0.2); g.add(panel); return g; }\n")
+ plan = StaticPlan(
+ object_name="Sign", summary="x", overall_bbox={"center": [0, 0.225, 0.1], "extents": [0.5, 0.45, 0.5]},
+ parts=[{"name": "Base", "role": "r", "description": "d", "bbox": {"center": [0, 0.175, 0], "extents": [0.4, 0.35, 0.3]}},
+ {"name": "Panel", "role": "r", "description": "d", "bbox": {"center": [0, 0.4, 0.2], "extents": [0.5, 0.1, 0.3]}}])
+ res = ThreeJsRuntime().build(stool_ws)
+ assert res.ok and res.census["placement_offset"] == [0, 0, -0.1]
+ rep = check_contract(measure_glb(res.glb_path), plan, language="threejs")
+ assert rep.passed, [f.message for f in rep.findings]
+ assert not [f for f in rep.findings if f.target in ("Base", "Panel")]
+ assert [f.message for f in rep.findings if "footprint" in f.message] # the offset is still reported, once, as WARN
+
+
+def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace):
+ """InstancedMesh must not export as EXT_mesh_gpu_instancing (trimesh ignores it):
+ measure/connectivity must see every instance exactly like the census does."""
+ from codeverse.spatial.connectivity import check_connectivity
+ from codeverse.spatial.measure import measure_glb
+
+ (stool_ws.src / "object.js").write_text(
+ "import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name = 'Fence';\n"
+ " const mat = new THREE.MeshStandardMaterial({ color: 0x885533 });\n"
+ " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05), mat, 10); posts.name = 'Posts';\n"
+ " const m = new THREE.Matrix4();\n"
+ " for (let i = 0; i < 10; i++) { m.makeTranslation(-2.25 + i * 0.5, 0.5, 0); posts.setMatrixAt(i, m); posts.setColorAt(i, new THREE.Color(i % 2 ? 0xff0000 : 0x00ff00)); }\n"
+ " posts.instanceMatrix.needsUpdate = true; g.add(posts);\n"
+ " const rail = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.05, 0.03), mat); rail.name = 'Rail'; rail.position.set(0, 1.025, 0); g.add(rail);\n"
+ " return g; }\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert res.ok, res.error_message
+ census = res.census
+ assert census["instanced_meshes_baked"] == 1 and census["tri_count"] == 132 and census["n_meshes"] == 11
+ assert [p["name"] for p in census["parts"]] == ["Posts", "Rail"]
+ assert "Posts_0" in census["parts"][0]["children"] and "Posts_9" in census["parts"][0]["children"]
+ raw = Path(res.glb_path).read_bytes()
+ header = json.loads(raw[20:20 + int.from_bytes(raw[12:16], "little")])
+ assert "EXT_mesh_gpu_instancing" not in (header.get("extensionsUsed") or [])
+ m = measure_glb(res.glb_path)
+ assert m.tri_count == census["tri_count"] and abs(m.ground_gap_m) < 1e-3
+ posts = next(p for p in m.parts if p.name == "Posts")
+ assert np.allclose(posts.bbox_min, census["parts"][0]["bbox_min"], atol=1e-3)
+ assert np.allclose(posts.bbox_max, census["parts"][0]["bbox_max"], atol=1e-3)
+ assert posts.tri_count == 120
+ assert len(census["materials"]) == 3 # base + two instance colours
+ assert check_connectivity(res.glb_path).passed
+
+
+def test_build_nan_geometry_names_mesh_part_and_file(stool_ws: Workspace):
+ """A NaN geometry error must name the mesh + part and route to src/parts/<snake>.js."""
+ (stool_ws.src / "parts" / "legs.js").write_text(
+ "import * as THREE from 'three';\nexport function buildLegs(T) { const g = new THREE.Group(); g.name = 'Legs';\n"
+ " const m = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0/0, 12), new THREE.MeshStandardMaterial());\n"
+ " m.name = 'LegMesh'; g.add(m); return g; }\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert not res.ok and res.error_type == "ContractError"
+ assert "'LegMesh'" in res.error_message and "part 'Legs'" in res.error_message and "NaN" in res.error_message
+ assert res.error_file == "src/parts/legs.js"
+ assert res.census["part"] == "Legs"
+ rec = json.loads((stool_ws.artifacts / "export_error.json").read_text())
+ assert rec["error"]["part"] == "Legs"
+
+
+def test_build_runs_exported_selfcheck(stool_ws: Workspace):
+ """`export function selfcheck(THREE, root)` is called by the harness: a throw fails
+ the build with the agent's message and the src frame; a passing one is recorded."""
+ p = stool_ws.src / "object.js"
+ src = p.read_text()
+ p.write_text(src + "export function selfcheck(THREE_, root) {\n const box = new THREE.Box3().setFromObject(root);\n"
+ " if (box.max.y < 1.0) throw new Error(`too short: ${box.max.y.toFixed(2)}`);\n}\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert not res.ok and res.error_type == "SelfCheckError"
+ assert res.error_message.startswith("selfcheck(THREE, root) threw: too short: 0.45")
+ assert res.error_file == "src/object.js" and res.error_line == 13
+ p.write_text(src + "export function selfcheck(THREE_, root) { return true; }\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert res.ok and res.census["selfcheck_ran"] is True
def test_build_async_build_and_texture_strip(stool_ws: Workspace):
diff --git a/harness/tests/threejs_render/test_error_routing.py b/harness/tests/threejs_render/test_error_routing.py
new file mode 100644
index 00000000..4c95a487
--- /dev/null
+++ b/harness/tests/threejs_render/test_error_routing.py
@@ -0,0 +1,30 @@
+"""ThreeJsRuntime error-record → BuildResult routing (pure python: no node needed)."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.languages.threejs.runtime import ThreeJsRuntime
+from codeverse.spatial.node import NodeResult
+from codeverse.workspace import Workspace
+
+
+def _res(error: dict) -> NodeResult:
+ return NodeResult(rc=1, stdout="", stderr="", last_json={"ok": False, "error": error}, duration_ms=1)
+
+
+def test_contract_error_part_routes_to_part_file(tmp_path: Path):
+ ws = Workspace(tmp_path)
+ (ws.src / "parts").mkdir(parents=True)
+ (ws.src / "parts" / "seat_cushion.js").write_text("export function buildSeatCushion(T) {}\n")
+ rt = ThreeJsRuntime()
+ err = {"type": "ContractError", "message": "Mesh 'Top' (in part 'SeatCushion') has NaN/Infinity vertex positions",
+ "file": "", "line": None, "frames": [{"file": "/abs/runtime_js/export_glb.mjs", "line": 9}], "part": "SeatCushion"}
+ out = rt._from_error_record(_res(err), ws)
+ assert out.error_type == "ContractError" and out.error_file == "src/parts/seat_cushion.js" and out.error_line is None
+ assert out.census["part"] == "SeatCushion"
+ # unknown part (no such file) → no guess; a src frame always wins over the part mapping
+ assert rt._from_error_record(_res({**err, "part": "Nope"}), ws).error_file == ""
+ assert rt._from_error_record(_res({**err, "file": "src/object.js", "line": 3}), ws).error_file == "src/object.js"
+ # no frames at all (e.g. module-level failure) keeps the entry-file fallback
+ assert rt._from_error_record(_res({**err, "part": "", "frames": []}), ws).error_file == "src/object.js"
diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.py
index 32bfba2d..2d60e0d6 100644
--- a/harness/tests/threejs_render/test_runtime_js.py
+++ b/harness/tests/threejs_render/test_runtime_js.py
@@ -21,6 +21,12 @@ def test_export_cli_writes_census_and_error_json(stool_ws: Workspace, tmp_path:
census = json.loads((stool_ws.root / "artifacts/c.json").read_text())
assert set(census) >= {"object_name", "parts", "tri_count", "bbox", "materials", "normalised_offset", "warnings", "tick_present"}
assert census["three_revision"] == "182"
+ # --normalise 1 (dataset canonicalisation only; never passed by ThreeJsRuntime) translates the group
+ (stool_ws.src / "object.js").write_text((stool_ws.src / "object.js").read_text().replace("return root;", "root.position.set(0.5, 0.2, 0); return root;"))
+ res = run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--out", "artifacts/n.glb", "--census", "artifacts/n.json", "--normalise", "1"], three_hook=True, timeout_s=60)
+ census = json.loads((stool_ws.root / "artifacts/n.json").read_text())
+ assert census["normalised_offset"] == census["placement_offset"] and abs(census["placement_offset"][0] + 0.5) < 1e-4
+ assert abs(census["bbox"]["min"][1]) < 1e-3 and any("--normalise 1" in w for w in census["warnings"])
# error path: unknown entry
with pytest.raises(NodeError) as ei:
run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--entry", "src/nope.js"], three_hook=True, timeout_s=60)
diff --git a/harness/tests/urdf_joints/conftest.py b/harness/tests/urdf_joints/conftest.py
index 8ffadc20..25df4375 100644
--- a/harness/tests/urdf_joints/conftest.py
+++ b/harness/tests/urdf_joints/conftest.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from pathlib import Path
+import numpy as np
import pytest
import trimesh
@@ -84,3 +85,50 @@ def drawer_plan() -> ArticulatedPlan:
joints=[JointPlan(name="slide", type="prismatic", parent="Carcass", child="Drawer", axis=(0, -1, 0),
pivot=(0, -0.21, 0.45), lower=0.0, upper=0.3, motion="slides out the front")],
)
+
+
+def _panel(lo, hi) -> trimesh.Trimesh:
+ lo, hi = np.asarray(lo, dtype=float), np.asarray(hi, dtype=float)
+ m = trimesh.creation.box(hi - lo)
+ m.apply_translation((lo + hi) / 2)
+ return m
+
+
+def agent_style_mesh(panels: list[tuple[tuple[float, float, float], tuple[float, float, float]]]) -> trimesh.Trimesh:
+ """What agent-built links look like after the wrapper join: touching panels that
+ share vertices (→ the merged mesh is NOT watertight) with inverted winding."""
+ m = trimesh.util.concatenate([_panel(lo, hi) for lo, hi in panels])
+ m.invert()
+ m.merge_vertices()
+ return m
+
+
+def write_carcass_drawer_robot(root: Path, *, drawer_shift_x: float = 0.0) -> tuple[Path, Path]:
+ """Cabinet carcass (5 panels, 30 mm sides) + open-top drawer, both agent-style meshes
+ (world coordinates, like the wrapper writes). ``drawer_shift_x`` slides the drawer
+ sideways: +0.032 drives it 30 mm through the right side panel."""
+ meshes = root / "meshes"
+ meshes.mkdir(parents=True, exist_ok=True)
+ carcass = agent_style_mesh([
+ ((-0.23, -0.18, 0.08), (-0.2, 0.21, 0.58)), ((0.2, -0.18, 0.08), (0.23, 0.21, 0.58)),
+ ((-0.23, -0.21, 0.58), (0.23, 0.21, 0.6)), ((-0.2, -0.18, 0.08), (0.2, 0.2, 0.092)),
+ ((-0.2, 0.2, 0.08), (0.2, 0.21, 0.58)),
+ ])
+ drawer = agent_style_mesh([
+ ((-0.198, -0.19, 0.445), (0.198, -0.172, 0.565)), ((-0.18, -0.17, 0.445), (0.18, 0.15, 0.455)),
+ ((-0.18, -0.17, 0.455), (-0.17, 0.15, 0.555)), ((0.17, -0.17, 0.455), (0.18, 0.15, 0.555)),
+ ((-0.17, 0.14, 0.455), (0.17, 0.15, 0.555)),
+ ])
+ assert not carcass.is_watertight and carcass.volume < 0 and not drawer.is_watertight and drawer.volume < 0
+ (meshes / "Carcass.glb").write_bytes(carcass.export(file_type="glb"))
+ (meshes / "Drawer.glb").write_bytes(drawer.export(file_type="glb"))
+ # drawer link frame at its front-bottom centre (world 0 -0.19 0.445); visual origin = -frame (+ shift)
+ urdf = root / "robot.urdf"
+ urdf.write_text(f"""<robot name="cabinet">
+<link name="Carcass"><visual><origin xyz="0 0 0"/><geometry><mesh filename="meshes/Carcass.glb"/></geometry></visual></link>
+<link name="Drawer"><visual><origin xyz="{drawer_shift_x} 0.19 -0.445"/><geometry><mesh filename="meshes/Drawer.glb"/></geometry></visual></link>
+<joint name="slide" type="prismatic"><parent link="Carcass"/><child link="Drawer"/>
+ <origin xyz="0 -0.19 0.445"/><axis xyz="0 -1 0"/><limit lower="0" upper="0.3" effort="10" velocity="1"/></joint>
+</robot>
+""")
+ return urdf, meshes
diff --git a/harness/tests/urdf_joints/test_export.py b/harness/tests/urdf_joints/test_export.py
index b0f0b20b..3655879e 100644
--- a/harness/tests/urdf_joints/test_export.py
+++ b/harness/tests/urdf_joints/test_export.py
@@ -5,11 +5,18 @@ from __future__ import annotations
import json
import struct
+import pytest
import trimesh
from PIL import Image
from codeverse.contracts.artifacts import RenderSet, RenderView
-from codeverse.spatial.joints import ARTICULATION_SHEET_NAME, load_urdf, render_poses, urdf_to_glb
+from codeverse.spatial.joints import (
+ ARTICULATION_SHEET_NAME,
+ UrdfError,
+ load_urdf,
+ render_poses,
+ urdf_to_glb,
+)
from codeverse.spatial.joints_export import make_sheet
from tests.urdf_joints.conftest import write_mesh_robot
@@ -111,3 +118,32 @@ def test_joint_sweep_observation_offline(tmp_path):
write_mesh_robot(ws.artifacts)
obs = joint_sweep_observation(ws, render=False, joint="hinge", expected_direction="front")
assert obs.ok and obs.numbers["max_penetration_m"] == 0.0 and obs.numbers["motion_check"]["ok"]
+
+
+def test_robot_named_like_a_link_keeps_frame_and_placement(tmp_path):
+ """``<robot name="body">`` with a root link ``body``: scene-graph node names must be
+ unique, so the root node gets a ``__root`` suffix instead of aliasing the link node
+ (which silently dropped the Z-up→Y-up rotation and the door's joint placement)."""
+ from codeverse.spatial.measure import measure_glb
+
+ urdf, meshes = write_mesh_robot(tmp_path)
+ urdf.write_text(urdf.read_text().replace('<robot name="cab">', '<robot name="body">'))
+ r = load_urdf(urdf, meshes)
+ glb = urdf_to_glb(r, tmp_path / "object.glb")
+ js = _gltf_json(glb)
+ names = [n["name"] for n in js["nodes"]]
+ assert names.count("body") == 1 and "body__root" in names
+ m = measure_glb(glb)
+ rows = {p.name: p for p in m.parts}
+ assert set(rows) == {"body", "door"} and m.ground_gap_m == pytest.approx(0.0, abs=1e-6)
+ assert rows["body"].bbox_max[1] == pytest.approx(0.8, abs=1e-6) # Y-up: height along y
+ assert rows["door"].bbox_min[0] == pytest.approx(-0.29, abs=1e-6) and rows["door"].bbox_max[0] == pytest.approx(0.29, abs=1e-6)
+ assert rows["door"].bbox_min[2] > 0.19 # door in front (+z) of the body, hinge placement applied
+
+
+def test_link_named_world_is_rejected(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path)
+ (meshes / "world.glb").write_bytes((meshes / "body.glb").read_bytes())
+ urdf.write_text(urdf.read_text().replace('name="body"', 'name="world"').replace('link="body"', 'link="world"').replace("meshes/body.glb", "meshes/world.glb"))
+ with pytest.raises(UrdfError, match="reserved"):
+ load_urdf(urdf, meshes)
diff --git a/harness/tests/urdf_joints/test_lint.py b/harness/tests/urdf_joints/test_lint.py
index 749c8870..03093875 100644
--- a/harness/tests/urdf_joints/test_lint.py
+++ b/harness/tests/urdf_joints/test_lint.py
@@ -97,7 +97,13 @@ def test_link_rules():
assert any("differs from <visual>" in m for m in _msgs(f, Severity.WARN))
f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="DoorOpen"').replace('link="door"', 'link="DoorOpen"').replace("meshes/door.glb", "meshes/DoorOpen.glb"))
msgs = _msgs(f, Severity.WARN)
- assert any("snake_case" in m for m in msgs) and any("state word" in m for m in msgs)
+ assert any("state word" in m for m in msgs)
+ # the plan's PascalCase part names are accepted silently (check_contract normalises names) …
+ f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="FrontDoor"').replace('link="door"', 'link="FrontDoor"').replace("meshes/door.glb", "meshes/FrontDoor.glb"))
+ assert f == []
+ # … but Blender auto-suffixes / spaces are not plain identifiers
+ f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="door.001"').replace('link="door"', 'link="door.001"').replace("meshes/door.glb", "meshes/door.001.glb"))
+ assert any("plain identifier" in m for m in _msgs(f, Severity.WARN))
f, _ = lint_urdf_text(GOOD.replace('<link name="door">', '<link name="door"><visual><geometry><mesh filename="meshes/door.glb"/></geometry></visual>'))
assert any("2 <visual>" in m for m in _msgs(f, Severity.ERROR))
@@ -126,3 +132,9 @@ def test_lint_workspace(tmp_path):
(ws.src / "model.py").write_text(MODEL)
rep = lint_workspace(ws)
assert rep.passed and rep.findings == []
+
+
+def test_reserved_link_name_world():
+ # glTF readers use 'world' as the scene-graph base frame: a link of that name cannot become a GLB node
+ f, _ = lint_urdf_text(GOOD.replace('name="body"', 'name="world"').replace('link="body"', 'link="world"').replace("meshes/body.glb", "meshes/world.glb"))
+ assert any("reserved" in m for m in _msgs(f, Severity.ERROR))
diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.py
index cc5dc5fe..6c53ad7e 100644
--- a/harness/tests/urdf_joints/test_live_blender.py
+++ b/harness/tests/urdf_joints/test_live_blender.py
@@ -46,6 +46,27 @@ def test_cabinet_door_end_to_end(tmp_path, cabinet_plan):
assert np.allclose(u.get_transform("door", "body"), fk(r, {"hinge": 1.0})["door"], atol=1e-6)
+@needs_blender
+def test_rest_shifted_skeleton_builds_clean(tmp_path, drawer_plan):
+ """Plan with rest ≠ 0 and the bbox authored AT that rest (drawer 0.1 m out): the
+ skeleton's shifted limits (-0.1 .. 0.2) put q=0 at the authored pose and @lower at the
+ closed position — no penetration anywhere in the sweep."""
+ plan = drawer_plan.model_copy(deep=True)
+ plan.parts[1].bbox.center = (0, -0.31, 0.45) # front panel 0.1 m out of the carcass
+ plan.joints[0].pivot = (0, -0.31, 0.45)
+ plan.joints[0].rest = 0.1
+ ws = Workspace(tmp_path / "drawer_rest").create()
+ rt = UrdfBlenderRuntime()
+ rt.skeleton(ws, plan)
+ assert 'lower="-0.1" upper="0.2"' in (ws.src / "robot.urdf").read_text()
+ res = rt.build(ws)
+ assert res.ok, res.error_message
+ r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")
+ closed = link_world_meshes(r, {"slide": -0.1})["drawer"].bounds
+ assert np.isclose(closed[1][1], -0.20, atol=1e-6) # back face of the panel flush with the carcass front
+ assert res.census["articulation"]["summary"]["max_penetration_m"] == 0.0
+
+
@needs_blender
def test_drawer_prismatic(tmp_path, drawer_plan):
ws = Workspace(tmp_path / "drawer").create()
diff --git a/harness/tests/urdf_joints/test_skeleton.py b/harness/tests/urdf_joints/test_skeleton.py
index 118b6b6f..e8fbfc61 100644
--- a/harness/tests/urdf_joints/test_skeleton.py
+++ b/harness/tests/urdf_joints/test_skeleton.py
@@ -41,7 +41,22 @@ def test_rest_shift():
)
fr = compute_urdf_frames(plan)
j = fr.joints[0]
- assert (j.lower, j.upper) == (-0.5, 1.0) # q=0 is the authored rest
+ assert (j.lower, j.upper) == (-0.5, 1.0) and j.rest == 0.5 # q=0 is the authored rest
+ # the rendered files SAY so, next to the shifted limit and the pivot, so the agent who
+ # reads the plan table (unshifted lower/upper/rest) and the skeleton sees one rule
+ urdf_text = render_urdf(fr)
+ assert '<limit lower="-0.5" upper="1" effort="10" velocity="1"/> <!-- plan lower=0 upper=1.5 rest=0.5' in urdf_text
+ assert "shifted by -rest" in urdf_text and "q=0 is the authored pose" in urdf_text
+ assert "(plan rest=0.5 → this pose is URDF q=0)" in render_model_py(plan, fr)
+ assert lint_urdf_text(urdf_text)[0] == []
+
+
+def test_no_rest_note_when_rest_is_zero(cabinet_plan):
+ fr = compute_urdf_frames(cabinet_plan)
+ urdf_text = render_urdf(fr)
+ assert all(j.rest == 0.0 for j in fr.joints)
+ assert "shifted by -rest" not in urdf_text and "plan rest=" not in render_model_py(cabinet_plan, fr)
+ assert '<limit lower="0" upper="1.57" effort="10" velocity="1"/>' in urdf_text
def test_rendered_files_lint_clean_and_load(tmp_path, cabinet_plan):
diff --git a/harness/tests/urdf_joints/test_sweep.py b/harness/tests/urdf_joints/test_sweep.py
index aa3a1557..23617e37 100644
--- a/harness/tests/urdf_joints/test_sweep.py
+++ b/harness/tests/urdf_joints/test_sweep.py
@@ -14,7 +14,11 @@ from codeverse.spatial.joints import (
sweep_collisions,
sweep_findings,
)
-from tests.urdf_joints.conftest import write_mesh_robot, write_prims_robot
+from tests.urdf_joints.conftest import (
+ write_carcass_drawer_robot,
+ write_mesh_robot,
+ write_prims_robot,
+)
def test_good_design_has_no_overlaps(tmp_path):
@@ -89,11 +93,57 @@ def test_motion_direction(tmp_path):
def test_trimesh_fallback_backend(tmp_path, monkeypatch):
+ import codeverse.spatial.joints_collide as jc
import codeverse.spatial.joints_sweep as js
- monkeypatch.setattr(js, "_fcl", None)
+ monkeypatch.setattr(jc, "_fcl", None)
r = load_urdf(write_prims_robot(tmp_path / "cab.urdf", axis_z=+1))
rep = js.sweep_collisions(r, pose_samples(r), volumes=False)
assert rep.summary.backend == "trimesh"
assert rep.summary.max_penetration_m > 0.1 and rep.summary.rest_max_penetration_m == 0.0
assert rep.summary.floating_links == []
+
+
[email protected]("fcl", [True, False], ids=["fcl", "trimesh-fallback"])
+def test_agent_style_meshes_penetration_is_real_and_deterministic(tmp_path, monkeypatch, fcl):
+ """Non-watertight, inverted-winding links (the wrapper's usual output): a clean design
+ must report no overlap and a drawer driven 30 mm through the side panel must be caught —
+ identically on every call (no random ray re-casts) and on both backends."""
+ import codeverse.spatial.joints_collide as jc
+
+ if not fcl:
+ monkeypatch.setattr(jc, "_fcl", None)
+ clean = load_urdf(*write_carcass_drawer_robot(tmp_path / "clean"))
+ assert not clean.links["Carcass"].mesh.is_watertight and clean.links["Carcass"].mesh.volume < 0
+ reps = [sweep_collisions(clean, pose_samples(clean, n_random=4, seed=0), volumes=False) for _ in range(3)]
+ assert all(r.summary.max_penetration_m == 0.0 and r.summary.overlapping_poses == [] for r in reps)
+ assert reps[0].summary.floating_links == [] and reps[0].summary.link_islands == {"Carcass": 5, "Drawer": 5}
+ assert reps[0].summary.backend == ("fcl" if fcl else "trimesh")
+
+ bad = load_urdf(*write_carcass_drawer_robot(tmp_path / "bad", drawer_shift_x=0.032))
+ rests = [sweep_collisions(bad, [{}]).summary.rest_max_penetration_m for _ in range(3)]
+ assert len(set(rests)) == 1 and 0.008 < rests[0] < 0.02 # 30 mm through a 30 mm panel → ≥ 10 mm to its surface
+ rep = sweep_collisions(bad, [{}])
+ ov = rep.per_pose[0].overlaps
+ assert [(o.a, o.b, o.approx) for o in ov] == [("Carcass", "Drawer", False)] # islands are watertight → exact
+ assert ov[0].volume_m3 is not None and ov[0].volume_m3 > 1e-6
+ sev = {x.target: x.severity for x in sweep_findings(rep, rest_max_m=0.005)}
+ assert sev["Carcass|Drawer"] == Severity.ERROR
+
+
+def test_welded_child_overlap_is_structural_not_motion(tmp_path):
+ """A handle sunk 3 mm into its door (fixed joint) never moves relative to the door:
+ one WARN under the rest policy, not an ERROR repeated for every swung pose."""
+ urdf, meshes = write_mesh_robot(tmp_path, handle=True)
+ urdf.write_text(urdf.read_text().replace('<origin xyz="-0.2 0.24 -0.4" rpy="0 0 0"/>', '<origin xyz="-0.2 0.243 -0.4" rpy="0 0 0"/>'))
+ r = load_urdf(urdf, meshes)
+ rep = sweep_collisions(r, pose_samples(r))
+ ovs = [(pr.label, o) for pr in rep.per_pose for o in pr.overlaps]
+ assert [(lbl, o.a, o.b, o.rigid) for lbl, o in ovs] == [("rest", "door", "handle", True)]
+ assert 0.0025 < rep.summary.rest_max_penetration_m < 0.0035 and rep.summary.overlapping_poses == ["rest"]
+ finds = sweep_findings(rep)
+ assert [(f.target, f.severity) for f in finds] == [("door|handle", Severity.WARN)]
+ # without a rest pose in the sweep the weld is still measured (once, first pose) and counts as rest penetration
+ rep2 = sweep_collisions(r, [{"hinge": 1.0}, {"hinge": 1.5}])
+ assert [len(pr.overlaps) for pr in rep2.per_pose] == [1, 0] and rep2.summary.rest_max_penetration_m > 0.0025
+ assert sweep_findings(rep2)[0].severity == Severity.WARN and "rigidly joined" in sweep_findings(rep2)[0].fix_hint