Skip to content

Official Codebase of 3DCodeVerse

Python

D104 Blender 5.2.2 LTS only + D105 argon program: variants, scene_blender, scene judge v2, strict placement, the loop (iteration 1)

gaoypeng24e1cb787be3
diff --git a/eval/README.md b/eval/README.md
index 71596044..089e4173 100644
--- a/eval/README.md
+++ b/eval/README.md
@@ -20,6 +20,15 @@ pip install -e ../harness # once; both evaluations import co
python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator agy:gemini-4-argon
python -m bench.report bench/out/static_objects_v1 # rebuild report.md + report.html
python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:agy:gemini-4-argon,oneshot:gemini:gemini-3.7-flash --out bench/out/compare_v1
+python -m bench.run_bench bench/prompts/scenes_v2.yaml --variant argon --judge gemini:gemini-4-argon # a per-model prompt/skill variant (D105) on every run
+python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon --languages scene_threejs,scene_blender \
+ --generator agy:gemini-4-argon --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 --rounds 2 --max-minutes 90
+python -m bench.loop generate --out bench/out/loop_argon --iter 0 [--n 30] [--rung 1] # the tuning loop (docs/EVAL.md §10)
+python -m bench.loop run --out bench/out/loop_argon --iter 0 [--resume] # one run_bench child per language
+python -m bench.loop diagnose --out bench/out/loop_argon --iter 0 # diagnosis.md: numbers + recommendations
+python -m bench.loop compare --out bench/out/loop_argon --iter 1 --against 0 # keep / revert / inconclusive per language
+python -m bench.loop judge-calib --out bench/out/loop_argon --iter 1 [--n 3] # the judge arm: within / between σ
+python -m bench.loop accept --out bench/out/loop_argon --iter 1 --note "…" # or rollback; status prints the ledger
python -m llm.config # doctor for the LLM evaluation: tools and assets it can / cannot find
python -m pytest # the bench tests (offline)
ruff check .
diff --git a/eval/bench/_fixed_eval.py b/eval/bench/_fixed_eval.py
index 57805177..d7279c38 100644
--- a/eval/bench/_fixed_eval.py
+++ b/eval/bench/_fixed_eval.py
@@ -32,6 +32,7 @@ from codeverse3d.contracts.run import RoundRecord
from codeverse3d.contracts.spec import Spec
from codeverse3d.conventions import OBJECT_VIEWS
from codeverse3d.judges.base import SLICE_TRACKS, JudgeInput, judged_subset, round_input
+from codeverse3d.proc import read_json_or_none
from codeverse3d.workspace import Workspace
RUBRIC = "static_object_v1"
@@ -162,7 +163,15 @@ class FixedEvaluator:
out.renders = frames_render_set(ws, build, 0)
elif spec.track is Track.SCENE:
from codeverse3d.spatial.frame_metrics import frame_gate_from_renders
-
+ from codeverse3d.spatial.scene_placement import placement_gate
+
+ # the deterministic placement caps (scene_v2: floating / sunken / interpenetration /
+ # scale, 2026-10-14) fire in every A/B cell as they do in the loop: the gate reads
+ # the build's census and the cell's plan.json (a one-shot arm has none — the
+ # plan-less checks still run); None when the census has no placement table
+ placement = placement_gate(ws, build.census, read_json_or_none(ws.plan_path))
+ if placement is not None:
+ out.gates.append(placement)
out.renders = self.runtime(spec.language).render_scene(ws, ws.renders_dir(0), orbit=True, times=(0.0, 1.5), sheet=True)
out.gates.append(frame_gate_from_renders(ws.renders_dir(0)))
else:
diff --git a/eval/bench/_loop_diag.py b/eval/bench/_loop_diag.py
new file mode 100644
index 00000000..0695ea87
--- /dev/null
+++ b/eval/bench/_loop_diag.py
@@ -0,0 +1,606 @@
+"""What an iteration's run records say (private: ``bench.loop diagnose / compare / judge-calib``).
+
+One :class:`RunDigest` per run, read off the things a run leaves behind — the bench row
+(``results.jsonl``), the typed ``record.json`` (``codeverse3d.record.record.load_record``), the
+picked round's gates / verdict / skills, and the deliverable's source — and three readers over a
+battery of them:
+
+* :func:`diagnose_dir` — the numbers and a RECOMMENDATIONS list produced by deterministic rules
+ (:data:`RULES`): a rate crosses its threshold → one named lever. No model reads the diagnosis;
+ a person does, before editing the variant.
+* :func:`compare_dirs` — iteration N against M, paired by prompt id: ``bench.stats.decide`` on the
+ picked score (the one paired rule every report uses, EVAL.md §8) PLUS the deterministic-gate veto —
+ the floating + sunken + interpenetration ERROR count per run must not rise by more than
+ :data:`VETO_RISE` on average, whatever the judge says (the owner's stricter contact standards,
+ 2026-10-14, are measured by the gate, not perceived by the VLM).
+* :func:`calib_summary` — the judge arm: within-run σ (the re-judge noise), between-run σ (the
+ spread the judge is asked to resolve), their ratio, and the gate-score correlations.
+
+Gate findings are counted by their TYPED kind (``skills.registry.finding_kind`` →
+``"scene_placement/floating"``), never by message text (Law 4).
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import math
+import re
+import statistics
+from collections import Counter
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from bench._jsonl import latest, read_jsonl
+from bench._records import records
+from bench.paired_compare import PairedStats, paired, paired_rows
+from bench.run_bench import BenchItemResult
+from bench.stats import correlation, decide
+from codeverse3d.addons.calibration import CalibrationRow, CalibrationTable
+from codeverse3d.addons.select import summarise
+from codeverse3d.contracts.artifacts import Severity
+from codeverse3d.contracts.run import RoundRecord, RunRecord
+from codeverse3d.record.record import RecordError, load_record, stop_reason
+from codeverse3d.skills.registry import finding_kind
+
+#: the gate kinds the owner's contact standards are about (spatial/scene_placement.py data.kind)
+PLACEMENT_KINDS: tuple[str, ...] = ("scene_placement/floating", "scene_placement/sunken",
+ "scene_placement/interpenetration")
+#: the veto: a variant whose runs gain more than this many placement ERRORs each, on average, is
+#: reverted whatever its score — one more floater per run is inside the gate's own run-to-run swing
+#: (the same prompt re-run moves 0-1 findings), two is a change in behaviour
+VETO_RISE = 1.0
+
+#: `from '../lib/<x>.js'` / `from './lib/<x>.js'` in an agent-written three.js file. A regex over
+#: SOURCE TEXT (the import specifier), the way B1's `library_rows` reads the catalog — not over an id.
+_JS_LIB_IMPORT = re.compile(r"""from\s+['"](?:\.\./|\./)+lib/([A-Za-z0-9_]+)\.js['"]""")
+#: the harness-owned library directory inside ``src/`` — its own files import each other and must
+#: not count as the AGENT reaching the library (HARNESS_OWNED_SRC: ``src/lib/``)
+_LIB_DIR = "lib"
+
+
+# --------------------------------------------------------------------------- one run
+class RunDigest(BaseModel):
+ """Everything the diagnosis and the comparison read off one run."""
+
+ id: str
+ status: str = ""
+ stop_reason: str = ""
+ score_baseline: float | None = None
+ score_picked: float | None = None
+ picked_round: int | None = None
+ criteria: dict[str, float] = Field(default_factory=dict, description="the picked verdict's per-criterion scores")
+ defects: dict[str, bool] = Field(default_factory=dict, description="the picked verdict's defect checklist")
+ caps: list[str] = Field(default_factory=list, description="cap rules applied on the picked verdict")
+ gate_errors: dict[str, int] = Field(default_factory=dict, description="typed kind → ERROR findings, picked round")
+ gate_warns: dict[str, int] = Field(default_factory=dict, description="typed kind → WARN findings, picked round")
+ issues: list[tuple[str, str]] = Field(default_factory=list, description="(kind, target word) per judge issue")
+ lib_modules: list[str] = Field(default_factory=list, description="distinct lib modules the agent's files import")
+ lib_imports: int = Field(default=0, description="import statements of lib modules in the agent's files")
+ cost_usd: float = 0.0
+ cost_by_stage: dict[str, float] = Field(default_factory=dict)
+ minutes: float | None = None
+ skills_listed: int = 0
+ skills_surfaced: int = 0
+ skills_deep: int = 0
+ deep_read_rate: float | None = Field(default=None, description="mean over the rounds that could measure it")
+ errors: str = ""
+
+ @property
+ def placement_errors(self) -> int:
+ return sum(self.gate_errors.get(k, 0) for k in PLACEMENT_KINDS)
+
+
+def _picked(run_dir: Path, rec: RunRecord) -> RoundRecord | None:
+ s = summarise(run_dir, record=rec)
+ idx = s.round
+ return next((r for r in rec.rounds if r.index == idx), None) if idx is not None else None
+
+
+def _issue_word(target: str) -> str:
+ """``ShojiVeranda/ShojiScreen`` → ``ShojiScreen``; ``BlackPine_5`` → ``BlackPine`` (the family, not the
+ instance): the pairs are counted across runs, where instance numbers only scatter them."""
+ seg = target.strip().split("/")[-1] or target.strip()
+ head, _, tail = seg.rpartition("_")
+ return head if head and tail.isdigit() else seg
+
+
+def py_lib_modules(path: Path) -> list[str]:
+ """``lib.<x>`` modules one agent-written python file imports (``ast``, never text)."""
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))
+ except SyntaxError:
+ return []
+ out: list[str] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
+ parts = node.module.split(".")
+ if parts[0] == _LIB_DIR:
+ out.extend([parts[1]] if len(parts) > 1 else [a.name for a in node.names])
+ elif isinstance(node, ast.Import):
+ for a in node.names:
+ parts = a.name.split(".")
+ if parts[0] == _LIB_DIR and len(parts) > 1:
+ out.append(parts[1])
+ return out
+
+
+def js_lib_modules(path: Path) -> list[str]:
+ """``lib/<x>.js`` modules one agent-written three.js file imports (relative specifiers)."""
+ return _JS_LIB_IMPORT.findall(path.read_text(encoding="utf-8", errors="replace"))
+
+
+def lib_usage(run_dir: Path) -> tuple[list[str], int]:
+ """``(distinct modules, import statements)`` over the agent's files under ``deliverable/src`` (the
+ packaged round) — ``src/`` when nothing was packaged. ``src/lib/`` itself is skipped: the library
+ importing itself is not the agent using it."""
+ src = run_dir / "deliverable" / "src"
+ if not src.is_dir():
+ src = run_dir / "src"
+ if not src.is_dir():
+ return [], 0
+ found: list[str] = []
+ for p in sorted(src.rglob("*")):
+ if not p.is_file() or _LIB_DIR in p.relative_to(src).parts[:-1]:
+ continue
+ if p.suffix == ".py":
+ found.extend(py_lib_modules(p))
+ elif p.suffix in (".js", ".mjs"):
+ found.extend(js_lib_modules(p))
+ return sorted(set(found)), len(found)
+
+
+def digest_run(run_dir: Path, row: BenchItemResult | None = None) -> RunDigest:
+ """The digest of one run directory; ``row`` is its bench row when the battery has one."""
+ d = RunDigest(id=row.id if row is not None else run_dir.name)
+ if row is not None:
+ d.status, d.errors = row.status, row.errors
+ d.score_baseline, d.score_picked, d.picked_round = row.score_baseline, row.score_picked, row.picked_round
+ d.cost_usd, d.minutes = row.cost_usd, row.minutes
+ try:
+ rec = load_record(run_dir)
+ except RecordError as e:
+ d.errors = d.errors or str(e)
+ return d
+ d.stop_reason = stop_reason(rec)
+ d.status = d.status or rec.status.value
+ d.cost_usd = d.cost_usd or rec.total_usage.cost_usd
+ d.minutes = rec.minutes if rec.minutes is not None else d.minutes
+ cost = rec.telemetry.cost if rec.telemetry is not None else None
+ if cost is not None:
+ d.cost_by_stage = {s.stage: round(s.cost_usd, 6) for s in cost.by_stage}
+ picked = _picked(run_dir, rec)
+ if picked is not None:
+ d.picked_round = picked.index
+ for g in picked.gates:
+ for f in g.findings:
+ kind = finding_kind(f)
+ if kind is None:
+ continue
+ bucket = d.gate_errors if f.severity == Severity.ERROR else d.gate_warns if f.severity == Severity.WARN else None
+ if bucket is not None:
+ bucket[kind] = bucket.get(kind, 0) + 1
+ j = picked.judgment
+ if j is not None and not j.degraded:
+ d.score_picked = j.overall if d.score_picked is None else d.score_picked
+ d.criteria = dict(j.scores)
+ d.issues = [(i.kind, _issue_word(i.target)) for i in j.issues]
+ raw = _raw(j.raw)
+ d.defects = {k: bool(v) for k, v in (raw.get("defects") or {}).items()}
+ d.caps = [str(c.get("rule", "")) for c in (raw.get("caps") or {}).get("caps_applied", []) if c.get("rule")]
+ if d.score_baseline is None:
+ base = next((r for r in rec.rounds if r.index == 0), None)
+ if base is not None and base.judgment is not None and not base.judgment.degraded:
+ d.score_baseline = base.judgment.overall
+ rates: list[float] = []
+ for r in rec.rounds:
+ if r.skills is None:
+ continue
+ d.skills_listed += len(r.skills.listed)
+ d.skills_surfaced += len(r.skills.surfaced)
+ d.skills_deep += len(r.skills.deep)
+ if (rate := r.skills.deep_read_rate) is not None:
+ rates.append(rate)
+ d.deep_read_rate = round(statistics.fmean(rates), 4) if rates else None
+ d.lib_modules, d.lib_imports = lib_usage(run_dir)
+ return d
+
+
+def _raw(text: str) -> dict[str, Any]:
+ try:
+ raw = json.loads(text) if text else {}
+ except ValueError:
+ return {}
+ return raw if isinstance(raw, dict) else {}
+
+
+def digests_for(out_lang: Path) -> dict[str, RunDigest]:
+ """prompt id → digest for one ``bench.run_bench`` output directory (its rows + its run dirs,
+ each run once — ``_records.records``)."""
+ rows: dict[str, BenchItemResult] = {}
+ jl = out_lang / "results.jsonl"
+ if jl.is_file():
+ rows = {r.id: r for r in latest(read_jsonl(jl, BenchItemResult)).values()}
+ out: dict[str, RunDigest] = {}
+ runs_root = out_lang / "runs"
+ if runs_root.is_dir():
+ for rec_path, data in records(runs_root, track="scene"):
+ run_dir = rec_path.parent
+ pid = str((data.get("spec") or {}).get("id", run_dir.name)).split("/")[-1]
+ # the live run is `runs/<id>`; a redo archives the old tree beside it as `<id>.attemptN`
+ # (run_bench.archive_attempt) with the SAME spec id, and sorts after it — never the digest
+ if run_dir.name != pid:
+ continue
+ out[pid] = digest_run(run_dir, rows.get(pid))
+ for pid, row in rows.items(): # a row whose run left no record (an error before the plan) still counts
+ out.setdefault(pid, digest_run(runs_root / pid, row))
+ return out
+
+
+# --------------------------------------------------------------------------- diagnosis
+@dataclass(frozen=True)
+class Rule:
+ """A deterministic lever: when ``metric`` crosses ``threshold`` (``above`` or below), say ``text``."""
+
+ name: str
+ metric: str
+ threshold: float
+ text: str
+ above: bool = True
+
+ def fires(self, value: float | None) -> bool:
+ if value is None:
+ return False
+ return value >= self.threshold if self.above else value < self.threshold
+
+
+RULES: tuple[Rule, ...] = (
+ Rule("floating", "floating_error_rate", 0.25,
+ "placement recipe + boost the placement skill: seat every placed thing on height_at / its support "
+ "(lib.place.seat); the gate ERRORs at 0.08 m or > 2 floaters per scene"),
+ Rule("sunken", "sunken_error_rate", 0.25,
+ "seating recipe: assets are buried, not hovering — seat by the evaluated bbox, never by the origin "
+ "(sunk ERROR at 0.20 m and 20 % of the height)"),
+ Rule("interpenetration", "interpenetration_error_rate", 0.25,
+ "clear_of self-check in the zone recipe + spacing in the layout prompt (overlap ERROR at 35 % of the smaller box)"),
+ Rule("library", "lib_modules_mean", 3.0,
+ "effects catalog presentation: the agent reaches fewer than three library modules per scene", above=False),
+ Rule("lighting", "dark_frame_rate", 0.20,
+ "lighting recipe: key/fill/exposure numbers per mood + boost the lighting skill (dark_frame caps at 0.55)"),
+ Rule("budget", "budget_stop_rate", 0.30,
+ "raise --max-minutes or cut the zone prompt: the clock stops the run before its rounds"),
+ Rule("weather", "infra_failed_rate", 0.20,
+ "provider weather, not the variant: `bench.loop run --resume` the iteration before reading it"),
+ Rule("unscored", "unscored_rate", 0.20,
+ "runs without a verdict: read the errors column (build / render / judge outage) before the scores"),
+ Rule("skills", "deep_read_rate_mean", 0.20,
+ "skills are listed but not read: shorten the index, name the chapter in the task text", above=False),
+ Rule("must", "missing_must_rate", 0.25,
+ "must-have wording: the contract lines fail the plan's acceptance items — the planner is not carrying them"),
+ Rule("camera", "camera_error_rate", 0.20,
+ "camera brief recipe: fit every authored camera to the content box, never inside geometry"),
+ Rule("free_exempt", "free_exempt_rate", 0.20,
+ "assets tagged placement='free' to dodge the gate: say in the contract that 'free' is for hanging / airborne things only"),
+)
+
+
+class Recommendation(BaseModel):
+ rule: str
+ metric: str
+ value: float
+ threshold: float
+ text: str
+
+
+class Diagnosis(BaseModel):
+ """One language of one iteration, diagnosed."""
+
+ language: str
+ out_dir: str
+ n: int = 0
+ by_status: dict[str, int] = Field(default_factory=dict)
+ n_scored: int = 0
+ baseline: dict[str, float | None] = Field(default_factory=dict, description="mean / median / sd")
+ picked: dict[str, float | None] = Field(default_factory=dict)
+ criteria_mean: dict[str, float] = Field(default_factory=dict)
+ defect_rates: dict[str, float] = Field(default_factory=dict, description="share of scored runs voting the defect")
+ caps_fired: dict[str, int] = Field(default_factory=dict, description="cap rule → runs it fired on")
+ gate_error_total: dict[str, int] = Field(default_factory=dict, description="typed kind → ERROR findings over the runs")
+ gate_error_runs: dict[str, int] = Field(default_factory=dict, description="typed kind → runs with at least one ERROR")
+ gate_warn_total: dict[str, int] = Field(default_factory=dict)
+ lib_modules_mean: float | None = None
+ lib_module_hist: dict[str, int] = Field(default_factory=dict, description="module → runs importing it")
+ cost_total: float = 0.0
+ cost_by_stage: dict[str, float] = Field(default_factory=dict)
+ minutes_mean: float | None = None
+ minutes_total: float = 0.0
+ stop_reasons: dict[str, int] = Field(default_factory=dict)
+ skills: dict[str, float | int | None] = Field(default_factory=dict)
+ top_issues: list[tuple[str, str, int]] = Field(default_factory=list, description="(kind, target word, n), 12 most frequent")
+ metrics: dict[str, float | None] = Field(default_factory=dict, description="the rates the rules read")
+ recommendations: list[Recommendation] = Field(default_factory=list)
+ runs: list[RunDigest] = Field(default_factory=list)
+
+
+def _stats(xs: Sequence[float]) -> dict[str, float | None]:
+ if not xs:
+ return {"mean": None, "median": None, "sd": None}
+ return {"mean": round(statistics.fmean(xs), 4), "median": round(statistics.median(xs), 4),
+ "sd": round(statistics.stdev(xs), 4) if len(xs) > 1 else None}
+
+
+def _rate(hits: int, n: int) -> float | None:
+ return round(hits / n, 4) if n else None
+
+
+def diagnose_digests(language: str, out_dir: Path, digests: Iterable[RunDigest]) -> Diagnosis:
+ runs = sorted(digests, key=lambda d: d.id)
+ diag = Diagnosis(language=language, out_dir=str(out_dir), n=len(runs), runs=runs)
+ diag.by_status = dict(Counter(d.status or "(none)" for d in runs))
+ evaluated = [d for d in runs if d.status != "infra_failed"]
+ scored = [d for d in evaluated if d.score_picked is not None]
+ gated = [d for d in evaluated if d.picked_round is not None]
+ diag.n_scored = len(scored)
+ diag.baseline = _stats([d.score_baseline for d in evaluated if d.score_baseline is not None])
+ diag.picked = _stats([d.score_picked for d in scored])
+ crit: dict[str, list[float]] = {}
+ defects: Counter[str] = Counter()
+ caps: Counter[str] = Counter()
+ issues: Counter[tuple[str, str]] = Counter()
+ for d in scored:
+ for k, v in d.criteria.items():
+ crit.setdefault(k, []).append(v)
+ defects.update(k for k, on in d.defects.items() if on)
+ caps.update(set(d.caps))
+ issues.update(d.issues)
+ diag.criteria_mean = {k: round(statistics.fmean(v), 4) for k, v in sorted(crit.items())}
+ diag.defect_rates = {k: _rate(n, len(scored)) or 0.0 for k, n in defects.most_common()}
+ diag.caps_fired = dict(caps.most_common())
+ diag.top_issues = [(k, w, n) for (k, w), n in issues.most_common(12)]
+ err_total: Counter[str] = Counter()
+ err_runs: Counter[str] = Counter()
+ warn_total: Counter[str] = Counter()
+ for d in gated:
+ err_total.update(d.gate_errors)
+ err_runs.update(d.gate_errors.keys())
+ warn_total.update(d.gate_warns)
+ diag.gate_error_total, diag.gate_error_runs = dict(err_total.most_common()), dict(err_runs.most_common())
+ diag.gate_warn_total = dict(warn_total.most_common())
+ with_src = [d for d in evaluated if d.lib_modules or d.lib_imports]
+ diag.lib_modules_mean = round(statistics.fmean(len(d.lib_modules) for d in gated), 3) if gated else None
+ diag.lib_module_hist = dict(Counter(m for d in with_src for m in d.lib_modules).most_common())
+ diag.cost_total = round(sum(d.cost_usd for d in runs), 4)
+ stage: Counter[str] = Counter()
+ for d in runs:
+ stage.update(d.cost_by_stage)
+ diag.cost_by_stage = {k: round(v, 4) for k, v in stage.most_common()}
+ minutes = [d.minutes for d in evaluated if d.minutes is not None]
+ diag.minutes_mean = round(statistics.fmean(minutes), 2) if minutes else None
+ diag.minutes_total = round(sum(minutes), 2)
+ diag.stop_reasons = dict(Counter(d.stop_reason or "(none)" for d in evaluated).most_common())
+ rates = [d.deep_read_rate for d in runs if d.deep_read_rate is not None]
+ diag.skills = {"listed": sum(d.skills_listed for d in runs), "surfaced": sum(d.skills_surfaced for d in runs),
+ "deep": sum(d.skills_deep for d in runs),
+ "deep_read_rate_mean": round(statistics.fmean(rates), 4) if rates else None}
+ n_eval, n_gated = len(evaluated), len(gated)
+ diag.metrics = {
+ "floating_error_rate": _rate(err_runs["scene_placement/floating"], n_gated),
+ "sunken_error_rate": _rate(err_runs["scene_placement/sunken"], n_gated),
+ "interpenetration_error_rate": _rate(err_runs["scene_placement/interpenetration"], n_gated),
+ "free_exempt_rate": _rate(sum(1 for d in gated if "scene_placement/free_exempt" in d.gate_errors
+ or "scene_placement/free_exempt" in d.gate_warns), n_gated),
+ "dark_frame_rate": _rate(err_runs["scene_frames/dark_frame"], n_gated),
+ "camera_error_rate": _rate(sum(1 for d in gated if any(k.startswith("scene_frames/camera_") for k in d.gate_errors)), n_gated),
+ "lib_modules_mean": diag.lib_modules_mean,
+ "budget_stop_rate": _rate(sum(1 for d in evaluated if d.stop_reason == "budget"), n_eval),
+ "infra_failed_rate": _rate(len(runs) - n_eval, len(runs)),
+ "unscored_rate": _rate(n_eval - len(scored), n_eval),
+ "deep_read_rate_mean": diag.skills["deep_read_rate_mean"],
+ "missing_must_rate": _rate(caps["missing_must_acceptance"], len(scored)),
+ }
+ diag.recommendations = [
+ Recommendation(rule=r.name, metric=r.metric, value=v, threshold=r.threshold, text=r.text)
+ for r in RULES if (v := diag.metrics.get(r.metric)) is not None and r.fires(v)
+ ]
+ return diag
+
+
+def diagnose_dir(language: str, out_lang: Path) -> Diagnosis:
+ """The diagnosis of one ``bench.run_bench`` output directory."""
+ return diagnose_digests(language, out_lang, digests_for(out_lang).values())
+
+
+def _f(x: float | None, fmt: str = ".3f") -> str:
+ return "—" if x is None else format(x, fmt)
+
+
+def _kv_table(title: str, rows: Iterable[tuple[str, Any]], head: tuple[str, str]) -> list[str]:
+ out = [f"### {title}", "", f"| {head[0]} | {head[1]} |", "|---|---|"]
+ out += [f"| {k} | {v} |" for k, v in rows]
+ return out + [""]
+
+
+def render_diagnosis(d: Diagnosis) -> str:
+ lines = [f"## {d.language} — {d.n} run(s) under `{d.out_dir}`", "",
+ "by status: " + ", ".join(f"{k} {n}" for k, n in sorted(d.by_status.items())) + "; "
+ f"scored {d.n_scored}; stop reasons: " + ", ".join(f"{k} {n}" for k, n in d.stop_reasons.items()), "",
+ "| score | mean | median | sd |", "|---|---|---|---|",
+ f"| baseline | {_f(d.baseline.get('mean'))} | {_f(d.baseline.get('median'))} | {_f(d.baseline.get('sd'))} |",
+ f"| picked | {_f(d.picked.get('mean'))} | {_f(d.picked.get('median'))} | {_f(d.picked.get('sd'))} |", ""]
+ lines += _kv_table("criteria (mean over scored runs)", ((k, _f(v)) for k, v in d.criteria_mean.items()), ("criterion", "mean"))
+ lines += _kv_table("defects (vote rate over scored runs)", ((k, format(v, ".0%")) for k, v in d.defect_rates.items()), ("defect", "rate"))
+ lines += _kv_table("caps fired (runs)", d.caps_fired.items(), ("rule", "runs"))
+ lines += ["### gates (picked round, typed kind)", "", "| kind | runs with ERROR | ERROR findings | WARN findings |", "|---|---|---|---|"]
+ kinds = sorted(set(d.gate_error_total) | set(d.gate_warn_total))
+ lines += [f"| {k} | {d.gate_error_runs.get(k, 0)} | {d.gate_error_total.get(k, 0)} | {d.gate_warn_total.get(k, 0)} |" for k in kinds]
+ lines += ["", f"### library: {_f(d.lib_modules_mean, '.2f')} modules per scene", ""]
+ lines += [f"- {m}: {n}" for m, n in list(d.lib_module_hist.items())[:20]] or ["- (no lib imports found)"]
+ lines += ["", f"### cost ${d.cost_total:.2f} total; minutes mean {_f(d.minutes_mean, '.1f')}, total {d.minutes_total:.0f}", ""]
+ lines += [f"- {k}: ${v:.2f}" for k, v in d.cost_by_stage.items()]
+ s = d.skills
+ lines += ["", f"### skills: listed {s.get('listed')}, surfaced {s.get('surfaced')}, deep {s.get('deep')}, "
+ f"deep-read rate {_f(s.get('deep_read_rate_mean'))}", ""]
+ lines += ["### judge issues (kind, target word)", ""] + [f"- {n:3}× {k} / {w}" for k, w, n in d.top_issues] + [""]
+ lines += ["### RECOMMENDATIONS", ""]
+ if d.recommendations:
+ lines += [f"- **{r.rule}** ({r.metric} = {r.value:.3g} vs {r.threshold:g}): {r.text}" for r in d.recommendations]
+ else:
+ lines += ["- (no rule fired)"]
+ lines += ["", "| metric | value |", "|---|---|"] + [f"| {k} | {_f(v)} |" for k, v in d.metrics.items()] + [""]
+ return "\n".join(lines)
+
+
+# --------------------------------------------------------------------------- compare
+class Comparison(BaseModel):
+ """Iteration ``a`` against ``b`` for one language: the score pairs plus the deterministic channels."""
+
+ language: str
+ name_a: str
+ name_b: str
+ paired: PairedStats
+ dropped_ids: list[str] = Field(default_factory=list, description="ids on one side only")
+ criteria_delta: dict[str, float] = Field(default_factory=dict, description="mean a − b per criterion")
+ gate_error_delta: dict[str, int] = Field(default_factory=dict, description="kind → Σ(a − b) ERROR findings over the pairs")
+ placement_rise: float | None = Field(default=None, description="mean a − b of the floating+sunken+interpenetration ERRORs per run")
+ cost_delta: float | None = Field(default=None, description="mean a − b, USD per run")
+ decision: str = Field(default="", description="keep | revert | inconclusive")
+ reason: str = ""
+
+
+def loop_verdict(st: PairedStats, placement_rise: float | None) -> tuple[str, str]:
+ """``(decision, reason)``: ``stats.decide`` on the paired picked scores, then the gate veto."""
+ d = decide(st.deltas)
+ decision = {"better": "keep", "worse": "revert"}.get(d.outcome, "inconclusive")
+ reason = d.reason
+ if placement_rise is not None and placement_rise > VETO_RISE:
+ decision = "revert"
+ reason = (f"gate veto: floating+sunken+interpenetration ERRORs rose by {placement_rise:+.2f} per run "
+ f"(limit {VETO_RISE:+.0f}); score said {d.outcome} — {d.reason}")
+ return decision, reason
+
+
+def compare_digests(language: str, name_a: str, name_b: str, st: PairedStats,
+ da: dict[str, RunDigest], db: dict[str, RunDigest]) -> Comparison:
+ cmp = Comparison(language=language, name_a=name_a, name_b=name_b, paired=st,
+ dropped_ids=sorted(set(da) ^ set(db)))
+ ids = [i for i in st.deltas if i in da and i in db]
+ crit: dict[str, list[float]] = {}
+ gates: Counter[str] = Counter()
+ rises: list[float] = []
+ costs: list[float] = []
+ for i in ids:
+ a, b = da[i], db[i]
+ for k in set(a.criteria) & set(b.criteria):
+ crit.setdefault(k, []).append(a.criteria[k] - b.criteria[k])
+ for k in set(a.gate_errors) | set(b.gate_errors):
+ gates[k] += a.gate_errors.get(k, 0) - b.gate_errors.get(k, 0)
+ rises.append(a.placement_errors - b.placement_errors)
+ costs.append(a.cost_usd - b.cost_usd)
+ cmp.criteria_delta = {k: round(statistics.fmean(v), 4) for k, v in sorted(crit.items())}
+ cmp.gate_error_delta = {k: v for k, v in sorted(gates.items()) if v}
+ cmp.placement_rise = round(statistics.fmean(rises), 4) if rises else None
+ cmp.cost_delta = round(statistics.fmean(costs), 4) if costs else None
+ cmp.decision, cmp.reason = loop_verdict(st, cmp.placement_rise)
+ return cmp
+
+
+def compare_dirs(language: str, dir_a: Path, dir_b: Path) -> Comparison:
+ """Iteration directory ``dir_a`` (the candidate) against ``dir_b`` (the reference), one language."""
+ cells, name_a, name_b = paired_rows(dir_a, dir_b)
+ st = paired(cells, name_a, name_b)
+ return compare_digests(language, name_a, name_b, st, digests_for(dir_a), digests_for(dir_b))
+
+
+def render_comparison(c: Comparison) -> str:
+ st = c.paired
+ ci = f"[{_f(st.ci95_low, '+.3f')}, {_f(st.ci95_high, '+.3f')}]" if st.ci95_low is not None else "—"
+ lines = [f"## {c.language}: {c.name_a} − {c.name_b}", "",
+ f"**{c.decision}** — {c.reason}", "",
+ f"pairs {st.n} (dropped: outage {st.dropped_infra}, unscored {st.dropped_unscored}, "
+ f"one side only {len(c.dropped_ids)}); mean picked {_f(st.mean_harness)} vs {_f(st.mean_oneshot)}; "
+ f"Δ {_f(st.mean_delta, '+.3f')} 95 % t-interval {ci}; W/L/T {st.wins}/{st.losses}/{st.ties}, "
+ f"sign p {_f(st.sign_p)}; cost Δ {_f(c.cost_delta, '+.2f')} $/run; "
+ f"placement ERRORs Δ {_f(c.placement_rise, '+.2f')} per run (veto above {VETO_RISE:+.0f})", ""]
+ if c.dropped_ids:
+ lines += ["dropped ids: " + ", ".join(c.dropped_ids), ""]
+ lines += _kv_table("Δ per criterion (mean a − b)", ((k, _f(v, "+.3f")) for k, v in c.criteria_delta.items()), ("criterion", "Δ"))
+ lines += _kv_table("Δ gate ERROR findings (Σ a − b over the pairs)", ((k, f"{v:+d}") for k, v in c.gate_error_delta.items()), ("kind", "Δ"))
+ lines += ["| id | Δ picked |", "|---|---|"] + [f"| {k} | {v:+.3f} |" for k, v in sorted(st.deltas.items())] + [""]
+ return "\n".join(lines)
+
+
+# --------------------------------------------------------------------------- judge calibration
+class CalibSummary(BaseModel):
+ """The judge arm of one iteration: is the re-judge noise small against the spread between runs?"""
+
+ language: str
+ model_id: str
+ n_samples: int
+ thinking: str
+ rounds: int = 0
+ errors: int = 0
+ within_sd: float | None = Field(default=None, description="rms of the per-round sample σ: the re-judge noise")
+ between_sd: float | None = Field(default=None, description="σ of the per-round means: the spread to resolve")
+ snr: float | None = Field(default=None, description="between_sd / within_sd")
+ pearson_errors_vs_score: float | None = None
+ spearman_errors_vs_score: float | None = None
+ pearson_stored_vs_new: float | None = Field(default=None, description="the in-run verdict against the re-judge")
+ mean_new: float | None = None
+ mean_stored: float | None = None
+ defects: dict[str, int] = Field(default_factory=dict)
+ caps: dict[str, int] = Field(default_factory=dict)
+ cost_usd: float = 0.0
+ latency_s_mean: float | None = None
+
+
+def calib_summary(language: str, tables: Sequence[CalibrationTable], *, thinking: str) -> CalibSummary:
+ rows: list[CalibrationRow] = [r for t in tables for r in t.rows]
+ ok = [r for r in rows if not r.error]
+ model_id = tables[0].model_id if tables else ""
+ n_samples = tables[0].n_samples if tables else 0
+ s = CalibSummary(language=language, model_id=model_id, n_samples=n_samples, thinking=thinking,
+ rounds=len(rows), errors=len(rows) - len(ok))
+ if not ok:
+ return s
+ s.within_sd = round(math.sqrt(statistics.fmean(r.std ** 2 for r in ok)), 4)
+ means = [r.mean for r in ok]
+ s.between_sd = round(statistics.stdev(means), 4) if len(means) > 1 else None
+ s.snr = round(s.between_sd / s.within_sd, 3) if s.between_sd is not None and s.within_sd else None
+ gate = [float(r.gate_errors) for r in ok]
+ s.pearson_errors_vs_score = _r(correlation(gate, means))
+ s.spearman_errors_vs_score = _r(correlation(gate, means, ranked=True))
+ stored = [(r.stored_overall, r.mean) for r in ok if r.stored_overall is not None]
+ s.pearson_stored_vs_new = _r(correlation([a for a, _ in stored], [b for _, b in stored]))
+ s.mean_new = round(statistics.fmean(means), 4)
+ s.mean_stored = round(statistics.fmean(a for a, _ in stored), 4) if stored else None
+ s.defects = dict(Counter(d for r in ok for d in r.defects_present).most_common())
+ s.caps = dict(Counter(c for r in ok for c in r.caps).most_common())
+ s.cost_usd = round(sum(r.cost_usd for r in rows), 4)
+ s.latency_s_mean = round(statistics.fmean(r.duration_s for r in ok), 1)
+ return s
+
+
+def _r(v: float | None) -> float | None:
+ return None if v is None else round(v, 4)
+
+
+def render_calib(s: CalibSummary) -> str:
+ lines = [f"## {s.language}: judge {s.model_id}, n_samples {s.n_samples}, thinking {s.thinking}", "",
+ f"rounds {s.rounds} (errors {s.errors}); within-sd {_f(s.within_sd)} (re-judge noise), "
+ f"between-sd {_f(s.between_sd)}, SNR {_f(s.snr, '.2f')}; mean new {_f(s.mean_new)} vs stored {_f(s.mean_stored)}; "
+ f"pearson(gate ERRORs, score) {_f(s.pearson_errors_vs_score, '+.3f')}, spearman {_f(s.spearman_errors_vs_score, '+.3f')}, "
+ f"pearson(stored, new) {_f(s.pearson_stored_vs_new, '+.3f')}; cost ${s.cost_usd:.2f}, "
+ f"latency {_f(s.latency_s_mean, '.0f')} s/round", ""]
+ lines += _kv_table("defects (rounds)", s.defects.items(), ("defect", "rounds"))
+ lines += _kv_table("caps (rounds)", s.caps.items(), ("rule", "rounds"))
+ return "\n".join(lines)
+
+
+__all__ = ["PLACEMENT_KINDS", "RULES", "VETO_RISE", "CalibSummary", "Comparison", "Diagnosis", "Recommendation",
+ "Rule", "RunDigest", "calib_summary", "compare_digests", "compare_dirs", "diagnose_digests",
+ "diagnose_dir", "digest_run", "digests_for", "js_lib_modules", "lib_usage", "loop_verdict",
+ "py_lib_modules", "render_calib", "render_comparison", "render_diagnosis"]
diff --git a/eval/bench/_loop_prompts.py b/eval/bench/_loop_prompts.py
new file mode 100644
index 00000000..d98f5e2e
--- /dev/null
+++ b/eval/bench/_loop_prompts.py
@@ -0,0 +1,324 @@
+"""The rung ladder and the planner-model request behind ``bench.loop generate`` (private).
+
+A loop iteration runs ~30 scene prompts per language, and the prompts have to be two things
+at once: HARD enough to move (an iteration that scores 0.8 on every prompt has nothing to
+learn), and PAIRABLE across iterations (``bench.loop compare`` pairs by prompt id). So the
+difficulty lives in a ladder of five rungs, each a set of OBJECTIVE knobs the owner fixed
+(zones / asset types / instance cap / lighting / effects), a rung's prompts are generated
+ONCE and cached, and an iteration's battery is a mix of the cached rungs up to ``--rung``.
+
+The model does not write the must_have lines. It returns STRUCTURED fields (zones, asset
+types with counts, a luminance band, one effect, one animation, a camera brief, ...) and the
+loop renders the scenes_v2 composition contract from them (:func:`contract_lines`) — so the
+counts always parse, the band is always a band, and the rung rules are checked on typed
+fields (:func:`check_prompt`), never by reading numbers back out of prose.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Literal
+
+from pydantic import BaseModel, Field, ValidationError
+
+from codeverse3d.contracts.chat import ChatMessage, ChatRequest
+from codeverse3d.contracts.common import Language
+from codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient
+from codeverse3d.spatial.frame_metrics import DARK_MEAN_LUM
+
+if TYPE_CHECKING:
+ from bench.run_bench import BenchPrompt
+
+Lighting = Literal["day", "dusk", "night"]
+Extra = Literal["interior", "water", "particles"]
+Category = Literal["urban", "rural", "nature", "waterfront", "interior", "industrial",
+ "transport", "fantasy", "historic", "garden"]
+
+#: the four features rungs 4 and 5 count ("two of night+water+interior+particles", "everything")
+FEATURE_POOL: tuple[str, ...] = ("night", "water", "interior", "particles")
+#: the band every generated luminance band must sit inside — a band outside it asks for a gated
+#: scene by construction, and the diagnosis would then blame the variant for the battery. The
+#: floor IS the scene_frames gate's threshold (``frame_metrics.DARK_MEAN_LUM``, imported, never a
+#: copy that drifts when the gate moves): an authored frame whose mean luminance is below it is a
+#: ``dark_frame`` ERROR, capped by the scene_v2 rubric. The gate has no ceiling on the mean
+#: (``blown_frame`` is a fraction of pure-white pixels, ``frame_metrics.BLOWN_FRAC``), so the
+#: ceiling is the loop's own margin under the white point.
+LUMINANCE_FLOOR = DARK_MEAN_LUM
+LUMINANCE_CEILING = 0.85
+
+
+@dataclass(frozen=True)
+class Rung:
+ """One difficulty rung: the objective knobs the owner fixed on 2026-10-14."""
+
+ level: int
+ zones: int # at least this many named zones
+ asset_types: int # at least this many distinct asset types
+ instances: int # the counts of every asset type sum to at most this
+ tier: str # the battery tier the rung's prompts are filed under
+ require_all: tuple[str, ...] = () # every one of these features
+ require_any: tuple[str, ...] = () # at least one of these
+ require_count: int = 0 # at least this many of FEATURE_POOL
+ forbid: tuple[str, ...] = ()
+ hero: bool = False # a moving hero asset is named
+ scale: bool = False # precise scale constraints are stated
+ brief: str = "" # the one line the generation prompt states
+
+
+RUNGS: dict[int, Rung] = {
+ 1: Rung(1, zones=3, asset_types=6, instances=40, tier="medium", require_all=("day",), forbid=("water",),
+ brief="daylight, no water — a small readable place"),
+ 2: Rung(2, zones=4, asset_types=8, instances=80, tier="medium", require_any=("dusk", "interior"),
+ brief="dusk lighting OR an interior"),
+ 3: Rung(3, zones=5, asset_types=10, instances=150, tier="hard", require_any=("night", "water", "particles"),
+ brief="night, water or particles"),
+ 4: Rung(4, zones=6, asset_types=12, instances=250, tier="hard", require_count=2, hero=True,
+ brief="two of night / water / interior / particles, plus a moving hero"),
+ 5: Rung(5, zones=6, asset_types=14, instances=400, tier="hard", require_all=FEATURE_POOL, hero=True, scale=True,
+ brief="night AND water AND an interior AND particles, a moving hero, precise scale constraints"),
+}
+
+
+class AssetCount(BaseModel):
+ name: str = Field(description="plural noun phrase, e.g. 'market stalls'")
+ count: int = Field(ge=1, description="how many instances the scene must place")
+ designs: int = Field(default=1, ge=1, description="distinct designs among them (1 = all alike)")
+
+
+class GeneratedPrompt(BaseModel):
+ """What the planner model returns per prompt — typed, so the contract is rendered, not parsed."""
+
+ title: str = Field(description="3-6 words")
+ category: Category
+ prompt: str = Field(description="the brief: 2-4 sentences naming the place, its zones, the time of day and one activity")
+ zones: list[str] = Field(description="named zones in walking order, short lowercase phrases")
+ asset_types: list[AssetCount]
+ lighting: Lighting
+ features: list[Extra] = Field(default_factory=list)
+ mood: str = Field(description="the lighting mood in one clause a viewer can verify in a render")
+ luminance_low: float = Field(ge=0.0, le=1.0, description="mean frame luminance band, low edge")
+ luminance_high: float = Field(ge=0.0, le=1.0, description="mean frame luminance band, high edge")
+ effect: str = Field(description="ONE water / weather / particle / shader effect, concrete and visible")
+ animation: str = Field(description="ONE thing that visibly moves between the sampled times")
+ camera: str = Field(description="ONE eye-level viewpoint — where it stands, what it looks along and its height, "
+ "e.g. 'at the quay's landward end looking along it at 1.6 m'; a still camera, "
+ "never a path")
+ hero: str = Field(default="", description="rungs 4-5: the one hero asset")
+ hero_motion: str = Field(default="", description="rungs 4-5: how the hero moves")
+ scale_constraints: list[str] = Field(default_factory=list, description="rung 5: 'the lighthouse is 18 m tall'")
+
+ @property
+ def feature_set(self) -> frozenset[str]:
+ return frozenset([self.lighting, *self.features])
+
+
+class GeneratedBattery(BaseModel):
+ prompts: list[GeneratedPrompt]
+
+
+#: one acceptance line per extra feature, fixed wording so every battery states them alike
+FEATURE_LINES: dict[str, str] = {
+ "interior": "interior: the authored cameras are inside the built space — floor, walls and ceiling enclose the view",
+ "water": "water: a water surface with reflections and visible ripples is in frame from an authored camera",
+ "particles": "particles: a soft particle effect (dust, steam, sparks, snow, rain) is visible, never hard-edged quads",
+}
+
+
+def check_prompt(gp: GeneratedPrompt, rung: Rung) -> list[str]:
+ """Every way ``gp`` falls short of ``rung`` — empty when it fits. The loop re-asks with this list."""
+ problems: list[str] = []
+ if len(gp.zones) < rung.zones:
+ problems.append(f"{gp.title!r}: {len(gp.zones)} zones, rung {rung.level} needs at least {rung.zones}")
+ if len({z.strip().lower() for z in gp.zones}) != len(gp.zones):
+ problems.append(f"{gp.title!r}: duplicate zone names")
+ if len(gp.asset_types) < rung.asset_types:
+ problems.append(f"{gp.title!r}: {len(gp.asset_types)} asset types, rung {rung.level} needs at least {rung.asset_types}")
+ total = sum(a.count for a in gp.asset_types)
+ if total > rung.instances:
+ problems.append(f"{gp.title!r}: {total} instances in total, rung {rung.level} allows at most {rung.instances}")
+ if not gp.luminance_low < gp.luminance_high:
+ problems.append(f"{gp.title!r}: luminance band {gp.luminance_low}-{gp.luminance_high} is not low < high")
+ if gp.luminance_low < LUMINANCE_FLOOR or gp.luminance_high > LUMINANCE_CEILING:
+ problems.append(f"{gp.title!r}: luminance band must sit inside {LUMINANCE_FLOOR}-{LUMINANCE_CEILING} "
+ "(the frame gate errors on darker / blown frames)")
+ have = gp.feature_set
+ for f in rung.require_all:
+ if f not in have:
+ problems.append(f"{gp.title!r}: rung {rung.level} requires {f!r} (has {sorted(have)})")
+ if rung.require_any and not have & set(rung.require_any):
+ problems.append(f"{gp.title!r}: rung {rung.level} requires one of {list(rung.require_any)} (has {sorted(have)})")
+ if rung.require_count and len(have & set(FEATURE_POOL)) < rung.require_count:
+ problems.append(f"{gp.title!r}: rung {rung.level} requires {rung.require_count} of {list(FEATURE_POOL)} (has {sorted(have)})")
+ for f in rung.forbid:
+ if f in have:
+ problems.append(f"{gp.title!r}: rung {rung.level} forbids {f!r}")
+ if rung.hero and not (gp.hero.strip() and gp.hero_motion.strip()):
+ problems.append(f"{gp.title!r}: rung {rung.level} needs a hero and its motion")
+ if rung.scale and len(gp.scale_constraints) < 2:
+ problems.append(f"{gp.title!r}: rung {rung.level} needs at least 2 scale constraints")
+ for field in ("effect", "animation", "camera", "mood", "prompt"):
+ if not getattr(gp, field).strip():
+ problems.append(f"{gp.title!r}: empty {field}")
+ return problems
+
+
+#: The contract's camera line (2026-10-15). Both scene languages render the AUTHORED cameras as stills
+#: at t = 0 and t = 1.5 s (``scene_blender.TIMES``, ``scene_threejs`` ``times``) — nothing dollies — so a
+#: brief that asked for a tracking camera was a must-have no run could satisfy: the harness planner turns
+#: every must_have line into a ``must`` acceptance item, and the judge marked it unverified in 5 of
+#: iteration 0's 60 runs ("remains stationary between t=0s and t=1.5s"), which caps the whole score
+#: (``missing_must_acceptance``). Every camera line starts with the prefix — :func:`migrate_camera_lines`
+#: recognises the form by it — and ends with the suffix.
+CAMERA_PREFIX = "camera: a FIXED eye-level camera"
+CAMERA_SUFFIX = ("; the harness renders still cameras only (nothing dollies or tracks); it never intersects any "
+ "geometry (no clipping, nothing cut by the near plane)")
+
+
+def camera_line(camera: str) -> str:
+ """The must-have line for a viewpoint brief (where it stands, what it looks along, its height)."""
+ return f"{CAMERA_PREFIX}, {camera.strip()}{CAMERA_SUFFIX}"
+
+
+def migrate_camera_lines(prompts: Sequence[BenchPrompt]) -> int:
+ """Rewrite, in place, every ``must_have`` camera line still in the old moving-camera form
+ (``camera: <route>; the camera never intersects …``) into the fixed form, keeping the route the model
+ wrote as where the viewpoint stands and looks; returns how many lines changed. Idempotent — a line
+ already in the fixed form is left alone, as is every non-camera line. The cached rung prompts keep
+ their ids (they pair iterations), so the line moves and nothing else does."""
+ n = 0
+ for p in prompts:
+ for i, line in enumerate(p.must_have):
+ if not line.startswith("camera: ") or line.startswith(CAMERA_PREFIX):
+ continue
+ route = line.removeprefix("camera: ").split(";", 1)[0].strip()
+ p.must_have[i] = (f'{CAMERA_PREFIX} standing where this route begins and looking along it — "{route}"'
+ f"{CAMERA_SUFFIX}")
+ n += 1
+ return n
+
+
+def contract_lines(gp: GeneratedPrompt) -> list[str]:
+ """The scenes_v2 composition contract rendered from the typed fields (the ``must_have`` list)."""
+ lines = [f"{len(gp.zones)} zones: {', '.join(z.strip() for z in gp.zones)}"]
+ for a in gp.asset_types:
+ line = f"at least {a.count} {a.name.strip()}"
+ if a.designs > 1:
+ line += f" using at least {a.designs} distinct designs"
+ lines.append(line)
+ lines.append(f"{gp.lighting} mood: {gp.mood.strip()} (mean luminance roughly "
+ f"{gp.luminance_low:.2f}-{gp.luminance_high:.2f}, no black or blown-out frames)")
+ lines.extend(FEATURE_LINES[f] for f in FEATURE_LINES if f in gp.features)
+ lines.append(f"effect: {gp.effect.strip()}")
+ lines.append(f"animation: {gp.animation.strip()}")
+ lines.append(camera_line(gp.camera))
+ if gp.hero.strip():
+ lines.append(f"hero: {gp.hero.strip()} — {gp.hero_motion.strip()}")
+ lines.extend(f"scale: {s.strip()}" for s in gp.scale_constraints if s.strip())
+ return lines
+
+
+def instance_total(gp: GeneratedPrompt) -> int:
+ return sum(a.count for a in gp.asset_types)
+
+
+# --------------------------------------------------------------------------- the request
+SYSTEM = (
+ "You write evaluation prompts for a procedural 3D scene generator: each prompt describes ONE place "
+ "that a coding agent must build as a multi-file scene (zones, instanced assets, lighting, one effect, "
+ "one animation, authored cameras). Prompts must be concrete, varied across categories and settings, "
+ "and buildable from primitives and a small effects library — no licensed characters, no text-heavy "
+ "signage, no real people. Answer ONLY with the JSON the schema describes."
+)
+
+
+def rung_text(rung: Rung) -> str:
+ lines = [
+ f"Rung {rung.level} ({rung.tier}): {rung.brief}.",
+ f"- at least {rung.zones} named zones, laid out so a walk-through camera passes them in order",
+ f"- at least {rung.asset_types} distinct asset types, each with an explicit instance count; the counts "
+ f"must sum to at most {rung.instances} instances in the whole scene",
+ "- lighting is one of day / dusk / night; extra features are any of interior / water / particles",
+ f"- a mean-luminance band inside {LUMINANCE_FLOOR:.2f}-{LUMINANCE_CEILING:.2f} that fits the mood "
+ f"(day ≈ 0.35-0.65, dusk ≈ 0.20-0.45, night ≈ {LUMINANCE_FLOOR:.2f}-0.35)",
+ "- exactly one effect (water surface, rain, snow, steam, dust, sparks, fog volume, a custom shader material)",
+ "- exactly one animation (a thing that visibly moves between two sampled times)",
+ "- a camera brief: ONE fixed eye-level viewpoint — where it stands, what it looks along and its height; "
+ "the scenes are rendered from still cameras only (nothing dollies or tracks), and the camera must never "
+ "intersect geometry",
+ ]
+ if rung.require_all:
+ lines.append(f"- REQUIRED features: {', '.join(rung.require_all)}")
+ if rung.require_any:
+ lines.append(f"- at least one of: {', '.join(rung.require_any)}")
+ if rung.require_count:
+ lines.append(f"- at least {rung.require_count} of: {', '.join(FEATURE_POOL)}")
+ if rung.forbid:
+ lines.append(f"- FORBIDDEN: {', '.join(rung.forbid)}")
+ if rung.hero:
+ lines.append("- name one HERO asset (the thing the scene is about) and how it moves")
+ if rung.scale:
+ lines.append("- state at least two PRECISE scale constraints in metres (a named asset's height or span)")
+ return "\n".join(lines)
+
+
+def build_request(rung: Rung, n: int, language: Language, *, label: str = "loop:generate",
+ previous_text: str = "", problems: Sequence[str] = ()) -> ChatRequest:
+ """The structured request for ``n`` prompts of ``rung``. A re-ask carries the previous answer
+ (``previous_text``, as the model wrote it) and the typed problems with it, so the model repairs
+ rather than reinvents."""
+ user = (
+ f"Write {n} distinct scene prompts for rung {rung.level}. The scenes will be built in "
+ f"{'Blender (bpy, Cycles)' if language is Language.SCENE_BLENDER else 'three.js (WebGL)'}; the prompt text "
+ "itself must stay engine-neutral.\n\n" + rung_text(rung) + "\n\n"
+ "Spread the prompts over the categories the schema lists (no category more than a quarter of them), "
+ "vary era, climate and scale, and keep every title unique. Zones are short lowercase phrases; asset "
+ "type names are plural nouns. A zone named in `zones` must be mentioned in the prompt text."
+ )
+ messages = [ChatMessage.user(user)]
+ if problems:
+ messages.append(ChatMessage.assistant(previous_text[:60_000] or "(no answer)"))
+ messages.append(ChatMessage.user(
+ "Your answer failed these checks — return the FULL corrected list (every prompt, same count), fixing "
+ "only what the checks name:\n- " + "\n- ".join(problems)))
+ return ChatRequest(messages=messages, system=SYSTEM, response_schema=GeneratedBattery.model_json_schema(),
+ temperature=0.9, thinking="medium", max_output_tokens=65_536, max_wait_s=900.0, label=label)
+
+
+def parse_battery(text: str, parsed: Any = None) -> tuple[GeneratedBattery | None, list[str]]:
+ """``(battery, problems)``: the model's answer validated against the schema; a parse or validation
+ failure is a problem the re-ask states, not an exception."""
+ try:
+ payload = parsed if parsed is not None else parse_json_lenient(text)
+ return GeneratedBattery.model_validate(payload), []
+ except (JsonParseError, ValidationError, TypeError) as e:
+ return None, [f"the answer did not match the schema: {str(e)[:600]}"]
+
+
+def check_battery(battery: GeneratedBattery, rung: Rung, n: int) -> list[str]:
+ """Every problem across the battery: the rung rules per prompt, the count, duplicate titles."""
+ problems: list[str] = []
+ if len(battery.prompts) < n:
+ problems.append(f"{len(battery.prompts)} prompts returned, {n} needed")
+ titles = [p.title.strip().lower() for p in battery.prompts]
+ if len(set(titles)) != len(titles):
+ problems.append("duplicate titles")
+ for gp in battery.prompts:
+ problems.extend(check_prompt(gp, rung))
+ return problems
+
+
+# --------------------------------------------------------------------------- the mix
+def mix_counts(top: int, n: int) -> dict[int, int]:
+ """How many prompts of each rung 1..``top`` an ``n``-prompt battery takes: an even split, the
+ remainder to the HARDEST rungs — so a battery at rung 2 keeps half of rung 1's ids (the pairs
+ ``compare`` needs against the previous iteration) and the other half moves up."""
+ if top < 1 or top > max(RUNGS):
+ raise ValueError(f"rung must be 1..{max(RUNGS)}, got {top}")
+ base, rem = divmod(n, top)
+ return {r: base + (1 if r > top - rem else 0) for r in range(1, top + 1)}
+
+
+__all__ = ["FEATURE_POOL", "RUNGS", "AssetCount", "GeneratedBattery", "GeneratedPrompt", "Rung",
+ "build_request", "camera_line", "check_battery", "check_prompt", "contract_lines", "instance_total",
+ "migrate_camera_lines", "mix_counts", "parse_battery", "rung_text"]
diff --git a/eval/bench/data/loop/README.md b/eval/bench/data/loop/README.md
new file mode 100644
index 00000000..8faaa9e8
--- /dev/null
+++ b/eval/bench/data/loop/README.md
@@ -0,0 +1,39 @@
+# `bench/data/loop/<name>/ledger.jsonl` — the decisions of a tuning loop
+
+One directory per loop (`bench.loop init --name <name>`), one append-only journal of every
+`accept` / `rollback` the loop recorded (`python -m bench.loop accept|rollback --out … --iter N`).
+It lives in the repo, not under the ignored `bench/out/`, because an accepted variant version is a
+claim about the prompts (`codeverse3d/prompts/variants/<v>/variant.toml` `version`), and a claim
+whose evidence is not in the tree is not reproducible. The runs themselves stay under
+`bench/out/<loop>/iter_NN/` (big, never committed); the row names what was measured and on what.
+
+Written through `bench/_jsonl.seal_for_append` (a SIGKILL mid-append costs one row, never the file)
+and read back as `bench.loop.LedgerRow`, one JSON object per line:
+
+| field | meaning |
+|---|---|
+| `ts` | ISO-8601 UTC, when the decision was recorded |
+| `iteration` | the `iter_NN` the decision is about |
+| `languages` | the loop's languages (`scene_threejs`, `scene_blender`) |
+| `variant` | the variant name (`argon`) |
+| `version_from` → `version_to` | `variant.toml` version before and after: an `accept` bumps it by one; a `rollback` keeps it (working edits discarded) or, when the iteration was itself the latest accept, returns to `version_from` of that accept |
+| `variant_hash` | the overlay fingerprint after the decision: `prompts.variants.variant_hash` — the number every run record of the iteration carries (`extra.variant.hash`, `SettingsSnapshot.variant_hash`; `README.md` is left out of it, so a README edit never moves it) — and the same `hash` the snapshot's `snapshot.json` records, so a snapshot pairs with the runs it was measured on. Only an overlay the variant layer does not know (a tmp tree in the tests) falls back to the loop's own sha256[:12] over every file |
+| `battery_sha` | sha256[:12] over the iteration's `battery_*.yaml` files — the prompts the verdict was measured on |
+| `verdicts` | language → `keep` / `revert` / `inconclusive` from `compare_<lang>.json` (empty when the iteration was never compared: iteration 0, or an accept on diagnosis alone) |
+| `decision` | `accept` or `rollback` |
+| `cost_usd` | the iteration's spend, summed over its `results.jsonl` rows |
+| `tree_commit`, `tree_dirty` | the harness checkout the iteration ran on (`git rev-parse HEAD`; dirty = tracked files modified under `harness/`) |
+| `note` | `--note …`, free text: what the iteration changed |
+
+The verdict rule behind `verdicts` is `bench/stats.decide` on the paired picked scores plus the
+deterministic-gate veto (`bench/_loop_diag.VETO_RISE`: floating + sunken + interpenetration ERRORs per
+run must not rise by more than one on average) — `eval/docs/EVAL.md` §10. The snapshot each accept
+takes (`bench/out/<loop>/snapshots/<v>_v<N>/`) is what a later `rollback` restores; `init` snapshots
+the version it found so the first rollback has somewhere to go.
+
+Before `accept` (and `init`) bump, snapshot or write anything, the skills overlay is PREFLIGHTED:
+`routes.toml` must type-check (`codeverse3d.skills.parse_routes`, the parser `variants_table` runs on
+it) and every bundle directory must pass `codeverse3d.skills.validate_bundle`. A run never refuses a
+broken overlay — a table that does not type-check is logged and the BASE table routes, an invalid
+bundle is skipped — so an iteration whose overlay carries a typo measures nothing about the variant;
+the loop is the one place that says no, and a row only ever records an overlay that would route.
diff --git a/eval/bench/h2h_glb.py b/eval/bench/h2h_glb.py
deleted file mode 100644
index a52f0910..00000000
--- a/eval/bench/h2h_glb.py
+++ /dev/null
@@ -1,294 +0,0 @@
-"""Objects head-to-head: this harness vs the astra3d-brilliana curated gallery.
-
-Protocol (one fixed judge, one renderer, one gate set, for BOTH sides):
-
-1. A battery ``bench/prompts/h2h_brilliana_v1_<lang>.yaml`` carries THEIR prompts
- verbatim with an empty ``must_have`` (their run had no checklist, so ours gets none);
- each prompt's last tag is the gallery slug.
-2. THEIR GLB is ``<gallery>/<slug>/object.glb`` (built by their harness, never
- rebuilt here). OUR GLB is the round ``codeverse3d.addons.select`` picks from the
- harness run under ``<bench_out>/<lang>/runs/<id>/``: that round's own GLB
- (``select.round_file`` — ``artifacts/rNN/object.glb``, or ``artifacts/object.glb`` of a run
- recorded before rounds kept their own, only for the round it rebuilt there); a picked round
- with none is an error, never the last build's GLB in its place.
-3. Both GLBs go through the object path of ``bench/_fixed_eval.FixedEvaluator``:
- ``glb_evidence`` (measure, connectivity in the prompt's language frame, 14-view render,
- clay views) → ``fixed_input`` (the harness's ``round_input``: clay montage + the GLB for the
- D48 slice channel) → ``VlmJudge(static_object_v1, gemini-3.1-pro-preview, n_samples=2)``
- with a ``Spec`` built from the prompt, so an EMPTY acceptance list. No build step: their
- side has no workspace to build from. Every judged side is cached as
- ``<out>/eval/<id>/<side>.json`` so a re-run never re-buys a verdict.
-4. Outputs: ``<out>/h2h.jsonl`` (one row per prompt), ``<out>/pairs/<id>.png``
- (their sheet | our sheet) and ``<out>/h2h_summary.md`` (paired mean delta, sd,
- exact two-sided sign test, per-language rows). The gallery's own score is kept
- in the row for reference only — it came from a different judge and is never
- compared with ours.
-
-Usage::
-
- python bench/h2h_glb.py bench/prompts/h2h_brilliana_v1_{blender,cadquery,threejs}.yaml \
- --gallery /home/yipeng/projects/astra3d-brilliana/gallery --bench-out bench/out/h2h_brilliana_v1
- python bench/h2h_glb.py <battery.yaml> --theirs-only --id h2h_c_clamp_mv # prove the judge path
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import statistics
-import sys
-from pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel, Field
-
-for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
- sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
-
-from bench._fixed_eval import RUBRIC, fixed_input, glb_evidence # noqa: E402
-from bench.run_bench import Battery, BenchPrompt # noqa: E402
-from bench.stats import sign_test # noqa: E402
-from codeverse3d.addons import select # noqa: E402
-from codeverse3d.proc import write_text_atomic # noqa: E402
-from codeverse3d.record.record import load_record # noqa: E402
-from codeverse3d.workspace import Workspace # noqa: E402
-
-JUDGE_MODEL = "gemini:gemini-3.1-pro-preview"
-N_SAMPLES = 2
-IN_PROGRESS = {"planning", "generating", "refining"} # RunStatus values of a run that has not stopped
-_H2H_TAGS = {"h2h", "brilliana"}
-PAYLOAD = "round_input" # the judge input a cached verdict was bought on (hand-built before 2026-09-24, N83)
-
-
-class Side(BaseModel):
- """One judged GLB (theirs or ours) — everything the row needs, nothing more."""
-
- source: str
- glb: str = ""
- score: float | None = None
- score_std: float = 0.0
- visual_score: float | None = None # the same judge with NO gate findings in its context: perception only
- passed: bool | None = None
- gate_errors: list[str] = Field(default_factory=list)
- floating_parts: int = 0
- tris: int | None = None
- parts: int | None = None
- ground_gap_m: float | None = None
- sheet: str = ""
- summary: str = ""
- error: str = ""
- rounds: int | None = None # harness side only
- cost_usd: float | None = None
- minutes: float | None = None
- status: str = ""
- gallery_score: float | None = None # their own judge; reference only
- payload: str = "" # PAYLOAD once judged on fixed_input; a cached verdict without it predates N83
-
-
-class Row(BaseModel):
- id: str
- slug: str
- language: str
- prompt: str
- theirs: Side
- ours: Side
- delta: float | None = None
- delta_visual: float | None = None
- side_by_side: str = ""
-
-
-# ----------------------------------------------------------------------------- locate
-def slug_of(item: BenchPrompt) -> str:
- slugs = [t for t in item.tags if t not in _H2H_TAGS]
- if not slugs:
- raise ValueError(f"{item.id}: no gallery slug tag")
- return slugs[-1]
-
-
-def their_side(gallery: Path, slug: str) -> Side:
- meta = json.loads((gallery / slug / "meta.json").read_text())
- glb = gallery / slug / "object.glb"
- return Side(source="brilliana", glb=str(glb), gallery_score=meta.get("score"),
- error="" if glb.is_file() else f"missing {glb}")
-
-
-def our_side(runs_dir: Path, item_id: str) -> Side:
- ws = runs_dir / item_id
- if not (ws / "record.json").is_file():
- return Side(source="3dcodeverse", status="not_run", error=f"no record.json under {ws}")
- try: # read once: the round addons/select picks
- rec = load_record(ws)
- picked = select.summarise(ws, record=rec).picked_round
- except Exception as e: # noqa: BLE001 - one unreadable record must not kill the battery
- return Side(source="3dcodeverse", error=f"unreadable record: {e}")
- status = rec.status.value
- side = Side(source="3dcodeverse", status=status, rounds=len(rec.rounds), cost_usd=rec.total_usage.cost_usd,
- minutes=round(rec.minutes or 0.0, 2))
- if status in IN_PROGRESS:
- side.error = f"run not finished (status={status!r})"
- elif picked is None:
- side.error = f"no judged round to hand over (status={status!r})"
- elif (glb := select.round_file(Workspace(ws), next(r for r in rec.rounds if r.index == picked))) is None:
- side.error = f"round {picked} kept no object.glb under {ws}" # never the last build's canonical one
- else:
- side.glb = str(glb)
- return side
-
-
-# ----------------------------------------------------------------------------- evaluate
-def build_spec(battery: Battery, item: BenchPrompt) -> Any:
- from codeverse3d.contracts.spec import Spec
-
- return Spec(id=f"h2h/{item.id}", track=battery.track, language=item.language or battery.language,
- prompt=item.prompt, tags=["h2h", *item.tags])
-
-
-def evaluate(side: Side, spec: Any, out_dir: Path, judge: Any) -> Side:
- """``glb_evidence`` → ``fixed_input`` → judge: the FixedEvaluator's object path, on a GLB with no workspace."""
- from codeverse3d.config import get_settings
-
- if side.error or not side.glb:
- return side
- try:
- m, gate, renders, clay = glb_evidence(Path(side.glb), out_dir / "renders", spec.language, get_settings())
- side.tris, side.parts, side.ground_gap_m = m.tri_count, m.n_meshes, round(m.ground_gap_m, 4)
- side.gate_errors = [f"{gate.gate}: {f.message}" for f in gate.errors]
- side.floating_parts = sum("is floating" in f.message for f in gate.errors)
- side.sheet, side.payload = renders.contact_sheet or "", PAYLOAD
- inp = fixed_input(spec, renders=renders, gates=[gate], measurement=m, geometry_views=clay, glb_path=side.glb)
- j = judge.judge(inp)
- side.score, side.score_std, side.passed, side.summary = j.overall, j.score_std, j.passed, j.summary
- (out_dir / "judgment.json").write_text(j.model_dump_json(indent=2))
- # Perception only: the gallery GLBs are merged, un-welded exports whose "floating"
- # findings are export artefacts as often as defects (a microscope whose stage
- # sits 22 mm from its arm in the mesh but looks attached), so a judge that reads
- # the gate text in its context caps them for what the eye cannot see. The
- # visual number is the fair headline; the gated one is what the harness would say.
- jv = judge.judge(inp.model_copy(update={"gates": []}))
- side.visual_score = jv.overall
- (out_dir / "judgment_visual.json").write_text(jv.model_dump_json(indent=2))
- except Exception as e: # noqa: BLE001 — one bad GLB must not kill the battery
- side.error = f"{type(e).__name__}: {e}"
- return side
-
-
-def cached_eval(side: Side, spec: Any, out_dir: Path, judge: Any, *, force: bool) -> Side:
- cache = out_dir / f"{side.source}.json"
- if cache.is_file() and not force:
- prev = Side.model_validate_json(cache.read_text())
- if prev.score is not None and prev.visual_score is not None and prev.glb == side.glb and prev.payload == PAYLOAD:
- return prev.model_copy(update={k: getattr(side, k) for k in ("rounds", "cost_usd", "minutes", "status")})
- out_dir.mkdir(parents=True, exist_ok=True)
- side = evaluate(side, spec, out_dir, judge)
- write_text_atomic(cache, side.model_dump_json(indent=2))
- return side
-
-
-def side_by_side(theirs: Side, ours: Side, dst: Path, slug: str) -> str:
- from PIL import Image, ImageDraw
-
- tiles = [(f"THEIRS brilliana/{slug}", theirs.sheet, theirs.score), (f"OURS 3dcodeverse/{slug}", ours.sheet, ours.score)]
- imgs = [Image.open(p).convert("RGB") if p and Path(p).is_file() else Image.new("RGB", (768, 768), (40, 40, 40)) for _, p, _ in tiles]
- h = min(i.height for i in imgs)
- imgs = [i.resize((int(i.width * h / i.height), h)) for i in imgs]
- band, gap = 36, 12
- canvas = Image.new("RGB", (sum(i.width for i in imgs) + gap, h + band), (20, 20, 20))
- draw, x = ImageDraw.Draw(canvas), 0
- for (label, _, score), im in zip(tiles, imgs, strict=True):
- canvas.paste(im, (x, band))
- draw.text((x + 8, 10), f"{label} score={score if score is None else f'{score:.3f}'}", fill=(255, 255, 255))
- x += im.width + gap
- dst.parent.mkdir(parents=True, exist_ok=True)
- canvas.save(dst)
- return str(dst)
-
-
-# ----------------------------------------------------------------------------- stats
-def _stats(rows: list[Row], *, visual: bool = False) -> str:
- d = [(r.delta_visual if visual else r.delta) for r in rows if (r.delta_visual if visual else r.delta) is not None]
- if not d:
- return "n=0 (no pair judged on both sides)"
- sd = statistics.stdev(d) if len(d) > 1 else 0.0
- wins, losses, p = sign_test(d)
- return (f"n={len(d)} mean Δ(ours−theirs)={statistics.mean(d):+.3f} sd={sd:.3f} "
- f"wins/losses/ties={wins}/{losses}/{len(d) - wins - losses} sign-test p={'n/a' if p is None else f'{p:.3f}'}")
-
-
-def summary_md(rows: list[Row]) -> str:
- out = ["# Objects head-to-head: 3dcodeverse vs astra3d-brilliana gallery", "",
- f"Judge: `{JUDGE_MODEL}` × {N_SAMPLES} samples, rubric `{RUBRIC}`, empty acceptance list, "
- "same renderer / views / connectivity gate on both GLBs.", "",
- f"**All languages, visual only (no gate text in the judge's context — the fair headline)**: {_stats(rows, visual=True)}",
- f"**All languages, gated (what the harness itself would say)**: {_stats(rows)}", ""]
- for lang in sorted({r.language for r in rows}):
- out.append(f"- **{lang}** visual: {_stats([r for r in rows if r.language == lang], visual=True)} · gated: {_stats([r for r in rows if r.language == lang])}")
- out += ["", "| id | lang | theirs visual | ours visual | Δ visual | theirs gated | ours gated | Δ gated | theirs gate errs / floating | ours gate errs / floating | ours rounds / $ / min | their gallery score (ref only) |",
- "|---|---|---|---|---|---|---|---|---|---|---|---|"]
- fmt = lambda v: "—" if v is None else f"{v:.3f}" # noqa: E731
- for r in rows:
- t, o = r.theirs, r.ours
- out.append(f"| {r.id} | {r.language} | {fmt(t.visual_score)} | {fmt(o.visual_score)} | {'—' if r.delta_visual is None else f'{r.delta_visual:+.3f}'} "
- f"| {fmt(t.score)} | {fmt(o.score)} | {'—' if r.delta is None else f'{r.delta:+.3f}'} "
- f"| {len(t.gate_errors)} / {t.floating_parts} | {len(o.gate_errors)} / {o.floating_parts} "
- f"| {o.rounds or '—'} / {'—' if o.cost_usd is None else f'{o.cost_usd:.2f}'} / {'—' if o.minutes is None else f'{o.minutes:.0f}'} "
- f"| {fmt(t.gallery_score)} |")
- errs = [f"- {r.id} {s.source}: {s.error}" for r in rows for s in (r.theirs, r.ours) if s.error]
- if errs:
- out += ["", "## Unjudged sides", *errs]
- return "\n".join(out) + "\n"
-
-
-# ----------------------------------------------------------------------------- main
-def run(batteries: list[Path], gallery: Path, bench_out: Path, out: Path, *, ids: set[str], theirs_only: bool, force: bool) -> list[Row]:
- from codeverse3d.cost import run_ledger
- from codeverse3d.judges.vlm_judge import VlmJudge
-
- judge = VlmJudge(rubric=RUBRIC, model_id=JUDGE_MODEL, n_samples=N_SAMPLES)
- rows: list[Row] = []
- out.mkdir(parents=True, exist_ok=True)
- with run_ledger(out, run="h2h_brilliana_v1"):
- for bpath in batteries:
- battery = Battery.load(bpath)
- runs_dir = bench_out / str(battery.language) / "runs"
- for item in battery.prompts:
- if ids and item.id not in ids:
- continue
- slug, spec, edir = slug_of(item), build_spec(battery, item), out / "eval" / item.id
- theirs = cached_eval(their_side(gallery, slug), spec, edir / "theirs", judge, force=force)
- ours = Side(source="3dcodeverse", status="skipped") if theirs_only else \
- cached_eval(our_side(runs_dir, item.id), spec, edir / "ours", judge, force=force)
- row = Row(id=item.id, slug=slug, language=str(spec.language), prompt=item.prompt, theirs=theirs, ours=ours)
- if theirs.score is not None and ours.score is not None:
- row.delta = round(ours.score - theirs.score, 4)
- if ours.visual_score is not None and theirs.visual_score is not None:
- row.delta_visual = round(ours.visual_score - theirs.visual_score, 4)
- if theirs.sheet or ours.sheet:
- row.side_by_side = side_by_side(theirs, ours, out / "pairs" / f"{item.id}.png", slug)
- rows.append(row)
- print(f"{item.id:<24} theirs={theirs.score} ours={ours.score} Δ={row.delta} "
- f"gates t/o={len(theirs.gate_errors)}/{len(ours.gate_errors)} {theirs.error or ours.error}")
- with (out / "h2h.jsonl").open("w") as fh:
- for r in rows:
- fh.write(r.model_dump_json() + "\n")
- (out / "h2h_summary.md").write_text(summary_md(rows))
- print(summary_md(rows))
- return rows
-
-
-def main() -> None:
- here = Path(__file__).resolve().parent
- ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0])
- ap.add_argument("batteries", nargs="+", type=Path)
- ap.add_argument("--gallery", type=Path, default=Path("/home/yipeng/projects/astra3d-brilliana/gallery"))
- ap.add_argument("--bench-out", type=Path, default=here / "out" / "h2h_brilliana_v1",
- help="root holding <lang>/runs/<id>/ (one `python -m bench.run_bench --out <root>/<lang>` per battery)")
- ap.add_argument("--out", type=Path, default=None, help="where h2h.jsonl / pairs/ / h2h_summary.md go (default: --bench-out)")
- ap.add_argument("--id", action="append", default=[], help="only these prompt ids")
- ap.add_argument("--theirs-only", action="store_true", help="judge only the gallery GLBs (proof of the judge path)")
- ap.add_argument("--force", action="store_true", help="ignore cached verdicts under <out>/eval/")
- a = ap.parse_args()
- run(a.batteries, a.gallery, a.bench_out, a.out or a.bench_out, ids=set(a.id), theirs_only=a.theirs_only, force=a.force)
-
-
-if __name__ == "__main__":
- main()
diff --git a/eval/bench/h2h_scene.py b/eval/bench/h2h_scene.py
deleted file mode 100644
index 45b9f763..00000000
--- a/eval/bench/h2h_scene.py
+++ /dev/null
@@ -1,278 +0,0 @@
-"""Head-to-head SCENE judge: this harness's ``scene`` track vs the owner's previous
-harnesses (scene_multifile / scene_multifile_graphics), one fixed judge for both sides.
-
-Protocol
---------
-* Prompts: ``bench/prompts/h2h_scene_v1.yaml`` — each prompt is the other harness's
- ``outputs/<name>/prompts/input.md`` verbatim, ``must_have`` empty (no checklist either
- side never saw). Tags ``[h2h, <source_repo>, <name>]`` bind a row to its origin.
-* THEIRS: the delivered renders at ``app/artifacts/best_parts/_assembly/object_render/``
- — authored cameras (``view_cam_*``) first, then the overview rig (``view_overview_*``),
- capped at ``MAX_VIEWS``; zone/probe frames are never shown. Their own judge score,
- wall time and cost come from ``run_report.json`` / ``trajectories/*/score.json``.
-* OURS: the round ``codeverse3d.addons.select`` picks from ``bench/out/h2h_scene_v1/runs/<id>/``
- (``rounds/rNN.json`` renders): the ``t=0`` views the scene judge saw (per-view ``judge``
- flag, authored cameras first), capped at ``MAX_VIEWS`` — stills only, so both sides are
- judged blind to animation in the same way.
-* Judge: ONE ``VlmJudge(rubric=scene_v1, gemini-3.1-pro-preview, n_samples=2)`` fed a
- ``JudgeInput(spec, RenderSet)`` with no gates, no measurement, no acceptance items and
- the same ``extra_context`` for both sides. Verdicts are cached per (id, side) under
- ``out/judge/`` so re-runs never re-pay.
-* Output: ``h2h.jsonl`` (one row per prompt), ``sheets/<id>.png`` (their strip over our
- strip), ``h2h_summary.md`` (paired delta mean/sd, exact sign test, time + cost).
-
-Usage: ``python bench/h2h_scene.py [--ids a,b] [--theirs-only] [--n-samples 2]``
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import statistics
-import sys
-from pathlib import Path
-from typing import Any
-
-from PIL import Image, ImageDraw
-from pydantic import BaseModel
-
-for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
- sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
-
-from bench.run_bench import Battery, BenchPrompt # noqa: E402
-from bench.stats import sign_test # noqa: E402
-from codeverse3d.addons import select # noqa: E402
-from codeverse3d.contracts.artifacts import RenderSet, RenderView # noqa: E402
-from codeverse3d.contracts.common import Language, Track # noqa: E402
-from codeverse3d.contracts.spec import Spec # noqa: E402
-from codeverse3d.proc import write_text_atomic # noqa: E402
-from codeverse3d.record.record import load_record # noqa: E402
-
-HERE = Path(__file__).resolve().parent
-BATTERY = HERE / "prompts" / "h2h_scene_v1.yaml"
-OUT = HERE / "out" / "h2h_scene_v1"
-REPOS = {"scene_multifile": Path("/home/yipeng/projects/scene_multifile"),
- "scene_multifile_graphics": Path("/home/yipeng/projects/scene_multifile_graphics")}
-THEIR_RENDERS = Path("app/artifacts/best_parts/_assembly/object_render")
-JUDGE_MODEL = "gemini:gemini-3.1-pro-preview"
-RUBRIC = "scene_v1"
-MAX_VIEWS = 10
-OVERVIEW_ORDER = ("overview_front_right", "overview_back_left", "overview_top", "overview_front", "overview_right", "overview_back", "overview_left")
-EXTRA_CONTEXT = ("STILLS ONLY: every view is a single frame at one time and NO motion measurement exists for this "
- "evaluation — answer nothing_moves=false and grade animation_life only from visible motion cues "
- "(wakes, particles, blur). The same rule applies to every scene in this comparison.")
-
-
-# ----------------------------------------------------------------------------- rows
-class TheirSide(BaseModel):
- score: float
- score_uncapped: float | None = None
- defect_penalty: float = 0.0
- their_own_score: float | None = None
- their_final_score: float | None = None
- duration_s: float = 0.0
- cost_usd: float = 0.0
- n_views: int = 0
- views: list[str] = []
-
-
-class OurSide(BaseModel):
- score: float
- score_uncapped: float | None = None
- defect_penalty: float = 0.0
- harness_score: float | None = None
- rounds: int = 0
- picked_round: int = 0
- cost_usd: float = 0.0
- minutes: float = 0.0
- n_views: int = 0
- status: str = ""
- views: list[str] = []
-
-
-class Row(BaseModel):
- id: str
- source_repo: str
- name: str
- theirs: TheirSide
- ours: OurSide | None = None
- delta: float | None = None
-
-
-def origin(item: BenchPrompt) -> tuple[str, str]:
- repo = next(t for t in item.tags if t in REPOS)
- return repo, item.tags[-1]
-
-
-# ----------------------------------------------------------------------------- theirs
-def their_frames(out_dir: Path) -> list[Path]:
- """Authored cameras first (sorted), then the overview rig in a fixed order; cap MAX_VIEWS."""
- rdir = out_dir / THEIR_RENDERS
- cams = sorted(rdir.glob("view_cam_*.png"))
- over = {p.stem[len("view_"):]: p for p in rdir.glob("view_overview_*.png")}
- ordered = [over[n] for n in OVERVIEW_ORDER if n in over] + [p for n, p in sorted(over.items()) if n not in OVERVIEW_ORDER]
- return (cams + ordered)[:MAX_VIEWS]
-
-
-def their_meta(out_dir: Path) -> dict[str, Any]:
- rep = json.loads((out_dir / "run_report.json").read_text())
- cost = rep.get("cost") or {}
- scores: list[tuple[int, float]] = []
- for f in sorted(out_dir.glob("trajectories/09_tool_judge_iter*/score.json")):
- s = json.loads(f.read_text()).get("overall_score")
- if isinstance(s, (int, float)):
- scores.append((int(f.parent.name.rsplit("iter", 1)[1]), float(s)))
- scores.sort()
- return {"duration_s": float(rep.get("duration_s") or 0.0),
- "cost_usd": float(cost.get("total_usd_all_iters") or cost.get("total_usd_last_iter") or 0.0),
- "their_own_score": max((s for _, s in scores), default=None), # best_snapshot ships the best round
- "their_final_score": scores[-1][1] if scores else None}
-
-
-# ----------------------------------------------------------------------------- ours
-def our_frames(run_dir: Path) -> tuple[list[RenderView], dict[str, Any]] | None:
- try: # read once: the round addons/select picks
- rec = load_record(run_dir)
- summary = select.summarise(run_dir, record=rec)
- except Exception: # noqa: BLE001 - a missing or unreadable record is a run we cannot compare
- return None
- picked = summary.picked_round if summary.picked_round is not None else 0
- rnd = next((r for r in rec.rounds if r.index == picked), None)
- if rnd is None or rnd.renders is None:
- return None
- stills = [v for v in rnd.renders.views if (v.time_s or 0.0) == 0.0 and v.mode == "shaded" and Path(v.path).is_file()]
- flagged = [v for v in stills if v.judge] or stills
- chosen = flagged[:MAX_VIEWS]
- meta = {"harness_score": summary.picked_score, "rounds": len(rec.rounds), "picked_round": picked,
- "cost_usd": rec.total_usage.cost_usd, "minutes": round(rec.minutes or 0.0, 2), "status": summary.stop_reason}
- return [RenderView(name=v.name, path=v.path, mode="shaded", width=v.width, height=v.height) for v in chosen], meta
-
-
-# ----------------------------------------------------------------------------- judge
-def render_set(views: list[RenderView]) -> RenderSet:
- return RenderSet(views=views, renderer="h2h_stills")
-
-
-def views_from_paths(paths: list[Path]) -> list[RenderView]:
- return [RenderView(name=p.stem[len("view_"):] if p.stem.startswith("view_") else p.stem, path=str(p), mode="shaded") for p in paths]
-
-
-def spec_for(item: BenchPrompt) -> Spec:
- return Spec(id=f"h2h_scene_v1/{item.id}", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt=item.prompt, tags=list(item.tags))
-
-
-def judge_side(judge: Any, spec: Spec, views: list[RenderView], cache: Path) -> dict[str, Any]:
- """One fixed-judge verdict, cached as JSON (re-runs never re-pay)."""
- from codeverse3d.judges.base import JudgeInput
-
- if cache.is_file():
- return json.loads(cache.read_text())
- inp = JudgeInput(spec=spec, renders=render_set(views), gates=[], acceptance=[], round_index=0, extra_context=EXTRA_CONTEXT)
- j = judge.judge(inp)
- cache.parent.mkdir(parents=True, exist_ok=True)
- write_text_atomic(cache, j.model_dump_json(indent=1))
- return json.loads(cache.read_text())
-
-
-def uncapped(verdict: dict[str, Any]) -> dict[str, Any]:
- """The weighted mean BEFORE defect penalties/caps (scene_v1 penalties can floor a bad scene at 0)."""
- raw = json.loads(verdict.get("raw") or "{}")
- return {"score_uncapped": raw.get("overall_uncapped"), "defect_penalty": float(raw.get("defect_penalty") or 0.0)}
-
-
-# ----------------------------------------------------------------------------- sheet
-def sheet(row_id: str, theirs: list[Path], ours: list[Path], out_png: Path, thumb_h: int = 180) -> None:
- def strip(paths: list[Path], label: str) -> Image.Image:
- thumbs = []
- for p in paths:
- with Image.open(p) as im:
- im = im.convert("RGB")
- thumbs.append(im.resize((max(1, int(im.width * thumb_h / im.height)), thumb_h)))
- w = sum(t.width for t in thumbs) + 4 * max(1, len(thumbs) - 1) if thumbs else 400
- canvas = Image.new("RGB", (w, thumb_h + 22), (20, 20, 20))
- ImageDraw.Draw(canvas).text((4, 4), label, fill=(255, 255, 255))
- x = 0
- for t, p in zip(thumbs, paths, strict=True):
- canvas.paste(t, (x, 22))
- ImageDraw.Draw(canvas).text((x + 3, 24), p.stem[:34], fill=(255, 255, 0))
- x += t.width + 4
- return canvas
-
- a, b = strip(theirs, f"{row_id} — THEIRS (authored cams + overview)"), strip(ours, f"{row_id} — OURS (picked round, t=0 judge views)")
- out = Image.new("RGB", (max(a.width, b.width), a.height + b.height + 6), (60, 60, 60))
- out.paste(a, (0, 0))
- out.paste(b, (0, a.height + 6))
- out_png.parent.mkdir(parents=True, exist_ok=True)
- out.save(out_png)
-
-
-# ----------------------------------------------------------------------------- summary
-def summary_md(rows: list[Row]) -> str:
- done = [r for r in rows if r.ours is not None and r.delta is not None]
- lines = ["# h2h_scene_v1 — scene track vs scene_multifile(_graphics)", "",
- f"Fixed judge: `{JUDGE_MODEL}` rubric `{RUBRIC}` n=2, stills only, no gates, no acceptance items; "
- f"≤ {MAX_VIEWS} views per side (theirs: view_cam_* then view_overview_*; ours: best-round t=0 judge views).", "",
- "| id | repo | theirs (fixed) | uncapped | their own | ours (fixed) | uncapped | harness | Δ ours−theirs | their min / $ | our min / $ | views t/o |",
- "|---|---|---|---|---|---|---|---|---|---|---|---|"]
- for r in rows:
- t, o = r.theirs, r.ours
- lines.append(f"| {r.id} | {r.source_repo} | {t.score:.3f} | {t.score_uncapped} | {t.their_own_score if t.their_own_score is not None else '—'} | "
- f"{f'{o.score:.3f}' if o else 'pending'} | {o.score_uncapped if o else '—'} | {o.harness_score if o else '—'} | {f'{r.delta:+.3f}' if r.delta is not None else '—'} | "
- f"{t.duration_s / 60:.1f} / {t.cost_usd:.2f} | {f'{o.minutes:.1f} / {o.cost_usd:.2f}' if o else '—'} | {t.n_views}/{o.n_views if o else 0} |")
- if done:
- d = [r.delta for r in done if r.delta is not None]
- up, down, p = sign_test(d)
- sd = statistics.stdev(d) if len(d) > 1 else 0.0
- lines += ["", f"**Paired (n={len(d)})**: mean Δ = {statistics.mean(d):+.3f}, sd = {sd:.3f}, "
- f"sign test: ours better on {up}/{up + down} (two-sided p = {'n/a' if p is None else f'{p:.3f}'}).",
- f"Mean minutes/scene: theirs {statistics.mean(r.theirs.duration_s for r in done) / 60:.1f}, ours {statistics.mean(r.ours.minutes for r in done if r.ours):.1f}; "
- f"mean $/scene: theirs {statistics.mean(r.theirs.cost_usd for r in done):.2f}, ours {statistics.mean(r.ours.cost_usd for r in done if r.ours):.2f}."]
- else:
- lines += ["", "No completed OUR runs yet — theirs judged only."]
- return "\n".join(lines) + "\n"
-
-
-# ----------------------------------------------------------------------------- main
-def main() -> None:
- ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
- ap.add_argument("--ids", default="", help="comma list of prompt ids (default all)")
- ap.add_argument("--theirs-only", action="store_true", help="judge only their side (proof mode)")
- ap.add_argument("--n-samples", type=int, default=2)
- ap.add_argument("--out", type=Path, default=OUT)
- ns = ap.parse_args()
- from codeverse3d.judges.vlm_judge import VlmJudge
-
- judge = VlmJudge(rubric=RUBRIC, model_id=JUDGE_MODEL, n_samples=ns.n_samples, label="h2h")
- battery = Battery.load(BATTERY)
- want = {s for s in ns.ids.split(",") if s}
- rows: list[Row] = []
- for item in battery.prompts:
- if want and item.id not in want:
- continue
- repo, name = origin(item)
- out_dir = REPOS[repo] / "outputs" / name
- spec = spec_for(item)
- tf = their_frames(out_dir)
- tj = judge_side(judge, spec, views_from_paths(tf), ns.out / "judge" / f"{item.id}_theirs.json")
- theirs = TheirSide(score=tj["overall"], n_views=len(tf), views=[p.name for p in tf], **uncapped(tj), **their_meta(out_dir))
- ours: OurSide | None = None
- of: list[Path] = []
- got = None if ns.theirs_only else our_frames(ns.out / "runs" / item.id)
- if got is not None:
- views, meta = got
- oj = judge_side(judge, spec, views, ns.out / "judge" / f"{item.id}_ours.json")
- ours = OurSide(score=oj["overall"], n_views=len(views), views=[v.name for v in views], **uncapped(oj), **meta)
- of = [Path(v.path) for v in views]
- row = Row(id=item.id, source_repo=repo, name=name, theirs=theirs, ours=ours,
- delta=round(ours.score - theirs.score, 4) if ours else None)
- rows.append(row)
- sheet(item.id, tf, of, ns.out / "sheets" / f"{item.id}.png")
- print(f"{item.id}: theirs {theirs.score:.3f} (own {theirs.their_own_score}) | ours {ours.score if ours else 'pending'} | Δ {row.delta}")
- ns.out.mkdir(parents=True, exist_ok=True)
- (ns.out / "h2h.jsonl").write_text("".join(r.model_dump_json() + "\n" for r in rows))
- (ns.out / "h2h_summary.md").write_text(summary_md(rows))
- print(summary_md(rows))
-
-
-if __name__ == "__main__":
- main()
diff --git a/eval/bench/loop.py b/eval/bench/loop.py
new file mode 100644
index 00000000..fd30e1c5
--- /dev/null
+++ b/eval/bench/loop.py
@@ -0,0 +1,993 @@
+"""The argon scene-tuning loop: generate → run → diagnose → compare → judge-calib → accept / rollback.
+
+ cd eval
+ python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon \\
+ --languages scene_threejs,scene_blender --generator agy:gemini-4-argon \\
+ --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 --rounds 2 --max-minutes 90
+ python -m bench.loop generate --out bench/out/loop_argon --iter 0 [--n 30] [--rung 1]
+ python -m bench.loop run --out bench/out/loop_argon --iter 0 [--languages scene_threejs] [--resume]
+ python -m bench.loop diagnose --out bench/out/loop_argon --iter 0
+ python -m bench.loop compare --out bench/out/loop_argon --iter 1 --against 0
+ python -m bench.loop judge-calib --out bench/out/loop_argon --iter 1 [--model …] [--thinking medium] [--n 3]
+ python -m bench.loop accept --out bench/out/loop_argon --iter 1 [--note …]
+ python -m bench.loop rollback --out bench/out/loop_argon --iter 1
+ python -m bench.loop status --out bench/out/loop_argon
+
+One iteration = one edit of a per-model prompt/skill VARIANT (``codeverse3d/prompts/variants/<v>/`` +
+``codeverse3d/skills/variants/<v>/``, D105) measured on ~30 scene prompts per language, run in
+parallel on the generator under test, judged by ONE fixed judge at ONE thinking level. ``init``
+freezes every knob in ``<out>/loop.json``; everything else reads it, so two iterations never differ
+in anything but the variant and (when ``--rung`` moves) the prompt mix.
+
+Layout of ``<out>``::
+
+ loop.json the fixed configuration (init)
+ prompts/rung_R_<lang>.yaml a rung's prompts, generated ONCE and reused (stable ids → pairs)
+ snapshots/<v>_v<N>/ the overlay dirs as accepted at version N (init writes v<current>)
+ iter_NN/battery_<lang>.yaml the iteration's battery (a rung mix), generate.json its composition
+ iter_NN/<lang>/ one ``bench.run_bench`` output per language (runs/, results.jsonl)
+ iter_NN/run.json child pids, exit codes, wall; run_<lang>.log their stdout
+ iter_NN/diagnosis.{md,json} diagnose; compare_<lang>.{md,json} compare; judge_calib_<lang>.{md,json}
+
+The ledger of decisions lives IN the repo — ``bench/data/loop/<name>/ledger.jsonl`` (format:
+``bench/data/loop/README.md``) — because an accepted variant version is a claim about the prompts,
+and a claim whose evidence is under the ignored ``bench/out/`` is not reproducible.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import logging
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import time
+import tomllib
+from collections.abc import Callable, Sequence
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import suppress
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Literal
+
+import yaml
+from pydantic import BaseModel, Field, field_validator
+
+for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
+ if str(_p) not in sys.path: # this tree's codeverse3d (harness/) + the `bench` package (eval/)
+ sys.path.insert(0, str(_p))
+
+from bench._jsonl import read_jsonl, seal_for_append # noqa: E402
+from bench._loop_diag import ( # noqa: E402
+ CalibSummary,
+ Comparison,
+ Diagnosis,
+ calib_summary,
+ compare_dirs,
+ diagnose_dir,
+ digests_for,
+ render_calib,
+ render_comparison,
+ render_diagnosis,
+)
+from bench._loop_prompts import ( # noqa: E402
+ RUNGS,
+ GeneratedBattery,
+ build_request,
+ check_battery,
+ contract_lines,
+ migrate_camera_lines,
+ mix_counts,
+ parse_battery,
+)
+from bench.run_bench import Battery, BenchPrompt # noqa: E402
+from codeverse3d.config import get_settings # noqa: E402
+from codeverse3d.contracts.common import TRACK_LANGUAGES, Language, Track # noqa: E402
+from codeverse3d.proc import install_stop_handlers, write_json_atomic # noqa: E402
+
+log = logging.getLogger(__name__)
+
+REPO = Path(__file__).resolve().parents[1] # eval/ — the children run `python -m bench.run_bench` here
+HARNESS = REPO.parent / "harness" # the tree whose variant the loop edits
+DATA_DIR = REPO / "bench" / "data" / "loop" # the ledgers (in git)
+LOOP_JSON = "loop.json"
+VARIANT_TOML = "variant.toml"
+#: the machine-wide Cycles slots the children share: 30 parallel runs render on ONE GPU, and
+#: `Render.blender_gpu_slots` defaults to 2 for an interactive box (D104 measured 0.21-0.64 s/frame
+#: on the GPU vs 2.3 s on the CPU, so a third slot is worth more than a third CPU render)
+BLENDER_GPU_SLOTS = "3"
+#: how long a stopped driver waits for a child to record its stop before SIGKILL: the child's own
+#: stop handler (`run_bench.main` installs it) unwinds within `proc.STOP_GRACE_S` = 30 s
+CHILD_STOP_GRACE_S = 45.0
+
+Thinking = Literal["off", "low", "medium", "high"]
+
+
+class LoopError(RuntimeError):
+ """A misconfiguration or a missing prerequisite — exit 2, never a traceback."""
+
+
+# --------------------------------------------------------------------------- configuration
+class LoopConfig(BaseModel):
+ """Everything an iteration runs with, frozen by ``init`` into ``<out>/loop.json``."""
+
+ schema_version: int = 1
+ name: str
+ out: Path
+ variant: str
+ languages: list[Language]
+ generator: str
+ judge: str
+ judge_thinking: Thinking = "medium"
+ planner: str = Field(default="", description="the battery-generation model; '' = Settings.default_planner")
+ parallel: int = Field(default=15, ge=1, description="run_bench workers PER LANGUAGE (the languages run side by side)")
+ stagger_s: float = Field(default=40.0, ge=0.0,
+ description="seconds between the launches of each child's first wave of workers "
+ "(run_bench --stagger); the children themselves launch stagger_s/2 apart")
+ rounds: int = Field(default=2, ge=0)
+ max_minutes: float = Field(default=90.0, gt=0)
+ n: int = Field(default=30, ge=1, description="prompts per battery")
+ track: Track = Track.SCENE
+ created_at: str = ""
+
+ @field_validator("languages")
+ @classmethod
+ def _scene_languages(cls, v: list[Language]) -> list[Language]:
+ allowed = TRACK_LANGUAGES[Track.SCENE]
+ bad = [x.value for x in v if x not in allowed]
+ if not v or bad:
+ raise ValueError(f"languages must be non-empty scene languages {[a.value for a in allowed]}, got {bad or v}")
+ if len(set(v)) != len(v):
+ raise ValueError(f"duplicate languages: {[x.value for x in v]}")
+ return v
+
+ def iter_dir(self, iteration: int) -> Path:
+ return self.out / f"iter_{iteration:02d}"
+
+ def save(self) -> Path:
+ self.out.mkdir(parents=True, exist_ok=True)
+ write_json_atomic(self.out / LOOP_JSON, self.model_dump(mode="json"))
+ return self.out / LOOP_JSON
+
+ @classmethod
+ def load(cls, out: Path | str) -> LoopConfig:
+ p = Path(out) / LOOP_JSON
+ if not p.is_file():
+ raise LoopError(f"no {LOOP_JSON} under {out}: run `bench.loop init --out {out} …` first")
+ return cls.model_validate_json(p.read_text())
+
+
+def parse_languages(text: str) -> list[Language]:
+ try:
+ return [Language(x.strip()) for x in text.split(",") if x.strip()]
+ except ValueError as e:
+ raise LoopError(f"unknown language in {text!r}: {e}") from e
+
+
+# --------------------------------------------------------------------------- the variant overlay
+def _variants_api() -> Any:
+ """``codeverse3d.prompts.variants`` (Lane V, D105) or a clear error — the loop reads a variant's
+ root and hash through it, and `run` hands the name to the children."""
+ try:
+ from codeverse3d.prompts import variants
+ except ImportError as e:
+ raise LoopError("this tree has no codeverse3d.prompts.variants (the D105 variant layer): "
+ "the loop's variant plumbing needs it") from e
+ missing = [n for n in ("variant_info", "variant_root", "variant_hash") if not hasattr(variants, n)]
+ if missing:
+ raise LoopError(f"codeverse3d.prompts.variants lacks {missing} (the design §0 contract)")
+ return variants
+
+
+def _variants_api_or_none() -> Any | None:
+ try:
+ return _variants_api()
+ except LoopError as e:
+ log.warning("%s", e)
+ return None
+
+
+def _check_variant_name(name: str) -> None:
+ """An unknown variant name is a configuration error (exit 2), caught where the layer is present."""
+ api = _variants_api_or_none()
+ if api is None or not name:
+ return
+ try:
+ api.variant_info(name)
+ except ValueError as e:
+ raise LoopError(str(e)) from e
+
+
+@dataclass(frozen=True)
+class VariantPaths:
+ """The two overlay directories of one variant, and the operations the loop does on them.
+ Injectable (tests point them at a tmp tree); :meth:`default` resolves the real ones."""
+
+ name: str
+ prompts_root: Path
+ skills_root: Path
+
+ @classmethod
+ def default(cls, name: str) -> VariantPaths:
+ from codeverse3d.prompts import PROMPTS_DIR
+ from codeverse3d.skills import skills_dir
+
+ api = _variants_api_or_none()
+ prompts_root = Path(api.variant_root(name)) if api is not None else PROMPTS_DIR / "variants" / name
+ return cls(name=name, prompts_root=prompts_root, skills_root=skills_dir() / "variants" / name)
+
+ @property
+ def toml(self) -> Path:
+ return self.prompts_root / VARIANT_TOML
+
+ def version(self) -> int:
+ if not self.toml.is_file():
+ raise LoopError(f"no {VARIANT_TOML} under {self.prompts_root}: is {self.name!r} a variant?")
+ data = tomllib.loads(self.toml.read_text())
+ try:
+ return int(data["variant"]["version"])
+ except (KeyError, TypeError, ValueError) as e:
+ raise LoopError(f"{self.toml}: [variant].version is missing or not an integer ({e})") from e
+
+ def set_version(self, new: int) -> None:
+ """Rewrite ONLY the ``version = N`` line of the ``[variant]`` table (comments and the other keys
+ stay as the author wrote them), and read it back through tomllib before trusting it."""
+ out: list[str] = []
+ table, done = "", False
+ for line in self.toml.read_text().splitlines(keepends=True):
+ s = line.strip()
+ if s.startswith("[") and s.endswith("]"):
+ table = s[1:-1].strip()
+ elif table == "variant" and not done and not s.startswith("#") and s.split("=", 1)[0].strip() == "version":
+ indent = line[: len(line) - len(line.lstrip())]
+ line = f"{indent}version = {new}\n"
+ done = True
+ out.append(line)
+ if not done:
+ raise LoopError(f"{self.toml}: no `version = N` line in [variant] to bump")
+ self.toml.write_text("".join(out))
+ if self.version() != new:
+ raise LoopError(f"{self.toml}: wrote version {new} but read back {self.version()}")
+
+ def files(self) -> list[tuple[str, bytes]]:
+ """``(relpath, bytes)`` of every overlay file, sorted — ``prompts/…`` and ``skills/…``."""
+ out: list[tuple[str, bytes]] = []
+ for label, root in (("prompts", self.prompts_root), ("skills", self.skills_root)):
+ if not root.is_dir():
+ continue
+ for p in sorted(root.rglob("*")):
+ if p.is_file() and "__pycache__" not in p.parts and p.suffix != ".pyc":
+ out.append((f"{label}/{p.relative_to(root).as_posix()}", p.read_bytes()))
+ return out
+
+ def overlay_hash(self) -> str:
+ """sha256[:12] over the sorted (relpath, bytes) of EVERY overlay file — the loop's own
+ fingerprint, used ONLY as the fallback of :meth:`ledger_hash` for a tree the variant layer
+ does not know (the tests' tmp overlays). It is not the number a run record carries: Lane V's
+ ``variant_hash`` leaves ``README.md`` out (documentation, not prompt material), so the two
+ differ for the shipped overlay by exactly that file."""
+ h = hashlib.sha256()
+ for rel, data in self.files():
+ h.update(rel.encode("utf-8") + b"\0" + data + b"\0")
+ return h.hexdigest()[:12]
+
+ def ledger_hash(self) -> str:
+ """THE hash of this overlay: ``prompts.variants.variant_hash`` — what every run record of the
+ iteration carries (``extra.variant.hash``, ``SettingsSnapshot.variant_hash``) — whenever these
+ paths are the real overlay; :meth:`overlay_hash` only for a tmp tree. The ledger row and the
+ snapshot both write this one, so a snapshot can be paired with the runs it was measured on."""
+ api = _variants_api_or_none()
+ if api is not None:
+ try:
+ if Path(api.variant_root(self.name)).resolve() == self.prompts_root.resolve():
+ return str(api.variant_hash(self.name))
+ except Exception as e: # noqa: BLE001 — an unknown name in a tmp tree: fall back
+ log.debug("variant_hash(%s) unavailable: %s", self.name, e)
+ return self.overlay_hash()
+
+ def preflight(self) -> None:
+ """Refuse a broken skills overlay BEFORE it is versioned, snapshotted or written to the ledger.
+
+ At run time the harness degrades silently — ``skills.variants_table`` logs a ``routes.toml``
+ that does not type-check and routes with the BASE table, ``iter_skills(strict=False)`` skips
+ an invalid overlay bundle — so an iteration whose overlay carries a typo measures the base
+ routing, its verdict is about nothing, and nothing would stop ``accept`` recording it as a new
+ version. This is where the loop says no, with the parsers the run uses: ``skills.parse_routes``
+ on the overlay's table (what ``variants_table`` calls on that file) and ``skills.validate_bundle``
+ on every bundle directory under the overlay. The first problem is a :class:`LoopError`."""
+ from codeverse3d.skills import ROUTES_FILE, bundle_dirs, parse_routes, validate_bundle
+
+ routes = self.skills_root / ROUTES_FILE
+ if routes.is_file():
+ try:
+ parse_routes(routes, variant=self.name)
+ except ValueError as e:
+ raise LoopError(f"variant {self.name!r}: {ROUTES_FILE} does not type-check (a run would route "
+ f"with the base table): {e}") from e
+ for bundle in bundle_dirs(self.skills_root):
+ problems = validate_bundle(bundle)
+ if problems:
+ raise LoopError(f"variant {self.name!r}: skill bundle {bundle.name} ({bundle}) is invalid (a run "
+ f"would skip it): " + "; ".join(problems))
+
+ def snapshot_to(self, dest: Path) -> Path:
+ """Copy both overlay dirs under ``dest/{prompts,skills}`` (replacing an older copy). The
+ ``snapshot.json`` beside them carries :meth:`ledger_hash` — the same number as the ledger row
+ and the iteration's run records, never the loop-private :meth:`overlay_hash`."""
+ if dest.exists():
+ shutil.rmtree(dest)
+ for label, root in (("prompts", self.prompts_root), ("skills", self.skills_root)):
+ if root.is_dir():
+ shutil.copytree(root, dest / label, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
+ (dest / "snapshot.json").write_text(json.dumps({
+ "variant": self.name, "version": self.version(), "hash": self.ledger_hash(),
+ "taken_at": datetime.now(UTC).isoformat(), "prompts_root": str(self.prompts_root),
+ "skills_root": str(self.skills_root)}, indent=2))
+ return dest
+
+ def restore_from(self, src: Path) -> None:
+ """Make both overlay dirs equal to the snapshot (a part the snapshot lacks is removed)."""
+ if not (src / "snapshot.json").is_file():
+ raise LoopError(f"{src} is not a loop snapshot (no snapshot.json)")
+ for label, root in (("prompts", self.prompts_root), ("skills", self.skills_root)):
+ if root.parent.name != "variants" or root.name != self.name:
+ raise LoopError(f"refusing to replace {root}: not a variants/<{self.name}> overlay directory")
+ if root.exists():
+ shutil.rmtree(root)
+ if (src / label).is_dir():
+ shutil.copytree(src / label, root)
+
+
+def snapshot_dir(cfg: LoopConfig, version: int) -> Path:
+ return cfg.out / "snapshots" / f"{cfg.variant}_v{version}"
+
+
+# --------------------------------------------------------------------------- init
+def init(cfg: LoopConfig, *, paths: VariantPaths | None = None) -> Path:
+ """Write ``loop.json`` and snapshot the overlay as it stands (``snapshots/<v>_v<current>``), so the
+ first ``rollback`` has a state to return to. A missing variant layer only costs the snapshot; a
+ skills overlay that would not route (:meth:`VariantPaths.preflight`) is refused before anything
+ is written."""
+ if (cfg.out / LOOP_JSON).is_file():
+ raise LoopError(f"{cfg.out / LOOP_JSON} exists: one loop per --out (status / iterations read it)")
+ _check_variant_name(cfg.variant) # before any money is spent
+ vp = paths or VariantPaths.default(cfg.variant)
+ vp.preflight()
+ cfg.created_at = datetime.now(UTC).isoformat()
+ p = cfg.save()
+ if vp.toml.is_file():
+ dest = snapshot_dir(cfg, vp.version())
+ if not dest.exists():
+ vp.snapshot_to(dest)
+ else:
+ log.warning("no %s under %s: no snapshot taken", VARIANT_TOML, vp.prompts_root)
+ return p
+
+
+# --------------------------------------------------------------------------- generate
+def rung_cache(cfg: LoopConfig, lang: Language, rung: int) -> Path:
+ return cfg.out / "prompts" / f"rung_{rung}_{lang.value}.yaml"
+
+
+def generation_meta(cfg: LoopConfig, iteration: int) -> dict[str, Any] | None:
+ p = cfg.iter_dir(iteration) / "generate.json"
+ return json.loads(p.read_text()) if p.is_file() else None
+
+
+def default_rung(cfg: LoopConfig, iteration: int) -> int:
+ """No ``--rung``: the previous iteration's (so the pairs are complete), else 1."""
+ for i in range(iteration - 1, -1, -1):
+ meta = generation_meta(cfg, i)
+ if meta is not None:
+ return int(meta["rung"])
+ return 1
+
+
+def rung_prompts(cfg: LoopConfig, lang: Language, rung: int, *, iteration: int,
+ chat_model: Any = None) -> list[BenchPrompt]:
+ """The rung's prompts for ``lang`` — from the cache, else generated once (one re-ask on a typed
+ failure) and cached under ``prompts/rung_R_<lang>.yaml`` with the ids they will keep forever."""
+ cache = rung_cache(cfg, lang, rung)
+ if cache.is_file():
+ data = yaml.safe_load(cache.read_text())
+ prompts = [BenchPrompt.model_validate(p) for p in data["prompts"]]
+ migrated = migrate_camera_lines(prompts)
+ if migrated:
+ # a cache written before 2026-10-15 carries the moving-camera line (iteration 0 ran with
+ # it): the ids stay — they pair iterations — and only that line moves, in the file too
+ data["prompts"] = [p.model_dump(mode="json", exclude_defaults=True) for p in prompts]
+ data["camera_lines_migrated"] = {"n": migrated, "at": datetime.now(UTC).isoformat()}
+ _write_cache(cache, data)
+ log.info("rung %d %s: migrated %d camera line(s) to the fixed-camera form in %s",
+ rung, lang.value, migrated, cache)
+ return prompts
+ r = RUNGS[rung]
+ if chat_model is None:
+ from codeverse3d.models.registry import get_chat_model
+
+ chat_model = get_chat_model(cfg.planner or get_settings().backends().planner)
+ resp = chat_model.generate(build_request(r, cfg.n, lang))
+ battery, problems = parse_battery(resp.text, resp.parsed)
+ if battery is not None:
+ problems = check_battery(battery, r, cfg.n)
+ if problems:
+ log.warning("rung %d %s: %d problem(s), re-asking once: %s", rung, lang.value, len(problems), problems[:3])
+ previous = resp.text or (json.dumps(resp.parsed) if resp.parsed is not None else "")
+ resp = chat_model.generate(build_request(r, cfg.n, lang, previous_text=previous, problems=problems,
+ label="loop:generate-reask"))
+ battery, problems = parse_battery(resp.text, resp.parsed)
+ if battery is not None:
+ problems = check_battery(battery, r, cfg.n)
+ if problems or battery is None:
+ raise LoopError(f"rung {rung} prompts for {lang.value} failed the rung rules after one re-ask:\n- "
+ + "\n- ".join(problems))
+ prompts = _bench_prompts(battery, lang, rung, iteration=iteration, n=cfg.n)
+ _write_cache(cache, {
+ "rung": rung, "language": lang.value, "n": len(prompts), "generated_at_iteration": iteration,
+ "model": str(getattr(chat_model, "id", "")), "generated_at": datetime.now(UTC).isoformat(),
+ "prompts": [p.model_dump(mode="json", exclude_defaults=True) for p in prompts],
+ })
+ return prompts
+
+
+def _write_cache(cache: Path, data: dict[str, Any]) -> None:
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ cache.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))
+
+
+def _bench_prompts(battery: GeneratedBattery, lang: Language, rung: int, *, iteration: int, n: int) -> list[BenchPrompt]:
+ r = RUNGS[rung]
+ return [BenchPrompt(id=f"it{iteration:02d}_{lang.value}_r{rung}_{k:02d}", prompt=" ".join(gp.prompt.split()),
+ tier=r.tier, category=gp.category, must_have=contract_lines(gp),
+ tags=[f"rung{rung}", gp.lighting, *gp.features, gp.title])
+ for k, gp in enumerate(battery.prompts[:n], 1)]
+
+
+def generate_iteration(cfg: LoopConfig, iteration: int, *, rung: int | None = None, n: int | None = None,
+ chat_model: Any = None) -> dict[Language, Path]:
+ """Write ``iter_NN/battery_<lang>.yaml`` per language: a mix of the cached rungs up to ``rung``
+ (:func:`bench._loop_prompts.mix_counts`), validated through ``Battery`` before it is written."""
+ rung = default_rung(cfg, iteration) if rung is None else rung
+ if rung not in RUNGS:
+ raise LoopError(f"--rung must be one of {sorted(RUNGS)}, got {rung}")
+ size = n or cfg.n
+ counts = mix_counts(rung, size)
+ iter_dir = cfg.iter_dir(iteration)
+ iter_dir.mkdir(parents=True, exist_ok=True)
+ out: dict[Language, Path] = {}
+ ids: dict[str, list[str]] = {}
+ for lang in cfg.languages:
+ prompts: list[BenchPrompt] = []
+ for level, k in counts.items():
+ cached = rung_prompts(cfg, lang, level, iteration=iteration, chat_model=chat_model)
+ if len(cached) < k:
+ log.warning("rung %d %s holds %d prompts, the mix wanted %d", level, lang.value, len(cached), k)
+ prompts.extend(cached[:k])
+ battery = Battery(name=f"{cfg.name}_it{iteration:02d}_{lang.value}", track=cfg.track, language=lang,
+ description=f"loop {cfg.name} iteration {iteration}: {size} scene prompts, rungs "
+ + ", ".join(f"{lvl}×{c}" for lvl, c in counts.items()),
+ prompts=prompts)
+ data = battery.model_dump(mode="json")
+ Battery.model_validate(data) # what the file will load as, not what we built
+ path = iter_dir / f"battery_{lang.value}.yaml"
+ path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))
+ out[lang] = path
+ ids[lang.value] = [p.id for p in prompts]
+ write_json_atomic(iter_dir / "generate.json", {
+ "iteration": iteration, "rung": rung, "n": size, "mix": {str(k): v for k, v in counts.items()},
+ "languages": [x.value for x in cfg.languages], "batteries": {k.value: str(v) for k, v in out.items()},
+ "ids": ids, "generated_at": datetime.now(UTC).isoformat()})
+ return out
+
+
+# --------------------------------------------------------------------------- run
+def child_argv(cfg: LoopConfig, lang: Language, battery: Path, out_lang: Path, *, resume: bool) -> list[str]:
+ """The ``python -m bench.run_bench`` command line of one language's child."""
+ argv = [sys.executable, "-m", "bench.run_bench", str(battery), "--out", str(out_lang),
+ "--generator", cfg.generator, "--judge", cfg.judge, "--parallel", str(cfg.parallel),
+ "--rounds", str(cfg.rounds), "--max-minutes", str(cfg.max_minutes), "--no-report"]
+ if cfg.planner:
+ argv += ["--planner", cfg.planner]
+ if cfg.variant:
+ argv += ["--variant", cfg.variant]
+ if cfg.stagger_s > 0:
+ argv += ["--stagger", str(cfg.stagger_s)]
+ if resume:
+ argv += ["--redo-status", "infra_failed"]
+ return argv
+
+
+def child_env(cfg: LoopConfig, base: dict[str, str] | None = None) -> dict[str, str]:
+ """The children's environment: the judge's thinking level, the variant (belt and braces beside
+ ``--variant``: every process of the run reads it), three GPU render slots, unbuffered logs."""
+ env = dict(os.environ if base is None else base)
+ env["C3D_JUDGE__THINKING"] = cfg.judge_thinking
+ if cfg.variant:
+ env["C3D_VARIANT"] = cfg.variant
+ else:
+ env.pop("C3D_VARIANT", None)
+ env["C3D_RENDER__BLENDER_GPU_SLOTS"] = BLENDER_GPU_SLOTS
+ env["PYTHONUNBUFFERED"] = "1"
+ return env
+
+
+def _terminate(proc: Any) -> None:
+ """SIGTERM the child's group (its own stop handler records the stop), SIGKILL after the grace."""
+ try:
+ os.killpg(proc.pid, signal.SIGTERM)
+ except (ProcessLookupError, PermissionError, AttributeError, TypeError):
+ with suppress(Exception):
+ proc.terminate()
+ deadline = time.monotonic() + CHILD_STOP_GRACE_S
+ while time.monotonic() < deadline and proc.poll() is None:
+ time.sleep(0.2)
+ if proc.poll() is None:
+ with suppress(Exception):
+ os.killpg(proc.pid, signal.SIGKILL)
+
+
+def run_iteration(cfg: LoopConfig, iteration: int, *, languages: Sequence[Language] = (), resume: bool = False,
+ popen: Callable[..., Any] = subprocess.Popen) -> dict[str, Any]:
+ """One child process per language, side by side (``parallel`` runs each), SIGTERM forwarded on a
+ stop; ``iter_NN/run.json`` carries pids while they run and exit codes + wall after."""
+ install_stop_handlers()
+ _check_variant_name(cfg.variant)
+ iter_dir = cfg.iter_dir(iteration)
+ langs = list(languages) or cfg.languages
+ meta: dict[str, Any] = {"iteration": iteration, "started_at": datetime.now(UTC).isoformat(), "resume": resume,
+ "children": {}}
+ children: dict[str, tuple[Any, Any]] = {}
+ t0 = time.monotonic()
+ try:
+ for lang in langs:
+ battery = iter_dir / f"battery_{lang.value}.yaml"
+ if not battery.is_file():
+ raise LoopError(f"no {battery.name} under {iter_dir}: run `bench.loop generate --iter {iteration}` first")
+ out_lang = iter_dir / lang.value
+ log_path = iter_dir / f"run_{lang.value}.log"
+ argv = child_argv(cfg, lang, battery, out_lang, resume=resume)
+ if children and cfg.stagger_s > 0:
+ # The languages' first waves interleave. agy holds ONE session per key machine-wide
+ # and there are 30 keys, so 15 + 15 parallel runs plus the harness's own planner /
+ # asset / judge calls all draw on the same 64-slot pool; two children launched
+ # together plan and single-shot their assets in the same minute and exhaust it
+ # (iteration 0: 160 of its 172 `asset.generate_failed` outages fell in the first ten
+ # minutes). Each child staggers its own first wave by stagger_s (`--stagger`); half
+ # that between the children puts one language's k-th launch between the other's.
+ time.sleep(cfg.stagger_s / 2)
+ fh = log_path.open("a")
+ fh.write(f"--- {datetime.now(UTC).isoformat()} {' '.join(argv)}\n")
+ fh.flush()
+ proc = popen(argv, cwd=str(REPO), env=child_env(cfg), stdout=fh, stderr=subprocess.STDOUT,
+ start_new_session=True)
+ children[lang.value] = (proc, fh)
+ meta["children"][lang.value] = {"argv": argv, "pid": proc.pid, "log": str(log_path), "out": str(out_lang),
+ "returncode": None}
+ write_json_atomic(iter_dir / "run.json", meta)
+ while any(p.poll() is None for p, _ in children.values()):
+ time.sleep(0.5)
+ except BaseException: # SystemExit(143) from the stop handler, KeyboardInterrupt, a LoopError mid-launch
+ for p, _ in children.values():
+ if p.poll() is None:
+ _terminate(p)
+ raise
+ finally:
+ for name, (p, fh) in children.items():
+ meta["children"][name]["returncode"] = p.poll()
+ fh.close()
+ meta["finished_at"] = datetime.now(UTC).isoformat()
+ meta["wall_s"] = round(time.monotonic() - t0, 1)
+ write_json_atomic(iter_dir / "run.json", meta)
+ return meta
+
+
+# --------------------------------------------------------------------------- diagnose / compare / judge-calib
+def _present(cfg: LoopConfig, iteration: int, languages: Sequence[Language] = ()) -> list[tuple[Language, Path]]:
+ out: list[tuple[Language, Path]] = []
+ for lang in (list(languages) or cfg.languages):
+ d = cfg.iter_dir(iteration) / lang.value
+ if d.is_dir():
+ out.append((lang, d))
+ else:
+ log.warning("iteration %d has no %s output (%s)", iteration, lang.value, d)
+ if not out:
+ raise LoopError(f"iteration {iteration} has no run output under {cfg.iter_dir(iteration)}")
+ return out
+
+
+def diagnose_iteration(cfg: LoopConfig, iteration: int, *, languages: Sequence[Language] = ()) -> dict[str, Diagnosis]:
+ out: dict[str, Diagnosis] = {}
+ for lang, d in _present(cfg, iteration, languages):
+ out[lang.value] = diagnose_dir(lang.value, d)
+ iter_dir = cfg.iter_dir(iteration)
+ write_json_atomic(iter_dir / "diagnosis.json", {k: v.model_dump(mode="json") for k, v in out.items()})
+ md = [f"# {cfg.name} — iteration {iteration} diagnosis", "",
+ f"variant `{cfg.variant}`, generator `{cfg.generator}`, judge `{cfg.judge}` @ {cfg.judge_thinking}", ""]
+ md += [render_diagnosis(v) for v in out.values()]
+ (iter_dir / "diagnosis.md").write_text("\n".join(md))
+ return out
+
+
+def compare_iteration(cfg: LoopConfig, iteration: int, against: int, *,
+ languages: Sequence[Language] = ()) -> dict[str, Comparison]:
+ if iteration == against:
+ raise LoopError("--against must name a different iteration")
+ out: dict[str, Comparison] = {}
+ for lang, d in _present(cfg, iteration, languages):
+ ref = cfg.iter_dir(against) / lang.value
+ if not ref.is_dir():
+ log.warning("iteration %d has no %s output to compare against", against, lang.value)
+ continue
+ c = compare_dirs(lang.value, d, ref)
+ out[lang.value] = c
+ iter_dir = cfg.iter_dir(iteration)
+ (iter_dir / f"compare_{lang.value}.md").write_text(
+ f"# {cfg.name} — iteration {iteration} vs {against}\n\n" + render_comparison(c))
+ write_json_atomic(iter_dir / f"compare_{lang.value}.json", c.model_dump(mode="json"))
+ if not out:
+ raise LoopError(f"nothing to compare: iteration {against} has no output for {[x.value for x in cfg.languages]}")
+ return out
+
+
+def judge_calib(cfg: LoopConfig, iteration: int, *, model_id: str = "", thinking: str = "", n_samples: int = 3,
+ languages: Sequence[Language] = (), calibrate_fn: Callable[..., Any] | None = None,
+ workers: int = 4) -> dict[str, CalibSummary]:
+ """Re-judge every run's PICKED round ``n_samples`` times in fixed montage order (the model's own
+ re-judge σ, not its order σ) and summarise per language — the loop's judge arm."""
+ model_id = model_id or cfg.judge
+ thinking = thinking or cfg.judge_thinking
+ if calibrate_fn is None:
+ from codeverse3d.addons.calibration import calibrate as calibrate_fn
+ out: dict[str, CalibSummary] = {}
+ iter_dir = cfg.iter_dir(iteration)
+ for lang, d in _present(cfg, iteration, languages):
+ digests = digests_for(d)
+ jobs = [(pid, dg.picked_round) for pid, dg in sorted(digests.items()) if dg.picked_round is not None]
+
+ def one(job: tuple[str, int], *, root: Path = d, lang_name: str = lang.value) -> Any | None:
+ pid, picked = job
+ try:
+ return calibrate_fn([root / "runs" / pid], model_id=model_id, n_samples=n_samples,
+ out_dir=iter_dir / "judge_calib" / lang_name / pid, geometry_mode=None,
+ rounds=[picked], thinking=thinking, max_workers=1, fixed_order=True)
+ except Exception as e: # noqa: BLE001 — one run's re-judge must not cost the table
+ log.warning("judge-calib %s/%s failed: %s", lang_name, pid, e)
+ return None
+
+ with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
+ tables = [t for t in pool.map(one, jobs) if t is not None]
+ s = calib_summary(lang.value, tables, thinking=thinking)
+ if not tables:
+ s.model_id, s.n_samples = model_id, n_samples
+ out[lang.value] = s
+ (iter_dir / f"judge_calib_{lang.value}.md").write_text(
+ f"# {cfg.name} — iteration {iteration} judge calibration\n\n" + render_calib(s))
+ write_json_atomic(iter_dir / f"judge_calib_{lang.value}.json", s.model_dump(mode="json"))
+ return out
+
+
+# --------------------------------------------------------------------------- the ledger: accept / rollback / status
+class LedgerRow(BaseModel):
+ """One decision about the variant (append-only ``ledger.jsonl``; see bench/data/loop/README.md)."""
+
+ ts: str
+ iteration: int
+ languages: list[str]
+ variant: str
+ version_from: int
+ version_to: int
+ variant_hash: str
+ battery_sha: str
+ verdicts: dict[str, str] = Field(default_factory=dict, description="language → keep | revert | inconclusive")
+ decision: Literal["accept", "rollback"]
+ cost_usd: float = 0.0
+ tree_commit: str = ""
+ tree_dirty: bool = False
+ note: str = ""
+
+
+def ledger_path(cfg: LoopConfig, data_dir: Path | None = None) -> Path:
+ return (data_dir or DATA_DIR) / cfg.name / "ledger.jsonl"
+
+
+def ledger_rows(path: Path) -> list[LedgerRow]:
+ return read_jsonl(path, LedgerRow)
+
+
+def append_ledger(path: Path, row: LedgerRow) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ seal_for_append(path)
+ with path.open("a") as fh:
+ fh.write(row.model_dump_json() + "\n")
+
+
+def battery_sha(iter_dir: Path) -> str:
+ """sha256[:12] over the iteration's battery files — what the row's verdict was measured on."""
+ h = hashlib.sha256()
+ for p in sorted(iter_dir.glob("battery_*.yaml")):
+ h.update(p.name.encode() + b"\0" + p.read_bytes() + b"\0")
+ return h.hexdigest()[:12]
+
+
+def tree_state(tree: Path = HARNESS) -> tuple[str, bool]:
+ """``(commit, dirty)`` of the harness checkout — a ledger row names the code its verdict ran on."""
+ try:
+ head = subprocess.run(["git", "-C", str(tree), "rev-parse", "HEAD"], capture_output=True, text=True,
+ check=False, timeout=30)
+ status = subprocess.run(["git", "-C", str(tree), "status", "--porcelain", "--untracked-files=no", "--", "."],
+ capture_output=True, text=True, check=False, timeout=30)
+ except (OSError, subprocess.SubprocessError):
+ return "", False
+ commit = head.stdout.strip() if head.returncode == 0 else ""
+ return commit, bool(status.returncode == 0 and status.stdout.strip())
+
+
+def iteration_cost(cfg: LoopConfig, iteration: int) -> float:
+ from bench.report import load_results
+
+ total = 0.0
+ for lang in cfg.languages:
+ d = cfg.iter_dir(iteration) / lang.value
+ if (d / "results.jsonl").is_file() or (d / "results.json").is_file():
+ total += sum(r.cost_usd for r in load_results(d))
+ return round(total, 4)
+
+
+def iteration_verdicts(cfg: LoopConfig, iteration: int) -> dict[str, str]:
+ out: dict[str, str] = {}
+ for lang in cfg.languages:
+ p = cfg.iter_dir(iteration) / f"compare_{lang.value}.json"
+ if p.is_file():
+ out[lang.value] = str(json.loads(p.read_text()).get("decision", ""))
+ return out
+
+
+def _row(cfg: LoopConfig, iteration: int, *, paths: VariantPaths, decision: Literal["accept", "rollback"],
+ version_from: int, version_to: int, note: str) -> LedgerRow:
+ commit, dirty = tree_state()
+ return LedgerRow(ts=datetime.now(UTC).isoformat(), iteration=iteration, languages=[x.value for x in cfg.languages],
+ variant=cfg.variant, version_from=version_from, version_to=version_to,
+ variant_hash=paths.ledger_hash(), battery_sha=battery_sha(cfg.iter_dir(iteration)),
+ verdicts=iteration_verdicts(cfg, iteration), decision=decision,
+ cost_usd=iteration_cost(cfg, iteration), tree_commit=commit, tree_dirty=dirty, note=note)
+
+
+def accept(cfg: LoopConfig, iteration: int, *, note: str = "", paths: VariantPaths | None = None,
+ data_dir: Path | None = None) -> LedgerRow:
+ """The overlay as it stands becomes version N+1: preflight it (a ``routes.toml`` that does not
+ type-check or an invalid bundle is refused — a run would have degraded to the base routing
+ silently), bump ``variant.toml``, snapshot both overlay dirs to ``snapshots/<v>_v<N+1>/``, append
+ the row."""
+ if not cfg.iter_dir(iteration).is_dir():
+ raise LoopError(f"iteration {iteration} does not exist under {cfg.out}")
+ vp = paths or VariantPaths.default(cfg.variant)
+ vp.preflight()
+ version_from = vp.version()
+ version_to = version_from + 1
+ vp.set_version(version_to)
+ vp.snapshot_to(snapshot_dir(cfg, version_to))
+ row = _row(cfg, iteration, paths=vp, decision="accept", version_from=version_from, version_to=version_to, note=note)
+ if not row.verdicts:
+ log.warning("iteration %d has no compare_<lang>.json: accepting without a verdict", iteration)
+ append_ledger(ledger_path(cfg, data_dir), row)
+ return row
+
+
+def rollback(cfg: LoopConfig, iteration: int, *, note: str = "", paths: VariantPaths | None = None,
+ data_dir: Path | None = None) -> LedgerRow:
+ """Return the overlay dirs to the last accepted state. An iteration that was itself the latest
+ ``accept`` is un-accepted (its ``version_from`` snapshot comes back and the version with it);
+ otherwise the working edits made for the iteration are discarded in favour of the current
+ version's snapshot."""
+ vp = paths or VariantPaths.default(cfg.variant)
+ current = vp.version()
+ rows = ledger_rows(ledger_path(cfg, data_dir))
+ accepts = [r for r in rows if r.decision == "accept"]
+ target = current
+ if accepts and accepts[-1].iteration == iteration and accepts[-1].version_to == current:
+ target = accepts[-1].version_from
+ src = snapshot_dir(cfg, target)
+ if not src.is_dir():
+ raise LoopError(f"no snapshot {src} to restore (init writes the current version's; accept writes each new one)")
+ vp.restore_from(src)
+ if vp.version() != target: # a snapshot taken before the bump still says the old number: pin it
+ vp.set_version(target)
+ row = _row(cfg, iteration, paths=vp, decision="rollback", version_from=current, version_to=target, note=note)
+ append_ledger(ledger_path(cfg, data_dir), row)
+ return row
+
+
+def iterations(cfg: LoopConfig) -> list[dict[str, Any]]:
+ """What each ``iter_NN`` holds: batteries, child exit codes, result counts, the files written."""
+ out: list[dict[str, Any]] = []
+ for d in sorted(cfg.out.glob("iter_*")):
+ if not d.is_dir():
+ continue
+ run = json.loads((d / "run.json").read_text()) if (d / "run.json").is_file() else {}
+ results: dict[str, int] = {}
+ for lang in cfg.languages:
+ jl = d / lang.value / "results.jsonl"
+ if jl.is_file():
+ results[lang.value] = len({r.get("id") for r in read_jsonl(jl)})
+ meta = generation_meta(cfg, int(d.name.split("_")[-1])) or {}
+ out.append({
+ "iteration": int(d.name.split("_")[-1]), "rung": meta.get("rung"),
+ "batteries": sorted(p.name for p in d.glob("battery_*.yaml")),
+ "exit_codes": {k: v.get("returncode") for k, v in run.get("children", {}).items()},
+ "results": results,
+ "diagnosis": (d / "diagnosis.md").is_file(),
+ "compare": sorted(p.stem.removeprefix("compare_") for p in d.glob("compare_*.json")),
+ "judge_calib": sorted(p.stem.removeprefix("judge_calib_") for p in d.glob("judge_calib_*.json")),
+ })
+ return out
+
+
+def status_text(cfg: LoopConfig, *, paths: VariantPaths | None = None, data_dir: Path | None = None) -> str:
+ vp = paths or VariantPaths.default(cfg.variant)
+ try:
+ version = f"v{vp.version()} ({vp.ledger_hash()})"
+ except LoopError as e:
+ version = f"unknown ({e})"
+ lines = [f"loop {cfg.name}: variant {cfg.variant} {version}; languages {', '.join(x.value for x in cfg.languages)}; "
+ f"generator {cfg.generator}; judge {cfg.judge} @ {cfg.judge_thinking}; parallel {cfg.parallel} per language "
+ f"(stagger {cfg.stagger_s:g} s), rounds {cfg.rounds}, max-minutes {cfg.max_minutes:g}; out {cfg.out}", "",
+ "| iter | rung | batteries | exit codes | results | diagnosis | compare | judge-calib |",
+ "|---|---|---|---|---|---|---|---|"]
+ for it in iterations(cfg):
+ lines.append(f"| {it['iteration']} | {it['rung'] or '—'} | {len(it['batteries'])} | "
+ f"{', '.join(f'{k}={v}' for k, v in it['exit_codes'].items()) or '—'} | "
+ f"{', '.join(f'{k}={v}' for k, v in it['results'].items()) or '—'} | "
+ f"{'yes' if it['diagnosis'] else '—'} | {', '.join(it['compare']) or '—'} | "
+ f"{', '.join(it['judge_calib']) or '—'} |")
+ rows = ledger_rows(ledger_path(cfg, data_dir))
+ lines += ["", f"ledger {ledger_path(cfg, data_dir)}: {len(rows)} row(s)", "",
+ "| ts | iter | decision | version | verdicts | cost | hash | tree | note |", "|---|---|---|---|---|---|---|---|---|"]
+ for r in rows:
+ lines.append(f"| {r.ts[:19]} | {r.iteration} | {r.decision} | {r.version_from}→{r.version_to} | "
+ f"{', '.join(f'{k}={v}' for k, v in r.verdicts.items()) or '—'} | ${r.cost_usd:.2f} | {r.variant_hash} | "
+ f"{r.tree_commit[:9]}{'-dirty' if r.tree_dirty else ''} | {r.note} |")
+ return "\n".join(lines)
+
+
+# --------------------------------------------------------------------------- CLI
+def _add_out(sp: argparse.ArgumentParser) -> None:
+ sp.add_argument("--out", type=Path, required=True, help="the loop directory (holds loop.json)")
+
+
+def _add_iter(sp: argparse.ArgumentParser) -> None:
+ sp.add_argument("--iter", dest="iteration", type=int, required=True, help="iteration number (0 = the base)")
+
+
+def _add_langs(sp: argparse.ArgumentParser) -> None:
+ sp.add_argument("--languages", default="", help="comma list; default: every language of the loop")
+
+
+def build_parser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(prog="python -m bench.loop", description=__doc__.split("\n\n")[0])
+ ap.add_argument("--data-dir", type=Path, default=None, help=f"where the ledgers live (default {DATA_DIR})")
+ sub = ap.add_subparsers(dest="cmd", required=True)
+
+ s = sub.add_parser("init", help="freeze the loop's configuration into <out>/loop.json")
+ s.add_argument("--name", required=True)
+ _add_out(s)
+ s.add_argument("--variant", required=True, help="the prompt/skill variant under test (codeverse3d/prompts/variants/<name>)")
+ s.add_argument("--languages", default="scene_threejs,scene_blender")
+ s.add_argument("--generator", default="agy:gemini-4-argon")
+ s.add_argument("--judge", default="gemini:gemini-4-argon")
+ s.add_argument("--judge-thinking", default="medium", choices=("off", "low", "medium", "high"))
+ s.add_argument("--planner", default="", help="battery-generation model (default: the settings planner)")
+ s.add_argument("--parallel", type=int, default=15, help="run_bench workers per language")
+ s.add_argument("--stagger", type=float, default=40.0,
+ help="seconds between the launches of each child's first wave of workers; the children launch "
+ "half that apart (0 = everything at once)")
+ s.add_argument("--rounds", type=int, default=2)
+ s.add_argument("--max-minutes", type=float, default=90.0)
+ s.add_argument("--n", type=int, default=30, help="prompts per battery")
+
+ s = sub.add_parser("generate", help="write the iteration's batteries (a mix of cached rungs)")
+ _add_out(s)
+ _add_iter(s)
+ s.add_argument("--n", type=int, default=None, help="prompts per battery (default: loop.json)")
+ s.add_argument("--rung", type=int, default=None, help=f"top rung of the mix, 1..{max(RUNGS)} (default: the previous iteration's, else 1)")
+
+ s = sub.add_parser("run", help="run the batteries: one bench.run_bench child per language")
+ _add_out(s)
+ _add_iter(s)
+ _add_langs(s)
+ s.add_argument("--resume", action="store_true", help="re-run the cells the weather lost (--redo-status infra_failed)")
+
+ s = sub.add_parser("diagnose", help="diagnosis.{md,json} from the iteration's run records")
+ _add_out(s)
+ _add_iter(s)
+ _add_langs(s)
+
+ s = sub.add_parser("compare", help="pair the iteration with another by prompt id: keep / revert / inconclusive")
+ _add_out(s)
+ _add_iter(s)
+ s.add_argument("--against", type=int, required=True, help="the reference iteration")
+ _add_langs(s)
+
+ s = sub.add_parser("judge-calib", help="re-judge the picked rounds n times: within / between σ, SNR, correlations")
+ _add_out(s)
+ _add_iter(s)
+ s.add_argument("--model", default="", help="judge model (default: the loop's judge)")
+ s.add_argument("--thinking", default="", choices=("", "off", "low", "medium", "high"), help="default: the loop's")
+ s.add_argument("--n", type=int, default=3, help="samples per round")
+ s.add_argument("--workers", type=int, default=4, help="runs re-judged side by side")
+ _add_langs(s)
+
+ for name, text in (("accept", "bump the variant version, snapshot the overlay, append the ledger row"),
+ ("rollback", "restore the last accepted overlay, append the ledger row")):
+ s = sub.add_parser(name, help=text)
+ _add_out(s)
+ _add_iter(s)
+ s.add_argument("--note", default="")
+
+ s = sub.add_parser("status", help="the ledger and the variant version")
+ _add_out(s)
+ return ap
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ ap = build_parser()
+ ns = ap.parse_args(argv)
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
+ try:
+ return _dispatch(ns)
+ except LoopError as e:
+ print(f"error: {e}", file=sys.stderr)
+ return 2
+
+
+def _dispatch(ns: argparse.Namespace) -> int:
+ if ns.cmd == "init":
+ cfg = LoopConfig(name=ns.name, out=ns.out.resolve(), variant=ns.variant, languages=parse_languages(ns.languages),
+ generator=ns.generator, judge=ns.judge, judge_thinking=ns.judge_thinking, planner=ns.planner,
+ parallel=ns.parallel, stagger_s=ns.stagger, rounds=ns.rounds, max_minutes=ns.max_minutes, n=ns.n)
+ print(f"wrote {init(cfg)}")
+ return 0
+ cfg = LoopConfig.load(ns.out)
+ langs = parse_languages(ns.languages) if getattr(ns, "languages", "") else []
+ if ns.cmd == "generate":
+ for lang, path in generate_iteration(cfg, ns.iteration, rung=ns.rung, n=ns.n).items():
+ print(f"{lang.value}: {path}")
+ return 0
+ if ns.cmd == "run":
+ meta = run_iteration(cfg, ns.iteration, languages=langs, resume=ns.resume)
+ for name, child in meta["children"].items():
+ print(f"{name}: exit {child['returncode']} ({child['log']})")
+ print(f"wall {meta['wall_s']:.0f} s → {cfg.iter_dir(ns.iteration) / 'run.json'}")
+ return 0 if all(c["returncode"] == 0 for c in meta["children"].values()) else 1
+ if ns.cmd == "diagnose":
+ for name, d in diagnose_iteration(cfg, ns.iteration, languages=langs).items():
+ print(f"{name}: {d.n} runs, picked mean {d.picked.get('mean')}, {len(d.recommendations)} recommendation(s)")
+ print(f"→ {cfg.iter_dir(ns.iteration) / 'diagnosis.md'}")
+ return 0
+ if ns.cmd == "compare":
+ for name, c in compare_iteration(cfg, ns.iteration, ns.against, languages=langs).items():
+ print(f"{name}: {c.decision} — {c.reason}")
+ return 0
+ if ns.cmd == "judge-calib":
+ for name, s in judge_calib(cfg, ns.iteration, model_id=ns.model, thinking=ns.thinking, n_samples=ns.n,
+ languages=langs, workers=ns.workers).items():
+ print(f"{name}: within-sd {s.within_sd} between-sd {s.between_sd} SNR {s.snr} (${s.cost_usd:.2f})")
+ return 0
+ if ns.cmd in ("accept", "rollback"):
+ fn = accept if ns.cmd == "accept" else rollback
+ row = fn(cfg, ns.iteration, note=ns.note, data_dir=ns.data_dir)
+ print(f"{row.decision}: {cfg.variant} v{row.version_from} → v{row.version_to} ({row.variant_hash}); "
+ f"verdicts {row.verdicts or '—'}; ledger {ledger_path(cfg, ns.data_dir)}")
+ return 0
+ if ns.cmd == "status":
+ print(status_text(cfg, data_dir=ns.data_dir))
+ return 0
+ raise LoopError(f"unknown command {ns.cmd!r}") # pragma: no cover — argparse restricts the choices
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/eval/bench/paired_compare.py b/eval/bench/paired_compare.py
index 9ffcf47f..ad57c6bd 100644
--- a/eval/bench/paired_compare.py
+++ b/eval/bench/paired_compare.py
@@ -262,6 +262,15 @@ def arm_names(a: Path, b: Path) -> tuple[str, str]:
return "/".join(pa[-depth:]), "/".join(pb[-depth:])
+def paired_rows(out_a: Path, out_b: Path) -> tuple[dict[tuple[str, str], CellResult], str, str]:
+ """Two ``bench.run_bench`` directories as the cells of two arms, named apart
+ (:func:`arm_names`) and deduplicated (``latest``): what ``--against`` and
+ ``bench.loop compare`` pair by prompt id — ``(cells, name_a, name_b)``."""
+ name_a, name_b = arm_names(Path(out_a), Path(out_b))
+ rows = rows_from_bench_run(Path(out_a), name_a) + rows_from_bench_run(Path(out_b), name_b)
+ return latest(rows), name_a, name_b
+
+
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("out_dir", help="a compare_backends output directory (holds results.jsonl)")
@@ -271,9 +280,8 @@ def main(argv: list[str] | None = None) -> int:
ns = ap.parse_args(argv)
out = Path(ns.out_dir)
if ns.against is not None:
- name_a, name_b = arm_names(out, ns.against)
- rows = rows_from_bench_run(out, name_a) + rows_from_bench_run(ns.against, name_b)
- stats = [paired(latest(rows), name_a, name_b)]
+ cells, name_a, name_b = paired_rows(out, ns.against)
+ stats = [paired(cells, name_a, name_b)]
md = render_markdown(stats, f"{name_a} vs {name_b}")
(out / "paired.md").write_text(md)
print(md)
diff --git a/eval/bench/prompts/h2h_brilliana_v1_blender.yaml b/eval/bench/prompts/h2h_brilliana_v1_blender.yaml
deleted file mode 100644
index 41998037..00000000
--- a/eval/bench/prompts/h2h_brilliana_v1_blender.yaml
+++ /dev/null
@@ -1,39 +0,0 @@
-name: h2h_brilliana_v1_blender
-track: static_object
-language: blender
-description: >
- Head-to-head vs the astra3d-brilliana curated gallery (showcase_tier=confirmed,
- template=blender_baseline). Prompts are THEIR prompts verbatim, must_have left
- empty on purpose so the brief is identical to what their run saw. Both GLBs are
- then judged by bench/h2h_glb.py with one fixed judge.
-prompts:
- - id: h2h_microscope_x1b
- tier: medium
- category: instruments
- prompt: a laboratory optical microscope with stage, eyepiece and focus knobs
- must_have: []
- tags: [h2h, brilliana, microscope-x1b]
- - id: h2h_deskfan_v2b
- tier: medium
- category: appliances
- prompt: a retro desk fan with wire cage and tilting head
- must_have: []
- tags: [h2h, brilliana, deskfan-v2b]
- - id: h2h_espresso_bl
- tier: medium
- category: appliances
- prompt: a chrome espresso machine with portafilter, steam wand and cup tray
- must_have: []
- tags: [h2h, brilliana, espresso-bl]
- - id: h2h_office_chair_lr
- tier: medium
- category: furniture
- prompt: a modern ergonomic office chair with five caster wheels
- must_have: []
- tags: [h2h, brilliana, office-chair-lr]
- - id: h2h_street_lamp_bl
- tier: medium
- category: lighting
- prompt: a Victorian cast-iron street lamp with three frosted globes
- must_have: []
- tags: [h2h, brilliana, street-lamp-bl]
diff --git a/eval/bench/prompts/h2h_brilliana_v1_cadquery.yaml b/eval/bench/prompts/h2h_brilliana_v1_cadquery.yaml
deleted file mode 100644
index 3aed0980..00000000
--- a/eval/bench/prompts/h2h_brilliana_v1_cadquery.yaml
+++ /dev/null
@@ -1,32 +0,0 @@
-name: h2h_brilliana_v1_cadquery
-track: static_object
-language: cadquery
-description: >
- Head-to-head vs the astra3d-brilliana curated gallery (showcase_tier=confirmed,
- template=cadquery_baseline). Prompts verbatim, must_have empty on purpose.
- (tlr-camera was skipped: its stored prompt is truncated at 200 chars.)
-prompts:
- - id: h2h_gate_valve_lr
- tier: medium
- category: mechanical
- prompt: a gate valve with a handwheel and bolted flanges
- must_have: []
- tags: [h2h, brilliana, gate-valve-lr]
- - id: h2h_telescope
- tier: medium
- category: instruments
- prompt: a brass refractor telescope on a wooden tripod, a long cylindrical tube with focus knobs, an eyepiece, a small finder scope, an adjustable altazimuth mount, antique scientific instrument
- must_have: []
- tags: [h2h, brilliana, telescope]
- - id: h2h_c_clamp_mv
- tier: medium
- category: tools
- prompt: a C-clamp with a threaded screw and swivel pad
- must_have: []
- tags: [h2h, brilliana, c-clamp-mv]
- - id: h2h_pipe_tee_c5
- tier: medium
- category: mechanical
- prompt: a pipe tee fitting with bolted flanges on all three ends
- must_have: []
- tags: [h2h, brilliana, pipe-tee-c5]
diff --git a/eval/bench/prompts/h2h_brilliana_v1_threejs.yaml b/eval/bench/prompts/h2h_brilliana_v1_threejs.yaml
deleted file mode 100644
index 7a8ce70d..00000000
--- a/eval/bench/prompts/h2h_brilliana_v1_threejs.yaml
+++ /dev/null
@@ -1,25 +0,0 @@
-name: h2h_brilliana_v1_threejs
-track: static_object
-language: threejs
-description: >
- Head-to-head vs the astra3d-brilliana curated gallery (showcase_tier=confirmed,
- template=react_threejs / threejs). Prompts verbatim, must_have empty on purpose.
-prompts:
- - id: h2h_desk_lamp_q2
- tier: medium
- category: lighting
- prompt: a vintage brass desk lamp with an articulated arm and a green glass shade
- must_have: []
- tags: [h2h, brilliana, desk-lamp-q2]
- - id: h2h_clock_q4
- tier: medium
- category: furniture
- prompt: an antique grandfather clock with a brass pendulum and glass door
- must_have: []
- tags: [h2h, brilliana, clock-q4]
- - id: h2h_lighthouse_1
- tier: medium
- category: buildings
- prompt: a red-and-white striped lighthouse with a lantern room and gallery railing
- must_have: []
- tags: [h2h, brilliana, lighthouse-1]
diff --git a/eval/bench/prompts/h2h_designmode_v1.yaml b/eval/bench/prompts/h2h_designmode_v1.yaml
deleted file mode 100644
index d0de6f97..00000000
--- a/eval/bench/prompts/h2h_designmode_v1.yaml
+++ /dev/null
@@ -1,670 +0,0 @@
-# h2h_designmode_v1 — generated 2026-09-25 from the design-mode repo (commit 465e8ad); edit here, not by hand-copying.
-name: h2h_designmode_v1
-track: static_object
-language: threejs
-description: 100 object briefs from github.com/jameson475/3d_batch_with_designmode (Claude Design outputs in its
- code/), verbatim, no must_have — every arm gets exactly the brief Claude Design got. tier = the repo's detail
- level (simple→easy, medium→medium, detailed→hard). ids are the repo's file stems, so `import:<repo>/code` scores
- Claude Design's own build(THREE) modules as src/object.js.
-prompts:
-- id: 01_desk_lamp
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: An articulated desk lamp with a weighted round base, two arm segments joined by hinges, and a cone shade
- with a glowing bulb.
-- id: 02_wooden_chair
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A simple Scandinavian wooden dining chair with four tapered legs, a slatted backrest, and a light oak
- finish.
-- id: 03_ceramic_mug
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A glazed ceramic coffee mug with a curved handle, a thick rim, and dark coffee inside.
-- id: 04_potted_succulent
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A small terracotta pot holding an echeveria succulent with rosette leaves arranged in a golden-angle spiral.
-- id: 05_retro_rocket
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A 1950s retro rocket ship with a pointed nose cone, porthole window, three swept fins, and a flame exhaust.
-- id: 06_lighthouse
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A red-and-white striped lighthouse on a rocky base, with a gallery railing and a glowing lantern room.
-- id: 07_bonsai_tree
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A bonsai tree in a shallow rectangular tray, with a recursively branching trunk and clustered foliage
- pads.
-- id: 08_toy_robot
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A boxy tin toy robot with antenna, glowing eyes, chest dial panel, jointed arms with claw hands, and wind-up
- key.
-- id: 09_spiral_staircase
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A cast-iron spiral staircase with 20 wedge-shaped treads around a central pole and a helical handrail.
-- id: 10_hot_air_balloon
- tier: hard
- category: batch_01
- tags:
- - detailed
- prompt: A hot air balloon with a teardrop envelope in alternating colored gores, suspension ropes, a burner, and
- a wicker basket.
-- id: 11_vintage_radio
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A 1940s tabletop tube radio with a rounded-top walnut cabinet, a fabric speaker grille, a glowing tuning
- dial, and two knobs.
-- id: 12_windmill
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A Dutch windmill with an octagonal tapered tower, a thatched cap, four lattice sails, and a wraparound
- balcony.
-- id: 13_sailboat
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A small wooden sloop sailboat with a curved hull, a single mast, a triangular mainsail and jib, and a
- boom.
-- id: 14_acoustic_guitar
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: An acoustic guitar with a figure-eight spruce body, a sound hole with rosette, a long fretted neck, a
- headstock with tuning pegs, and six strings.
-- id: 15_park_bench
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A classic park bench with cast-iron scrolled side frames, wooden slat seat and curved backrest, and armrests.
-- id: 16_mushroom_cluster
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A cluster of five fly-agaric mushrooms of different sizes growing from a mossy log, red caps with white
- spots.
-- id: 17_castle_tower
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A medieval stone castle tower with crenellated battlements, arrow-slit windows, a wooden door, and a flag
- on a pole.
-- id: 18_hourglass
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: An antique hourglass with a turned wooden frame, three spindle posts, a glass double bulb, and sand mid-flow.
-- id: 19_satellite
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A communications satellite with a gold-foil bus, two deployable solar panel wings, a parabolic dish antenna,
- and thruster nozzles.
-- id: 20_treasure_chest
- tier: hard
- category: batch_02
- tags:
- - detailed
- prompt: A pirate treasure chest with a half-cylinder lid propped open, iron bands and rivets, a padlock hasp,
- and gold coins spilling out.
-- id: 21_bicycle
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A classic city bicycle with spoked wheels, a diamond steel frame, a leather saddle, curved handlebars,
- and a front basket.
-- id: 22_grand_piano
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A glossy black grand piano with a curved case, a propped-open lid, 52 white and 36 black keys, three legs,
- and pedals.
-- id: 23_teapot
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A round porcelain teapot with blue bands, a curved spout, a loop handle, and a lid with a knob, on a saucer.
-- id: 24_film_camera
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A vintage 35mm rangefinder film camera with a leatherette body, chrome top plate, a lens barrel with focus
- ring, dials, and a shutter button.
-- id: 25_desk_fan
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A retro oscillating desk fan with a round wire cage, four curved blades, a motor housing, a tilting neck,
- and a heavy base.
-- id: 26_wine_set
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A dark green wine bottle with a cork and label beside a stemmed wine glass half-filled with red wine.
-- id: 27_anvil
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A blacksmith's anvil with a tapered horn, a flat face with a hardy hole, a waisted body, mounted on a
- tree-stump block with a hammer resting on it.
-- id: 28_fire_hydrant
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A red cast-iron fire hydrant with a domed bonnet, a pentagonal operating nut, two side hose outlets with
- chained caps, and a flanged base bolted to the sidewalk.
-- id: 29_umbrella
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: An open umbrella with an eight-panel canopy in alternating colors, visible ribs, a finial tip, and a curved
- wooden J-handle, tilted as if held.
-- id: 30_pagoda
- tier: hard
- category: batch_03
- tags:
- - detailed
- prompt: A five-tiered East Asian pagoda on a stone plinth, each tier with red columns and upturned curved eaves,
- topped by a bronze spire with rings.
-- id: 31_steam_locomotive
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A toy-scale steam locomotive with a cylindrical boiler, smokestack, steam dome, cab with windows, cowcatcher,
- and six red driving wheels linked by coupling rods.
-- id: 32_desk_globe
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A desk globe tilted at 23.5 degrees on a brass meridian ring and a turned wooden stand, with procedurally
- generated continents.
-- id: 33_bookshelf
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A wooden bookshelf with four shelves filled with books of varied heights, thicknesses and colors, some
- leaning, plus a small plant on top.
-- id: 34_candelabra
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: An ornate silver five-arm candelabra with S-curved arms, drip cups, lit white candles with flames, and
- a turned base.
-- id: 35_birdhouse
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A painted wooden birdhouse on a post, with a pitched shingled roof, a round entrance hole, a perch dowel,
- and a small bird sitting on the roof.
-- id: 36_snowman
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A three-ball snowman with a carrot nose, coal eyes and buttons, stick arms, a knitted striped scarf, and
- a black top hat, standing on a snowy mound.
-- id: 37_telescope
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A brass refracting telescope on a wooden tripod with an altitude mount, a finder scope, an eyepiece, and
- a dew shield, pointed at the sky.
-- id: 38_wooden_barrel
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: An oak wine barrel built from individual bulging staves held by four iron hoops, with a round head and
- a bung hole, lying on a wooden cradle.
-- id: 39_wind_chime
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A hanging wind chime with a round wooden top disk, six aluminum tubes of graded lengths on strings, a
- central striker, and a sail.
-- id: 40_oil_lantern
- tier: hard
- category: batch_04
- tags:
- - detailed
- prompt: A hurricane oil lantern with a red-painted fuel tank, a glass globe with a glowing flame, a wire guard,
- a vented cap, and a bail handle.
-- id: 41_office_chair
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: An ergonomic office swivel chair with a five-star base on casters, a gas-lift column, a padded seat, a
- curved mesh backrest, and armrests.
-- id: 42_knight_helmet
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: 'A medieval knight''s great helm on a display stand: a steel bucket helmet with a riveted cross reinforcement,
- eye slits, breathing holes, and a red plume.'
-- id: 43_microscope
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A laboratory compound microscope with a curved arm, an angled eyepiece tube, a rotating nosepiece with
- three objectives, a mechanical stage with slide clips, coarse and fine focus knobs, and a base lamp.
-- id: 44_cupcake
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A cupcake in a pleated paper liner topped with a swirled pink frosting spiral, rainbow sprinkles, and
- a cherry with a stem.
-- id: 45_traffic_cones
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: Three orange traffic cones with white reflective bands on square black bases, one knocked over, next to
- a striped road barrier on A-frame legs.
-- id: 46_chess_set
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A corner of a wooden chessboard with a Staunton-style king, queen, rook, bishop, and pawn in ivory and
- ebony, all turned on a lathe.
-- id: 47_wheelbarrow
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A garden wheelbarrow with a deep green steel tray, a single pneumatic front wheel, tubular handles with
- rubber grips, rear legs, and a load of soil.
-- id: 48_jellyfish
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A translucent glowing jellyfish with a scalloped bell, frilly oral arms, and long trailing tentacles that
- wave in sine curves.
-- id: 49_grandfather_clock
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A tall mahogany grandfather clock with an arched hood, a clock face with Roman-numeral ticks and hands,
- a glass-front trunk showing a brass pendulum and weights, and a plinth base.
-- id: 50_ferris_wheel
- tier: hard
- category: batch_05
- tags:
- - detailed
- prompt: A carnival Ferris wheel with a double-rim spoked wheel, twelve colorful gondolas hanging level, an A-frame
- support tower, and light bulbs along the rim.
-- id: 51_apple
- tier: easy
- category: batch_06
- tags:
- - simple
- prompt: A red apple.
-- id: 52_donut
- tier: easy
- category: batch_06
- tags:
- - simple
- prompt: A donut with pink icing and sprinkles.
-- id: 53_coffee_table
- tier: medium
- category: batch_06
- tags:
- - medium
- prompt: A mid-century modern coffee table with a walnut oval top and splayed legs.
-- id: 54_rubber_duck
- tier: easy
- category: batch_06
- tags:
- - simple
- prompt: A rubber duck.
-- id: 55_pencil
- tier: easy
- category: batch_06
- tags:
- - simple
- prompt: A yellow pencil.
-- id: 56_alarm_clock
- tier: medium
- category: batch_06
- tags:
- - medium
- prompt: A classic twin-bell alarm clock with a hammer between the bells and little feet.
-- id: 57_saguaro_cactus
- tier: medium
- category: batch_06
- tags:
- - medium
- prompt: A saguaro cactus with two arms in a clay pot, with ribbed stems and spines.
-- id: 58_laptop
- tier: medium
- category: batch_06
- tags:
- - medium
- prompt: An open laptop with a keyboard, trackpad, and a glowing screen.
-- id: 59_electric_guitar
- tier: hard
- category: batch_06
- tags:
- - detailed
- prompt: A sunburst electric guitar with an offset double-cutaway solid body, a white pickguard, three single-coil
- pickups, volume and tone knobs, a whammy bar, a maple neck with dot inlays, and a six-in-line headstock.
-- id: 60_space_shuttle
- tier: hard
- category: batch_06
- tags:
- - detailed
- prompt: 'A space shuttle orbiter stacked for launch: the white orbiter with black heat-shield underside and delta
- wings, mounted on a large orange external fuel tank flanked by two white solid rocket boosters, standing on
- a launch platform.'
-- id: 61_tree
- tier: easy
- category: batch_07
- tags:
- - simple
- prompt: A tree.
-- id: 62_house
- tier: easy
- category: batch_07
- tags:
- - simple
- prompt: A small house.
-- id: 63_old_key
- tier: easy
- category: batch_07
- tags:
- - simple
- prompt: An old key.
-- id: 64_street_lamp
- tier: medium
- category: batch_07
- tags:
- - medium
- prompt: A Victorian cast-iron street lamp with a lantern head and a fluted post.
-- id: 65_sofa
- tier: medium
- category: batch_07
- tags:
- - medium
- prompt: A three-seat fabric sofa with rounded arms, seat cushions, and throw pillows.
-- id: 66_fishbowl
- tier: medium
- category: batch_07
- tags:
- - medium
- prompt: A round glass fishbowl with water, gravel, a plant, and a goldfish.
-- id: 67_viking_ship
- tier: hard
- category: batch_07
- tags:
- - detailed
- prompt: A Viking longship with an overlapping clinker-built plank hull, a carved dragon-head prow and curled stern,
- a single mast with a red-and-white striped square sail, a row of painted round shields along each gunwale, and
- oars.
-- id: 68_drum_kit
- tier: hard
- category: batch_07
- tags:
- - detailed
- prompt: 'A five-piece rock drum kit: a bass drum with a logo head and pedal, a snare on a stand, two rack toms
- mounted on the bass drum, a floor tom on legs, a hi-hat, and two cymbals on boom stands, all with sparkle-red
- wraps and chrome hoops.'
-- id: 69_mailbox
- tier: easy
- category: batch_07
- tags:
- - simple
- prompt: A mailbox.
-- id: 70_skateboard
- tier: medium
- category: batch_07
- tags:
- - medium
- prompt: A skateboard with a concave deck, kicktails, trucks, and colorful wheels.
-- id: 71_star
- tier: easy
- category: batch_08
- tags:
- - simple
- prompt: A gold star.
-- id: 72_gem
- tier: easy
- category: batch_08
- tags:
- - simple
- prompt: A blue gemstone.
-- id: 73_bucket
- tier: easy
- category: batch_08
- tags:
- - simple
- prompt: A metal bucket.
-- id: 74_toaster
- tier: medium
- category: batch_08
- tags:
- - medium
- prompt: A retro chrome two-slice toaster with toast popping out.
-- id: 75_headphones
- tier: medium
- category: batch_08
- tags:
- - medium
- prompt: Over-ear headphones with a padded headband and cushioned ear cups.
-- id: 76_excavator
- tier: hard
- category: batch_08
- tags:
- - detailed
- prompt: A yellow hydraulic excavator on steel crawler tracks, with a rotating cab with windows, a counterweight,
- and an articulated boom, stick, and toothed bucket driven by hydraulic cylinders, digging pose.
-- id: 77_carousel
- tier: hard
- category: batch_08
- tags:
- - detailed
- prompt: A fairground carousel with a striped conical canopy with scalloped valance, a central mirrored column,
- twisted brass poles, eight horses at alternating heights, a round wooden platform, and bulbs around the canopy
- edge.
-- id: 78_ice_cream
- tier: easy
- category: batch_08
- tags:
- - simple
- prompt: An ice cream cone.
-- id: 79_picnic_table
- tier: medium
- category: batch_08
- tags:
- - medium
- prompt: A wooden picnic table with attached benches and a checkered tablecloth.
-- id: 80_trophy
- tier: medium
- category: batch_08
- tags:
- - medium
- prompt: A gold trophy cup with two handles on a marble base.
-- id: 81_cloud
- tier: easy
- category: batch_09
- tags:
- - simple
- prompt: A cloud.
-- id: 82_mushroom_house
- tier: medium
- category: batch_09
- tags:
- - medium
- prompt: A fairy-tale mushroom house with a round door, windows, and a chimney.
-- id: 83_biplane
- tier: hard
- category: batch_09
- tags:
- - detailed
- prompt: A 1930s biplane with fabric-covered upper and lower wings joined by struts and bracing wires, an open
- cockpit with a windscreen, a radial engine with a two-blade wooden propeller, a tail with rudder and elevators,
- and fixed landing gear with spoked wheels.
-- id: 84_vase
- tier: easy
- category: batch_09
- tags:
- - simple
- prompt: A vase.
-- id: 85_watering_can
- tier: medium
- category: batch_09
- tags:
- - medium
- prompt: A green metal watering can with a long spout and a sprinkler rose.
-- id: 86_stone_bridge
- tier: hard
- category: batch_09
- tags:
- - detailed
- prompt: A medieval stone arch bridge with three semicircular arches of individual voussoir stones, cutwater piers,
- a paved deck, and low parapet walls, spanning a stream.
-- id: 87_toy_blocks
- tier: easy
- category: batch_09
- tags:
- - simple
- prompt: Toy blocks.
-- id: 88_sewing_machine
- tier: hard
- category: batch_09
- tags:
- - detailed
- prompt: An antique black cast-iron sewing machine with gold decals, a curved arm and head, a hand wheel, a needle
- bar and presser foot above a chrome bed plate, a thread spool on a pin, mounted on a wooden base.
-- id: 89_bell
- tier: easy
- category: batch_09
- tags:
- - simple
- prompt: A bell.
-- id: 90_kite
- tier: easy
- category: batch_09
- tags:
- - simple
- prompt: A kite.
-- id: 91_snail
- tier: medium
- category: batch_10
- tags:
- - medium
- prompt: A garden snail with a spiral shell and eye stalks.
-- id: 92_robot_vacuum
- tier: easy
- category: batch_10
- tags:
- - simple
- prompt: A robot vacuum.
-- id: 93_water_tower
- tier: medium
- category: batch_10
- tags:
- - medium
- prompt: A rooftop wooden water tower on a steel stand with a conical roof and a ladder.
-- id: 94_typewriter
- tier: hard
- category: batch_10
- tags:
- - detailed
- prompt: 'A 1920s manual typewriter in black enamel: four staggered rows of round glass-topped keys with chrome
- rims, a semicircular basket of typebars, a platen roller with knobs and a sheet of paper, a carriage return
- lever, and gold lettering.'
-- id: 95_igloo
- tier: easy
- category: batch_10
- tags:
- - simple
- prompt: An igloo.
-- id: 96_tent
- tier: easy
- category: batch_10
- tags:
- - simple
- prompt: A camping tent.
-- id: 97_submarine
- tier: medium
- category: batch_10
- tags:
- - medium
- prompt: A yellow cartoon submarine with portholes, a periscope, and a propeller.
-- id: 98_treehouse
- tier: hard
- category: batch_10
- tags:
- - detailed
- prompt: 'A treehouse built into a large oak: a thick trunk with branching limbs and leafy canopy clusters, a plank
- platform with railings resting on the branches, a small cabin with a shingled roof and a window, a rope ladder
- hanging to the ground, and a tire swing on another branch.'
-- id: 99_pumpkin
- tier: easy
- category: batch_10
- tags:
- - simple
- prompt: A pumpkin.
-- id: 100_gramophone
- tier: hard
- category: batch_10
- tags:
- - detailed
- prompt: 'An antique gramophone: a square mahogany cabinet with a side winding crank, a turntable with a black
- shellac record showing grooves and a red label, a curved tonearm with a soundbox and needle, and a large flared
- brass horn.'
diff --git a/eval/bench/prompts/h2h_scene_v1.yaml b/eval/bench/prompts/h2h_scene_v1.yaml
deleted file mode 100644
index 1cf94c68..00000000
--- a/eval/bench/prompts/h2h_scene_v1.yaml
+++ /dev/null
@@ -1,41 +0,0 @@
-name: h2h_scene_v1
-track: scene
-language: scene_threejs
-description: >
- Head-to-head SCENE battery: 5 prompts taken VERBATIM from the owner's previous
- harnesses (scene_multifile x4, scene_multifile_graphics x1; prompts/input.md of
- each output, whole file, nothing stripped). must_have is deliberately EMPTY so
- neither side is scored against a checklist the other never saw; the fixed judge
- is bench/h2h_scene.py (scene_v1, gemini-3.1-pro-preview, n=2) over both sides'
- authored-camera stills.
-prompts:
- - id: h2h_bb1_bigben
- tier: hard
- category: landmark
- tags: [h2h, scene_multifile, bb1_bigben]
- prompt: |-
- Westminster at golden hour seen from the south bank of the Thames: Big Ben's clock tower rising over the Houses of Parliament with its full gothic riverfront facade, Westminster Bridge crossing the foreground with red double-decker buses and black cabs in traffic, the London Eye downstream catching the light, river boats mid-crossing, wrought-iron lamp posts and crowds of tourists along both embankments, the river alive with reflections, pigeons wheeling over the water.
- - id: h2h_co1_colosseum
- tier: hard
- category: landmark
- tags: [h2h, scene_multifile, co1_colosseum]
- prompt: |-
- The Roman Colosseum at midday, seen whole from the Piazza del Colosseo: the full elliptical amphitheatre with its four tiers, arched arcades ringing every level, the broken upper ring exposing the inner wall, travertine gleaming, the hypogeum passages visible through the open arena floor, tour groups and street vendors around the base, horse carriages and scooters on the cobbled piazza, umbrella pines and the Arch of Constantine to one side, hard Mediterranean shadows.
- - id: h2h_ct2_x_bookstore
- tier: easy
- category: interior
- tags: [h2h, scene_multifile, ct2_x_bookstore]
- prompt: |-
- A cozy bookstore interior with warm lighting, tall shelves of books, and a reading nook
- - id: h2h_ct2_wg_cyberpunk
- tier: easy
- category: urban
- tags: [h2h, scene_multifile, ct2_wg_cyberpunk]
- prompt: |-
- A neon-lit cyberpunk street with rain reflections
- - id: h2h_b01_neon_alley
- tier: medium
- category: urban
- tags: [h2h, scene_multifile_graphics, b01_neon_alley]
- prompt: |-
- A narrow city alley at night full of neon signs, their light thrown onto the wet road and the facing wall, steam from a vent, a few people walking.
diff --git a/eval/bench/run_bench.py b/eval/bench/run_bench.py
index 850d476e..08b2c897 100644
--- a/eval/bench/run_bench.py
+++ b/eval/bench/run_bench.py
@@ -34,8 +34,10 @@ import sys
import traceback
from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
+from contextlib import AbstractContextManager, nullcontext
from datetime import UTC, datetime
from pathlib import Path
+from time import sleep
from typing import Any
import yaml
@@ -51,9 +53,9 @@ from codeverse3d.addons import select # noqa: E402
from codeverse3d.config import get_settings # noqa: E402
from codeverse3d.contracts.common import TRACK_INFO, Backends, Budget, Language, Track # noqa: E402
from codeverse3d.contracts.run import RunRecord # noqa: E402
-from codeverse3d.contracts.spec import Constraints, ReferenceImage, Spec # noqa: E402
+from codeverse3d.contracts.spec import Constraints, ReferenceImage, RunOptions, Spec # noqa: E402
from codeverse3d.cost import run_ledger # noqa: E402
-from codeverse3d.proc import exclusive # noqa: E402
+from codeverse3d.proc import exclusive, install_stop_handlers # noqa: E402
from codeverse3d.record.record import load_record # noqa: E402
from codeverse3d.workspace import Workspace # noqa: E402
@@ -127,6 +129,9 @@ class BenchOptions(BaseModel):
#: in flight, so 8 cells sit near 7 — far inside the 64-call model knee — and
#: their builds sit inside the 16-build subprocess knee.
parallel: int = 8
+ stagger_s: float = Field(default=0.0, ge=0.0,
+ description="seconds between the launches of the FIRST wave's workers; later cells "
+ "start when an earlier one finishes, which is already staggered")
limit: int | None = None
ids: list[str] = Field(default_factory=list)
tiers: list[str] = Field(default_factory=list)
@@ -136,6 +141,8 @@ class BenchOptions(BaseModel):
redo_status: list[str] = Field(default_factory=list,
description="re-run prompts already recorded with one of these statuses "
"(the point of `infra_failed`: retry what the weather lost)")
+ variant: str = Field(default="", description="the per-model prompt/skill variant every run is created with "
+ "(RunOptions.variant, D105); '' = resolve from Settings like `3dcode make`")
REFS_DIR = Path(__file__).resolve().parent / "refs"
@@ -172,23 +179,54 @@ def discover_references(item: BenchPrompt, track: Track, *, battery_dir: Path |
def build_spec(
battery: Battery, item: BenchPrompt, *, backends: Backends, rounds: int,
- max_minutes: float, tag0: str, extra_tags: Sequence[str] = (),
+ max_minutes: float, tag0: str, extra_tags: Sequence[str] = (), variant: str = "",
) -> Spec:
"""Shared Spec core for bench drivers (``run_bench`` / ``compare_backends``).
- Drivers resolve their own ``Backends`` and pass their leading tag."""
+ Drivers resolve their own ``Backends`` and pass their leading tag; ``variant`` is frozen on
+ ``RunOptions.variant`` the way ``3dcode make --variant`` freezes it (the track activates it)."""
return Spec(
id=f"{battery.name}/{item.id}", track=battery.track, language=item.language or battery.language, prompt=item.prompt,
constraints=Constraints(must_have=list(item.must_have), dimensions_m=item.dimensions_m),
references=discover_references(item, battery.track, battery_dir=battery.source_dir),
budget=Budget(max_rounds=rounds, max_minutes=max_minutes),
backends=backends, tags=[tag0, battery.name, item.tier, item.category, *extra_tags, *item.tags],
+ options=RunOptions(variant=variant),
)
+def resolve_variant(name: str, generator_id: str) -> str:
+ """The variant a bench run is created with: ``name`` when stated (``--variant``), else what the
+ settings resolve for the generator (``prompts.variants.resolve_variant`` — the same rule as
+ ``3dcode make``), else the base. A tree without the variant layer (pre-D105) resolves to the base
+ unless a name was stated, which it cannot honour."""
+ if name:
+ return name
+ try:
+ from codeverse3d.prompts.variants import resolve_variant as _resolve
+ except ImportError:
+ return ""
+ return str(_resolve(get_settings(), generator_id) or "")
+
+
+def activate_variant(name: str) -> AbstractContextManager[Any]:
+ """``prompts.variants.activate(name)`` for the block (prompt / skill loads of THIS thread read the
+ overlay) — a no-op for the base. A stated name on a tree without the layer is an error, never a
+ silent base run: that would be an A/B comparing a tree against itself."""
+ if not name:
+ return nullcontext()
+ try:
+ from codeverse3d.prompts.variants import activate
+ except ImportError as e:
+ raise RuntimeError(f"--variant {name!r} needs codeverse3d.prompts.variants (D105), which this tree "
+ f"does not have: {e}") from e
+ return activate(name)
+
+
def spec_for(battery: Battery, item: BenchPrompt, opts: BenchOptions) -> Spec:
backends = get_settings().backends(generator=opts.generator, planner=opts.planner, judge=opts.judge)
return build_spec(battery, item, backends=backends, rounds=opts.rounds,
- max_minutes=opts.max_minutes, tag0="bench")
+ max_minutes=opts.max_minutes, tag0="bench",
+ variant=resolve_variant(opts.variant, backends.generator))
def record_minutes(run_dir: Path) -> float:
@@ -278,8 +316,19 @@ def run_battery(
battery_path: Path | str, out_dir: Path | str, opts: BenchOptions | None = None, *,
run_fn: RunFn | None = None, on_result: Callable[[BenchItemResult], None] | None = None,
) -> list[BenchItemResult]:
- """Run (or resume) a battery; returns every result (previous + new)."""
+ """Run (or resume) a battery; returns every result (previous + new). A stated ``opts.variant``
+ is active for the whole battery (``activate_variant``) and frozen on every spec, which is what
+ the worker threads' runs read (``BaseTrack.run`` activates ``spec.options.variant`` — a
+ ContextVar does not cross into a pool thread by itself)."""
opts = opts or BenchOptions()
+ with activate_variant(opts.variant):
+ return _run_battery(battery_path, out_dir, opts, run_fn=run_fn, on_result=on_result)
+
+
+def _run_battery(
+ battery_path: Path | str, out_dir: Path | str, opts: BenchOptions, *,
+ run_fn: RunFn | None, on_result: Callable[[BenchItemResult], None] | None,
+) -> list[BenchItemResult]:
run_fn = run_fn or default_run_track
battery = Battery.load(battery_path)
out = Path(out_dir)
@@ -295,7 +344,14 @@ def run_battery(
del done[pid]
todo = [p for p in select_prompts(battery, ids=opts.ids, tiers=opts.tiers, limit=opts.limit) if p.id not in done]
- def _one(item: BenchPrompt) -> BenchItemResult:
+ def _one(k: int, item: BenchPrompt) -> BenchItemResult:
+ if opts.stagger_s > 0 and 0 < k < opts.parallel:
+ # The first wave launches together, and every run plans and single-shots its assets the
+ # moment it starts — N of those at once is what exhausts the key pool (loop iteration 0:
+ # 160 of its 172 `asset.generate_failed` outages fell in the runs' first ten minutes). A
+ # later cell starts when an earlier one finishes, which is staggered by itself. Before
+ # the workspace, so a resumed or --redo-status cell staggers too.
+ sleep(k * opts.stagger_s)
ws = Workspace(out / "runs" / item.id)
if item.id in redo_ids and ws.exists():
# A redo starts FRESH: resuming the old workspace keeps its spec (the old
@@ -331,7 +387,7 @@ def run_battery(
seal_for_append(results_jsonl) # a kill left the last row unterminated; do not glue onto it
with ThreadPoolExecutor(max_workers=max(1, opts.parallel)) as pool, results_jsonl.open("a") as fh:
- futs = {pool.submit(_one, item): item for item in todo}
+ futs = {pool.submit(_one, k, item): item for k, item in enumerate(todo)}
for fut in as_completed(futs):
res = fut.result()
done[res.id] = res
@@ -363,6 +419,9 @@ def main(argv: Sequence[str] | None = None) -> int:
ap.add_argument("--judge", help="fixed judge model for the whole battery")
ap.add_argument("--parallel", type=int, default=None,
help="workers (default: BenchOptions.parallel — the measured knee)")
+ ap.add_argument("--stagger", type=float, default=None,
+ help="seconds between the launches of the first wave's workers (default: BenchOptions.stagger_s, "
+ "0 = all at once); a cell that starts when another finishes is staggered by itself")
ap.add_argument("--rounds", type=int, default=4)
ap.add_argument("--max-minutes", type=float, default=60.0,
help="wall-clock budget per run; size it to the weather (RUNBOOK 7.x: 120 in a 503 storm, "
@@ -374,19 +433,27 @@ def main(argv: Sequence[str] | None = None) -> int:
help="comma list of recorded statuses to re-run, e.g. infra_failed once the provider recovers")
ap.add_argument("--report", action=argparse.BooleanOptionalAction, default=True,
help="write report.md + report.html when the battery ends")
+ ap.add_argument("--variant", default="",
+ help="per-model prompt/skill variant for every run (codeverse3d/prompts/variants/<name>, D105); "
+ "default: what the settings resolve for the generator, like `3dcode make`")
ns = ap.parse_args(argv)
if not ns.battery.is_file():
ap.error(f"battery not found: {ns.battery}")
- if ns.rounds < 0 or (ns.parallel is not None and ns.parallel < 1):
- ap.error("--rounds must be >= 0 and --parallel >= 1")
- # one source of truth for the worker count: BenchOptions.parallel (the measured knee)
+ if ns.rounds < 0 or (ns.parallel is not None and ns.parallel < 1) or (ns.stagger is not None and ns.stagger < 0):
+ ap.error("--rounds must be >= 0, --parallel >= 1 and --stagger >= 0")
+ # A SIGTERM (the loop driver stopping, a timeout) kills every live agent / blender / chrome group
+ # of this battery and ends the process so the runs record their stop; without it the worker
+ # threads' children outlived the driver and kept billing (live, 2026-10-13).
+ install_stop_handlers()
+ # one source of truth for the worker count and the stagger: BenchOptions (the measured knee; none)
opts = BenchOptions(generator=ns.generator, planner=ns.planner, judge=ns.judge, rounds=ns.rounds,
max_minutes=ns.max_minutes, limit=ns.limit, ids=ns.ids, tiers=ns.tiers,
- redo_status=[x for x in ns.redo_status.split(",") if x],
- **({} if ns.parallel is None else {"parallel": ns.parallel}))
+ redo_status=[x for x in ns.redo_status.split(",") if x], variant=ns.variant,
+ **({} if ns.parallel is None else {"parallel": ns.parallel}),
+ **({} if ns.stagger is None else {"stagger_s": ns.stagger}))
out = ns.out or Path(__file__).resolve().parent / "out" / ns.battery.stem
- print(f"battery={ns.battery} out={out} generator={ns.generator or 'default'} judge={ns.judge or 'default'}",
- flush=True)
+ print(f"battery={ns.battery} out={out} generator={ns.generator or 'default'} judge={ns.judge or 'default'}"
+ + (f" variant={ns.variant}" if ns.variant else ""), flush=True)
def _on(res: BenchItemResult) -> None:
print(f" [{res.status}] {res.id}: baseline={res.score_baseline} picked={res.score_picked} "
diff --git a/eval/bench/scene_regate.py b/eval/bench/scene_regate.py
index ee7e9853..0bae3a56 100644
--- a/eval/bench/scene_regate.py
+++ b/eval/bench/scene_regate.py
@@ -12,8 +12,17 @@ connectivity threshold from 374 recorded rounds.
Per run it prints the ERROR findings the record holds, the ERROR findings the current
`scene_placement` raises on the same workspace, and the difference split into GONE and
-NEW. A rule that only ever produces GONE has not been shown to be safe — it has been
-shown to be quiet; read the NEW column and the ones that stayed.
+NEW — per run by message, and over the corpus PER KIND (typed `data.kind`: floating,
+sunken, unsupported, cantilevered, interpenetration, scale, free_exempt), which is the
+column a threshold change is read in. A rule that only ever produces GONE has not been
+shown to be safe — it has been shown to be quiet; read the NEW column and the ones that
+stayed.
+
+A scene_blender record (entry `src/scene.py`) is probed on the census GLB its last build
+kept (`artifacts/census.glb`, through the same driver and placement code, no settle — D3)
+with the bpy facts merged as the build merged them; a run whose GLB is gone is rebuilt by
+the runtime's own probe on a COPY of the workspace, since that probe writes its artifacts
+and a recorded run is read-only.
`scene_frames` is not re-run here: its findings need pixels, so re-evaluating it costs a
render per camera rather than one probe. Use `runtime_js/render_scene.mjs` directly for
@@ -24,14 +33,22 @@ from __future__ import annotations
import argparse
import json
+import shutil
import sys
+import tempfile
+from collections import Counter
from pathlib import Path
+from typing import Any
for _p in (Path(__file__).resolve().parents[2] / "harness", Path(__file__).resolve().parents[1]):
sys.path.insert(0, str(_p)) # this tree's codeverse3d (harness/) + the `bench` package (eval/)
from bench._records import records # noqa: E402
-from codeverse3d.contracts.artifacts import Severity # noqa: E402
+from codeverse3d.contracts.artifacts import GateReport, Severity # noqa: E402
+from codeverse3d.contracts.common import ENTRY_FILE, Language # noqa: E402
+from codeverse3d.languages.base import get_runtime # noqa: E402
+from codeverse3d.proc import read_json_or_none # noqa: E402
+from codeverse3d.spatial.probes import offline_report # noqa: E402
from codeverse3d.spatial.render_scene import ( # noqa: E402
SceneRenderError,
probe_env_args,
@@ -41,49 +58,129 @@ from codeverse3d.spatial.scene_placement import placement_gate # noqa: E402
from codeverse3d.workspace import Workspace # noqa: E402
GATE = "scene_placement"
+#: the kinds the corpus table reports, in the order the gate grades them (typed ``data.kind``)
+KINDS = ("floating", "sunken", "unsupported", "cantilevered", "interpenetration", "scale", "free_exempt")
+#: what a copy of a scene_blender workspace needs to build again — the agent's sources, the hero
+#: GLBs, the plan, the stage records the gate reads — never the round's artifacts, renders or git
+WORKSPACE_PARTS = ("src", "public", "plan.json", "spec.json", "stages")
+
+
+def run_language(record: dict[str, Any]) -> Language:
+ """The record's scene language (``spec.language``); a record from before scene_blender is three.js."""
+ raw = (record.get("spec") or {}).get("language")
+ return Language(str(raw)) if raw else Language.SCENE_THREEJS
def scene_runs(root: Path) -> list[Path]:
- """Every recorded scene run under ``root`` that still has a workspace to probe."""
- return [rec.parent for rec, _ in records(root, track="scene") if (rec.parent / "src" / "scene.js").is_file()]
+ """Every recorded scene run under ``root`` that still has its language's entry file to probe."""
+ return [rec.parent for rec, data in records(root, track="scene")
+ if (rec.parent / ENTRY_FILE[run_language(data)]).is_file()]
-def recorded_errors(record: dict) -> list[str]:
- """The ERROR messages `scene_placement` raised in the LAST recorded round."""
+def _last_placement_findings(record: dict[str, Any]) -> list[dict[str, Any]]:
+ """The `scene_placement` findings of the LAST recorded round (as the record wrote them)."""
for rnd in reversed(record.get("rounds") or []):
for g in rnd.get("gates") or []:
if g.get("gate") == GATE:
- return [str(f.get("message", "")) for f in (g.get("findings") or [])
- if f.get("severity") == "error"]
+ return [f for f in (g.get("findings") or []) if isinstance(f, dict)]
return []
-def probe(ws: Path, *, timeout_s: float) -> dict | None:
- """Boot the workspace and return its census, or None when it will not boot. The driver
- runs as the round's probe does (``run_scene_script`` + ``probe_env_args``: the same node,
- settle / camera-repair / exposure policy) but writes nothing into the recorded run."""
+def recorded_errors(record: dict[str, Any]) -> list[str]:
+ """The ERROR messages `scene_placement` raised in the LAST recorded round."""
+ return [str(f.get("message", "")) for f in _last_placement_findings(record) if f.get("severity") == "error"]
+
+
+def recorded_kinds(record: dict[str, Any]) -> Counter[str]:
+ """The last recorded round's ERRORs by typed ``data.kind`` (a finding without one is ``untyped``)."""
+ return Counter(str((f.get("data") or {}).get("kind") or "untyped")
+ for f in _last_placement_findings(record) if f.get("severity") == "error")
+
+
+def report_kinds(report: GateReport | None) -> Counter[str]:
+ """A fresh report's ERRORs by typed ``data.kind``."""
+ return Counter(str(f.data.get("kind") or "untyped") for f in (report.findings if report else [])
+ if f.severity == Severity.ERROR)
+
+
+def _driver_summary(args: list[str], *, timeout_s: float) -> dict[str, Any] | None:
+ """One ``probe_scene.mjs`` boot (the round's driver: same node, same flags), no file written into
+ the recorded run; None when the driver itself could not run."""
try:
- res = run_scene_script("probe_scene.mjs", ["--ws", str(ws), "--gpu", "off", "--timeout-ms",
- str(int(timeout_s * 1000)), *probe_env_args()],
+ res = run_scene_script("probe_scene.mjs", [*args, "--gpu", "off", "--timeout-ms", str(int(timeout_s * 1000))],
timeout_s=timeout_s + 60)
except SceneRenderError:
return None
- return res.summary.get("census") if (res.summary.get("boot") or {}).get("ok") else None
+ return res.summary
+
+
+def _probe_copy(ws: Path, language: Language, *, timeout_s: float) -> dict[str, Any] | None:
+ """The runtime's own probe on a copy of the workspace: it rebuilds (Blender) and writes its
+ artifacts, and a recorded run is read-only reference material."""
+ with tempfile.TemporaryDirectory(prefix="c3d-regate-") as tmp:
+ copy = Path(tmp) / ws.name
+ copy.mkdir()
+ for part in WORKSPACE_PARTS:
+ src = ws / part
+ if src.is_dir():
+ shutil.copytree(src, copy / part)
+ elif src.is_file():
+ shutil.copy2(src, copy / part)
+ res = get_runtime(language).probe(Workspace(copy).create(), timeout_s=timeout_s)
+ return res.census if res.ok and res.census else None
+
+
+def probe(ws: Path, *, timeout_s: float, language: Language = Language.SCENE_THREEJS) -> dict[str, Any] | None:
+ """Boot the workspace and return its census, or None when it will not boot. A three.js
+ scene runs as the round's probe does (``run_scene_script`` + ``probe_env_args``: the same
+ node, settle / camera-repair / exposure policy); a Blender scene is probed on the census
+ GLB its last build kept, else rebuilt on a copy. Nothing is written into the recorded run."""
+ ws = ws.resolve() # the node driver runs under runtime_js/: a battery root given relative would not be found
+ if language is Language.SCENE_BLENDER:
+ glb = ws / "artifacts" / "census.glb"
+ if not glb.is_file():
+ return _probe_copy(ws, language, timeout_s=timeout_s)
+ summary = _driver_summary(["--ws", str(ws), "--glb", str(glb), "--no-settle"], timeout_s=timeout_s)
+ if summary is None:
+ return None
+ _, census = offline_report(summary, read_json_or_none(ws / "artifacts" / "bpy_census.json") or {})
+ if census:
+ census["language"] = language.value # the hints speak bpy, as the build's census does
+ return census or None
+ summary = _driver_summary(["--ws", str(ws), *probe_env_args()], timeout_s=timeout_s)
+ if summary is None:
+ return None
+ return summary.get("census") if (summary.get("boot") or {}).get("ok") else None
-def regate(run: Path, *, timeout_s: float) -> dict:
+def regate(run: Path, *, timeout_s: float) -> dict[str, Any]:
record = json.loads((run / "record.json").read_text())
+ language = run_language(record)
before = recorded_errors(record)
- census = probe(run, timeout_s=timeout_s)
+ before_kinds = recorded_kinds(record)
+ census = probe(run, timeout_s=timeout_s, language=language)
if census is None:
- return {"run": run.name, "booted": False, "before": before, "after": None}
+ return {"run": run.name, "language": language.value, "booted": False, "before": before,
+ "before_kinds": before_kinds, "after": None, "after_kinds": None}
# the round's own entry point (D82), so this measures the GATE and not a copy of it: it
# reads the zone layouts and the assets the asset stage could not build from stages/ —
# a first version of this script passed the layouts envelope unopened and a REAL density
# finding read as one the gate change had removed
report = placement_gate(Workspace(run), census, record.get("plan") or {})
after = [f.message for f in (report.findings if report else []) if f.severity == Severity.ERROR]
- return {"run": run.name, "booted": True, "before": before, "after": after}
+ return {"run": run.name, "language": language.value, "booted": True, "before": before,
+ "before_kinds": before_kinds, "after": after, "after_kinds": report_kinds(report)}
+
+
+def kind_diff(before: Counter[str], after: Counter[str]) -> dict[str, tuple[int, int, int, int]]:
+ """Per kind ``(recorded, now, gone, new)`` for one run: counts, not identities, so a finding
+ that changed its wording stays one finding."""
+ out: dict[str, tuple[int, int, int, int]] = {}
+ for kind in sorted(set(KINDS) | set(before) | set(after), key=lambda k: (k not in KINDS, KINDS.index(k) if k in KINDS else 0, k)):
+ b, a = before.get(kind, 0), after.get(kind, 0)
+ if b or a:
+ out[kind] = (b, a, max(b - a, 0), max(a - b, 0))
+ return out
def _head(msg: str) -> str:
@@ -97,11 +194,12 @@ def report(root: Path, *, timeout_s: float) -> str:
return f"no recorded scene workspaces under {root}"
lines = [f"# {GATE} re-run over {len(runs)} recorded workspace(s) under {root}", ""]
tot_before = tot_after = tot_gone = tot_new = 0
+ by_kind: dict[str, list[int]] = {}
rows = []
for run in runs:
r = regate(run, timeout_s=timeout_s)
if not r["booted"]:
- rows.append(f"| {r['run']} | {len(r['before'])} | — | — | — | did not boot |")
+ rows.append(f"| {r['run']} | {r['language']} | {len(r['before'])} | — | — | — | did not boot |")
continue
b, a = {_head(m) for m in r["before"]}, {_head(m) for m in r["after"]}
gone, new = sorted(b - a), sorted(a - b)
@@ -109,14 +207,22 @@ def report(root: Path, *, timeout_s: float) -> str:
tot_after += len(r["after"])
tot_gone += len(gone)
tot_new += len(new)
- rows.append(f"| {r['run']} | {len(r['before'])} | {len(r['after'])} | {len(gone)} | {len(new)} | |")
+ for kind, counts in kind_diff(r["before_kinds"], r["after_kinds"]).items():
+ acc = by_kind.setdefault(kind, [0, 0, 0, 0])
+ for i, v in enumerate(counts):
+ acc[i] += v
+ rows.append(f"| {r['run']} | {r['language']} | {len(r['before'])} | {len(r['after'])} | {len(gone)} | {len(new)} | |")
if gone or new:
lines.append(f"### {r['run']}")
lines += [f" GONE {m[:150]}" for m in gone]
lines += [f" NEW {m[:150]}" for m in new]
lines.append("")
- head = ["| run | recorded ERRORs | now | gone | new | note |", "|---|--:|--:|--:|--:|---|", *rows,
+ head = ["| run | language | recorded ERRORs | now | gone | new | note |", "|---|---|--:|--:|--:|--:|---|", *rows,
"", f"**totals** recorded {tot_before}, now {tot_after}, gone {tot_gone}, new {tot_new}", ""]
+ if by_kind:
+ head += ["## ERRORs by kind (booted runs; `data.kind`)", "| kind | recorded | now | gone | new |", "|---|--:|--:|--:|--:|"]
+ head += [f"| {kind} | {b} | {a} | {g} | {n} |" for kind, (b, a, g, n) in by_kind.items()]
+ head.append("")
return "\n".join([lines[0], "", *head, *lines[1:]])
diff --git a/eval/bench/scene_stats.py b/eval/bench/scene_stats.py
index 4c014881..3f1c0560 100644
--- a/eval/bench/scene_stats.py
+++ b/eval/bench/scene_stats.py
@@ -11,8 +11,10 @@ and each layer leaves its own events and artefacts:
Reports, per battery: how many plans needed a re-ask, what the planner chose for each
asset (``threejs`` procedural module vs ``blender_glb`` hero built with bpy), how many
assets needed a repair pass, how many placements each zone produced, which gates failed
-and how often, and what the judge complained about. The point is the LAYER attribution:
-a defect in the plan or in the assets follows any change to the assembly language.
+and how often — and which KINDS of finding (typed ``data.kind``: ``scene_placement/floating``,
+``scene_frames/dark_frame`` …, never a message match), and what the judge complained about.
+The point is the LAYER attribution: a defect in the plan or in the assets follows any
+change to the assembly language.
"""
from __future__ import annotations
@@ -31,6 +33,13 @@ from bench._records import records # noqa: E402
from codeverse3d.spatial.node import browser_was_lost # noqa: E402
+def finding_kind(gate: str, finding: dict) -> str:
+ """``gate/kind`` of a recorded finding from its typed ``data.kind`` (``untyped`` without one)."""
+ data = finding.get("data")
+ kind = data.get("kind") if isinstance(data, dict) else None
+ return f"{gate}/{kind if isinstance(kind, str) and kind else 'untyped'}"
+
+
def runs(root: Path) -> list[tuple[str, dict, list[dict]]]:
"""``(prompt id, record, events)`` per scene run under ``root``, once per run."""
out = []
@@ -55,6 +64,8 @@ def layers(rows: list[tuple[str, dict, list[dict]]]) -> dict:
placements: list[int] = []
gates = Counter()
gate_errors = Counter()
+ gate_kinds = Counter() # gate/kind -> ERROR findings (browser losses excluded)
+ gate_warn_kinds = Counter() # gate/kind -> WARN findings
judge = Counter()
scores: list[float] = []
for _pid, rec, events in rows:
@@ -102,6 +113,11 @@ def layers(rows: list[tuple[str, dict, list[dict]]]) -> dict:
lost = [f for f in errors if browser_was_lost(f.get("message", ""))]
real = [f for f in errors if f not in lost]
gate_errors[name] += len(real)
+ for f in real:
+ gate_kinds[finding_kind(name, f)] += 1
+ for f in g.get("findings") or []:
+ if f.get("severity") == "warn":
+ gate_warn_kinds[finding_kind(name, f)] += 1
if lost:
gates[f"{name}:LOST"] += len(lost)
round_lost = True
@@ -118,6 +134,7 @@ def layers(rows: list[tuple[str, dict, list[dict]]]) -> dict:
judge[f"{issue.get('severity', '?')}/{issue.get('kind', '?')}"] += 1
return {"plan": plan, "build": build, "assets": assets, "asset_kind": asset_kind, "tris": tris,
"placements": placements, "gates": gates, "gate_errors": gate_errors,
+ "gate_kinds": gate_kinds, "gate_warn_kinds": gate_warn_kinds,
"judge": judge, "scores": scores}
@@ -153,6 +170,11 @@ def report(root: Path) -> str:
if lost_rounds:
out.append(f"\n {lost_rounds} round(s) lost their browser mid-render: those findings are the "
f"machine, not the scene, and are counted in the last column only.")
+ kinds = sorted(set(d["gate_kinds"]) | set(d["gate_warn_kinds"]),
+ key=lambda k: (-d["gate_kinds"][k], -d["gate_warn_kinds"][k], k))
+ if kinds:
+ out += ["", "## gate findings by kind", "| gate/kind | ERROR | WARN |", "|---|--:|--:|"]
+ out += [f"| {k} | {d['gate_kinds'][k]} | {d['gate_warn_kinds'][k]} |" for k in kinds]
if d["judge"]:
out += ["", "## judge issues (severity/kind)"]
out += [f" {n:3}x {k}" for k, n in d["judge"].most_common(12)]
diff --git a/eval/docs/EVAL.md b/eval/docs/EVAL.md
index 1350a0f5..b556b4d0 100644
--- a/eval/docs/EVAL.md
+++ b/eval/docs/EVAL.md
@@ -54,6 +54,18 @@ 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.
+**Generated batteries (2026-10-14, §10).** The argon loop writes its own scene batteries under
+`bench/out/<loop>/iter_NN/battery_<lang>.yaml` (`bench.loop generate`; never checked in): the same
+`Battery` schema, 30 prompts per language per iteration, every `must_have` the scenes_v2 composition
+contract — named zones, asset types with counts, a luminance band, one effect, one animation, a camera
+brief with a no-clip requirement — RENDERED from typed fields the planner model returns
+(`bench/_loop_prompts.py`), so the counts always parse. Difficulty is a ladder of five rungs with
+objective knobs (rung 1: 3 zones / 6 asset types / ≤ 40 instances / day / no water … rung 5: 6+ zones /
+14 types / 400 / night + water + interior + particles + a moving hero + precise scale constraints); a
+rung's prompts are generated ONCE and cached (`prompts/rung_R_<lang>.yaml`) with ids
+`it{NN}_{lang}_r{R}_{k:02d}` that never change, so iterations pair by id; `--rung R` mixes rungs
+1..R evenly (the remainder to the hardest), which keeps half of the pairs when the mix moves up.
+
## 3. Harness battery runs (`python -m bench.run_bench`)
```bash
@@ -300,6 +312,67 @@ Notes: the earlier criteria-first schema compressed flash to 0.6–0.7 (std 0.01
on 2026-09-22), and the 0.072 round-to-round spread in the corpus is generation variance,
not the judge. Untested: temperature 0.0 (brilliana measured 0.013
vs 0.035 between 0.0 and 0.2 on 512 calls) — one more $8 battery.
+* **scene_v2 (2026-10-14): the scene judge gets stricter and detail-aware; scene_v1 is frozen
+ for replays.** Part of the argon scene-tuning program (D105): the owner asked for stricter
+ connectivity / contact standards, and the scene judge was the lenient half of them — the
+ placement gate measured floating / sunken / interpenetration while the rubric had one −0.06
+ "floating or sunken" tick, no interpenetration or scale item at all, a floating cap at 0.70
+ that fired twice (the gate rule plus a `gate: '*'` `floating_part` twin), and a camera cap
+ naming five kinds nothing emitted. What moved, all of it pinned by `tests/judges/`:
+ * **Checklist** — `floating_or_sunken_asset` splits into `floating_asset` (−0.10, cap 0.60)
+ and `sunken_asset` (−0.08, 0.65); new `interpenetration` (−0.08, 0.70), `wrong_scale`
+ (−0.06, 0.75), `hard_edged_particles` (−0.04), `missing_planned_element` (−0.06),
+ `hero_misplaced` (−0.06) — the object rubric's weights for the same faults. The five
+ composition items keep ≤ 0.05 and no cap (Σ 0.18); the whole list sums to 1.02 (v1: 0.60).
+ Every claim of floating / sunken / clipping / scale must name its view and its asset.
+ * **Caps** — one `scene_placement` rule per typed kind (`floating`+`unsupported` 0.60,
+ `sunken` 0.65, `interpenetration` 0.70, `scale` 0.75, `free_exempt` 0.75), the `floating_part`
+ twin deleted, `camera_in_geometry` on the kinds `scene_frames` really emits
+ (`camera_in_geometry / camera_underground / camera_blocked`), `missing_must_acceptance` graded
+ like the object tracks. The frame caps (dark 0.55 / blown 0.60 / flat 0.65 / content_small
+ 0.60), the build / shader / console caps and the pass threshold (0.70) are v1's.
+ * **The veto is scoped to the rule's kinds — `SCORING_VERSION` 4** (`rubrics._rule_gates_clean`).
+ A failed report used to cancel `measured_absent` whatever it failed on; on the scene track the
+ placement rows and the plan checks share one report, so a `no_fog` ERROR let every floating
+ claim stand although the rows had measured none. Now a watched report is clean for a rule
+ when it ran and has no ERROR of the rule's kinds and no WARN of those kinds at or over the
+ rule's `veto_warn_keys` line (scene_v2: `gap_m` 0.02 / `sunk_m` 0.10 / `overlap` 0.20 / any
+ scale factor — a WARN-band hover at 0.08 m keeps the judge's tick, and so does a 3 cm one:
+ the gap line is the INDOOR tolerance = `contact_m`, so a floating / unsupported WARN the gate
+ raised is never vetoed; it was the outdoor 0.05 until 2026-10-15 and vetoed 2-5 cm indoor
+ hovers the gate had flagged). The object rubrics keep the `depth_m` ≥ 8 mm default; a failed
+ report that names no ERROR finding is still not clean.
+ * **Scale** — six anchors per criterion (1.0 / 0.85 / 0.7 / 0.55 / 0.4 / 0.1) and a CALIBRATION
+ block with fixed points: a bare skeleton ≤ 0.35, a correct-but-plain diorama ≈ 0.55, a
+ photographable place ≥ 0.80, the two at least 0.3 apart. The 2026-08-30 bins (0.1–0.3 /
+ ~0.5 / 0.8+) left the 0.55–0.75 band where most argon rounds land without an anchor.
+ * **What the judge sees** (`prompt_builder`, scene branch only — the object text is pinned
+ byte-identical): gate reports ordered placement → frames → lint, the WARNs grouped by
+ (gate, kind) as the object ledger branch groups them, one **MEASURED PLACEMENT** line from
+ the gate's own summary (checked / placed / exempt / free-tagged, the count per kind with its
+ worst gap / sink / overlap, the thresholds when the gate recorded them, and a PLACEMENT
+ PASSED sentence on a clean report); the rig text says the high overviews lift room
+ ceilings and drop the fog. **Contact crops**: for every placement finding that carries
+ `data.bbox` (ERROR first, one per asset, up to `Settings.judge.detail_crops` after the centre
+ crop) the finding's box is projected through the judged overview tile that shows it largest
+ (the elevation-weighted `CONTACT_TILE_WEIGHT`: the contact tile 1.5×, top-down 0.25×) and
+ sent as `CONTACT CROP — <asset> (gate: floating 0.12 m)`, labelled diagnostic — judge the
+ contact, not the composition. The audit behind it is the 2026-08-30 one: the judge reads
+ the gate's sentences, not the pictures; a crop puts the measured contact in front of it.
+ * **A fourth overview** — `overview_low_front` (az 20°, el 7°; `orbit.mjs fitContactCamera`:
+ 1.2× the content span out, 0.4 m up, aimed at the ground edge of the content box, fog
+ kept) joins the rig and the judge subset (`MAX_JUDGE_OVERVIEWS` 3 → 4, both renderers); the
+ scene montage cap moves 3 → 4 (D47's 5 was measured on the object rig only) so the fourth
+ tile is not silently dropped. `judge_prompt_hash` moves for every rubric (the rig rules
+ are shared), the manifest with it.
+ * **Thinking** — `VlmJudge(thinking=None)` reads `Settings.judge.thinking`
+ (`C3D_JUDGE__THINKING`; argon thinks only from `medium`), `3dcode judge --thinking` and
+ `addons.calibration --thinking` default to it, the record's sampling snapshot carries it.
+ * **The A/B evaluator** (`eval/bench/_fixed_eval.py`) runs `placement_gate` on a scene cell
+ before the judge, so the deterministic caps fire in a compare cell as in the loop.
+ * Not measured yet: the loop's judge-calibration arm (`bench.loop judge-calib`) is the
+ within-sd / between-sd / SNR readout for scene_v2 under argon@medium; until it runs, the
+ numbers above are the rubric's, not a battery's.
* Never tune rubric text against the battery you report on; bump the rubric version
(`*_v2`) instead and re-run.
@@ -365,6 +438,13 @@ verdict is `bench/stats.decide`, the one paired rule of every report (owner, 202
> `paired_compare` says better / worse / inconclusive and `ab_view` B wins / loses / Inconclusive
> by the same rule (without the veto).
+**The loop's rule (2026-10-14, `bench.loop compare`, §10)** is the same `decide` on the paired picked
+score — keep / revert / inconclusive — plus a *deterministic-gate veto* in place of the A/B rig's
+per-prompt regression veto: the floating + sunken + interpenetration ERROR count per run (the
+`scene_placement` gate's typed kinds) must not rise by more than one on average over the pairs, or the
+iteration is reverted whatever the judge said. The contact standards the owner tightened that day
+are measured by the gate, not perceived by the VLM, so the gate gets the last word.
+
Until 2026-09-24 the A/B rule was a threshold — keep iff mean ≥ +0.02 and no regression; revert
iff mean ≤ −0.02 or ≥ 2 regressions — and on `[0.25, 0.01, 0.00, 0.02]` it said keep where
`paired_compare` said unsupported and `ab_view` inconclusive. Summaries written before then carry
@@ -598,6 +678,8 @@ settling before a larger n measures the rubric's preference with more precision.
### 8.7 Head-to-head against the previous harnesses (2026-08-26, first pass)
No such comparison existed before today; their scores are their own judges'. Protocol:
+> **Removed 2026-10-14 (owner: the repo is standalone).** The head-to-head scripts `bench/h2h_glb.py` / `bench/h2h_scene.py` and the `h2h_*` batteries compared this harness with other checkouts (astra3d-brilliana's gallery, the scene_multifile repos, Claude Design outputs) and were deleted together with those dependencies; the paragraphs below are kept as the historical record of what was measured.
+
`bench/h2h_glb.py` (objects) takes 12 confirmed entries of astra3d-brilliana's gallery (prompt
verbatim, `must_have` empty), our runs on the same prompts (generator
**`api-agent:gemini:gemini-3.7-flash`** — the in-process arm, retired two days later by `66175ec`;
@@ -672,6 +754,86 @@ re-run; **cells dropped as `infra_failed` and `budget_exhausted`, per arm** (§7
omitted drop count is an unreadable table); links to `record.json` / `report.html`
under `bench/out/`.
+## 10. The argon loop (`bench/loop.py`, 2026-10-14)
+
+One iteration = one edit of a per-model prompt/skill **variant** (`codeverse3d/prompts/variants/<v>/`
++ `codeverse3d/skills/variants/<v>/`, D105; `argon` first), measured on ~30 scene prompts per language
+run in parallel on the generator under test (`agy:gemini-4-argon`), judged by ONE fixed judge at ONE
+thinking level (`gemini:gemini-4-argon` @ medium — the level at which argon's within-sd is 0.012, §6).
+`init` freezes every knob in `<out>/loop.json`; nothing else takes a model or a budget flag, so two
+iterations never differ in anything but the variant and (when `--rung` moves) the prompt mix.
+
+```bash
+cd eval
+python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon \
+ --languages scene_threejs,scene_blender --generator agy:gemini-4-argon \
+ --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 --rounds 2 --max-minutes 90
+python -m bench.loop generate --out bench/out/loop_argon --iter 0 # batteries (§2: rung mix, cached ids)
+python -m bench.loop run --out bench/out/loop_argon --iter 0 # 2 children × 15 runs; --resume redoes infra_failed
+python -m bench.loop diagnose --out bench/out/loop_argon --iter 0 # diagnosis.md / .json
+# … edit the variant overlay (prompts, skills routes) for iteration 1 …
+python -m bench.loop generate --out bench/out/loop_argon --iter 1 # same rung → the same ids
+python -m bench.loop run --out bench/out/loop_argon --iter 1
+python -m bench.loop diagnose --out bench/out/loop_argon --iter 1
+python -m bench.loop compare --out bench/out/loop_argon --iter 1 --against 0 # keep / revert / inconclusive
+python -m bench.loop judge-calib --out bench/out/loop_argon --iter 1 # the judge arm
+python -m bench.loop accept --out bench/out/loop_argon --iter 1 --note "placement recipe" # or rollback
+python -m bench.loop status --out bench/out/loop_argon
+```
+
+* **generate** renders every battery's `must_have` contract from the planner model's typed fields
+ (`bench/_loop_prompts.contract_lines`), never from prose. Its camera line changed on 2026-10-15:
+ it now states ONE fixed eye-level viewpoint (where it stands, what it looks along, its height),
+ because both scene languages render the authored cameras as stills at t = 0 and t = 1.5 s and the
+ old "tracks / dollies along …" brief was a must-have no run could satisfy (iteration 0: unverified
+ in 5 of 60 runs, a `missing_must_acceptance` cap on the whole score). A rung cache written before
+ that date is migrated in place by the next `generate` (`migrate_camera_lines`: the route the model
+ wrote becomes where the camera stands; ids untouched, `camera_lines_migrated` stamped in the file),
+ so iteration 1 vs 0 pairs runs whose briefs differ in that one line.
+* **run** is one `python -m bench.run_bench … --variant <v> --no-report` child per language, side
+ by side, with `C3D_JUDGE__THINKING=<level>`, `C3D_VARIANT=<v>`, `C3D_RENDER__BLENDER_GPU_SLOTS=3`
+ (30 runs share one GPU) and `PYTHONUNBUFFERED=1`; the driver installs the harness's stop handlers
+ and forwards SIGTERM to the children, whose own handlers (`run_bench.main`) kill their agent /
+ Blender / Chrome groups so every run records its stop. `iter_NN/run.json` carries pids, exit codes
+ and the wall clock. Launches are staggered (`stagger_s`, `init --stagger`, default 40 s;
+ 2026-10-15): each child's first wave of workers starts `stagger_s` apart (`run_bench --stagger`)
+ and the two children half a stagger apart, so the languages' waves interleave — agy holds one
+ session per key machine-wide, there are 30 keys, and 15 + 15 runs plus the harness's own planner /
+ asset / judge calls share a 64-slot pool; iteration 0 launched all 30 at once and 160 of its 172
+ `asset.generate_failed` key-pool outages fell in the runs' first ten minutes. A later cell starts
+ when an earlier one finishes, which is staggered by itself.
+* **diagnose** reads the run records (`_records.records`, `load_record`): n by status, baseline /
+ picked mean / median / sd, per-criterion means, defect vote rates, caps fired, gate ERROR / WARN
+ counts by TYPED kind (`skills.registry.finding_kind`), library reach (lib modules imported by the
+ agent's files under `deliverable/src`, `src/lib/` itself excluded), cost by stage, minutes, stop
+ reasons, skills listed vs read, the 12 most frequent judge (kind, target-word) pairs — and a
+ RECOMMENDATIONS list from deterministic rules (`bench/_loop_diag.RULES`): floating ERROR rate ≥ 25 %
+ → the placement recipe + skill boost; < 3 lib modules per scene → the effects catalog presentation;
+ dark_frame ≥ 20 % → the lighting recipe; budget stops ≥ 30 % → raise `--max-minutes` / cut the zone
+ prompt; outages ≥ 20 % → `run --resume` first; and so on. A person reads it before editing the
+ variant; no model does.
+* **compare** pairs iteration N with M by prompt id (common ids only; the dropped ids are listed):
+ paired Δ picked score with its 95 % t-interval, the exact sign test, mean Δ per criterion, Δ gate
+ ERRORs per kind, Δ cost — and the verdict of §8's loop rule: `stats.decide` plus the placement veto
+ (floating + sunken + interpenetration ERRORs per run must not rise by > 1 on average).
+* **judge-calib** re-judges every run's PICKED round n times in fixed montage order
+ (`addons.calibration.calibrate(fixed_order=True)` — the model's own re-judge σ, not its order σ):
+ within-sd (rms of the per-round σ), between-sd (σ of the per-round means), their ratio (SNR),
+ Pearson / Spearman of gate ERRORs against the score, the defect histogram, cost and latency. The
+ judge is a measuring instrument; this is its calibration certificate per iteration.
+* **accept** first refuses an overlay whose `routes.toml` does not type-check or whose bundles fail
+ `validate_bundle` (the standards of `3dcode skills validate`), then bumps `variant.toml`'s `version`, snapshots both overlay dirs to
+ `<out>/snapshots/<v>_v<N>/`, and appends a row to `bench/data/loop/<name>/ledger.jsonl` (format:
+ `bench/data/loop/README.md`); **rollback** restores the last accepted snapshot (an iteration that
+ was itself the latest accept is un-accepted, version and all); **status** prints the ledger and the
+ version. Iteration 0 runs the base prompts under the variant plumbing (the `argon` overlay ships
+ empty), so every later verdict is against a measured baseline, not a remembered one.
+
+What the loop cannot do: it never edits the variant itself (the recommendations are levers, the edit
+is a person's), it never compares across rungs (the pairs are by id, so a moved mix compares only the
+ids both iterations ran), and a `keep` over 30 pairs is still one battery's verdict — §8's noise floor
+applies, which is why the gate veto and the judge arm sit beside the score.
+
## Judge experiments log
**2026-08-29 — profiles and the detail round.** `RoundPolicy.detail_rounds` is tri-state
diff --git a/eval/llm/CLAUDE.md b/eval/llm/CLAUDE.md
index 0bef7f03..ec0bf9ce 100644
--- a/eval/llm/CLAUDE.md
+++ b/eval/llm/CLAUDE.md
@@ -7,7 +7,7 @@ this package is the portable re-implementation (provenance in `docs/inventory_*.
- **Paths**: never hardcode; everything goes through `config.py` (`C3D_EVAL_DATA`, `C3D_TOOLS`, `C3D_BLENDER` …).
Large assets live under `$C3D_EVAL_DATA` (hub/, refs/, out/), never in git. `data/prompts/*.jsonl` are committed.
- **Environment**: conda env `cv3d-eval` (`~/miniconda3/envs/cv3d-eval/bin/python`): vLLM 0.28 + torch cu130
- (RTX 5090 works), cadquery, playwright, trimesh, transformers. Blender 5.0.1 at `~/.local/bin/blender-5.0`
+ (RTX 5090 works), cadquery, playwright, trimesh, transformers. Blender 5.2.2 LTS at `~/.local/bin/blender-5.2`
(bundled python has scipy 1.17.1 + shapely), OpenSCAD AppImage + glslang under `~/3dcodeverse_data/tools`.
`python -m llm.config` is the doctor.
- **Protocols**: keep the report protocol (`3dcodebench_text`, `heldout_*`) byte-identical to
diff --git a/eval/llm/README.md b/eval/llm/README.md
index 7325095b..0c8cb9f5 100644
--- a/eval/llm/README.md
+++ b/eval/llm/README.md
@@ -124,7 +124,7 @@ three.js 40/40 — identical to the report's reference counts.
The harness batteries (`../bench/prompts/*.yaml`, the ten in `config.HARNESS_BATTERIES`) have no ground truth; their quality score is the calibrated
Gemini VLM judge in `harness/codeverse3d/judges` (14-view rig, rubric `static_object_v1`, σ ≈ 0.03 at n=3).
-`docs/inventory_harness_bench.md` §7 shows the minimal call sequence (`FixedEvaluator`, `h2h_glb.py`) to
+`docs/inventory_harness_bench.md` §7 shows the minimal call sequence (`FixedEvaluator`) to
judge a GLB produced here without the agentic pipeline.
## Provenance
diff --git a/eval/llm/config.py b/eval/llm/config.py
index fc72dd95..072e584d 100644
--- a/eval/llm/config.py
+++ b/eval/llm/config.py
@@ -6,7 +6,7 @@ variables first and sensible defaults second:
C3D_EVAL_DATA root for downloaded assets, reference meshes and run outputs
(default ~/3dcodeverse_data/3dcodeverse_eval)
C3D_EVAL_OUT run outputs (default $C3D_EVAL_DATA/out)
- C3D_TOOLS directory holding blender-5.0.1-linux-x64/, openscad/, glslang/
+ C3D_TOOLS directory holding blender-5.2.2-linux-x64/, openscad/, glslang/
(default ~/3dcodeverse_data/tools)
C3D_BLENDER, C3D_OPENSCAD, C3D_GLSLANG, C3D_CQ_PYTHON explicit binaries
C3D_XLIBS extra shared-library dir prepended to LD_LIBRARY_PATH for Blender/OpenSCAD
@@ -56,8 +56,8 @@ def _first_existing(*cands: str | Path | None) -> Path | None:
def find_blender() -> Path | None:
return _first_existing(
os.environ.get("C3D_BLENDER"),
- "~/.local/bin/blender-5.0",
- TOOLS_DIR / "blender-5.0.1-linux-x64" / "blender",
+ "~/.local/bin/blender-5.2",
+ TOOLS_DIR / "blender-5.2.2-linux-x64" / "blender",
shutil.which("blender"),
)
diff --git a/eval/llm/docs/inventory_finetune_eval.md b/eval/llm/docs/inventory_finetune_eval.md
index a1842945..00b9054c 100644
--- a/eval/llm/docs/inventory_finetune_eval.md
+++ b/eval/llm/docs/inventory_finetune_eval.md
@@ -1,6 +1,6 @@
# Inventory: the existing `finetune/eval` + `scripts` evaluation code
-Read-only audit of `/home/yipeng/3dcodeverse/finetune/` (2026-09-08). This is the reference for what
+Read-only audit of `finetune/` (2026-09-08). This is the reference for what
`3dcodeverse_eval/` re-implements portably. All paths relative to `finetune/` unless absolute.
## 1. Evaluation suites
diff --git a/eval/llm/docs/inventory_harness_bench.md b/eval/llm/docs/inventory_harness_bench.md
index 5512e9d5..02b8b245 100644
--- a/eval/llm/docs/inventory_harness_bench.md
+++ b/eval/llm/docs/inventory_harness_bench.md
@@ -1,6 +1,6 @@
# Inventory: the `harness/bench` evaluation layer (what is reusable for LLM/VLM eval)
-Read-only audit of `/home/yipeng/3dcodeverse/harness/` (2026-09-08). Paths relative to `harness/`.
+Read-only audit of `harness/` (2026-09-08). Paths relative to `harness/`.
## 1. Prompt batteries (`bench/prompts/*.yaml`)
diff --git a/eval/llm/setup.sh b/eval/llm/setup.sh
index 2418f7a5..8b734d83 100644
--- a/eval/llm/setup.sh
+++ b/eval/llm/setup.sh
@@ -27,13 +27,17 @@ log "python: $PY"
pyyaml tqdm pillow "transformers>=4.50" accelerate pytest
"$PY" -m playwright install chromium
-# ---------------------------------------------------------------------------------------------- Blender 5.0.1
-if [ ! -x "$TOOLS/blender-5.0.1-linux-x64/blender" ]; then
- log "downloading Blender 5.0.1"
- curl -L -o "$TOOLS/blender.tar.xz" https://download.blender.org/release/Blender5.0/blender-5.0.1-linux-x64.tar.xz
- tar -xJf "$TOOLS/blender.tar.xz" -C "$TOOLS" && rm "$TOOLS/blender.tar.xz"
+# ---------------------------------------------------------------------------------------------- Blender 5.2.2 LTS
+# The one supported Blender (harness D104, 2026-10-14): 5.2 LTS only, no 4.2 / 5.0 compatibility.
+BL_VER=5.2.2
+if [ ! -x "$TOOLS/blender-$BL_VER-linux-x64/blender" ]; then
+ log "downloading Blender $BL_VER LTS"
+ curl -L -o "$TOOLS/blender.tar.xz" "https://download.blender.org/release/Blender5.2/blender-$BL_VER-linux-x64.tar.xz"
+ curl -L -o "$TOOLS/blender.sha256" "https://download.blender.org/release/Blender5.2/blender-$BL_VER.sha256"
+ (cd "$TOOLS" && grep "blender-$BL_VER-linux-x64.tar.xz" blender.sha256 | sed "s#blender-$BL_VER-linux-x64.tar.xz#blender.tar.xz#" | sha256sum -c -)
+ tar -xJf "$TOOLS/blender.tar.xz" -C "$TOOLS" && rm "$TOOLS/blender.tar.xz" "$TOOLS/blender.sha256"
fi
-BPY="$(ls -d "$TOOLS"/blender-5.0.1-linux-x64/5.0/python/bin/python3* | head -1)"
+BPY="$(ls -d "$TOOLS"/blender-$BL_VER-linux-x64/5.2/python/bin/python3* | head -1)"
"$BPY" -m ensurepip >/dev/null 2>&1 || true
"$BPY" -m pip install -q "scipy>=1.14" shapely # 15/212 reference scripts import scipy; one needs shapely
# libSM / libICE / libglvnd are often missing on headless boxes; unpack the Ubuntu debs locally (no sudo)
@@ -45,13 +49,13 @@ if [ ! -e "$XLIBS/libOpenGL.so.0" ] || [ ! -e "$XLIBS/libSM.so.6" ]; then
for d in *.deb; do [ -f "$d" ] && dpkg-deb -x "$d" "$HOME/.local/xlibs"; done
popd >/dev/null; rm -rf "$tmp"
fi
-cat > "$HOME/.local/bin/blender-5.0" <<EOF
+cat > "$HOME/.local/bin/blender-5.2" <<EOF
#!/bin/bash
export LD_LIBRARY_PATH="$XLIBS:\${LD_LIBRARY_PATH:-}"
-exec "$TOOLS/blender-5.0.1-linux-x64/blender" "\$@"
+exec "$TOOLS/blender-$BL_VER-linux-x64/blender" "\$@"
EOF
-chmod +x "$HOME/.local/bin/blender-5.0"
-"$HOME/.local/bin/blender-5.0" --version | head -1
+chmod +x "$HOME/.local/bin/blender-5.2"
+"$HOME/.local/bin/blender-5.2" --version | head -1
# ---------------------------------------------------------------------------------------------- OpenSCAD (nightly, --export-format binstl)
if [ ! -x "$TOOLS/openscad/AppRun" ]; then
diff --git a/eval/tests/test_bench.py b/eval/tests/test_bench.py
index 74225a3c..3e3bcf38 100644
--- a/eval/tests/test_bench.py
+++ b/eval/tests/test_bench.py
@@ -27,9 +27,7 @@ def test_all_batteries_are_valid():
assert len(ids) == len(set(ids)), path.name
tiers = {p.tier for p in b.prompts}
assert tiers <= {"easy", "medium", "hard"}, path.name
- # Head-to-head batteries keep the other side's brief verbatim: no must
- # items by design (bench/h2h_*.py).
- assert all(p.must_have for p in b.prompts) or b.name.startswith("h2h_"), path.name
+ assert all(p.must_have for p in b.prompts), path.name
if b.name in expected: # Other batteries are owned elsewhere; only their schema is checked here.
assert len(tiers) == 3, path.name
assert len(b.prompts) == expected[b.name], path.name
@@ -250,18 +248,99 @@ def test_the_launcher_hands_its_flags_to_run_battery(tmp_path: Path, monkeypatch
monkeypatch.setattr(rb, "run_battery", fake)
battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"
assert rb.main([str(battery), "--out", str(tmp_path), "--generator", "g", "--judge", "j", "--rounds", "2",
- "--max-minutes", "120", "--parallel", "3", "--id", "a", "--id", "b", "--tier", "easy",
- "--limit", "5", "--redo-status", "infra_failed,error", "--no-report"]) == 0
+ "--max-minutes", "120", "--parallel", "3", "--stagger", "12", "--id", "a", "--id", "b",
+ "--tier", "easy", "--limit", "5", "--redo-status", "infra_failed,error", "--no-report"]) == 0
o = seen["opts"]
- assert (o.generator, o.judge, o.rounds, o.max_minutes, o.parallel, o.limit) == ("g", "j", 2, 120.0, 3, 5)
+ assert (o.generator, o.judge, o.rounds, o.max_minutes, o.parallel, o.stagger_s, o.limit) == ("g", "j", 2, 120.0, 3, 12.0, 5)
assert o.ids == ["a", "b"] and o.tiers == ["easy"] and o.redo_status == ["infra_failed", "error"]
assert seen["out"] == tmp_path and "0 results" in capsys.readouterr().out
- # no --parallel / --out: BenchOptions' measured knee, and bench/out/<battery name>
+ # no --parallel / --stagger / --out: BenchOptions' measured knee, no stagger, and bench/out/<battery name>
assert rb.main([str(battery), "--no-report"]) == 0
- assert seen["opts"].parallel == BenchOptions().parallel
+ assert seen["opts"].parallel == BenchOptions().parallel and seen["opts"].stagger_s == BenchOptions().stagger_s == 0.0
assert seen["out"] == REPO / "bench" / "out" / "static_objects_v1"
- with pytest.raises(SystemExit):
- rb.main([str(battery), "--rounds", "-1"])
+ for bad in (["--rounds", "-1"], ["--parallel", "0"], ["--stagger", "-1"]):
+ with pytest.raises(SystemExit):
+ rb.main([str(battery), *bad])
+
+
+def test_the_first_wave_is_staggered_and_later_cells_are_not(tmp_path: Path, monkeypatch):
+ """``--stagger S`` (2026-10-15): the k-th worker of the FIRST wave sleeps k·S before it touches its
+ workspace — a redone cell too, before its old tree is archived — and a later cell never sleeps: it
+ starts when an earlier one finishes, which is staggered by itself. The loop's iteration 0 launched
+ 30 runs at once and 160 of its 172 key-pool outages fell in the runs' first ten minutes."""
+ import bench.run_bench as rb
+
+ battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"
+ ids = [p.id for p in Battery.load(battery).prompts[:2]]
+ out = tmp_path / "out"
+ naps: list[tuple[float, bool]] = []
+ # the module's own binding, never the global: pytest-xdist's worker threads sleep too
+ monkeypatch.setattr(rb, "sleep", lambda s: naps.append((s, (out / "runs" / f"{ids[1]}.attempt1").exists())))
+ res = run_battery(battery, out, BenchOptions(parallel=3, limit=5, stagger_s=7.0), run_fn=_fake_run_fn({}))
+ assert len(res) == 5 and sorted(s for s, _ in naps) == [7.0, 14.0], "workers 1 and 2 of the wave; cells 3 and 4 never"
+ naps.clear()
+ run_battery(battery, tmp_path / "flat", BenchOptions(parallel=3, limit=5), run_fn=_fake_run_fn({}))
+ assert naps == [], "no --stagger: the whole wave launches at once"
+ # a --redo-status re-run of two recorded cells is a first wave of two: the second staggers, and it
+ # does so BEFORE its workspace is archived (the old tree is still the live one while it sleeps)
+ run_battery(battery, out, BenchOptions(parallel=2, ids=ids, redo_status=[res[0].status], stagger_s=7.0),
+ run_fn=_fake_run_fn({}))
+ assert naps == [(7.0, False)] and (out / "runs" / f"{ids[1]}.attempt1").is_dir()
+
+
+def test_a_variant_is_frozen_on_every_spec_and_active_for_the_battery(tmp_path: Path, monkeypatch):
+ """``--variant NAME`` (D105): ``RunOptions.variant`` on each spec — what the track activates in its
+ worker thread — and ``prompts.variants.activate`` around the battery; a stated name on a tree
+ without the layer is an error, never a silent base run."""
+ import sys
+ import types
+ from contextlib import contextmanager
+
+ import bench.run_bench as rb
+
+ fake = types.ModuleType("codeverse3d.prompts.variants")
+ fake.active = ""
+ fake.seen: list[str] = []
+
+ @contextmanager
+ def activate(name: str):
+ fake.active = name
+ try:
+ yield
+ finally:
+ fake.active = ""
+
+ fake.activate = activate
+ fake.resolve_variant = lambda settings, generator_id: {"agy:gemini-4-argon": "argon"}.get(generator_id, "")
+ monkeypatch.setitem(sys.modules, "codeverse3d.prompts.variants", fake)
+ battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"
+ inner = _fake_run_fn({})
+
+ def run(spec, ws, resume):
+ fake.seen.append(f"{spec.options.variant}/{fake.active}")
+ return inner(spec, ws, resume)
+
+ run_battery(battery, tmp_path / "a", BenchOptions(parallel=1, limit=2, variant="argon", generator="g"), run_fn=run)
+ assert fake.seen == ["argon/argon"] * 2 and fake.active == "", "frozen on the spec, active for the block, released"
+ spec = json.loads((tmp_path / "a" / "runs" / "furn_easy_stool" / "spec.json").read_text())
+ assert spec["options"]["variant"] == "argon"
+ # no --variant: the settings resolve it for the generator, as `3dcode make` does — frozen, not activated
+ fake.seen.clear()
+ run_battery(battery, tmp_path / "b", BenchOptions(parallel=1, limit=1, generator="agy:gemini-4-argon"), run_fn=run)
+ assert fake.seen == ["argon/"]
+ run_battery(battery, tmp_path / "c", BenchOptions(parallel=1, limit=1, generator="codex:gpt-6.1-sol"), run_fn=run)
+ assert fake.seen[-1] == "/"
+ # the launcher hands the flag over and installs the stop handlers
+ seen: dict = {}
+ monkeypatch.setattr(rb, "run_battery", lambda battery, out, opts, *, on_result=None: seen.update(opts=opts) or [])
+ monkeypatch.setattr(rb, "install_stop_handlers", lambda: seen.update(handlers=True))
+ assert rb.main([str(battery), "--out", str(tmp_path / "d"), "--variant", "argon", "--no-report"]) == 0
+ assert seen["opts"].variant == "argon" and seen["handlers"] is True
+ # a tree without the layer: the base resolves silently, a stated name does not
+ monkeypatch.setitem(sys.modules, "codeverse3d.prompts.variants", None)
+ assert rb.resolve_variant("", "agy:gemini-4-argon") == ""
+ with pytest.raises(RuntimeError, match="prompts.variants"):
+ run_battery(battery, tmp_path / "e", BenchOptions(parallel=1, limit=1, variant="argon"), run_fn=inner)
def test_the_report_command_rebuilds_the_report(tmp_path: Path, capsys):
diff --git a/eval/tests/test_fixed_eval_language.py b/eval/tests/test_fixed_eval_language.py
index 1a25d5ed..71e7f32d 100644
--- a/eval/tests/test_fixed_eval_language.py
+++ b/eval/tests/test_fixed_eval_language.py
@@ -107,6 +107,54 @@ def test_scene_cells_are_judged_on_their_cameras_and_orbit_frames(monkeypatch, t
assert [a.text for a in seen["inp"].acceptance] == ["boats"]
+def test_scene_cells_run_the_placement_gate_before_the_judge(monkeypatch, tmp_path):
+ """scene_v2 (2026-10-14): a scene cell's deterministic placement caps fire in an A/B exactly as in
+ the loop — ``placement_gate`` over the build's census and the cell's plan.json, before the frames
+ gate; a build whose census has no placement table (the fake above) adds no report."""
+ import json
+ from types import SimpleNamespace
+
+ from bench._fixed_eval import FixedEvaluator
+ from codeverse3d.contracts.artifacts import BuildResult, GateReport, RenderSet, RenderView
+ from codeverse3d.contracts.common import Track
+ from codeverse3d.contracts.spec import Spec
+ from codeverse3d.workspace import Workspace
+
+ ws = Workspace(tmp_path / "run").create()
+ ws.plan_path.write_text(json.dumps({"title": "quay", "setting": "a harbour quay", "zones": [{"name": "Quay", "contents": ["Crate"]}],
+ "assets": [{"name": "Crate", "approx_size_m": [1.0, 1.0, 1.0]}]}))
+ png = tmp_path / "f.png"
+ png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 16)
+ census = {"language": "scene_threejs", "placement": {
+ "assets": [{"name": "Crate", "zone": "Quay", "ground_gap_m": 0.31, "support": "ground_y", "sunk_m": 0.0,
+ "bbox": {"min": [0, 0.31, 0], "max": [1, 1.31, 1], "size": [1, 1, 1]}}],
+ "interpenetrations": [], "total": 1, "checked": 1, "exempt": {}, "ground_y": 0.0}}
+ build = BuildResult(ok=True, language="scene_threejs", glb_path=None, census=census)
+ ev = FixedEvaluator("fake:judge", n_samples=1)
+ ev._runtimes[Language.SCENE_THREEJS] = SimpleNamespace(
+ lint=lambda ws: GateReport(gate="lint", passed=True), build=lambda ws, timeout_s: build,
+ render_scene=lambda ws, out, **kw: RenderSet(views=[RenderView(name="Establishing_t0", path=str(png))], renderer="fake"))
+ import bench._fixed_eval as fe
+ import codeverse3d.spatial.frame_metrics as fm
+ monkeypatch.setattr(fm, "frame_gate_from_renders", lambda src: GateReport(gate="scene_frames", passed=True))
+ seen: dict[str, object] = {}
+
+ class _J:
+ def judge(self, inp):
+ seen["inp"] = inp
+ return SimpleNamespace(overall=0.5, passed=False)
+ monkeypatch.setattr(fe.FixedEvaluator, "judge_for", lambda self, spec: _J())
+ spec = Spec(id="s", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a quay")
+ out = ev.evaluate(ws, spec)
+ assert out.error == "", out.error
+ gates = seen["inp"].gates
+ assert [g.gate for g in gates] == ["lint", "scene_placement", "scene_frames"]
+ placement = gates[1]
+ assert not placement.passed and [f.data["kind"] for f in placement.errors] == ["floating"]
+ assert placement.errors[0].target == "Quay/Crate" and placement.errors[0].data["gap_m"] == 0.31
+ assert "Quay/Crate is floating 0.31 m" in placement.errors[0].message
+
+
def test_the_fixed_judge_reads_the_in_run_payload_for_the_same_round(monkeypatch, tmp_path):
"""N83 (audit 2026-09-24): the fixed judge built its JudgeInput by hand — no clay views, no
GLB (so no D48 slices on a floating-part cell), connectivity without the language. It is now
diff --git a/eval/tests/test_infra_failures.py b/eval/tests/test_infra_failures.py
index 9e05db78..0669dc9f 100644
--- a/eval/tests/test_infra_failures.py
+++ b/eval/tests/test_infra_failures.py
@@ -64,8 +64,8 @@ def test_scene_pairwise_uses_the_same_track_rubric_as_fixed_evaluation(tmp_path,
pairs = cb.run_pairwise(battery, cells, arms, tmp_path, cb.CompareOptions(),
cb.CompareDeps(FakeEvaluator(), pairwise_judge=Judge))
- assert seen == ["scene_v1"]
- assert pairs[0].rubric == "scene_v1"
+ assert seen == ["scene_v2"]
+ assert pairs[0].rubric == "scene_v2"
OUTAGES = [
"ModelError: Gemini API error 503: This model is currently experiencing high demand.",
diff --git a/eval/tests/test_loop.py b/eval/tests/test_loop.py
new file mode 100644
index 00000000..37c8ad95
--- /dev/null
+++ b/eval/tests/test_loop.py
@@ -0,0 +1,700 @@
+"""``bench/loop.py``: the argon scene-tuning loop, driven offline with fakes (no model, no child process)."""
+
+from __future__ import annotations
+
+import json
+import logging
+import sys
+import time
+from pathlib import Path
+from types import SimpleNamespace as NS
+from typing import Any
+
+import pytest
+import yaml
+
+from bench import loop
+from bench._loop_diag import (
+ PLACEMENT_KINDS,
+ compare_dirs,
+ diagnose_dir,
+ js_lib_modules,
+ loop_verdict,
+ py_lib_modules,
+)
+from bench._loop_prompts import (
+ LUMINANCE_CEILING,
+ LUMINANCE_FLOOR,
+ RUNGS,
+ AssetCount,
+ GeneratedBattery,
+ GeneratedPrompt,
+ camera_line,
+ check_prompt,
+ contract_lines,
+ migrate_camera_lines,
+ mix_counts,
+ rung_text,
+)
+from bench.paired_compare import PairedStats
+from bench.run_bench import Battery, BenchItemResult, BenchPrompt
+from codeverse3d.addons.calibration import CalibrationRow, CalibrationTable
+from codeverse3d.contracts.chat import ChatRequest, ChatResponse
+from codeverse3d.contracts.common import Language, Usage
+from codeverse3d.prompts.variants import variant_hash
+from codeverse3d.spatial.frame_metrics import DARK_MEAN_LUM
+from tests.conftest import make_fake_run
+
+THREEJS, BLENDER = Language.SCENE_THREEJS, Language.SCENE_BLENDER
+CATEGORIES = ("urban", "rural", "nature", "waterfront", "interior", "industrial", "transport", "fantasy", "historic", "garden")
+#: a night band that clears the gate's floor by a margin, whatever the floor is set to
+NIGHT_LOW = LUMINANCE_FLOOR + 0.03
+#: an overlay bundle `skills.validate_bundle` accepts (measured, verified, a body): what accept lets through
+VALID_SKILL = (
+ "---\nname: c3d-scene-placement\ndescription: Seat every asset on its support. Use when placement fires.\n"
+ 'license: Apache-2.0\nmetadata:\n evidence: measured\n verified: "2026-10-14"\n---\n\n'
+ "# c3d-scene-placement\n\nRule one: measure the gap before you move anything.\n")
+
+
+# --------------------------------------------------------------------------- fixtures
+def cfg(tmp_path: Path) -> loop.LoopConfig:
+ c = loop.LoopConfig(name="t_loop", out=tmp_path / "loop", variant="argon", languages=[THREEJS, BLENDER],
+ generator="agy:gemini-4-argon", judge="gemini:gemini-4-argon", judge_thinking="medium",
+ parallel=2, rounds=1, max_minutes=10.0, n=6)
+ c.save()
+ return c
+
+
+def overlay(tmp_path: Path) -> loop.VariantPaths:
+ """A variant's two overlay directories, the way Lane V lays them out, in a tmp tree."""
+ prompts = tmp_path / "prompts" / "variants" / "argon"
+ skills = tmp_path / "skills" / "variants" / "argon"
+ prompts.mkdir(parents=True)
+ skills.mkdir(parents=True)
+ (prompts / "variant.toml").write_text(
+ '[variant]\nname = "argon"\n# the loop bumps it on accept\nversion = 1\n'
+ 'generators = ["agy:gemini-4-argon"]\ndescription = "argon on the scene track"\n\n[knobs]\nskills_max = 4\n')
+ (prompts / "README.md").write_text("# argon\n")
+ (skills / "routes.toml").write_text("# no rows yet\n")
+ return loop.VariantPaths(name="argon", prompts_root=prompts, skills_root=skills)
+
+
+def good_prompt(rung: int, k: int) -> GeneratedPrompt:
+ """A prompt that satisfies rung ``rung``'s rules (and only just: the counts sit under the cap)."""
+ r = RUNGS[rung]
+ count = max(1, r.instances // r.asset_types)
+ lighting = {1: "day", 2: "dusk", 3: "night", 4: "night", 5: "night"}[rung]
+ features = {1: [], 2: [], 3: [], 4: ["water"], 5: ["interior", "water", "particles"]}[rung]
+ return GeneratedPrompt(
+ title=f"place {rung}-{k}", category=CATEGORIES[k % len(CATEGORIES)],
+ prompt=f"a place number {k} at rung {rung} with zone 0 and zone 1 and a walk-through",
+ zones=[f"zone {i}" for i in range(r.zones)],
+ asset_types=[AssetCount(name=f"things {i}", count=count, designs=2 if i == 0 else 1) for i in range(r.asset_types)],
+ lighting=lighting, features=features, mood="warm low sun" if lighting != "night" else "lantern glow",
+ luminance_low=NIGHT_LOW if lighting == "night" else 0.3, luminance_high=0.35 if lighting == "night" else 0.6,
+ effect="steam rising from two vents", animation="a wheel turns continuously",
+ camera="at the lane's near end looking along it at 1.6 m",
+ hero="the hero wheel" if r.hero else "", hero_motion="rotates once per 8 s" if r.hero else "",
+ scale_constraints=["the tower is 18 m tall", "the arch spans 6 m"] if r.scale else [],
+ )
+
+
+def good_battery(rung: int, n: int) -> GeneratedBattery:
+ return GeneratedBattery(prompts=[good_prompt(rung, k) for k in range(n)])
+
+
+class FakePlanner:
+ """Answers a generation request from a script: ``answers[call index]`` → the JSON text. The rung
+ is read off the request so one fake serves every rung; ``None`` means "a good battery"."""
+
+ provider, model, id = "gemini", "gemini-4-argon", "gemini:gemini-4-argon"
+
+ def __init__(self, answers: list[GeneratedBattery | None] | None = None):
+ self.answers = answers or []
+ self.requests: list[ChatRequest] = []
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ self.requests.append(request)
+ text = request.messages[0].text
+ rung = int(text.split("for rung ", 1)[1].split(".", 1)[0])
+ n = int(text.split("Write ", 1)[1].split(" ", 1)[0])
+ i = len(self.requests) - 1
+ battery = self.answers[i] if i < len(self.answers) and self.answers[i] is not None else good_battery(rung, n)
+ return ChatResponse(text=json.dumps(battery.model_dump(mode="json")),
+ usage=Usage(backend="gemini", model="gemini-4-argon", input_tokens=10, output_tokens=10))
+
+
+def _write_rows(out_lang: Path, rows: list[BenchItemResult]) -> None:
+ out_lang.mkdir(parents=True, exist_ok=True)
+ (out_lang / "results.jsonl").write_text("".join(r.model_dump_json() + "\n" for r in rows))
+
+
+def _scene_run(out_lang: Path, pid: str, scores: tuple[float, float], *, placement_errors: int = 0,
+ lib_imports: tuple[str, ...] = ("noise", "finish"), defects: dict[str, bool] | None = None,
+ caps: list[str] = ()) -> BenchItemResult:
+ """A scene run under ``out_lang/runs/<pid>``: make_fake_run's record + a scene_placement gate on the
+ picked round (round 1, the higher score), a deliverable with lib imports, and its bench row."""
+ ws, rec = make_fake_run(out_lang / "runs", pid, language=THREEJS, generator="agy:gemini-4-argon", scores=scores)
+ data = json.loads(ws.record_path.read_text())
+ picked = data["rounds"][1]
+ findings = [{"gate": "scene_placement", "severity": "error", "target": f"Zone/Crate_{i}",
+ "message": f"Crate_{i} floats 0.12 m above Ground", "data": {"kind": "floating", "gap_m": 0.12}}
+ for i in range(placement_errors)]
+ findings.append({"gate": "scene_placement", "severity": "warn", "target": "Zone/Lamp", "message": "Lamp sunken 0.11 m",
+ "data": {"kind": "sunken", "sunk_m": 0.11}})
+ findings.append({"gate": "scene_placement", "severity": "info", "target": "scene", "message": "summary",
+ "data": {"kind": "summary"}})
+ picked["gates"].append({"gate": "scene_placement", "passed": placement_errors == 0, "findings": findings})
+ picked["judgment"]["raw"] = json.dumps({"defects": defects or {}, "caps": {"caps_applied": [{"rule": c, "cap": 0.6} for c in caps]}})
+ data["extra"] = {"stop_reason": "max_rounds"}
+ ws.record_path.write_text(json.dumps(data))
+ src = ws.root / "deliverable" / "src"
+ (src / "zones").mkdir(parents=True)
+ (src / "lib").mkdir()
+ (src / "zones" / "quay.js").write_text("".join(f"import {{ x{i} }} from '../lib/{m}.js';\n" for i, m in enumerate(lib_imports)))
+ (src / "scene.js").write_text("import { env } from './env.js';\nimport * as three from 'three';\n")
+ (src / "lib" / "noise.js").write_text("import { k } from './finish.js';\n") # the library's own import: not the agent's
+ return BenchItemResult(id=pid, tier="medium", category="urban", score_baseline=scores[0], score_picked=scores[1],
+ picked_round=1, rounds=2, cost_usd=1.5, minutes=12.0, status="max_rounds",
+ workspace=str(ws.root), generator="agy:gemini-4-argon", judge="gemini:gemini-4-argon")
+
+
+# --------------------------------------------------------------------------- init
+def test_init_writes_the_config_and_snapshots_the_overlay(cfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path):
+ (cfg.out / loop.LOOP_JSON).unlink() # the fixture saved it; init refuses to overwrite one
+ p = loop.init(cfg, paths=overlay)
+ assert p == cfg.out / "loop.json" and loop.LoopConfig.load(cfg.out).languages == [THREEJS, BLENDER]
+ snap = cfg.out / "snapshots" / "argon_v1"
+ assert (snap / "prompts" / "variant.toml").is_file() and (snap / "skills" / "routes.toml").is_file()
+ snapshot = json.loads((snap / "snapshot.json").read_text())
+ assert snapshot["version"] == 1 and snapshot["hash"] == overlay.ledger_hash(), "the ledger's number, not a private one"
+ with pytest.raises(loop.LoopError):
+ loop.init(cfg, paths=overlay)
+ with pytest.raises(ValueError): # a scene loop runs scene languages only
+ loop.LoopConfig(name="x", out=tmp_path, variant="argon", languages=[Language.BLENDER], generator="g", judge="j")
+ assert loop.parse_languages("scene_threejs, scene_blender") == [THREEJS, BLENDER]
+ with pytest.raises(loop.LoopError):
+ loop.parse_languages("scene_threejs,nope")
+
+
+# --------------------------------------------------------------------------- the rungs
+def test_the_rung_ladder_is_the_owners_table_and_the_mix_splits_evenly():
+ assert [(r.zones, r.asset_types, r.instances) for r in RUNGS.values()] == [
+ (3, 6, 40), (4, 8, 80), (5, 10, 150), (6, 12, 250), (6, 14, 400)]
+ assert mix_counts(1, 30) == {1: 30} and mix_counts(2, 30) == {1: 15, 2: 15}
+ assert mix_counts(4, 30) == {1: 7, 2: 7, 3: 8, 4: 8}, "the remainder goes to the hardest rungs"
+ assert sum(mix_counts(5, 30).values()) == 30
+ with pytest.raises(ValueError):
+ mix_counts(6, 30)
+ for level in RUNGS:
+ assert check_prompt(good_prompt(level, 0), RUNGS[level]) == [], level
+ # rung 1: day and no water; rung 4: a hero; rung 5: scale constraints; everyone: a band the gate accepts
+ wet = good_prompt(1, 0).model_copy(update={"features": ["water"]})
+ assert any("forbids 'water'" in p for p in check_prompt(wet, RUNGS[1]))
+ dark = good_prompt(1, 0).model_copy(update={"luminance_low": 0.05})
+ assert any("luminance band" in p for p in check_prompt(dark, RUNGS[1]))
+ assert any("hero" in p for p in check_prompt(good_prompt(3, 0), RUNGS[4]))
+ assert any("scale" in p for p in check_prompt(good_prompt(4, 0), RUNGS[5]))
+ few = good_prompt(2, 0).model_copy(update={"zones": ["a", "b"]})
+ assert any("needs at least 4" in p for p in check_prompt(few, RUNGS[2]))
+ lines = contract_lines(good_prompt(4, 1))
+ assert lines[0].startswith("6 zones: ") and "at least 20 things 0 using at least 2 distinct designs" in lines
+ assert any(ln.startswith("night mood:") and f"mean luminance roughly {NIGHT_LOW:.2f}-0.35" in ln for ln in lines)
+ assert any(ln.startswith("water:") for ln in lines) and any(ln.startswith("hero: the hero wheel") for ln in lines)
+ assert any("never intersects any geometry" in ln for ln in lines)
+
+
+def test_the_camera_line_is_a_still_viewpoint_and_old_lines_migrate_once():
+ """Both scene languages render the authored cameras as STILLS at t = 0 and t = 1.5 s, so a brief that
+ asked for a dolly was a must-have no run could satisfy (iteration 0: unverified in 5 of 60 runs, a
+ `missing_must_acceptance` cap on the whole score). The line now states a fixed eye-level viewpoint;
+ a cached line of the old form is rewritten around the route the model wrote, once."""
+ assert camera_line(" at the quay's landward end looking along it at 1.6 m ") == (
+ "camera: a FIXED eye-level camera, at the quay's landward end looking along it at 1.6 m; the harness renders "
+ "still cameras only (nothing dollies or tracks); it never intersects any geometry (no clipping, nothing cut by "
+ "the near plane)")
+ lines = contract_lines(good_prompt(1, 0))
+ assert [ln for ln in lines if ln.startswith("camera: ")] == [camera_line("at the lane's near end looking along it at 1.6 m")]
+ assert "still cameras only (nothing dollies or tracks)" in rung_text(RUNGS[1]) and "path" not in rung_text(RUNGS[1])
+ old_line = ("camera: tracks forward from the gravel access path to the shaded bottling corner at 1.6 m height; the "
+ "camera never intersects any geometry (no clipping, nothing cut by the near plane)")
+ old = BenchPrompt(id="it00_scene_threejs_r1_01", prompt="p", tier="medium",
+ must_have=["3 zones: a, b, c", old_line, "effect: steam rising from a grate"])
+ fresh = BenchPrompt(id="it02_scene_threejs_r2_01", prompt="p", tier="medium",
+ must_have=[camera_line("at the gate looking in at 1.6 m"), "animation: the awning extends"])
+ assert migrate_camera_lines([old, fresh]) == 1
+ assert old.must_have == [
+ "3 zones: a, b, c",
+ 'camera: a FIXED eye-level camera standing where this route begins and looking along it — "tracks forward from '
+ 'the gravel access path to the shaded bottling corner at 1.6 m height"; the harness renders still cameras only '
+ "(nothing dollies or tracks); it never intersects any geometry (no clipping, nothing cut by the near plane)",
+ "effect: steam rising from a grate"]
+ assert fresh.must_have == [camera_line("at the gate looking in at 1.6 m"), "animation: the awning extends"]
+ assert migrate_camera_lines([old, fresh]) == 0, "idempotent: the fixed form is recognised, nothing moves twice"
+
+
+def test_the_luminance_floor_is_the_frame_gates_dark_threshold():
+ """The floor the batteries' bands must clear IS ``frame_metrics.DARK_MEAN_LUM`` (imported, never a
+ copy): the day the gate is raised, the loop must not keep generating night prompts whose scenes are
+ ``dark_frame``-gated by construction — a diagnosis would blame the variant for the battery."""
+ assert LUMINANCE_FLOOR == DARK_MEAN_LUM and 0.0 < LUMINANCE_FLOOR < LUMINANCE_CEILING < 1.0
+ assert f"{DARK_MEAN_LUM:.2f}" in rung_text(RUNGS[3]), "the generation prompt states the gate's floor"
+ under = good_prompt(3, 0).model_copy(update={"luminance_low": DARK_MEAN_LUM - 0.01,
+ "luminance_high": DARK_MEAN_LUM + 0.2})
+ assert any("luminance band" in p for p in check_prompt(under, RUNGS[3]))
+ at = under.model_copy(update={"luminance_low": DARK_MEAN_LUM})
+ assert check_prompt(at, RUNGS[3]) == [], "AT the threshold is not gated (the gate fires on mean < threshold)"
+
+
+# --------------------------------------------------------------------------- generate
+def test_generate_writes_valid_batteries_with_stable_ids_and_a_rising_mix(cfg: loop.LoopConfig):
+ fake = FakePlanner()
+ paths = loop.generate_iteration(cfg, 0, rung=1, chat_model=fake)
+ assert set(paths) == {THREEJS, BLENDER} and len(fake.requests) == 2, "one generation per language"
+ b = Battery.load(paths[THREEJS])
+ assert b.language is THREEJS and b.name == "t_loop_it00_scene_threejs"
+ assert [p.id for p in b.prompts] == [f"it00_scene_threejs_r1_{k:02d}" for k in range(1, 7)]
+ assert {p.tier for p in b.prompts} == {"medium"} and all("rung1" in p.tags for p in b.prompts)
+ assert b.prompts[0].must_have[0] == "3 zones: zone 0, zone 1, zone 2"
+ assert fake.requests[0].response_schema is not None and fake.requests[0].label == "loop:generate"
+ assert "rung 1" in fake.requests[0].messages[0].text and "FORBIDDEN: water" in fake.requests[0].messages[0].text
+ assert (cfg.out / "prompts" / "rung_1_scene_threejs.yaml").is_file()
+ # iteration 1 at the same rung: the cache answers, the ids pair
+ loop.generate_iteration(cfg, 1, chat_model=fake)
+ assert len(fake.requests) == 2
+ assert [p.id for p in Battery.load(cfg.iter_dir(1) / "battery_scene_threejs.yaml").prompts] == [p.id for p in b.prompts]
+ assert loop.default_rung(cfg, 2) == 1
+ # --rung 2 moves half the mix up: rung 1's first three ids stay, rung 2 is generated now (ids say it02)
+ paths2 = loop.generate_iteration(cfg, 2, rung=2, chat_model=fake)
+ assert len(fake.requests) == 4
+ ids = [p.id for p in Battery.load(paths2[THREEJS]).prompts]
+ assert ids[:3] == [f"it00_scene_threejs_r1_{k:02d}" for k in (1, 2, 3)]
+ assert ids[3:] == [f"it02_scene_threejs_r2_{k:02d}" for k in (1, 2, 3)]
+ meta = json.loads((cfg.iter_dir(2) / "generate.json").read_text())
+ assert meta["rung"] == 2 and meta["mix"] == {"1": 3, "2": 3} and meta["ids"]["scene_threejs"] == ids
+ assert loop.default_rung(cfg, 3) == 2, "the next iteration keeps the rung unless told otherwise"
+ with pytest.raises(loop.LoopError):
+ loop.generate_iteration(cfg, 3, rung=9, chat_model=fake)
+
+
+def test_generate_migrates_an_old_rung_cache_in_place_and_keeps_its_ids(cfg: loop.LoopConfig, caplog):
+ """A rung cache written before 2026-10-15 carries the moving-camera line iteration 0 ran with; the
+ next `generate` rewrites that line in the cache (ids untouched — they pair iterations), says so, and
+ builds the battery from the fixed form. A cache already in the new form is left alone."""
+ fake = FakePlanner()
+ loop.generate_iteration(cfg, 0, rung=1, chat_model=fake)
+ cache = cfg.out / "prompts" / "rung_1_scene_threejs.yaml"
+ data = yaml.safe_load(cache.read_text())
+ old_line = ("camera: dollies along the lane at 1.6 m; the camera never intersects any geometry (no clipping, nothing "
+ "cut by the near plane)")
+ for p in data["prompts"]: # age the cache to the form iteration 0 was generated with
+ p["must_have"] = [old_line if ln.startswith("camera: ") else ln for ln in p["must_have"]]
+ cache.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=120))
+ untouched = (cfg.out / "prompts" / "rung_1_scene_blender.yaml").read_text()
+ with caplog.at_level(logging.INFO):
+ paths = loop.generate_iteration(cfg, 1, chat_model=fake)
+ assert len(fake.requests) == 2, "the cache answered: nothing was regenerated"
+ after = yaml.safe_load(cache.read_text())
+ assert [p["id"] for p in after["prompts"]] == [p["id"] for p in data["prompts"]]
+ assert after["camera_lines_migrated"]["n"] == 6 and after["generated_at"] == data["generated_at"]
+ migrated = [ln for p in after["prompts"] for ln in p["must_have"] if ln.startswith("camera: ")]
+ assert len(migrated) == 6 and all(
+ ln.startswith('camera: a FIXED eye-level camera standing where this route begins and looking along it — '
+ '"dollies along the lane at 1.6 m"; the harness renders still cameras only') for ln in migrated)
+ assert "migrated 6 camera line(s)" in caplog.text
+ assert (cfg.out / "prompts" / "rung_1_scene_blender.yaml").read_text() == untouched, "already in the new form"
+ b = Battery.load(paths[THREEJS])
+ assert all(any(ln.startswith("camera: a FIXED eye-level camera") for ln in p.must_have) for p in b.prompts)
+ stamp = cache.stat().st_mtime_ns
+ loop.generate_iteration(cfg, 2, chat_model=fake)
+ assert cache.stat().st_mtime_ns == stamp, "idempotent: a migrated cache is not rewritten again"
+
+
+def test_generate_reasks_once_with_the_typed_problems_then_refuses(tmp_path: Path):
+ c = loop.LoopConfig(name="t", out=tmp_path / "l", variant="argon", languages=[THREEJS], generator="g", judge="j", n=4)
+ c.save()
+ bad = good_battery(1, 4)
+ bad.prompts[0].zones = ["only one"]
+ fake = FakePlanner([bad, None])
+ loop.generate_iteration(c, 0, rung=1, chat_model=fake)
+ assert len(fake.requests) == 2 and fake.requests[1].label == "loop:generate-reask"
+ reask = fake.requests[1].messages
+ assert reask[1].role == "assistant" and reask[2].role == "user" and "needs at least 3" in reask[2].text
+ assert len(yaml.safe_load((c.out / "prompts" / "rung_1_scene_threejs.yaml").read_text())["prompts"]) == 4
+ c2 = loop.LoopConfig(name="t2", out=tmp_path / "l2", variant="argon", languages=[THREEJS], generator="g", judge="j", n=4)
+ c2.save()
+ with pytest.raises(loop.LoopError, match="after one re-ask"):
+ loop.generate_iteration(c2, 0, rung=1, chat_model=FakePlanner([bad, bad]))
+ assert not (c2.out / "prompts").exists(), "a battery that failed the rung rules is never cached"
+
+
+# --------------------------------------------------------------------------- run
+class FakePopen:
+ calls: list[dict[str, Any]] = []
+
+ def __init__(self, argv: list[str], **kw: Any):
+ self.argv, self.kw, self.pid, self.returncode = argv, kw, 4242 + len(FakePopen.calls), 0
+ FakePopen.calls.append({"argv": argv, **kw})
+
+ def poll(self) -> int:
+ return self.returncode
+
+ def wait(self, timeout: float | None = None) -> int:
+ return self.returncode
+
+
+def test_run_builds_the_child_argv_and_env_and_records_exit_codes(cfg: loop.LoopConfig, monkeypatch):
+ loop.generate_iteration(cfg, 0, rung=1, chat_model=FakePlanner())
+ installed: list[bool] = []
+ monkeypatch.setattr(loop, "install_stop_handlers", lambda: installed.append(True))
+ naps: list[float] = []
+ # the module's view of `time`, never the global sleep: pytest-xdist's worker threads sleep too
+ monkeypatch.setattr(loop, "time", NS(sleep=lambda s: naps.append(s), monotonic=time.monotonic))
+ FakePopen.calls = []
+ meta = loop.run_iteration(cfg, 0, popen=FakePopen)
+ assert installed == [True] and len(FakePopen.calls) == 2, "one child per language, side by side"
+ assert naps == [cfg.stagger_s / 2] == [20.0], "the second child launches half a stagger after the first"
+ call = FakePopen.calls[0]
+ argv = call["argv"]
+ assert argv[:3] == [sys.executable, "-m", "bench.run_bench"] and argv[3] == str(cfg.iter_dir(0) / "battery_scene_threejs.yaml")
+ assert argv[argv.index("--out") + 1] == str(cfg.iter_dir(0) / "scene_threejs")
+ for flag, value in (("--generator", "agy:gemini-4-argon"), ("--judge", "gemini:gemini-4-argon"), ("--parallel", "2"),
+ ("--stagger", "40.0"), ("--rounds", "1"), ("--max-minutes", "10.0"), ("--variant", "argon")):
+ assert argv[argv.index(flag) + 1] == value, flag
+ assert "--no-report" in argv and "--redo-status" not in argv and "--planner" not in argv
+ env = call["env"]
+ assert (env["C3D_JUDGE__THINKING"], env["C3D_VARIANT"], env["C3D_RENDER__BLENDER_GPU_SLOTS"], env["PYTHONUNBUFFERED"]) == \
+ ("medium", "argon", "3", "1")
+ assert call["cwd"] == str(loop.REPO) and call["start_new_session"] is True
+ run = json.loads((cfg.iter_dir(0) / "run.json").read_text())
+ assert run["children"]["scene_threejs"]["pid"] == 4242 and run["children"]["scene_blender"]["returncode"] == 0
+ assert run["wall_s"] >= 0 and (cfg.iter_dir(0) / "run_scene_threejs.log").read_text().startswith("--- ")
+ assert meta["children"]["scene_blender"]["argv"][3].endswith("battery_scene_blender.yaml")
+ # --resume re-runs what the weather lost; one language only runs one child
+ FakePopen.calls = []
+ naps.clear()
+ loop.run_iteration(cfg, 0, languages=[BLENDER], resume=True, popen=FakePopen)
+ assert len(FakePopen.calls) == 1 and FakePopen.calls[0]["argv"][-2:] == ["--redo-status", "infra_failed"]
+ assert naps == [], "one child: nothing to interleave with"
+ with pytest.raises(loop.LoopError, match="generate"):
+ loop.run_iteration(cfg, 5, popen=FakePopen)
+ # the stagger is a loop knob: a loop.json from before it loads with the default, and 0 means no flag
+ data = json.loads((cfg.out / loop.LOOP_JSON).read_text())
+ del data["stagger_s"]
+ (cfg.out / loop.LOOP_JSON).write_text(json.dumps(data))
+ assert loop.LoopConfig.load(cfg.out).stagger_s == 40.0
+ flat = cfg.model_copy(update={"stagger_s": 0.0})
+ assert "--stagger" not in loop.child_argv(flat, THREEJS, Path("b.yaml"), Path("o"), resume=False)
+ with pytest.raises(ValueError):
+ loop.LoopConfig(name="x", out=cfg.out, variant="argon", languages=[THREEJS], generator="g", judge="j", stagger_s=-1)
+ base = loop.child_env(loop.LoopConfig(name="b", out=cfg.out, variant="", languages=[THREEJS], generator="g", judge="j"),
+ base={"C3D_VARIANT": "stale"})
+ assert "C3D_VARIANT" not in base, "no variant: the launching shell's cannot leak into the base run"
+
+
+# --------------------------------------------------------------------------- diagnose
+def test_lib_import_scanners_read_the_agents_files(tmp_path: Path):
+ py = tmp_path / "zone.py"
+ py.write_text("from lib.place import seat\nimport lib.noise\nfrom lib import scatter, motion\nfrom os import path\n"
+ "import math\nfrom .local import x\n")
+ assert sorted(set(py_lib_modules(py))) == ["motion", "noise", "place", "scatter"]
+ js = tmp_path / "zone.js"
+ js.write_text("import { fbm } from '../lib/noise.js';\nimport { finish } from \"./lib/finish.js\";\n"
+ "import * as THREE from 'three';\nimport { x } from '../other/lib/x.js';\n")
+ assert js_lib_modules(js) == ["noise", "finish"]
+ (tmp_path / "broken.py").write_text("def (:\n")
+ assert py_lib_modules(tmp_path / "broken.py") == []
+
+
+def test_diagnose_reads_records_gates_library_use_and_recommends(cfg: loop.LoopConfig):
+ out_lang = cfg.iter_dir(0) / "scene_threejs"
+ rows = [
+ _scene_run(out_lang, "it00_scene_threejs_r1_01", (0.5, 0.7), placement_errors=2,
+ defects={"floating_asset": True, "flat_ground": False}, caps=["floating_asset"]),
+ _scene_run(out_lang, "it00_scene_threejs_r1_02", (0.4, 0.6), placement_errors=1, lib_imports=("noise",),
+ defects={"floating_asset": True}, caps=["floating_asset", "missing_must_acceptance"]),
+ _scene_run(out_lang, "it00_scene_threejs_r1_03", (0.6, 0.8), lib_imports=("noise", "finish", "sky", "water")),
+ _scene_run(out_lang, "it00_scene_threejs_r1_04", (0.55, 0.65)),
+ BenchItemResult(id="it00_scene_threejs_r1_05", tier="medium", status="infra_failed", errors="ModelError: 503 overloaded"),
+ ]
+ _write_rows(out_lang, rows)
+ # a redo archived an older tree beside run 04 (run_bench.archive_attempt): same spec id, sorts
+ # after the live run — it must never stand in for it
+ _scene_run(out_lang, "it00_scene_threejs_r1_04.attempt1", (0.1, 0.1), placement_errors=5)
+ stale = json.loads((out_lang / "runs" / "it00_scene_threejs_r1_04.attempt1" / "record.json").read_text())
+ stale["spec"]["id"] = "it00_scene_threejs_r1_04"
+ (out_lang / "runs" / "it00_scene_threejs_r1_04.attempt1" / "record.json").write_text(json.dumps(stale))
+ d = diagnose_dir("scene_threejs", out_lang)
+ assert d.n == 5 and d.by_status == {"infra_failed": 1, "max_rounds": 4} and d.n_scored == 4
+ assert d.picked["mean"] == pytest.approx(0.6875) and d.baseline["mean"] == pytest.approx(0.5125)
+ assert set(d.criteria_mean) == {"fidelity", "geometry"} and d.criteria_mean["fidelity"] == pytest.approx(0.6875)
+ assert d.gate_error_runs["scene_placement/floating"] == 2 and d.gate_error_total["scene_placement/floating"] == 3
+ assert d.gate_warn_total["scene_placement/sunken"] == 4 and "scene_placement/summary" not in d.gate_warn_total
+ assert d.defect_rates == {"floating_asset": 0.5} and d.caps_fired == {"floating_asset": 2, "missing_must_acceptance": 1}
+ assert d.lib_module_hist == {"noise": 4, "finish": 3, "sky": 1, "water": 1}, "src/lib's own imports never count"
+ assert d.lib_modules_mean == pytest.approx((2 + 1 + 4 + 2) / 4)
+ assert d.metrics["floating_error_rate"] == 0.5 and d.metrics["infra_failed_rate"] == 0.2
+ assert d.metrics["missing_must_rate"] == 0.25 and d.metrics["budget_stop_rate"] == 0.0
+ fired = {r.rule for r in d.recommendations}
+ assert {"floating", "library", "weather", "must"} <= fired and "lighting" not in fired and "budget" not in fired
+ # minutes come from the record (RunRecord.minutes, THE number), never the row: make_fake_run's
+ # plan step 24 s active + two 12 s rounds = 0.8 min, whatever the row says
+ assert d.stop_reasons == {"max_rounds": 4} and d.cost_total == pytest.approx(6.0) and d.minutes_mean == pytest.approx(0.8)
+ assert d.top_issues[0][0] == "geometry" and d.top_issues[0][1] == "Leg"
+ # the command writes both files, every language in one diagnosis
+ res = loop.diagnose_iteration(cfg, 0)
+ assert set(res) == {"scene_threejs"} # scene_blender never ran: skipped with a warning
+ md = (cfg.iter_dir(0) / "diagnosis.md").read_text()
+ assert "RECOMMENDATIONS" in md and "placement recipe" in md and "scene_placement/floating | 2 | 3 | 0" in md
+ data = json.loads((cfg.iter_dir(0) / "diagnosis.json").read_text())
+ assert data["scene_threejs"]["n"] == 5 and len(data["scene_threejs"]["runs"]) == 5
+ with pytest.raises(loop.LoopError):
+ loop.diagnose_iteration(cfg, 7)
+
+
+# --------------------------------------------------------------------------- compare
+def _stats(deltas: dict[str, float]) -> PairedStats:
+ return PairedStats(harness_arm="a", oneshot_arm="b", n=len(deltas), deltas=deltas)
+
+
+def test_the_loop_verdict_is_decide_plus_the_gate_veto():
+ up = {f"p{i}": d for i, d in enumerate((0.10, 0.11, 0.09, 0.12))}
+ assert loop_verdict(_stats(up), 0.0)[0] == "keep"
+ assert loop_verdict(_stats(up), None)[0] == "keep"
+ assert loop_verdict(_stats({k: -v for k, v in up.items()}), 0.0)[0] == "revert"
+ assert loop_verdict(_stats({"p0": 0.25, "p1": 0.01, "p2": 0.0, "p3": 0.02}), 0.0)[0] == "inconclusive"
+ assert loop_verdict(_stats({"p0": 0.3, "p1": 0.3}), 0.0)[0] == "inconclusive", "two pairs decide nothing"
+ decision, reason = loop_verdict(_stats(up), 1.5)
+ assert decision == "revert" and reason.startswith("gate veto") and "score said better" in reason
+ assert loop_verdict(_stats(up), 1.0)[0] == "keep", "a rise AT the limit is not a veto"
+
+
+def test_compare_pairs_by_id_and_the_placement_veto_overrides_the_score(cfg: loop.LoopConfig):
+ a, b = cfg.iter_dir(1) / "scene_threejs", cfg.iter_dir(0) / "scene_threejs"
+ ids = [f"it00_scene_threejs_r1_{k:02d}" for k in range(1, 5)]
+ _write_rows(b, [_scene_run(b, pid, (0.4, 0.6)) for pid in ids] + [_scene_run(b, "it00_scene_threejs_r1_09", (0.4, 0.6))])
+ _write_rows(a, [_scene_run(a, pid, (0.4, 0.6 + 0.1 * (i + 1) / (i + 1))) for i, pid in enumerate(ids)])
+ c = compare_dirs("scene_threejs", a, b)
+ assert c.paired.n == 4 and c.dropped_ids == ["it00_scene_threejs_r1_09"]
+ assert c.paired.mean_delta == pytest.approx(0.1) and c.decision == "keep"
+ assert c.criteria_delta == {"fidelity": pytest.approx(0.1), "geometry": pytest.approx(0.1)}
+ assert c.placement_rise == 0.0 and c.gate_error_delta == {} and c.cost_delta == 0.0
+ # the same scores, but the candidate's scenes gain two floating ERRORs each: the gate wins
+ a2 = cfg.iter_dir(2) / "scene_threejs"
+ _write_rows(a2, [_scene_run(a2, pid, (0.4, 0.7), placement_errors=2) for pid in ids])
+ c2 = compare_dirs("scene_threejs", a2, b)
+ assert c2.placement_rise == 2.0 and c2.decision == "revert" and "gate veto" in c2.reason
+ assert c2.gate_error_delta == {"scene_placement/floating": 8} and PLACEMENT_KINDS[0] == "scene_placement/floating"
+ res = loop.compare_iteration(cfg, 2, 0)
+ assert res["scene_threejs"].decision == "revert"
+ md = (cfg.iter_dir(2) / "compare_scene_threejs.md").read_text()
+ assert "**revert**" in md and "| it00_scene_threejs_r1_01 | +0.100 |" in md
+ assert json.loads((cfg.iter_dir(2) / "compare_scene_threejs.json").read_text())["paired"]["n"] == 4
+ with pytest.raises(loop.LoopError):
+ loop.compare_iteration(cfg, 2, 2)
+
+
+# --------------------------------------------------------------------------- judge-calib
+def test_judge_calib_rejudges_each_picked_round_in_fixed_order_and_summarises(cfg: loop.LoopConfig):
+ out_lang = cfg.iter_dir(0) / "scene_threejs"
+ _write_rows(out_lang, [_scene_run(out_lang, "p1", (0.5, 0.7), placement_errors=2), _scene_run(out_lang, "p2", (0.6, 0.9))])
+ seen: list[dict[str, Any]] = []
+
+ def fake_calibrate(run_dirs, **kw):
+ seen.append({"run_dirs": run_dirs, **kw})
+ pid = Path(run_dirs[0]).name
+ mean, std = (0.65, 0.02) if pid == "p1" else (0.88, 0.04)
+ row = CalibrationRow(run=pid, round=kw["rounds"][0], kind="refine", gate_errors=2 if pid == "p1" else 0,
+ gate_warnings=1, stored_overall=0.7 if pid == "p1" else 0.9, mean=mean, std=std,
+ uncapped=mean, defect_penalty=0.0, defects_present=["floating_asset"] if pid == "p1" else [],
+ caps=["floating_asset"] if pid == "p1" else [], passed=True, n_used=3, cost_usd=0.05,
+ duration_s=20.0)
+ return CalibrationTable(model_id=kw["model_id"], n_samples=kw["n_samples"], fixed_order=True, rows=[row])
+
+ res = loop.judge_calib(cfg, 0, calibrate_fn=fake_calibrate, workers=2)
+ assert len(seen) == 2 and {s["rounds"][0] for s in seen} == {1}, "the picked round only"
+ assert all(s["fixed_order"] and s["thinking"] == "medium" and s["model_id"] == "gemini:gemini-4-argon"
+ and s["n_samples"] == 3 and s["geometry_mode"] is None for s in seen)
+ assert all(str(s["out_dir"]).startswith(str(cfg.iter_dir(0) / "judge_calib" / "scene_threejs")) for s in seen)
+ s = res["scene_threejs"]
+ assert s.rounds == 2 and s.within_sd == pytest.approx(((0.02 ** 2 + 0.04 ** 2) / 2) ** 0.5, abs=1e-4)
+ assert s.between_sd == pytest.approx(0.1626, abs=1e-3) and s.snr == pytest.approx(s.between_sd / s.within_sd, abs=1e-2)
+ assert s.defects == {"floating_asset": 1} and s.caps == {"floating_asset": 1} and s.cost_usd == pytest.approx(0.1)
+ assert s.mean_stored == pytest.approx(0.8) and s.pearson_errors_vs_score is None, "two rounds: no correlation"
+ md = (cfg.iter_dir(0) / "judge_calib_scene_threejs.md").read_text()
+ assert "within-sd" in md and "gemini:gemini-4-argon" in md
+ assert json.loads((cfg.iter_dir(0) / "judge_calib_scene_threejs.json").read_text())["thinking"] == "medium"
+ res2 = loop.judge_calib(cfg, 0, model_id="gemini:other", thinking="high", n_samples=5, calibrate_fn=fake_calibrate)
+ assert seen[-1]["model_id"] == "gemini:other" and seen[-1]["thinking"] == "high" and res2["scene_threejs"].n_samples == 5
+
+
+# --------------------------------------------------------------------------- accept / rollback / status
+def test_accept_bumps_snapshots_and_rollback_restores(cfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path):
+ data_dir = tmp_path / "data"
+ (cfg.out / loop.LOOP_JSON).unlink()
+ loop.init(cfg, paths=overlay)
+ it1 = cfg.iter_dir(1)
+ it1.mkdir(parents=True)
+ (it1 / "battery_scene_threejs.yaml").write_text("name: x\n")
+ (it1 / "compare_scene_threejs.json").write_text(json.dumps({"decision": "keep"}))
+ # the iteration-1 edit of the overlay
+ (overlay.prompts_root / "scene_threejs").mkdir()
+ (overlay.prompts_root / "scene_threejs" / "cookbook.md").write_text("# seat everything\n")
+ (overlay.skills_root / "routes.toml").write_text('[[boost]]\nskill = "c3d-scene-placement"\ndelta = 20\n')
+ before = overlay.overlay_hash()
+ row = loop.accept(cfg, 1, note="placement recipe", paths=overlay, data_dir=data_dir)
+ assert (row.decision, row.version_from, row.version_to, row.note) == ("accept", 1, 2, "placement recipe")
+ assert row.verdicts == {"scene_threejs": "keep"} and row.languages == ["scene_threejs", "scene_blender"]
+ assert row.variant_hash == overlay.overlay_hash() != before, "the bump is part of the hash"
+ assert row.battery_sha and len(row.battery_sha) == 12 and row.cost_usd == 0.0
+ assert overlay.version() == 2
+ toml = overlay.toml.read_text()
+ assert "# the loop bumps it on accept" in toml and "version = 2" in toml and "[knobs]" in toml
+ snap2 = cfg.out / "snapshots" / "argon_v2"
+ assert (snap2 / "prompts" / "scene_threejs" / "cookbook.md").is_file() and "delta = 20" in (snap2 / "skills" / "routes.toml").read_text()
+ assert json.loads((snap2 / "snapshot.json").read_text())["hash"] == row.variant_hash, "one number for the snapshot and the row"
+ ledger = loop.ledger_path(cfg, data_dir)
+ assert ledger == data_dir / "t_loop" / "ledger.jsonl" and len(loop.ledger_rows(ledger)) == 1
+ # iteration 2 edits, then a rollback: the edits go, version 2 stays
+ (overlay.prompts_root / "scene_threejs" / "cookbook.md").write_text("# a worse idea\n")
+ (overlay.prompts_root / "scene_threejs" / "extra.md").write_text("x\n")
+ it2 = cfg.iter_dir(2)
+ it2.mkdir()
+ row2 = loop.rollback(cfg, 2, note="worse", paths=overlay, data_dir=data_dir)
+ assert (row2.decision, row2.version_from, row2.version_to) == ("rollback", 2, 2)
+ assert (overlay.prompts_root / "scene_threejs" / "cookbook.md").read_text() == "# seat everything\n"
+ assert not (overlay.prompts_root / "scene_threejs" / "extra.md").exists() and overlay.version() == 2
+ # rolling back the accepted iteration itself un-accepts it: v1 comes back, cookbook and boost gone
+ row3 = loop.rollback(cfg, 1, paths=overlay, data_dir=data_dir)
+ assert (row3.version_from, row3.version_to) == (2, 1) and overlay.version() == 1
+ assert not (overlay.prompts_root / "scene_threejs").exists() and (overlay.skills_root / "routes.toml").read_text() == "# no rows yet\n"
+ rows = loop.ledger_rows(ledger)
+ assert [r.decision for r in rows] == ["accept", "rollback", "rollback"] and rows[0].ts < rows[-1].ts
+ text = loop.status_text(cfg, paths=overlay, data_dir=data_dir)
+ assert "variant argon v1" in text and "| 1 | accept | 1→2 |" in text and "scene_threejs=keep" in text
+ with pytest.raises(loop.LoopError, match="snapshot"):
+ loop.rollback(loop.LoopConfig(name="other", out=tmp_path / "o", variant="argon", languages=[THREEJS],
+ generator="g", judge="j"), 1, paths=overlay, data_dir=data_dir)
+ stray = loop.VariantPaths(name="argon", prompts_root=tmp_path / "not_an_overlay", skills_root=overlay.skills_root)
+ (tmp_path / "not_an_overlay").mkdir()
+ with pytest.raises(loop.LoopError, match="refusing"):
+ stray.restore_from(cfg.out / "snapshots" / "argon_v1")
+
+
+def test_the_snapshot_hash_is_the_ledger_hash_not_the_loops_own(cfg: loop.LoopConfig, overlay: loop.VariantPaths,
+ tmp_path: Path, monkeypatch):
+ """snapshot.json, the ledger row and the iteration's run records must say ONE number — the variant
+ layer's ``variant_hash`` (README.md left out) — so a snapshot pairs with the runs it was measured on;
+ the loop's own ``overlay_hash`` (every file) is only the fallback for a tree the layer does not know."""
+
+ class FakeVariants:
+ """The D105 API, pointed at the tmp overlay: it knows the tree and hashes it its own way."""
+
+ def variant_info(self, name: str) -> Any:
+ return NS(name=name, version=1)
+
+ def variant_root(self, name: str) -> Path:
+ return overlay.prompts_root
+
+ def variant_hash(self, name: str) -> str:
+ return "feedfacecafe"
+
+ monkeypatch.setattr(loop, "_variants_api_or_none", lambda: FakeVariants())
+ assert overlay.ledger_hash() == "feedfacecafe" != overlay.overlay_hash()
+ snap = overlay.snapshot_to(tmp_path / "snap")
+ assert json.loads((snap / "snapshot.json").read_text())["hash"] == "feedfacecafe"
+ (cfg.out / loop.LOOP_JSON).unlink()
+ loop.init(cfg, paths=overlay)
+ assert json.loads((cfg.out / "snapshots" / "argon_v1" / "snapshot.json").read_text())["hash"] == "feedfacecafe"
+ cfg.iter_dir(1).mkdir()
+ row = loop.accept(cfg, 1, paths=overlay, data_dir=tmp_path / "data")
+ assert row.variant_hash == "feedfacecafe"
+ assert json.loads((cfg.out / "snapshots" / "argon_v2" / "snapshot.json").read_text())["hash"] == row.variant_hash
+ # a tree the layer does not know (another prompts_root): the fallback, and it is the same number
+ # in the row and the snapshot
+ stray = loop.VariantPaths(name="argon", prompts_root=tmp_path / "elsewhere" / "variants" / "argon",
+ skills_root=overlay.skills_root)
+ stray.prompts_root.mkdir(parents=True)
+ (stray.prompts_root / "variant.toml").write_text('[variant]\nname = "argon"\nversion = 1\n')
+ assert stray.ledger_hash() == stray.overlay_hash() != "feedfacecafe"
+ assert json.loads((stray.snapshot_to(tmp_path / "stray") / "snapshot.json").read_text())["hash"] == stray.overlay_hash()
+
+
+def test_the_shipped_overlays_snapshot_hash_is_the_run_records_hash(tmp_path: Path):
+ """The real ``argon`` overlay, read-only (``snapshot_to`` only copies): the snapshot's number IS
+ ``prompts.variants.variant_hash`` — what a run record carries — and the loop-private fingerprint
+ differs from it by the README.md the overlay ships."""
+ real = loop.VariantPaths.default("argon")
+ data = json.loads((real.snapshot_to(tmp_path / "real") / "snapshot.json").read_text())
+ assert data["hash"] == real.ledger_hash() == variant_hash("argon") and len(data["hash"]) == 12
+ if any(rel.endswith("/README.md") for rel, _ in real.files()):
+ assert real.overlay_hash() != data["hash"], "README.md is in the tree but never in the record's hash"
+
+
+def test_init_and_accept_refuse_a_skills_overlay_a_run_would_degrade(cfg: loop.LoopConfig, overlay: loop.VariantPaths,
+ tmp_path: Path):
+ """A run never refuses a broken overlay — ``variants_table`` logs a routes.toml that does not
+ type-check and routes with the BASE table, ``iter_skills`` skips an invalid bundle — so the loop
+ must, BEFORE a version, a snapshot or a ledger row claims the overlay was measured."""
+ data_dir = tmp_path / "data"
+ (cfg.out / loop.LOOP_JSON).unlink()
+ routes = overlay.skills_root / "routes.toml"
+ routes.write_text('[[route]]\nrule = "V1"\nskill = "c3d-scene-materials"\npriority = "85"\ntracks = ["scene"]\n')
+ with pytest.raises(loop.LoopError, match="routes.toml does not type-check.*priority must be an integer"):
+ loop.init(cfg, paths=overlay)
+ assert not (cfg.out / loop.LOOP_JSON).exists() and not (cfg.out / "snapshots").exists(), "refused before anything was written"
+ routes.write_text("# no rows yet\n")
+ loop.init(cfg, paths=overlay)
+ cfg.iter_dir(1).mkdir(parents=True)
+
+ def refused(pattern: str) -> None:
+ with pytest.raises(loop.LoopError, match=pattern):
+ loop.accept(cfg, 1, paths=overlay, data_dir=data_dir)
+ assert overlay.version() == 1 and not (cfg.out / "snapshots" / "argon_v2").exists()
+ assert not loop.ledger_path(cfg, data_dir).exists()
+
+ # a rule id the base table already uses; then an overlay bundle the run would skip: a frontmatter
+ # naming another bundle, then one that parses but fails the library's standards
+ routes.write_text('[[route]]\nrule = "R1"\nskill = "c3d-scene-materials"\npriority = 85\ntracks = ["scene"]\n')
+ refused("already taken")
+ routes.write_text('[[boost]]\nskill = "c3d-scene-materials"\ndelta = 20\n')
+ bundle = overlay.skills_root / "c3d-scene-placement"
+ bundle.mkdir()
+ (bundle / "SKILL.md").write_text("---\nname: c3d-other\ndescription: x\n---\n\nbody\n")
+ refused(r"skill bundle c3d-scene-placement .* is invalid .*directory name")
+ (bundle / "SKILL.md").write_text("---\nname: c3d-scene-placement\ndescription: x\n---\n\nbody\n")
+ refused("metadata.verified")
+ # fixed: accept goes through, and the snapshot carries the bundle
+ (bundle / "SKILL.md").write_text(VALID_SKILL)
+ row = loop.accept(cfg, 1, paths=overlay, data_dir=data_dir)
+ assert row.version_to == 2 and (cfg.out / "snapshots" / "argon_v2" / "skills" / "c3d-scene-placement" / "SKILL.md").is_file()
+ assert overlay.preflight() is None and len(loop.ledger_rows(loop.ledger_path(cfg, data_dir))) == 1
+
+
+def test_accept_needs_the_iteration_and_a_version_line(cfg: loop.LoopConfig, overlay: loop.VariantPaths, tmp_path: Path):
+ with pytest.raises(loop.LoopError, match="does not exist"):
+ loop.accept(cfg, 3, paths=overlay, data_dir=tmp_path / "d")
+ overlay.toml.write_text('[variant]\nname = "argon"\n')
+ with pytest.raises(loop.LoopError):
+ overlay.version()
+ overlay.toml.write_text('[variant]\nname = "argon"\nversion = 3\n[knobs]\nversion = 9\n')
+ overlay.set_version(4)
+ assert overlay.toml.read_text() == '[variant]\nname = "argon"\nversion = 4\n[knobs]\nversion = 9\n', "only [variant].version moves"
+
+
+# --------------------------------------------------------------------------- CLI
+def test_the_cli_dispatches_and_refuses_without_a_loop(tmp_path: Path, capsys, monkeypatch):
+ assert loop.main(["status", "--out", str(tmp_path / "none")]) == 2
+ assert "bench.loop init" in capsys.readouterr().err
+ out = tmp_path / "l"
+ monkeypatch.setattr(loop, "_variants_api_or_none", lambda: None)
+ assert loop.main(["init", "--name", "t", "--out", str(out), "--variant", "argon", "--languages", "scene_threejs",
+ "--parallel", "3", "--stagger", "5", "--rounds", "1", "--max-minutes", "20", "--n", "4"]) == 0
+ c = loop.LoopConfig.load(out)
+ assert (c.parallel, c.stagger_s, c.rounds, c.max_minutes, c.n, c.languages) == (3, 5.0, 1, 20.0, 4, [THREEJS])
+ assert c.out == out.resolve() and c.judge_thinking == "medium"
+ assert loop.main(["init", "--name", "t", "--out", str(out), "--variant", "argon"]) == 2, "one loop per --out"
+ assert loop.main(["status", "--out", str(out)]) == 0
+ assert "loop t: variant argon" in capsys.readouterr().out
diff --git a/eval/tests/test_scene_regate.py b/eval/tests/test_scene_regate.py
index 9878ce1c..ac6ed187 100644
--- a/eval/tests/test_scene_regate.py
+++ b/eval/tests/test_scene_regate.py
@@ -3,17 +3,36 @@
from __future__ import annotations
import json
+from collections import Counter
from pathlib import Path
+from types import SimpleNamespace
-from bench.scene_regate import _head, recorded_errors, regate, scene_runs
+from bench.scene_regate import (
+ _head,
+ kind_diff,
+ probe,
+ recorded_errors,
+ recorded_kinds,
+ regate,
+ report,
+ report_kinds,
+ run_language,
+ scene_runs,
+)
+from codeverse3d.contracts.artifacts import GateFinding, GateReport
+from codeverse3d.contracts.common import Language
-def _run(root: Path, name: str, *, track: str = "scene", with_src: bool = True) -> Path:
+def _run(root: Path, name: str, *, track: str = "scene", with_src: bool = True, language: str | None = "scene_threejs",
+ entry: str | None = None) -> Path:
d = root / name / "run"
(d / "src").mkdir(parents=True, exist_ok=True)
if with_src:
- (d / "src" / "scene.js").write_text("export async function createScene() {}")
- (d / "record.json").write_text(json.dumps({"spec": {"track": track, "id": name}, "rounds": []}))
+ (d / "src" / (entry or ("scene.py" if language == "scene_blender" else "scene.js"))).write_text("# entry")
+ spec = {"track": track, "id": name}
+ if language:
+ spec["language"] = language
+ (d / "record.json").write_text(json.dumps({"spec": spec, "rounds": []}))
return d
@@ -35,31 +54,41 @@ def test_regate_reads_the_stage_records_the_round_gate_reads(tmp_path: Path, mon
"groups": [{"name": "VillageQuay", "instances": 179}],
"placement": {"assets": [{"name": "Bollard", "zone": "VillageQuay", "ground_gap_m": 0.0,
"support": "Ground"}], "pairs": []}}
- monkeypatch.setattr(sr, "probe", lambda ws, timeout_s: census)
+ monkeypatch.setattr(sr, "probe", lambda ws, timeout_s, language: census)
after = regate(run, timeout_s=1.0)["after"]
assert any("holds ~179 instances but its layout budgeted 443" in m for m in after), after
assert not any("BronzeCenser" in m for m in after), after
-def test_only_scene_runs_with_a_workspace_are_re_gated(tmp_path: Path) -> None:
+def test_only_scene_runs_with_their_entry_file_are_re_gated(tmp_path: Path) -> None:
+ """A run is probed through its language's entry (``ENTRY_FILE``): a scene_blender record wants
+ ``src/scene.py``, a three.js one ``src/scene.js``; a record without a language is three.js."""
_run(tmp_path, "scene_ok")
_run(tmp_path, "an_object", track="static_object")
_run(tmp_path, "scene_no_src", with_src=False)
+ _run(tmp_path, "bpy_ok", language="scene_blender")
+ _run(tmp_path, "bpy_wrong_entry", language="scene_blender", entry="scene.js")
+ _run(tmp_path, "old_record", language=None)
names = {p.parent.name for p in scene_runs(tmp_path)}
- assert names == {"scene_ok"}, "a run whose src/ is gone cannot be re-probed"
+ assert names == {"scene_ok", "bpy_ok", "old_record"}, "a run whose entry is gone cannot be re-probed"
+ assert run_language({"spec": {"language": "scene_blender"}}) is Language.SCENE_BLENDER
+ assert run_language({"spec": {}}) is Language.SCENE_THREEJS
def test_the_errors_read_back_are_the_last_round_s(tmp_path: Path) -> None:
run = _run(tmp_path, "c")
record = {"rounds": [
{"index": 0, "gates": [{"gate": "scene_placement", "passed": False, "findings": [
- {"severity": "error", "message": "round 0 defect"}]}]},
+ {"severity": "error", "message": "round 0 defect", "data": {"kind": "sunken"}}]}]},
{"index": 1, "gates": [{"gate": "scene_placement", "passed": False, "findings": [
- {"severity": "error", "message": "round 1 defect"},
- {"severity": "warn", "message": "a warning is not an error"}]}]},
+ {"severity": "error", "message": "round 1 defect", "data": {"kind": "floating", "gap_m": 0.3}},
+ {"severity": "error", "message": "round 1 defect two", "data": {"kind": "floating", "gap_m": 0.2}},
+ {"severity": "error", "message": "an old finding without a kind"},
+ {"severity": "warn", "message": "a warning is not an error", "data": {"kind": "unsupported"}}]}]},
]}
(run / "record.json").write_text(json.dumps(record))
- assert recorded_errors(record) == ["round 1 defect"]
+ assert recorded_errors(record) == ["round 1 defect", "round 1 defect two", "an old finding without a kind"]
+ assert recorded_kinds(record) == Counter({"floating": 2, "untyped": 1})
def test_two_wordings_of_one_defect_match() -> None:
@@ -68,3 +97,88 @@ def test_two_wordings_of_one_defect_match() -> None:
a = "BlackPine_5 is sunken 3.46 m into AtmosphereHaze — raise it by 3.46 m"
b = "BlackPine_5 is sunken 3.46 m into AtmosphereHaze (8 columns)"
assert _head(a) == _head(b)
+
+
+def test_kinds_are_counted_not_matched_on_messages() -> None:
+ """Per kind ``(recorded, now, gone, new)`` from typed ``data.kind`` on both sides."""
+ rep = GateReport.of("scene_placement", [
+ GateFinding(gate="scene_placement", severity="error", message="x", data={"kind": "floating"}),
+ GateFinding(gate="scene_placement", severity="error", message="y", data={"kind": "scale"}),
+ GateFinding(gate="scene_placement", severity="warn", message="z", data={"kind": "floating"}),
+ GateFinding(gate="scene_placement", severity="info", message="s", data={"kind": "summary"})])
+ assert report_kinds(rep) == Counter({"floating": 1, "scale": 1}) and report_kinds(None) == Counter()
+ diff = kind_diff(Counter({"floating": 2, "sunken": 1}), report_kinds(rep))
+ assert diff == {"floating": (2, 1, 1, 0), "sunken": (1, 0, 1, 0), "scale": (0, 1, 0, 1)}
+ assert list(diff) == ["floating", "sunken", "scale"] # the gate's order, not alphabetical
+
+
+def test_a_blender_record_is_probed_on_its_kept_census_glb(tmp_path: Path, monkeypatch) -> None:
+ """scene_blender: the same driver on ``artifacts/census.glb`` (no settle — the picture is Blender's)
+ with the bpy facts merged as the build merges them; nothing written into the recorded run."""
+ import bench.scene_regate as sr
+
+ run = _run(tmp_path, "bpy", language="scene_blender")
+ (run / "artifacts").mkdir()
+ (run / "artifacts" / "census.glb").write_bytes(b"glTF")
+ (run / "artifacts" / "bpy_census.json").write_text(json.dumps({"fog": {"type": "VolumeBox"}, "background": "sky:MULTIPLE_SCATTERING",
+ "lights": 1, "unique_tris": 120}))
+ seen: list[list[str]] = []
+
+ def fake_driver(args, *, timeout_s):
+ seen.append(list(args))
+ return {"boot": {"ok": True, "camera_problems": []}, "console_errors": [],
+ "census": {"totals": {"meshes": 3}, "fog": None, "background": None, "groups": [],
+ "placement": {"assets": [{"name": "Crate", "zone": "Yard", "ground_gap_m": 0.3, "support": "Ground"}]}}}
+
+ monkeypatch.setattr(sr, "_driver_summary", fake_driver)
+ before = sorted(p.name for p in (run / "artifacts").iterdir())
+ census = probe(run, timeout_s=5.0, language=Language.SCENE_BLENDER)
+ assert seen and "--glb" in seen[0] and "--no-settle" in seen[0] and str(run / "artifacts" / "census.glb") in seen[0]
+ assert census["language"] == "scene_blender" and census["fog"] == {"type": "VolumeBox"} and census["totals"]["lights"] == 1
+ assert census["placement"]["assets"][0]["name"] == "Crate"
+ assert sorted(p.name for p in (run / "artifacts").iterdir()) == before
+ # and the whole re-gate: a floating ERROR now, nothing recorded → NEW, per kind
+ r = regate(run, timeout_s=5.0)
+ assert r["booted"] and r["language"] == "scene_blender" and r["after_kinds"] == Counter({"floating": 1})
+
+
+def test_a_blender_record_without_its_glb_is_rebuilt_on_a_copy(tmp_path: Path, monkeypatch) -> None:
+ """The runtime's probe rebuilds in Blender and writes its artifacts, so it runs on a copy of the
+ agent's files, never in the recorded run."""
+ import bench.scene_regate as sr
+
+ run = _run(tmp_path, "bpy2", language="scene_blender")
+ (run / "public" / "assets").mkdir(parents=True)
+ (run / "public" / "assets" / "hero.glb").write_bytes(b"glTF")
+ (run / "plan.json").write_text("{}")
+ probed: list[Path] = []
+
+ class FakeRuntime:
+ def probe(self, ws, *, timeout_s):
+ probed.append(ws.root)
+ assert (ws.root / "src" / "scene.py").is_file() and (ws.root / "public" / "assets" / "hero.glb").is_file()
+ return SimpleNamespace(ok=True, census={"placement": {"assets": []}, "language": "scene_blender"})
+
+ monkeypatch.setattr(sr, "get_runtime", lambda language: FakeRuntime())
+ census = probe(run, timeout_s=5.0, language=Language.SCENE_BLENDER)
+ assert census == {"placement": {"assets": []}, "language": "scene_blender"}
+ assert probed and probed[0] != run and not probed[0].is_relative_to(run)
+ assert not (run / "artifacts").exists() and not probed[0].exists() # the copy is gone, the run untouched
+
+
+def test_the_report_tallies_errors_per_kind(tmp_path: Path, monkeypatch) -> None:
+ import bench.scene_regate as sr
+
+ run = _run(tmp_path, "k")
+ (run / "record.json").write_text(json.dumps({
+ "spec": {"track": "scene", "language": "scene_threejs"}, "plan": {"setting": "meadow", "zones": [], "assets": []},
+ "rounds": [{"index": 0, "gates": [{"gate": "scene_placement", "passed": False, "findings": [
+ {"severity": "error", "message": "Yard/Rock is sunken 0.5 m into Terrain", "data": {"kind": "sunken"}}]}]}]}))
+ census = {"fog": {"type": "Fog"}, "background": "#aabbcc", "placement": {"assets": [
+ {"name": "Lantern", "zone": "Yard", "ground_gap_m": 0.3, "support": "Ground",
+ "bbox": {"min": [0, 0, 0], "max": [1, 1, 1], "size": [1, 1, 1]}}]}}
+ monkeypatch.setattr(sr, "probe", lambda ws, timeout_s, language: census)
+ text = report(tmp_path, timeout_s=1.0)
+ assert "## ERRORs by kind" in text
+ assert "| floating | 0 | 1 | 0 | 1 |" in text and "| sunken | 1 | 0 | 1 | 0 |" in text
+ assert "| run | scene_threejs | 1 | 1 | 1 | 1 | |" in text # the run directory (k/run), as before
diff --git a/eval/tests/test_scene_stats.py b/eval/tests/test_scene_stats.py
index 09eeff41..3207e42e 100644
--- a/eval/tests/test_scene_stats.py
+++ b/eval/tests/test_scene_stats.py
@@ -85,3 +85,28 @@ def test_the_build_layer_is_attributed(tmp_path: Path) -> None:
b = layers(runs(tmp_path))["build"]
assert dict(b) == {"failed": 2, "harness_retry": 1, "repair": 1, "ok": 1}
assert "## build" in report(tmp_path)
+
+
+def test_gate_findings_are_counted_per_typed_kind(tmp_path: Path) -> None:
+ """``gate_kinds`` / ``gate_warn_kinds`` read ``data.kind`` (never the message); a finding without
+ one is ``untyped``; a browser loss is the box and is not a kind."""
+ def finding(sev: str, kind: str | None, msg: str = "m") -> dict:
+ f = {"severity": sev, "message": msg}
+ if kind is not None:
+ f["data"] = {"kind": kind}
+ return f
+
+ _run(tmp_path, "kinds", [
+ {"gate": "scene_placement", "passed": False, "findings": [
+ finding("error", "floating"), finding("error", "floating"), finding("error", "sunken"),
+ finding("warn", "unsupported"), finding("error", None), finding("info", "summary")]},
+ {"gate": "scene_frames", "passed": False, "findings": [finding("error", "dark_frame"), finding("error", None, DETACHED)]},
+ ])
+ d = layers(runs(tmp_path))
+ assert d["gate_kinds"] == {"scene_placement/floating": 2, "scene_placement/sunken": 1, "scene_placement/untyped": 1,
+ "scene_frames/dark_frame": 1}
+ assert d["gate_warn_kinds"] == {"scene_placement/unsupported": 1}
+ text = report(tmp_path)
+ assert "## gate findings by kind" in text
+ assert "| scene_placement/floating | 2 | 0 |" in text and "| scene_placement/unsupported | 0 | 1 |" in text
+ assert text.index("| scene_placement/floating | 2 | 0 |") < text.index("| scene_placement/sunken | 1 | 0 |")
diff --git a/finetune/docs/SETUP.md b/finetune/docs/SETUP.md
index 2d2b0aad..1a0f6380 100644
--- a/finetune/docs/SETUP.md
+++ b/finetune/docs/SETUP.md
@@ -51,7 +51,7 @@ pip uninstall -y torchaudio # a mismatched torchaudio bre
## 2. External tools (called by absolute path from `eval/`)
| tool | how | path key |
|---|---|---|
-| Blender 5.0.1 (headless; executes generated bpy code, exports GLB) | `wget https://download.blender.org/release/Blender5.0/blender-5.0.1-linux-x64.tar.xz && tar xf … -C $WORKSPACE/tools` — **then `blender-5.0.1-linux-x64/5.0/python/bin/python3.11 -m pip install scipy`**: 15 of the 212 3DCodeBench reference scripts import scipy, and without it any model that writes the same idiom is scored as a failure (this cost the tuned 27B 8.1 points before we caught it) | `BLENDER` in `eval/run_bench.py`, `eval/blender_dialect_eval.py`, `scripts/*dpo*.sh` |
+| Blender 5.2.2 LTS (headless; executes generated bpy code, exports GLB) | `wget https://download.blender.org/release/Blender5.2/blender-5.2.2-linux-x64.tar.xz && tar xf … -C $WORKSPACE/tools` — **then `blender-5.2.2-linux-x64/5.0/python/bin/python3.11 -m pip install scipy`**: 15 of the 212 3DCodeBench reference scripts import scipy, and without it any model that writes the same idiom is scored as a failure (this cost the tuned 27B 8.1 points before we caught it) | `BLENDER` in `eval/run_bench.py`, `eval/blender_dialect_eval.py`, `scripts/*dpo*.sh` |
| OpenSCAD (nightly AppImage, extracted so it runs without FUSE) | `wget …/OpenSCAD-2026.08.19-x86_64.AppImage && ./OpenSCAD-*.AppImage --appimage-extract` → `squashfs-root/AppRun` | `OPENSCAD` in `eval/dialect_runners.py` |
| glslangValidator | conda-forge `glslang` (in `llmft`) | `GLSLANG` in `eval/dialect_runners.py` |
| Chromium (Playwright) | see `llmft` above | `PLAYWRIGHT_BROWSERS_PATH` |
@@ -72,7 +72,7 @@ import torch, transformers, trimesh, cadquery; print(torch.__version__, torch.cu
PY
conda activate lf && python -c "import llamafactory, fla, flash_attn, triton; print(llamafactory.__version__, triton.__version__)"
conda activate vllm && python -c "import vllm; print(vllm.__version__)"
-$WORKSPACE/tools/blender-5.0.1-linux-x64/blender -b --version | head -1
+$WORKSPACE/tools/blender-5.2.2-linux-x64/blender -b --version | head -1
$WORKSPACE/tools/openscad/squashfs-root/AppRun --version
# 1-GPU LoRA dry run (tiny dataset), then merge, then a 5-prompt generation:
GPUS=0 scripts/lf_train.sh configs/lf/lora_v1.yaml num_train_epochs=0.01
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
index 69ef9bf7..2acc50e8 100644
--- a/harness/CLAUDE.md
+++ b/harness/CLAUDE.md
@@ -1,7 +1,7 @@
# 3dcodeverse — standing context
Backend harness (python package `codeverse3d`, CLI `3dcodeverse` / short alias `3dcode`,
-repo path `/home/yipeng/3dcodeverse/harness`) for LLM-written **raw** 3D code:
+repo path `harness/` under the 3dcodeverse checkout) 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. **The coding agent is always a VENDOR's** — antigravity (`agy`, Google's
@@ -40,7 +40,7 @@ score-vs-complexity corpus study) before changing anything.
## Supported versions (what other people can run this on)
python **3.13** (one fixed version — owner's decision 2026-08-26; no floor, no matrix) ·
-node **20.6+** · Blender 4.2+ · Linux x86_64. **There is no CI** (removed 2026-08-26 by the
+node **20.6+** · Blender **5.2 LTS** only (D104, 2026-10-14; 4.2 / 5.0 compatibility dropped) · Linux x86_64. **There is no CI** (removed 2026-08-26 by the
owner): run `ruff check codeverse3d tests` and the offline suite locally BEFORE every
push, with `set -o pipefail` so a `| tail` cannot swallow a red exit. The version lives in
`pyproject` `requires-python` + ruff `target-version` + `setup.sh`, and
@@ -48,12 +48,14 @@ push, with `set -o pipefail` so a `| tail` cannot swallow a red exit. The versi
`tests/core/test_portability.py`. Details: `docs/INSTALL.md` §2.1.
## Environment (this machine)
-- Gemini keys: `~/.config/astra3d/gemini_keys.env` (15 keys, the owner's list of 2026-09-22) → `get_settings().gemini_api_keys`
+- Gemini keys: `~/.config/astra3d/gemini_keys.env` (30 keys, the owner's list of 2026-10-14: Scene1-10, Argon1-10, argon-test-1..10) → `get_settings().gemini_api_keys`
(or `GEMINI_API_KEYS` / `GEMINI_API_KEY` env). Settings: `~/.config/3dcodeverse/config.yaml`
or `./3dcodeverse.yaml`, env prefix `C3D_` (the pre-D78 `CV3D_*` names are still read; the
grammar and examples: docs/INSTALL.md §8.3). Every `C3D_*` switch is a `Settings` field read through `get_settings()`
where it is used — never read the environment by hand.
-- Blender 5.0.1 headless: `~/.local/bin/blender-5.0` (always `--factory-startup`; clear scene).
+- Blender 5.2.2 LTS headless: `~/.local/bin/blender-5.2` (always `--factory-startup`; clear scene). The judged-frame
+ fast path is Cycles CUDA + GPU OIDN + persistent data (D104; measured 0.21 s/frame at 1024x576 after the first);
+ OptiX is unavailable under WSL2 and probing it crashes Blender — never enumerate it.
- Node 24 (floor 20.6) + `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`; `C3D_RENDER_GPU=on|off|auto`); SwiftShader fallback.
@@ -70,7 +72,8 @@ push, with `set -o pipefail` so a `| tail` cannot swallow a red exit. The versi
captioner default to `gemini:gemini-4-argon` too.
`gemini-3.7-flash` stays the cheap API model (single-shot / economy, flash judge — lenient; 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.
+ n_samples=1); flash + `--n 3` is the cheap fallback, pro for calibration/eval. The argon loop judges with
+ `gemini:gemini-4-argon` at `judge.thinking=medium` (argon does not think at 'low'; D105) on rubric `scene_v2`.
- Live runs under `runs/` (`e2e_*`): read-only reference material; never modify.
- Every model call and vendor session is priced into the run's `telemetry/cost.jsonl` — the ONLY record of
money: `record.total_usage` is its sum at list price (D84). A run's minutes are its steps' time minus
@@ -78,19 +81,21 @@ push, with `set -o pipefail` so a `| tail` cannot swallow a red exit. The versi
## Commands
```
-pip install -e /home/yipeng/3dcodeverse/harness # once (entry points: 3dcodeverse, 3dcode)
-cd /home/yipeng/3dcodeverse/harness
+pip install -e harness # once, from the 3dcodeverse checkout (entry points: 3dcodeverse, 3dcode)
+cd harness
3dcodeverse doctor [--live] [--no-gpu] [--json]
3dcodeverse make "a mid-century wooden dining chair" --track static_object --language blender
3dcodeverse make "..." --profile economy|balanced|quality # one dial: models, judge n, rounds, candidates, texture, ceilings (--profile == C3D_PROFILE)
3dcodeverse make "..." --track static_object --language threejs --generator agy:gemini-4-argon
3dcodeverse make "..." --track articulated_object --language urdf_blender
3dcodeverse make "..." --track scene --language scene_threejs --rounds 2 --max-minutes 60
+3dcodeverse make "..." --track scene --language scene_blender --rounds 2 --max-minutes 90 # bpy scene on Blender 5.2.2 (D105): harness-owned src/lib, Cycles judged frames
+3dcodeverse make "..." --variant argon # per-model prompt/skill overlay: prompts/variants/<name>/ + skills/variants/<name>/ (D105; C3D_VARIANT, C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}')
3dcodeverse make "neon rain on a window" --track graphics --language glsl_shader
3dcodeverse make "..." --image ref.png --candidates 3 --rounds 2 --dim height=0.45 --must "three legs" --texture --no-run
3dcodeverse make "..." --no-pick # a run = baseline + --rounds refine rounds (fixed); make then picks a round → deliverable/ unless --no-pick
3dcode pick <slug> [--by score|pairwise] [--round N] [--texture] [--judge MODEL] # hand over a round (codeverse3d/addons/select.py)
-3dcode resume <slug> · 3dcode show <slug> [--section status] (`status` = its STATUS section) · 3dcode render <slug> [--mode wire] · 3dcode judge <slug> [--model ... --n 3]
+3dcode resume <slug> · 3dcode show <slug> [--section status] (`status` = its STATUS section) · 3dcode render <slug> [--mode wire] · 3dcode judge <slug> [--model ... --n 3 --thinking medium]
3dcode texture pass <slug> [--no-judge] · 3dcode texture scene-pack <slug> · 3dcode texture show <slug>
3dcode tools list · 3dcode tools measure --workspace runs/<slug> · 3dcode mcp --workspace runs/<slug>
3dcode cost <slug> · 3dcode cost --runs-dir ../eval/bench/out/<battery> · 3dcode cost cache <slug>
@@ -100,6 +105,7 @@ cd /home/yipeng/3dcodeverse/harness
3dcode gallery serve [ROOTS...] [--port 8765] [--reload] · 3dcode gallery build --out gallery.html [--embed]
(cd ../eval && python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-3.1-pro-preview) # report: python -m bench.report bench/out/<battery>
python -m codeverse3d.addons.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/
+(cd ../eval && python -m bench.loop init --name argon_scene --out bench/out/loop_argon --variant argon --languages scene_threejs,scene_blender --judge gemini:gemini-4-argon --judge-thinking medium --parallel 15 && python -m bench.loop generate --iter 0 && python -m bench.loop run --iter 0 && python -m bench.loop diagnose --iter 0) # the argon loop (eval/docs/EVAL.md §10): then compare --iter N --against M · judge-calib --iter N · accept|rollback --iter N · status
python ../eval/bench/complexity_report.py ../eval/bench/out --recursive # score-vs-complexity + $/complexity point (eval/docs/COMPLEXITY.md)
python ../eval/bench/compare_backends.py --prompts ../eval/bench/prompts/compare_v1.yaml --arms harness:agy:gemini-3.6-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out ../eval/bench/out/compare_v1
python -m tests.prompts.manifest [--bless | --dump DIR] # what every model is shown, pinned (RUNBOOK §8): bless only a change a model is MEANT to see
diff --git a/harness/README.md b/harness/README.md
index 0cd9c56a..9daec78c 100644
--- a/harness/README.md
+++ b/harness/README.md
@@ -70,7 +70,7 @@ runtime_js/ node side: [email protected] + headless-Chrome render/probe hosts
Design laws, the full package map and what each stage does: `docs/ARCHITECTURE.md`.
**Supported versions:** python **3.13** and node **20.6+** (Linux x86_64; Blender
-4.2+ optional). Developed and measured on python 3.13 / node 24; there is no CI — the offline suite and
+5.2 LTS optional). Developed and measured on python 3.13 / node 24; there is no CI — the offline suite and
`ruff` run locally before every push. See `docs/INSTALL.md` §2.1.
```bash
diff --git a/harness/codeverse3d/addons/calibration.py b/harness/codeverse3d/addons/calibration.py
index 500997f2..19cb5792 100644
--- a/harness/codeverse3d/addons/calibration.py
+++ b/harness/codeverse3d/addons/calibration.py
@@ -249,7 +249,7 @@ def calibrate(
out_dir: Path | str | None = None,
geometry_mode: str | None = "clay",
rounds: list[int] | None = None,
- thinking: str = "low",
+ thinking: str | None = None,
max_workers: int = 4,
chat_model: Any = None,
fixed_order: bool = False,
@@ -260,8 +260,11 @@ def calibrate(
never touches the run directories. ``chat_model`` injects a ChatModel (tests).
``fixed_order`` sends every sample the same montage order, so ``mean_std`` becomes the
model's own re-judge σ instead of its order-permutation σ (see ``VlmJudge.fixed_order``).
+ ``thinking`` defaults to ``Settings.judge.thinking`` — the level the in-run judge uses, so
+ a calibration measures the judge the loop runs (gemini-4-argon thinks only from 'medium', D105).
"""
model_id = model_id or get_settings().default_judge
+ thinking = thinking or get_settings().judge.thinking
out = Path(out_dir) if out_dir else Path.cwd()
out.mkdir(parents=True, exist_ok=True)
cases: list[RoundCase] = []
@@ -307,7 +310,8 @@ def main(argv: list[str] | None = None) -> int:
ap.add_argument("--out", default=".", help="output directory (json + md)")
ap.add_argument("--geometry", default="clay", help="clay | normals | none (geometry montage for the picked round)")
ap.add_argument("--rounds", default="", help="comma-separated round indices (default all)")
- ap.add_argument("--thinking", default="low")
+ ap.add_argument("--thinking", default=None, choices=("off", "low", "medium", "high"),
+ help="judge thinking level (default: Settings.judge.thinking / C3D_JUDGE__THINKING)")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--fixed-order", action="store_true",
help="same montage order for every sample: measures the model's re-judge σ, not order robustness")
diff --git a/harness/codeverse3d/addons/skill_targets.py b/harness/codeverse3d/addons/skill_targets.py
index ad6387c9..478b5618 100644
--- a/harness/codeverse3d/addons/skill_targets.py
+++ b/harness/codeverse3d/addons/skill_targets.py
@@ -287,6 +287,53 @@ TARGETS: tuple[Target, ...] = (
caveat="NOT yet measurable here: judged quality only. A variance census (per-material "
"value spread over sampled texels) is the candidate instrument.",
),
+ # ------------------------------------------------------------- 2026-10-14 scene_blender (D105)
+ Target(
+ skill="c3d-bpy-scene-placement",
+ metric="bpy_placement_errors",
+ direction=DOWN,
+ unit="ERROR findings per run",
+ source=SRC_GATE,
+ kinds=("scene_placement/floating", "scene_placement/sunken", "scene_placement/unsupported",
+ "scene_placement/interpenetration"),
+ severities=("error",),
+ languages=("scene_blender",),
+ why="the bundle's whole method is seating every placed row on height_at or its support; the loop's "
+ "own accept rule vetoes an iteration whose floating+sunken+interpenetration ERROR count per run "
+ "rises, so the bundle is measured by the number the loop already reads",
+ caveat="unsupported is a WARN-only kind in scene_placement.py today, so it contributes zero until the "
+ "gate escalates it; cantilevered and free_exempt route the bundle (R30) but are not counted — "
+ "cantilevered is WARN-only and free_exempt is one finding per report, not per asset.",
+ ),
+ Target(
+ skill="c3d-bpy-scene-lighting",
+ metric="bpy_exposure_findings",
+ direction=DOWN,
+ unit="findings per run",
+ source=SRC_GATE,
+ kinds=("scene_frames/dark_frame", "scene_frames/flat_frame", "scene_frames/blown_frame"),
+ languages=("scene_blender",),
+ why="the bundle is the exposure thresholds of frame_metrics.py restated with the Cycles/AgX bands "
+ "measured under them; the gate counts exactly the frames it failed to light",
+ caveat="the same three kinds as c3d-scene-lighting, over a disjoint language: a run is scene_threejs "
+ "or scene_blender, never both, so each A/B still names one owner. The uniqueness test must key "
+ "on (kind, language), not on the kind alone.",
+ ),
+ Target(
+ skill="c3d-bpy-scene-materials",
+ metric="flat_principled_materials",
+ direction=DOWN,
+ unit="materials whose Base Color, Roughness and Metallic are all unlinked constants (prospective census)",
+ source=SRC_ARTIFACT,
+ languages=("scene_blender",),
+ measurable=False,
+ why="placeholder_material, flat_ground and monotonous_vegetation are judge defects with no deterministic "
+ "twin; the census GLB reads three Principled default values and a linked socket exports as its default",
+ caveat="NOT yet measurable here: judged quality only. The candidate instrument is one census field per "
+ "material — which of Base Color / Roughness / Metallic / Normal are linked — written by "
+ "wrappers/_census_glb.py next to the values it already reads; until it exists this row is a "
+ "finding about the bundle, not a number.",
+ ),
)
BY_SKILL: dict[str, Target] = {t.skill: t for t in TARGETS}
@@ -315,10 +362,18 @@ CLAIMS_DIR = "_claims"
PROMPT_CLAIMS = "_claims.toml"
-def claims_path(name: str, root: Path | None = None) -> Path:
+def claims_path(skill: Skill | str, root: Path | None = None) -> Path:
+ """The claims file for ``skill``: a ``Skill``'s OWN root first (``<its dir>.parent/_claims/<name>.toml``
+ — a variant overlay bundle pins its numbers beside itself, D105), then the library root ``root``
+ (default ``skills_dir()``). A bare name looks in the library root only."""
from codeverse3d.skills import skills_dir
+ name = skill.name if isinstance(skill, Skill) else skill
base = Path(root) if root is not None else skills_dir()
+ if isinstance(skill, Skill):
+ own = skill.dir.parent / CLAIMS_DIR / f"{name}.toml"
+ if own.is_file():
+ return own
return base / CLAIMS_DIR / f"{name}.toml"
@@ -331,9 +386,10 @@ def _load_rows(p: Path) -> list[dict[str, Any]]:
return [dict(r) for r in rows]
-def load_claims(name: str, root: Path | None = None) -> list[dict[str, Any]]:
- """The claim rows for one skill ([] when the bundle pins nothing)."""
- return _load_rows(claims_path(name, root))
+def load_claims(skill: Skill | str, root: Path | None = None) -> list[dict[str, Any]]:
+ """The claim rows for one skill ([] when the bundle pins nothing); a ``Skill`` finds an overlay's
+ own ``_claims/`` first (:func:`claims_path`)."""
+ return _load_rows(claims_path(skill, root))
def resolve(dotted: str) -> Any:
@@ -426,7 +482,7 @@ def check_rows(rows: list[dict[str, Any]], read: Any) -> list[str]:
def check_claims(skill: Skill, root: Path | None = None) -> list[str]:
"""Every stale or missing claim in one bundle, as human lines (empty == clean)."""
try:
- rows = load_claims(skill.name, root)
+ rows = load_claims(skill, root)
except (ValueError, OSError) as e:
return [f"claims file unreadable: {e}"]
return check_rows(rows, lambda f: skill.body if not f else (skill.dir / f).read_text())
@@ -442,7 +498,7 @@ def check_prompt_claims(root: Path | None = None) -> list[str]:
return check_rows(rows, lambda f: (base / f).read_text() if f else "")
-def claim_bases(name: str, root: Path | None = None) -> dict[str, tuple[str, Any]]:
+def claim_bases(skill: Skill | str, root: Path | None = None) -> dict[str, tuple[str, Any]]:
"""``key -> (dotted target, live value)`` — the agreement test's real comparison.
WHY not the rendered text: two skills may honestly quote one constant in two units.
@@ -452,7 +508,7 @@ def claim_bases(name: str, root: Path | None = None) -> dict[str, tuple[str, Any
is compared — the pre-scale value, and the target it came from.
"""
out: dict[str, tuple[str, Any]] = {}
- for row in load_claims(name, root):
+ for row in load_claims(skill, root):
key = row.get("key")
if not key or not (row.get("python") or row.get("js")):
continue
diff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.py
index ba49c4d0..0d8c45ac 100644
--- a/harness/codeverse3d/cli/_common.py
+++ b/harness/codeverse3d/cli/_common.py
@@ -339,3 +339,70 @@ def resolve_dial(
)
+# --------------------------------------------------------------------------- the variant (D105)
+@dataclass(frozen=True)
+class ResolvedVariant:
+ """The prompt/skill variant a ``3dcode make`` freezes on ``RunOptions.variant``: its name
+ (``""`` = base), version and overlay hash, and where the choice came from."""
+
+ name: str
+ version: int
+ hash: str
+ source: str # "--variant" | "settings.variant" | "settings.variants" | "" (base)
+
+ @property
+ def label(self) -> str:
+ """One line for the run table: ``argon v1 (3f2a…) via --variant``, or ``base``."""
+ return f"{self.name} v{self.version} ({self.hash}) via {self.source}" if self.name else "base"
+
+
+def resolve_variant(settings: Any | None, generator: str, flag: str | None = None) -> ResolvedVariant:
+ """THE resolver for the variant (a sibling of :func:`resolve_dial`): ``--variant NAME`` (``flag``)
+ over ``settings.variant`` (``C3D_VARIANT``) over ``settings.variants[<generator>]`` — the id as
+ typed, then by ``<kind>:<served model>`` — over the base. An unknown name is the typed
+ 'bad configuration' refusal (exit 2) BEFORE a run directory exists, never a traceback after
+ the paid plan stage."""
+ from codeverse3d.prompts import variants as V
+
+ settings = settings or get_settings()
+ try:
+ if flag and flag.strip():
+ name, source = flag.strip(), "--variant"
+ else:
+ name = V.resolve_variant(settings, generator)
+ source = ("settings.variant" if name and settings.variant.strip() == name
+ else "settings.variants" if name else "")
+ if not name:
+ return ResolvedVariant(name="", version=0, hash="", source="")
+ info = V.variant_info(name)
+ return ResolvedVariant(name=name, version=info.version, hash=V.variant_hash(name), source=source)
+ except ValueError as e:
+ raise CliError(f"bad configuration: {e}", code=2) from e
+
+
+def record_variant(record: RunRecord) -> str:
+ """The variant a stored run used: the spec's frozen name, else what the track stamped on the record
+ (``extra["variant"]["name"]`` — a run that resolved it from the process switch)."""
+ block = record.extra.get("variant")
+ stamped = str(block.get("name") or "") if isinstance(block, dict) else ""
+ return record.spec.options.variant or stamped
+
+
+@contextmanager
+def replay_variant(record: RunRecord) -> Iterator[str]:
+ """Activate the variant a stored run used, so a replay (``3dcode judge``) reads the prompt files the
+ run read. A variant this tree no longer ships is a warning and the base prompts, never a refusal:
+ the renders and gates being replayed are on disk."""
+ from codeverse3d.prompts.variants import activate, variant_info
+
+ name = record_variant(record)
+ if name:
+ try:
+ variant_info(name)
+ except ValueError as e:
+ warn(f"replaying with the base prompts: {e}")
+ name = ""
+ with activate(name):
+ yield name
+
+
diff --git a/harness/codeverse3d/cli/inspect_cmd.py b/harness/codeverse3d/cli/inspect_cmd.py
index 1c78dafb..ca31738b 100644
--- a/harness/codeverse3d/cli/inspect_cmd.py
+++ b/harness/codeverse3d/cli/inspect_cmd.py
@@ -103,6 +103,10 @@ def judge(
] = None,
model: Annotated[str | None, typer.Option("--model", help="judge chat model id")] = None,
n: Annotated[int, typer.Option("--n", min=1)] = 1,
+ thinking: Annotated[
+ str | None, typer.Option("--thinking", help="off | low | medium | high (default: Settings.judge.thinking, "
+ "C3D_JUDGE__THINKING; gemini-4-argon thinks only from medium)"),
+ ] = None,
runs_dir: RunsDirOpt = None,
) -> None:
"""Re-judge a round with the SAME inputs as the in-run judge (renders + measurement +
@@ -125,17 +129,24 @@ def judge(
if rnd is None or rnd.renders is None or not rnd.renders.views:
raise C.CliError(f"round {idx} has no renders (rounds/r{idx:02d}.json / record.json)")
rubric_name = J.rubric_for(rec, rnd, rubric)
- inp = J.build_judge_input(ws, rec, rnd)
+ with C.replay_variant(rec): # the run's prompt/skill overlay (D105): the replay reads what the run read
+ inp = J.build_judge_input(ws, rec, rnd)
# an archived run keeps its sheet but may have pruned the per-view PNGs: say so, instead of
# the judge's own FileNotFoundError / JudgeImageError escaping as a traceback
missing = [v.path for v in inp.renders.views if not Path(v.path).is_file()]
if missing:
raise C.CliError(f"round {idx}: {len(missing)} of its {len(inp.renders.views)} judged renders are not on disk "
f"(e.g. {missing[0]}): nothing to re-judge it from", code=2)
- judge_obj = J.make_judge(rec.spec, rubric_name, model or rec.spec.backends.judge, n)
+ # --thinking is a replay knob (D105): the level reaches the judge as its own, else the settings'
+ try:
+ judge_obj = J.make_judge(rec.spec, rubric_name, model or rec.spec.backends.judge, n,
+ **({"thinking": thinking} if thinking else {}))
+ except ValueError as e: # an unknown thinking level
+ raise C.CliError(str(e), code=2) from e
n_images = J.count_prompt_images(inp, rubric_name, judge_obj)
- # writes artifacts/judge/rNN_cli.json into the run: one writer per run dir
- with C.mutating(ws, what=f"3dcode judge {ws.root.name}", action="judge"):
+ # writes artifacts/judge/rNN_cli.json into the run: one writer per run dir; the verdict is built
+ # under the run's variant, like its inputs above
+ with C.mutating(ws, what=f"3dcode judge {ws.root.name}", action="judge"), C.replay_variant(rec):
try:
# a re-judge joins the run's ledger (and its record's total) when it has one; otherwise
# the per-process log (a ledger holding only this verdict would be read as the whole run's cost)
@@ -159,6 +170,7 @@ def judge(
"overall": f"{verdict.overall:.3f}",
"passed": verdict.passed,
"std": verdict.score_std,
+ "thinking": getattr(judge_obj, "thinking", "-"), # a judge class of its own may carry none
"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,
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 2addd844..cb5a99e0 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -276,6 +276,15 @@ def make(
"montage size and the texture pass together)",
),
] = None,
+ variant: Annotated[
+ str,
+ typer.Option(
+ "--variant",
+ help="per-model prompt/skill variant (an overlay under codeverse3d/prompts/variants/<name>/ "
+ "and codeverse3d/skills/variants/<name>/, frozen on the spec); default: C3D_VARIANT, else "
+ "C3D_VARIANTS[<generator>] by the id as typed and then by its served model, else the base",
+ ),
+ ] = "",
rounds: Annotated[
int | None,
typer.Option(
@@ -393,6 +402,9 @@ def make(
generator=generator, planner=planner, judge=judge, captioner=captioner
)
C.check_backends(backends)
+ # the prompt/skill variant, resolved ONCE here (flag > C3D_VARIANT > C3D_VARIANTS by the generator
+ # id) and frozen on the spec: the track activates what the spec says, on `resume` too
+ chosen = C.resolve_variant(settings, backends.generator, variant)
# validate the whole Spec BEFORE touching the filesystem: an invalid
# track/language combination must not leave an orphan run directory behind.
try:
@@ -412,7 +424,8 @@ def make(
# options.profile records the dial this run resolved to, whichever way it was
# named (flag, C3D_PROFILE, config.yaml), so `3dcode resume` re-applies it
backends=backends,
- options=RunOptions(candidates=candidates, texture=texture, profile=dial.profile),
+ options=RunOptions(candidates=candidates, texture=texture, profile=dial.profile,
+ variant=chosen.name),
seed=seed,
tags=tag,
)
@@ -440,6 +453,7 @@ def make(
"rounds": rounds,
"candidates": candidates,
"texture": texture,
+ "variant": chosen.label,
},
)
)
diff --git a/harness/codeverse3d/cli/skills_cmd.py b/harness/codeverse3d/cli/skills_cmd.py
index 1654a81a..70434599 100644
--- a/harness/codeverse3d/cli/skills_cmd.py
+++ b/harness/codeverse3d/cli/skills_cmd.py
@@ -44,21 +44,26 @@ def list_skills(
from codeverse3d.skills import iter_skills
from codeverse3d.skills.registry import ROUTED_SKILLS, ROUTES
- found = list(iter_skills())
+ # the base library, then every shipped variant's overlay (D105): an overlay row is labelled with
+ # its variant, and under --routes it lists the overlay's own [[route]] rows beside the base table
+ roots = _roots()
+ found = [(root, s) for root in roots for s in iter_skills(root.path)]
+ overlay_rows = {root.variant: _overlay_routes(root.variant) for root in roots if root.variant}
t = Table(title="3dcode skills")
- for col in ("name", "evidence", "verified", "lines", "~tokens", "refs", "target", "dir",
+ for col in ("name", "variant", "evidence", "verified", "lines", "~tokens", "refs", "target", "dir",
*(["routes"] if routes else [])):
t.add_column(col)
- for s in found:
+ for root, s in found:
tg = target_for(s.name)
- row = [s.name, s.evidence, s.verified, str(s.body_lines), str(s.body_tokens), str(len(s.references)),
- tg.metric if tg else "[red]none[/]",
+ row = [s.name, root.variant, s.evidence, s.verified, str(s.body_lines), str(s.body_tokens),
+ str(len(s.references)), tg.metric if tg else "[red]none[/]",
("" if not tg else tg.direction if tg.measurable else f"{tg.direction} ?")]
if routes:
- row.append(",".join(r.rule for r in ROUTES if r.skill == s.name))
+ table = (*ROUTES, *overlay_rows.get(root.variant, ()))
+ row.append(",".join(r.rule for r in table if r.skill == s.name))
t.add_row(*row)
console.print(t)
- missing = [n for n in ROUTED_SKILLS if n not in {s.name for s in found}]
+ missing = [n for n in ROUTED_SKILLS if n not in {s.name for root, s in found if not root.variant}]
if missing:
console.print(f"[yellow]{len(missing)} routed skill(s) have no bundle yet:[/] {', '.join(missing)}")
@@ -90,31 +95,87 @@ def validate(
from codeverse3d.skills.model import SkillError, parse_skill
from codeverse3d.skills.registry import ROUTED_SKILLS
- dirs = bundle_dirs()
- bad = 0
- for d in dirs:
- issues = validate_bundle(d)
- with contextlib.suppress(SkillError): # a parse failure is already reported above
- issues += check_claims(parse_skill(d))
- if issues:
- bad += 1
- console.print(f"[red]FAIL[/] {d.name}")
- for i in issues:
- console.print(f" - {i}")
- else:
- console.print(f"[green]ok[/] {d.name}")
+ # every root a run can route from: the base library, then each shipped variant's overlay (D105) —
+ # an overlay bundle is routed the moment its variant is active, so a malformed one fails HERE,
+ # labelled `<variant>/<bundle>`, instead of being skipped from a session with a logged warning
+ roots = _roots()
+ total = bad = tables_bad = 0
+ base_names: set[str] = set()
+ unshipped: list[str] = [] # overlay rows that route a bundle no root ships
+ for root in roots:
+ dirs = bundle_dirs(root.path)
+ total += len(dirs)
+ for d in dirs:
+ issues = validate_bundle(d)
+ with contextlib.suppress(SkillError): # a parse failure is already reported above
+ issues += check_claims(parse_skill(d))
+ if issues:
+ bad += 1
+ console.print(f"[red]FAIL[/] {root.label(d.name)}")
+ for i in issues:
+ console.print(f" - {i}")
+ else:
+ console.print(f"[green]ok[/] {root.label(d.name)}")
+ if not root.variant:
+ base_names = {d.name for d in dirs}
+ continue
+ table_bad, orphans = _check_table(root, base_names | {d.name for d in dirs})
+ tables_bad += table_bad
+ if orphans:
+ style = "red" if strict else "yellow"
+ console.print(f"[{style}]{root.variant}/routes.toml: {len(orphans)} row(s) route a bundle "
+ f"nobody ships:[/] {', '.join(orphans)}")
+ unshipped += orphans
prompt_issues = check_prompt_claims() # the prompt corpus's pinned numbers, the same check
for i in prompt_issues:
console.print(f"[red]FAIL[/] prompts/_claims.toml - {i}")
- missing = [n for n in ROUTED_SKILLS if n not in {d.name for d in dirs}]
+ missing = [n for n in ROUTED_SKILLS if n not in base_names]
if missing:
style = "red" if strict else "yellow"
console.print(f"[{style}]{len(missing)} routed skill(s) have no bundle:[/] {', '.join(missing)}")
- console.print(f"\n{len(dirs) - bad}/{len(dirs)} bundles valid")
- if bad or prompt_issues or (strict and missing):
+ console.print(f"\n{total - bad}/{total} bundles valid"
+ + (f", {tables_bad} routes.toml invalid" if tables_bad else ""))
+ if bad or tables_bad or prompt_issues or (strict and (missing or unshipped)):
raise typer.Exit(code=1)
+def _roots() -> list:
+ """Every root the library ships (``skills.shipped_roots``); a shipped ``variant.toml`` that does not
+ parse is reported and exits 1 rather than tracing back."""
+ from codeverse3d.skills import shipped_roots
+
+ try:
+ return shipped_roots()
+ except ValueError as e:
+ err_console.print(f"[red]FAIL[/] variants - {e}")
+ raise typer.Exit(code=1) from e
+
+
+def _overlay_routes(variant: str) -> tuple:
+ """A variant's own ``[[route]]`` rows for the ``--routes`` column; a table that does not type-check
+ is said once here and listed as empty (``skills validate`` is where it fails)."""
+ from codeverse3d.skills import variants_table
+
+ try:
+ return variants_table(variant).routes
+ except ValueError as e:
+ err_console.print(f"[yellow]{variant}/routes.toml rejected:[/] {e}")
+ return ()
+
+
+def _check_table(root, available: set[str]) -> tuple[int, list[str]]:
+ """One overlay's ``routes.toml``: ``(1 if it does not type-check else 0, the rows whose skill no root
+ ships as ``RULE -> skill``)``. The failure is printed here, FAIL-labelled by the variant."""
+ from codeverse3d.skills import variants_table
+
+ try:
+ table = variants_table(root.variant)
+ except ValueError as e:
+ console.print(f"[red]FAIL[/] {root.variant}/routes.toml - {e}")
+ return 1, []
+ return 0, [f"{r.rule} -> {r.skill}" for r in table.routes if r.skill not in available]
+
+
@skills_app.command("report")
def report(
runs_dir: Annotated[Path, typer.Argument(help="a runs root, a bench out dir, or one workspace")],
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index 42e8f853..8e6e45c6 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -67,12 +67,13 @@ Flag = Annotated[bool, WrapValidator(_or_default)]
Count = Annotated[int, Field(ge=0), WrapValidator(_or_default)]
-#: the oldest Blender the wrappers support (docs/INSTALL.md §2.1); ``3dcode doctor`` checks it
-BLENDER_MIN: tuple[int, int] = (4, 2)
+#: THE supported Blender: 5.2 LTS (owner, 2026-10-14 — developed and measured on 5.2.2; 4.2 / 5.0
+#: compatibility was dropped, D104). ``3dcode doctor`` fails anything older.
+BLENDER_MIN: tuple[int, int] = (5, 2)
class Binaries(BaseModel):
- blender: str = Field(default="", description="path to a Blender 4.2+/5.x binary (headless capable)")
+ blender: str = Field(default="", description="path to the Blender 5.2 LTS binary (headless capable)")
node: str = "node"
claude_cli: str = "claude"
codex_cli: str = "codex"
@@ -105,12 +106,18 @@ class Render(BaseModel):
"the node side reads too)")
sheet_cols: int = 4
sheet_tile: int = 384
- # scene_blender pictures (spatial/render_blender.py, owner D1/D8 2026-09-24). Measured on this
- # box at 1024x576: Cycles CUDA 32 spp + OIDN 0.9 s/frame (light scene) - 3.6 s (heavy), CPU 2.9 s
- # at 16 spp; EEVEE 64 spp 1.5 - 3.0 s plus a 7-12 s shader compile per process, GPU only under the
- # Mesa d3d12 env (spatial/gl_render.GPU_ENV) — without it EEVEE silently lands on llvmpipe (10x).
+ # scene_blender pictures (spatial/render_blender.py, owner D1/D8 2026-09-24; the 5.2.2 fast path D104,
+ # 2026-10-14). Measured on this box (RTX 5090, Blender 5.2.2 LTS, 1024x576, 460 objects): Cycles
+ # CUDA 32 spp + GPU OIDN 0.64 s/frame, 0.21 s/frame once persistent data keeps the synced scene
+ # between the cameras of one job (8 frames 5.3 s → 2.2 s); 64 spp 0.69 s, 128 spp 0.86 s; CPU 2.3 s
+ # at 32 spp. EEVEE in background is SLOWER here: 5.2 s/frame + a 12 s shader compile per process,
+ # GPU only under the Mesa d3d12 env (spatial/gl_render.GPU_ENV) — without it EEVEE silently lands
+ # on llvmpipe (10x). OptiX is unavailable under WSL2 (and probing it crashes Blender): CUDA only.
blender_engine: Annotated[Literal["cycles", "eevee"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
default="cycles", description="judged-frame engine for scene_blender (C3D_RENDER__BLENDER_ENGINE)")
+ blender_frame_time_limit_s: float = Field(
+ default=20.0, ge=0, description="Cycles time cap per judged frame, seconds (0 = none): a heavy scene stops "
+ "sampling early instead of eating the render timeout (C3D_RENDER__BLENDER_FRAME_TIME_LIMIT_S)")
blender_samples: int = Field(
default=32, ge=1, description="Cycles samples (adaptive + OIDN) / EEVEE TAA samples; the profile dial sets "
"economy 16 · balanced 32 · quality 64 (C3D_RENDER__BLENDER_SAMPLES)")
@@ -122,7 +129,7 @@ class Render(BaseModel):
"<cache_dir>/slots/blender_gpu/)")
blender_gpu_wait_s: float = Field(
default=60.0, ge=0, description="how long a render waits for a GPU slot before it renders on the CPU "
- "(~3.3x slower, measured)")
+ "(~4x slower, measured on 5.2.2)")
class Limits(BaseModel):
@@ -206,6 +213,35 @@ class Judge(BaseModel):
"interior slice images + one provenance-elicitation sentence to an object-track verdict whose "
"connectivity gate carries an ERROR; clean rounds build a byte-identical payload either way. "
"Slice render is local CPU; no profile touches this dial (the channel measured ≤ $0).")
+ thinking: Annotated[Literal["off", "low", "medium", "high"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
+ default="low",
+ description="the in-run VLM judge's thinking level (C3D_JUDGE__THINKING; models/gemini.THINKING_BUDGET). "
+ "'low' = 1024 tokens is enough for gemini-3.1-pro; gemini-4-argon thinks only from 'medium' "
+ "(4096) — measured 2026-10-14 on 19 scene/object rounds: argon@medium within-sd .012 vs .029 at low, "
+ "same cost, same mean (D105). `3dcode judge --thinking` replays with another level.")
+
+
+class Placement(BaseModel):
+ """The scene_placement gate's thresholds (spatial/scene_placement.py), metres / fractions. Settings
+ fields so a per-model variant or an A/B can tighten them and the record names what a run used.
+ The defaults are the STRICT standards the owner asked for on 2026-10-14 (D105; the 2026-09
+ calibration was floating ERROR 0.15 m / > 3, sunk ERROR 0.30 m + 25 %, overlap WARN 0.20 /
+ ERROR 0.60): a 8 cm hover, a 20 cm burial or a 35 % box overlap is an ERROR now, and a
+ 10 % overlap is reported. The JS measurement (host_placement.mjs) keeps its own CONTACT /
+ FLOATING / SUNK constants: these decide severities only."""
+
+ contact_m: float = Field(default=0.02, ge=0, description="foot within this of a surface = seated")
+ floating_outdoor_m: float = Field(default=0.05, ge=0, description="gap above which an outdoor asset floats")
+ floating_indoor_m: float = Field(default=0.02, ge=0, description="gap above which an indoor asset floats")
+ floating_error_m: float = Field(default=0.08, ge=0, description="a gap this large is an ERROR (else WARN)")
+ floating_error_count: int = Field(default=2, ge=0, description="more floating assets than this = ERROR")
+ sunk_m: float = Field(default=0.10, ge=0, description="burial deeper than this = WARN")
+ sunk_error_m: float = Field(default=0.20, ge=0, description="burial deeper than this AND > sunk_error_frac of the height = ERROR")
+ sunk_error_frac: float = Field(default=0.20, ge=0, le=1)
+ overlap_warn: float = Field(default=0.10, ge=0, le=1, description="AABB overlap (fraction of the smaller box) = interpenetration WARN")
+ overlap_error: float = Field(default=0.35, ge=0, le=1, description="… = interpenetration ERROR")
+ free_exempt_warn: float = Field(default=0.25, ge=0, le=1, description="share of placed assets tagged placement='free' above which the gate WARNs (the agent is hiding from it)")
+ free_exempt_error: float = Field(default=0.50, ge=0, le=1, description="… above which it is an ERROR")
class Settings(BaseSettings):
@@ -250,6 +286,7 @@ class Settings(BaseSettings):
limits: Limits = Field(default_factory=Limits)
rate: Rate = Field(default_factory=Rate)
judge: Judge = Field(default_factory=Judge)
+ placement: Placement = Field(default_factory=Placement)
gemini_api_keys: list[str] = Field(default_factory=list)
anthropic_api_key: str = ""
@@ -276,6 +313,18 @@ class Settings(BaseSettings):
"Owner's rule 2026-08-27: time may be generous, errors may not.")
profile: str = Field(default="balanced", description="economy | balanced | quality")
+ # Per-model prompt/skill variants (D105, 2026-10-14): an overlay directory
+ # codeverse3d/prompts/variants/<name>/ (prompt files that shadow the base ones) plus
+ # codeverse3d/skills/variants/<name>/ (bundles that shadow base bundles, routes.toml with
+ # boosts). Chosen EXPLICITLY — by name, or by an exact generator-id lookup — never by a
+ # regex over the model id (Law 4). `3dcode make --variant` freezes the choice on the spec.
+ variant: str = Field(default="", description="prompt/skill variant for every run of this process "
+ "(C3D_VARIANT; a name under codeverse3d/prompts/variants/); '' = base")
+ variants: dict[str, str] = Field(default_factory=dict, description="exact generator id → variant name, "
+ "e.g. {'agy:gemini-4-argon': 'argon'} (yaml mapping, or env as JSON "
+ "C3D_VARIANTS='{\"agy:gemini-4-argon\": \"argon\"}'); consulted when "
+ "`variant` is empty, by the id as typed and then by '<kind>:<served model>'")
+
# ------------------------------------------------------------------ switches
# The A/B switches and runtime overrides, each read as C3D_<NAME> at the call that uses
# it. An A/B arm is a child process with its own environment (eval/bench/ab_plan.py), and
@@ -390,7 +439,7 @@ class Settings(BaseSettings):
configured one that is not there is "none", never a silent substitute for it."""
if self.binaries.blender:
return shutil.which(self.binaries.blender) or ""
- for cand in ("blender-5.0", "blender", "blender-5.1", "blender-4.2"):
+ for cand in ("blender-5.2", "blender"):
p = shutil.which(cand)
if p:
return p
diff --git a/harness/codeverse3d/contracts/common.py b/harness/codeverse3d/contracts/common.py
index e0eadb7e..871d2f39 100644
--- a/harness/codeverse3d/contracts/common.py
+++ b/harness/codeverse3d/contracts/common.py
@@ -63,7 +63,7 @@ class TrackInfo(BaseModel):
TRACK_INFO: dict[Track, TrackInfo] = {
Track.STATIC_OBJECT: TrackInfo(rubric="static_object_v1", label="3D Objects"),
Track.ARTICULATED_OBJECT: TrackInfo(rubric="articulated_v1", label="Articulated Objects"),
- Track.SCENE: TrackInfo(rubric="scene_v1", label="3D Scenes", best_of_n=False, likeness_refs=True),
+ Track.SCENE: TrackInfo(rubric="scene_v2", label="3D Scenes", best_of_n=False, likeness_refs=True),
Track.GRAPHICS: TrackInfo(rubric="shader_v2", label="Procedural Graphics", likeness_refs=True),
}
diff --git a/harness/codeverse3d/contracts/plan.py b/harness/codeverse3d/contracts/plan.py
index da4d7678..018975c0 100644
--- a/harness/codeverse3d/contracts/plan.py
+++ b/harness/codeverse3d/contracts/plan.py
@@ -12,11 +12,12 @@ from __future__ import annotations
import contextlib
import math
import re
-from typing import Annotated, Literal
+from typing import Annotated, Any, Literal
from pydantic import AfterValidator, BaseModel, Field, field_validator, model_validator
from codeverse3d.contracts.common import (
+ Language,
MimicSpec,
Vec3,
mimic_issues,
@@ -561,13 +562,21 @@ SCENE_ASSET_KINDS: dict[str, tuple[str, ...]] = {
}
+#: what ``AssetPlan.kind`` means to the planner of each scene language — the description the
+#: swapped schema carries (scene_threejs keeps the field's own text, byte-identical)
+SCENE_KIND_DOCS: dict[str, str] = {
+ "scene_blender": "bpy = a procedural Blender module (src/assets/<snake>.py, built once at the origin and "
+ "placed as collection instances); blender_glb = a hero built as an object and shipped as a GLB",
+}
+
+
class AssetPlan(BaseModel):
name: str = Field(description="PascalCase asset name")
kind: Literal["threejs", "bpy", "blender_glb"] = Field(
description="threejs = procedural module; blender_glb = built with bpy and compiled to a GLB",
# the schema a planner is handed names the kinds of ITS language (SCENE_ASSET_KINDS): the
# default is scene_threejs's, byte-identical to before `bpy` existed; a scene_blender
- # planner swaps in its own enum
+ # planner swaps in its own enum (``scene_plan_schema``)
json_schema_extra={"enum": list(SCENE_ASSET_KINDS["scene_threejs"])},
)
description: str
@@ -656,6 +665,23 @@ class ScenePlan(BaseModel):
return self
+def scene_plan_schema(language: Language | str) -> dict[str, Any]:
+ """The ``ScenePlan`` JSON schema a planner of ``language`` is handed: ``AssetPlan.kind``'s enum
+ (and its description) are that language's (:data:`SCENE_ASSET_KINDS`). scene_threejs's is
+ ``ScenePlan.model_json_schema()`` byte for byte — the default the field carries — so every
+ recorded scene_threejs planner request is unchanged; a scene_blender planner is offered
+ ``bpy`` / ``blender_glb`` and never ``threejs``. ``KeyError`` for a language that plans no
+ scene."""
+ kinds = SCENE_ASSET_KINDS[Language(language).value]
+ schema = ScenePlan.model_json_schema()
+ kind = schema["$defs"]["AssetPlan"]["properties"]["kind"]
+ kind["enum"] = list(kinds)
+ doc = SCENE_KIND_DOCS.get(Language(language).value)
+ if doc:
+ kind["description"] = doc
+ return schema
+
+
class ZonePlacement(BaseModel):
"""One asset's placement inside a zone, decided by the L2 zone director.
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
index bd73ac39..17cae703 100644
--- a/harness/codeverse3d/contracts/run.py
+++ b/harness/codeverse3d/contracts/run.py
@@ -275,6 +275,9 @@ class SettingsSnapshot(BaseModel):
price_table_version: str = Field(default="", description="content hash of codeverse3d.models.pricing.PRICES")
render: dict[str, Any] = Field(default_factory=dict, description="resolved render settings (size, gpu, sheet)")
limits: dict[str, Any] = Field(default_factory=dict, description="resolved timeouts / parallelism")
+ variant: str = Field(default="", description="per-model prompt/skill variant the run used ('' = base; D105)")
+ variant_version: int = Field(default=0, description="the variant's version from its variant.toml (0 = base)")
+ variant_hash: str = Field(default="", description="sha256[:12] over the variant overlay's files (name, text), '' = base")
class StageCost(BaseModel):
diff --git a/harness/codeverse3d/contracts/spec.py b/harness/codeverse3d/contracts/spec.py
index 3072d854..ef8edf8d 100644
--- a/harness/codeverse3d/contracts/spec.py
+++ b/harness/codeverse3d/contracts/spec.py
@@ -41,6 +41,9 @@ class RunOptions(BaseModel):
profile: str = Field(default="", description="cost/quality dial this run was created with "
"(codeverse3d/cost/profiles.py); '' = the settings default, and a resume "
"re-applies it so judge samples / montage size / turn cap survive")
+ variant: str = Field(default="", description="per-model prompt/skill variant this run was created with "
+ "(codeverse3d/prompts/variants/<name>/, D105); '' = the base prompts and skills; "
+ "frozen here so a resume and the record name the same overlay")
class Spec(BaseModel):
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index ff977d82..a03899cd 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -197,11 +197,17 @@ def front_view(views: Sequence[RenderView]) -> RenderView | None:
return next(iter(views_by_preference(views, FRONT_VIEW_NAMES)), views[0] if views else None)
-#: Scene overview rig (scenes sit on ground: aerial + eye level, no underside).
+#: Scene overview rig (scenes sit on ground: aerial + eye level, no underside). The
+#: ``overview_*`` views reach the judge (the first ``render_scene.MAX_JUDGE_OVERVIEWS``);
+#: ``overview_low_front`` (2026-10-14, scene_v2) is the CONTACT camera — elevation under 10°
+#: puts it at ground level just outside the content (``orbit.mjs fitContactCamera``), the
+#: angle at which daylight under a base and a part through a neighbour are visible, and the
+#: tile the judge's contact crops are cut from. The ``eye_*`` views are diagnostics only.
SCENE_VIEWS: tuple[ViewPreset, ...] = (
ViewPreset("overview_front_right", 40.0, 32.0),
ViewPreset("overview_back_left", 220.0, 32.0),
ViewPreset("overview_top", 0.0, 87.0),
+ ViewPreset("overview_low_front", 20.0, 7.0),
ViewPreset("eye_front", 0.0, 10.0),
ViewPreset("eye_right", 90.0, 14.0),
ViewPreset("eye_back_left", 235.0, 12.0),
diff --git a/harness/codeverse3d/cost/context.py b/harness/codeverse3d/cost/context.py
index b1652e8d..b21e19d0 100644
--- a/harness/codeverse3d/cost/context.py
+++ b/harness/codeverse3d/cost/context.py
@@ -16,8 +16,9 @@ role" for the call that is about to happen. Precedence:
*generation* label because the session knows more than a call made inside it
does: a best-of-N candidate session runs with ``job.kind="candidate"`` while a
tool it calls bills a model under a plain ``baseline`` label;
-4. what is left of the label (a generation stage, the round tag) — which also
- survives a thread hop that a ``ContextVar`` does not.
+4. what is left of the label (a generation stage, the round tag) — kept explicit because the
+ ambient context is bound per stage, not per call (``proc.fan_out`` does copy ContextVars into
+ its workers, D105; the label is the finer attribution).
A label that names nothing (:data:`~codeverse3d.cost.types.Stage.OTHER`) states
nothing and never displaces anything.
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 013d8ec9..ebfd8cb6 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -69,7 +69,7 @@ def check_blender() -> list[Row]:
b = s.resolve_blender()
if not b:
return [("blender", "FAIL", f"C3D_BINARIES__BLENDER={s.binaries.blender} is not an executable"
- if s.binaries.blender else "no binary (set C3D_BINARIES__BLENDER or put blender-5.0 on PATH)")]
+ if s.binaries.blender else "no binary (set C3D_BINARIES__BLENDER or put blender-5.2 on PATH)")]
okk, v = _ver([b, "--version"], timeout=60)
m = re.search(r"Blender (\d+)\.(\d+)", v)
if okk and m and (int(m[1]), int(m[2])) < BLENDER_MIN:
@@ -77,10 +77,13 @@ def check_blender() -> list[Row]:
return [("blender", "OK" if okk else "FAIL", f"{v} @ {b}")]
-#: one headless Blender run: the Cycles CUDA device list and (with EEVEE) a 32x18 EEVEE frame whose GL
-#: renderer string says whether the d3d12 env put it on the GPU or it fell to llvmpipe
+#: one headless Blender run: the Cycles CUDA device list, one timed 256x144 32-spp Cycles frame on it
+#: (the judged-frame fast path: GPU OIDN + persistent data, render_bpy_scene.setup_render) and (with
+#: EEVEE) a 32x18 EEVEE frame whose GL renderer string says whether the d3d12 env put it on the GPU
+#: or it fell to llvmpipe. OptiX is never probed (no libnvoptix under WSL2: init error 7804, and
+#: switching the compute device type back afterwards crashes Blender 5.2.2).
_BLENDER_RENDER_PROBE = """
-import json, sys
+import json, sys, time
import bpy
out = {}
p = bpy.context.preferences.addons["cycles"].preferences
@@ -90,6 +93,25 @@ try:
out["cuda"] = [d.name for d in p.devices if d.type == "CUDA"]
except Exception as e:
out["cuda"], out["cuda_error"] = [], str(e)[:200]
+if out["cuda"]:
+ try:
+ for d in p.devices:
+ d.use = d.type == "CUDA"
+ sc = bpy.context.scene
+ sc.render.engine = "CYCLES"
+ sc.cycles.device = "GPU"
+ sc.cycles.samples = 32
+ sc.cycles.use_adaptive_sampling = True
+ sc.cycles.use_denoising = True
+ sc.cycles.denoiser = "OPENIMAGEDENOISE"
+ sc.cycles.denoising_use_gpu = True
+ sc.render.use_persistent_data = True
+ sc.render.resolution_x, sc.render.resolution_y = 256, 144
+ t = time.perf_counter()
+ bpy.ops.render.render()
+ out["cycles_ms"] = int((time.perf_counter() - t) * 1000)
+ except Exception as e:
+ out["cycles_error"] = str(e)[:200]
if "--eevee" in sys.argv:
try:
sc = bpy.context.scene
@@ -130,11 +152,14 @@ def check_blender_render(*, eevee: bool = True, timeout_s: int = 120) -> list[Ro
res = json.loads(line.removeprefix("C3D_DOCTOR "))
r = s.render
cuda = res.get("cuda") or []
+ timed = (f", 32 spp 256x144 frame {res['cycles_ms']} ms (GPU OIDN + persistent data)" if res.get("cycles_ms") is not None
+ else f", timed frame failed: {res['cycles_error']}" if res.get("cycles_error") else "")
rows: list[Row] = [(
- "blender cycles", "OK" if cuda else "WARN",
- (f"CUDA: {', '.join(cuda)}" if cuda else f"no CUDA device{' (' + res['cuda_error'] + ')' if res.get('cuda_error') else ''}"
- " — scene_blender frames render on the CPU (~3.3x slower)")
- + f"; judged frames: {r.blender_engine} {r.blender_samples} spp, device {r.blender_device}")]
+ "blender cycles", "OK" if cuda and not res.get("cycles_error") else "WARN",
+ (f"CUDA: {', '.join(cuda)}{timed}" if cuda else f"no CUDA device{' (' + res['cuda_error'] + ')' if res.get('cuda_error') else ''}"
+ " — scene_blender frames render on the CPU (~4x slower)")
+ + f"; judged frames: {r.blender_engine} {r.blender_samples} spp, device {r.blender_device}, "
+ f"frame cap {r.blender_frame_time_limit_s:g}s")]
if eevee:
gl = str(res.get("gl") or "")
if res.get("gl_error") or not gl:
@@ -302,7 +327,13 @@ def check_skills() -> list[Row]:
passes — the failure is invisible except as a read rate of zero a battery later. So
the wiring gets a check you can run before spending money."""
from codeverse3d.agents.backends import ALLOWED_TOOLS
- from codeverse3d.skills import bundle_dirs, skills_dir, validate_bundle
+ from codeverse3d.skills import (
+ bundle_dirs,
+ shipped_roots,
+ skills_dir,
+ validate_bundle,
+ variants_table,
+ )
from codeverse3d.skills.materialize import SKILL_ROOTS
from codeverse3d.skills.registry import ROUTED_SKILLS
@@ -321,6 +352,29 @@ def check_skills() -> list[Row]:
missing = [n for n in ROUTED_SKILLS if n not in {d.name for d in dirs}]
if missing:
rows.append(("skills routing", "WARN", f"{len(missing)} routed skill(s) have no bundle: {', '.join(missing[:4])}…"))
+ # every shipped variant's overlay (D105), one `skills overlay` row each with the variant leading
+ # the detail: its bundles are routed the moment the variant is active, so they are checked like
+ # the base — an invalid one named `<variant>/<bundle>` — and so is its routes.toml, which
+ # attach_skills would otherwise reject with a logged warning
+ try:
+ overlays = [r for r in shipped_roots() if r.variant]
+ except ValueError as e:
+ overlays = []
+ rows.append(("skills variants", "FAIL", f"a shipped variant.toml does not parse: {e}"))
+ for root in overlays:
+ odirs = bundle_dirs(root.path)
+ invalid = [root.label(d.name) for d in odirs if validate_bundle(d)]
+ try:
+ table = variants_table(root.variant)
+ table_bad = False
+ table_note = ("routes.toml: no rows" if table.empty else
+ f"routes.toml: {len(table.routes)} row(s), {len(table.boosts)} boost(s), "
+ f"{len(table.disabled)} disabled")
+ except ValueError as e:
+ table_bad, table_note = True, f"routes.toml invalid: {e}"
+ rows.append(("skills overlay", "FAIL" if invalid or table_bad else "OK",
+ f"{root.variant}: {len(odirs)} bundles, {len(invalid)} invalid"
+ + (f": {', '.join(invalid)}" if invalid else "") + f"; {table_note}"))
rows.append(("skills discovery", "OK", "materialised into " + " + ".join(SKILL_ROOTS)))
rows.append(("claude-code Skill tool", "OK" if "Skill" in ALLOWED_TOOLS else "FAIL",
"in --allowedTools" if "Skill" in ALLOWED_TOOLS else "missing: claude-code would deny skill activation"))
diff --git a/harness/codeverse3d/judges/prompt_builder.py b/harness/codeverse3d/judges/prompt_builder.py
index 0ed1df8f..3b0668a9 100644
--- a/harness/codeverse3d/judges/prompt_builder.py
+++ b/harness/codeverse3d/judges/prompt_builder.py
@@ -17,6 +17,7 @@ import hashlib
import json
import math
import random
+from collections.abc import Sequence
from dataclasses import dataclass, replace
from pathlib import Path
from typing import TYPE_CHECKING, Literal
@@ -153,8 +154,14 @@ OBJECT_RANK = (
#: The rig names come from ``conventions.SCENE_VIEWS`` — anything else in a scene render
#: set is a camera the SCENE authored, whatever it is called (they are PascalCase plan
#: names such as ``Establishing``, never a fixed prefix).
-SCENE_OVERVIEW_RANK = ("overview_front_right", "overview_back_left", "overview_top", "eye_front", "eye_right", "eye_back_left")
+SCENE_OVERVIEW_RANK = ("overview_front_right", "overview_back_left", "overview_top", "overview_low_front",
+ "eye_front", "eye_right", "eye_back_left")
SCENE_RIG_NAMES = frozenset(v.name for v in SCENE_VIEWS) | frozenset(SCENE_OVERVIEW_RANK)
+#: the rig tiles a contact crop may be cut from (the judged ``overview_*`` views; the eye
+#: rig never reaches the judge, so a crop from it would cite a tile the judge cannot see)
+SCENE_OVERVIEW_NAMES = frozenset(n for n in SCENE_OVERVIEW_RANK if n.startswith("overview"))
+#: the gate whose findings become contact crops and the MEASURED PLACEMENT line
+PLACEMENT_GATE = "scene_placement"
POSE_PREFIX = "pose_"
POSE_SHEET_NAMES = ("articulation_sheet", "pose_sheet")
_POSITIONS = {
@@ -228,8 +235,10 @@ def plan_montages(
scene: bool = False,
max_montages: int = MAX_MONTAGES,
detail_crops: int = MAX_DETAIL_CROPS,
+ gates: Sequence[GateReport] = (),
) -> list[Montage]:
- """Decide which montages a judge call gets (see module docstring for the priority)."""
+ """Decide which montages a judge call gets (see module docstring for the priority).
+ ``gates`` feed a scene's contact crops (``plan_detail_crops``); objects ignore them."""
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)]
@@ -254,7 +263,7 @@ def plan_montages(
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)])
+ chosen.extend(plan_detail_crops(shaded, scene=scene, gates=gates, limit=max(0, detail_crops)))
return chosen
@@ -267,20 +276,218 @@ def _match_geometry(geometry: list[RenderView], primary: tuple[RenderView, ...])
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:
+def plan_detail_crops(shaded: list[RenderView], *, scene: bool, gates: Sequence[GateReport] = (),
+ limit: int = MAX_DETAIL_CROPS) -> list[Montage]:
+ """The crops a verdict sends, ``limit`` = ``Settings.judge.detail_crops`` (0 = none).
+
+ Objects: the centre crop of the best view at 2× (detail legibility) + the ground band of
+ the lowest view, cut to ``limit``. Scenes (scene_v2, 2026-10-14): the centre crop plus up
+ to ``limit`` CONTACT CROPS — close-ups around the placement findings the gate measured
+ (``plan_contact_crops``), so the judge sees the daylight under a base at crop scale
+ instead of reading the gate's sentence about it.
+ """
+ if not shaded or limit <= 0:
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")]
+ centre = 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
+ return [centre, *plan_contact_crops(shaded, gates)[:limit]]
+ out = [centre]
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[:limit]
+
+
+# --------------------------------------------------------------------------- scene contact crops
+#: a crop smaller than this of the frame (per axis) would upscale a 1024-px tile past ~4.5×
+CONTACT_CROP_MIN_FRAC = 0.22
+#: padding around the projected asset box, as a fraction of the box's own size: the gap
+#: under a base and the neighbour a part passes through are OUTSIDE the box
+CONTACT_CROP_PAD = 0.6
+#: an asset filling more than this of the tile on either axis needs no crop: the tile is the crop
+CONTACT_CROP_MAX_FRAC = 0.8
+#: which rig tile a crop prefers, by the tile's elevation: ``(upper bound, weight)`` rows, the
+#: first whose bound exceeds the elevation applies. The ground-level contact tile (< 10°) is
+#: built for this and counts 1.5×; a 32° overview counts as drawn; a top-down tile (≥ 60°)
+#: shows a base's shadow, not its gap, and is the last resort at a quarter.
+CONTACT_TILE_WEIGHT: tuple[tuple[float, float], ...] = ((10.0, 1.5), (60.0, 1.0), (90.1, 0.25))
+#: placement kinds that carry a per-asset box, and how their magnitude is printed in the label
+CONTACT_KINDS: dict[str, tuple[str, str]] = {
+ "floating": ("gap_m", "{:.2f} m"), "unsupported": ("gap_m", "{:.2f} m"), "cantilevered": ("gap_max_m", "{:.2f} m"),
+ "sunken": ("sunk_m", "{:.2f} m"), "interpenetration": ("overlap", "{:.0%}"), "scale": ("factor", "{:g}×"),
+}
+
+
+def _camera_frame(view: RenderView) -> tuple[tuple[float, float, float], ...] | None:
+ """``(eye, forward, right, up)`` of a view's camera in the GLB frame, with THREE's lookAt
+ roll (world up +Y unless the view is vertical, then −Z) — the convention ``orbit.mjs``
+ fits the rig with, so a projection here lands where the tile drew it."""
+ if view.camera_position is None or view.look_at is None:
+ return None
+ eye = tuple(float(c) for c in view.camera_position)
+ f = tuple(float(target) - e for target, e in zip(view.look_at, eye, strict=True))
+ fl = math.hypot(*f)
+ if fl < 1e-9:
+ return None
+ f = (f[0] / fl, f[1] / fl, f[2] / fl)
+ up0 = (0.0, 0.0, -1.0) if abs(f[1]) > 0.9999 else (0.0, 1.0, 0.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)
+ if rl < 1e-9:
+ return None
+ r = (r[0] / rl, r[1] / rl, r[2] / rl)
+ 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])
+ return eye, f, r, u
+
+
+def _view_aspect(view: RenderView) -> float:
+ return view.width / view.height if view.width > 0 and view.height > 0 else 16 / 9
+
+
+def project_box(view: RenderView, center: Sequence[float], size: Sequence[float]) -> tuple[float, float, float, float] | None:
+ """The frame-fraction box ``(left, top, right, bottom)`` the GLB-frame AABB ``center ±
+ size/2`` covers in ``view`` (vertical ``fov``, the rig's 50° when the record has none), or
+ None when the camera is unknown, a corner is behind the lens, or the box's centre is
+ outside the frame. Fractions may run past 0..1 for a box that is partly out of frame."""
+ frame = _camera_frame(view)
+ if frame is None:
+ return None
+ eye, f, r, u = frame
+ tan_v = math.tan(math.radians(float(view.fov or 50.0)) / 2)
+ tan_h = tan_v * _view_aspect(view)
+ half = [abs(float(s)) / 2 for s in size]
+ pts = [(float(center[0]) + sx * half[0], float(center[1]) + sy * half[1], float(center[2]) + sz * half[2])
+ for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)]
+ us: list[float] = []
+ vs: list[float] = []
+ for p in [tuple(float(c) for c in center), *pts]:
+ rel = (p[0] - eye[0], p[1] - eye[1], p[2] - eye[2])
+ depth = rel[0] * f[0] + rel[1] * f[1] + rel[2] * f[2]
+ if depth <= 1e-6:
+ return None
+ x = (rel[0] * r[0] + rel[1] * r[1] + rel[2] * r[2]) / (depth * tan_h)
+ y = (rel[0] * u[0] + rel[1] * u[1] + rel[2] * u[2]) / (depth * tan_v)
+ us.append((x + 1) / 2)
+ vs.append((1 - y) / 2)
+ if not (0.0 <= us[0] <= 1.0 and 0.0 <= vs[0] <= 1.0): # the centre must be in the picture
+ return None
+ return min(us[1:]), min(vs[1:]), max(us[1:]), max(vs[1:])
+
+
+def _finding_box(f: GateFinding) -> tuple[list[float], list[float]] | None:
+ """``(center, size)`` from a placement finding's ``data.bbox`` (scene_placement, 2026-10-14), or None."""
+ box = f.data.get("bbox") if isinstance(f.data, dict) else None
+ if not isinstance(box, dict):
+ return None
+ try:
+ center = [float(c) for c in box.get("center") or ()]
+ size = [float(s) for s in box.get("size") or ()]
+ except (TypeError, ValueError):
+ return None
+ if len(center) != 3 or len(size) != 3 or max(size) <= 0:
+ return None
+ return center, size
+
+
+def _contact_label(f: GateFinding) -> str:
+ kind = str(f.data.get("kind") or "")
+ key, fmt = CONTACT_KINDS.get(kind, ("", ""))
+ v = f.data.get(key) if key else None
+ mag = fmt.format(float(v)) if isinstance(v, (int, float)) and not isinstance(v, bool) else ""
+ return f"CONTACT CROP — {f.target or 'asset'} (gate: {kind}{' ' + mag if mag else ''})"
+
+
+def _crop_around(box: tuple[float, float, float, float]) -> tuple[float, float, float, float]:
+ """A crop window around a projected box: padded by ``CONTACT_CROP_PAD``, never under
+ ``CONTACT_CROP_MIN_FRAC`` on either axis, shifted (not shrunk) back inside the frame."""
+ left, top, right, bottom = box
+ cx, cy = (left + right) / 2, (top + bottom) / 2
+ hw = max((right - left) * (1 + CONTACT_CROP_PAD) / 2, CONTACT_CROP_MIN_FRAC / 2)
+ hh = max((bottom - top) * (1 + CONTACT_CROP_PAD) / 2, CONTACT_CROP_MIN_FRAC / 2)
+
+ def span(c: float, h: float) -> tuple[float, float]:
+ lo, hi = c - h, c + h
+ if lo < 0:
+ hi, lo = min(1.0, hi - lo), 0.0
+ if hi > 1:
+ lo, hi = max(0.0, lo - (hi - 1)), 1.0
+ return round(lo, 4), round(hi, 4)
+
+ x0, x1 = span(cx, hw)
+ y0, y1 = span(cy, hh)
+ return x0, y0, x1, y1
+
+
+def placement_findings_for_crops(gates: Sequence[GateReport]) -> list[GateFinding]:
+ """The scene_placement findings a contact crop can be cut for: ERROR before WARN, the larger
+ magnitude first, one per asset, only those carrying a box."""
+ rank = {Severity.ERROR: 0, Severity.WARN: 1, Severity.INFO: 2}
+ found: list[GateFinding] = [f for g in gates if g.gate == PLACEMENT_GATE for f in g.findings
+ if f.severity != Severity.INFO and str(f.data.get("kind") or "") in CONTACT_KINDS
+ and _finding_box(f) is not None]
+
+ def magnitude(f: GateFinding) -> float:
+ key = CONTACT_KINDS[str(f.data.get("kind"))][0]
+ v = f.data.get(key)
+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0.0
+
+ out: list[GateFinding] = []
+ seen: set[str] = set()
+ for f in sorted(found, key=lambda f: (rank[f.severity], -magnitude(f))):
+ if (f.target or "") in seen:
+ continue
+ seen.add(f.target or "")
+ out.append(f)
+ return out
+
+
+def _tile_weight(elevation_deg: float) -> float:
+ return next(w for bound, w in CONTACT_TILE_WEIGHT if elevation_deg < bound)
+
+
+def plan_contact_crops(shaded: list[RenderView], gates: Sequence[GateReport]) -> list[Montage]:
+ """One crop per placement finding (``placement_findings_for_crops`` order), cut from the
+ judged overview tile that shows the asset largest: every ``overview_*`` view at the first
+ time whose camera is recorded projects the finding's box (``project_box``), its projected
+ size weighted by the tile's elevation (``CONTACT_TILE_WEIGHT``: the ground-level contact
+ tile first, the top-down one last); a tile where the box fills the frame needs no crop. No
+ box, no camera, no tile that sees it — no crop: the verdict never dies on a crop. Added
+ 2026-10-14 (scene_v2) because the judge read the gate's floating sentences instead of the
+ pictures: the crop puts the measured contact in front of it at the scale a person would
+ check."""
+ overviews = [v for v in shaded if v.name in SCENE_OVERVIEW_NAMES]
+ if not overviews:
+ return []
+ t0 = min((v.time_s if v.time_s is not None else 0.0) for v in overviews)
+ tiles = [v for v in overviews if (v.time_s if v.time_s is not None else 0.0) == t0]
+ out: list[Montage] = []
+ for f in placement_findings_for_crops(gates):
+ box = _finding_box(f)
+ if box is None:
+ continue
+ best: tuple[float, RenderView, tuple[float, float, float, float]] | None = None
+ for i, v in enumerate(tiles):
+ proj = project_box(v, *box)
+ if proj is None:
+ continue
+ w, h = proj[2] - proj[0], proj[3] - proj[1]
+ if max(w, h) > CONTACT_CROP_MAX_FRAC:
+ continue
+ el = (view_az_el(v) or (0.0, 0.0))[1]
+ score = max(w, h) * _tile_weight(el) - i * 1e-6 # ties keep rank order
+ if best is None or score > best[0]:
+ best = (score, v, proj)
+ if best is None:
+ continue
+ _, view, proj = best
+ out.append(Montage("detail", (view,), _contact_label(f), crop=_crop_around(proj),
+ hint=f"diagnostic close-up cut from {view.name} at a placement finding the gate measured: "
+ "judge the CONTACT — does the base meet what is under it, does the part pass through "
+ "its neighbour — not the composition, lighting or dressing"))
return out
@@ -537,7 +744,7 @@ def contact_ledger(gates: list[GateReport]) -> tuple[GateReport, GateFinding] |
return None
-def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: int = 8) -> str:
+def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: int = 8, scene: bool = False) -> str:
"""The judge's gate facts. ERRORs are listed as recorded. With a contact ledger the
connectivity WARNs are not prose any more: the audit of 420 judged static rounds
(2026-08-30, eval/docs/EVAL.md §6) found the judge marking interpenetration on every gate
@@ -546,9 +753,13 @@ def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: i
13 of 24 flags flipped). So the WARNs become one measured line and a MEASURED STRUCTURE
block (contacts, planned joins contact/open, floor gaps) the judge can cite instead.
Without a ledger (older rounds) the text is the pre-ledger text byte for byte, which is
- what keeps ``3dcode judge <old-slug>`` comparable with the verdict it stored."""
+ what keeps ``3dcode judge <old-slug>`` comparable with the verdict it stored.
+ ``scene`` (scene_v2, 2026-10-14) is the scene track's own branch — ``_scene_gates_section``;
+ the object text above is untouched by it."""
if not gates:
return "GATE FINDINGS: (no gates run)"
+ if scene:
+ return _scene_gates_section(gates, max_errors=max_errors, max_warns=max_warns)
status = ", ".join(f"{g.gate}={'pass' if g.passed else 'FAIL'}" for g in gates)
lines = [f"GATE FINDINGS (deterministic; treat as facts): {status}"]
errs = [_finding_line(g, f) for g in gates for f in g.findings if f.severity == Severity.ERROR]
@@ -586,6 +797,96 @@ def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: i
return "\n".join(lines)
+# --------------------------------------------------------------------------- the scene branch
+#: the order the scene gates are listed in: what was measured about the place first (the
+#: placement rows), then the frames, then lint / build / console reports. A typed rank, so a
+#: new gate name lands in the tail by default — never a regex on the name.
+SCENE_GATE_ORDER: dict[str, int] = {PLACEMENT_GATE: 0, "scene_frames": 1}
+#: the per-kind magnitude a MEASURED PLACEMENT line reports as "worst" (the same keys the
+#: findings carry; cantilevered rows report their widest column gap)
+PLACEMENT_WORST: dict[str, tuple[str, str]] = {
+ "floating": ("gap_m", "{:.2f} m"), "sunken": ("sunk_m", "{:.2f} m"), "unsupported": ("gap_m", "{:.2f} m"),
+ "interpenetration": ("overlap", "{:.0%} of the smaller box"), "cantilevered": ("gap_max_m", "{:.2f} m"),
+}
+
+
+def _scene_gates_section(gates: list[GateReport], *, max_errors: int, max_warns: int) -> str:
+ """The scene judge's gate facts (scene_v2): reports in ``SCENE_GATE_ORDER``, the ERRORs as
+ recorded, one MEASURED PLACEMENT line built from the scene_placement report's own counts
+ (``placement_block``), and the WARNs grouped by (gate, kind) as the object ledger branch
+ groups them — eight flat lines used to cut a round's WARNs mid-list with every frame
+ WARN behind the placement ones."""
+ ordered = sorted(gates, key=lambda g: SCENE_GATE_ORDER.get(g.gate, len(SCENE_GATE_ORDER)))
+ status = ", ".join(f"{g.gate}={'pass' if g.passed else 'FAIL'}" for g in ordered)
+ lines = [f"GATE FINDINGS (deterministic; treat as facts): {status}"]
+ errs = [_finding_line(g, f) for g in ordered for f in g.findings if f.severity == Severity.ERROR]
+ lines += _capped("errors", errs, max_errors)
+ block = placement_block(gates)
+ if block:
+ lines.append(block)
+ warns = [(g, f) for g in ordered for f in g.findings if f.severity == Severity.WARN]
+ lines += _grouped_warnings(warns, max_warns)
+ if not errs and not warns:
+ lines.append("no errors or warnings — every checked asset is seated, the frames are exposed and the contracts hold.")
+ return "\n".join(lines)
+
+
+def placement_report(gates: Sequence[GateReport]) -> GateReport | None:
+ return next((g for g in gates if g.gate == PLACEMENT_GATE), None)
+
+
+def placement_block(gates: Sequence[GateReport]) -> str:
+ """MEASURED PLACEMENT: the scene_placement gate's own summary (checked / placed / exempt /
+ free-tagged, the count per kind) with the worst magnitude per kind read off the typed
+ findings, the thresholds the gate used when it recorded them, and — on a clean report — the
+ sentence that tells the judge which checklist items the measurement already answered (the
+ arithmetic veto, ``rubrics.measured_absent``, holds when the judge does not listen). Empty
+ without the gate or when its probe failed (nothing was measured)."""
+ rep = placement_report(gates)
+ if rep is None:
+ return ""
+ summary = next((f for f in rep.findings if f.severity == Severity.INFO and f.data.get("kind") == "summary"), None)
+ if summary is None:
+ return ""
+ d = summary.data
+ counts = {k: int(v) for k, v in (d.get("counts") or {}).items() if isinstance(v, (int, float))}
+ exempt = {str(k): int(v) for k, v in (d.get("exempt") or {}).items() if isinstance(v, (int, float))}
+ worst: dict[str, float] = {}
+ for f in rep.findings:
+ kind = str(f.data.get("kind") or "")
+ if f.severity == Severity.INFO or kind not in PLACEMENT_WORST:
+ continue
+ v = f.data.get(PLACEMENT_WORST[kind][0])
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
+ worst[kind] = max(worst.get(kind, 0.0), float(v))
+ free = sum(1 for g in gates if g.gate == PLACEMENT_GATE for f in g.findings if f.data.get("kind") == "free_exempt")
+ head = (f"MEASURED PLACEMENT (scene_placement gate: every placed asset's foot columns against what is under it, "
+ f"every pair's box overlap): {int(d.get('checked') or 0)} assets checked of {int(d.get('total') or 0)} placed, "
+ f"{sum(exempt.values())} exempt ({exempt.get('free', 0)} tagged free)")
+ # the gate's own per-kind counts (floating / sunken / unsupported / interpenetration, in its
+ # order), then any kind only the findings know (a cantilevered row has no count yet)
+ kinds = [k for k in PLACEMENT_WORST if k in counts] + [k for k in worst if k not in counts]
+ parts = []
+ for kind in kinds:
+ text = f"{counts.get(kind, 0) or sum(1 for f in rep.findings if f.data.get('kind') == kind)} "
+ text += "interpenetrating" if kind == "interpenetration" else kind
+ if kind in worst:
+ text += f" (worst {PLACEMENT_WORST[kind][1].format(worst[kind])})"
+ parts.append(text)
+ head += ": " + ", ".join(parts) + "."
+ if free:
+ head += " The share of assets tagged placement='free' is over the line (see the free_exempt finding): an author hiding from the gate."
+ thresholds = d.get("thresholds")
+ if isinstance(thresholds, dict) and thresholds:
+ head += " Thresholds: " + ", ".join(f"{k} {float(v):g}" for k, v in sorted(thresholds.items())
+ if isinstance(v, (int, float)) and not isinstance(v, bool)) + "."
+ if rep.passed and not any(counts.get(k, 0) for k in kinds) and not worst:
+ head += (" PLACEMENT PASSED: no checked asset floats, sinks or overlaps another beyond the thresholds. A dark seam "
+ "under a base is contact, not daylight: mark floating_asset / sunken_asset / interpenetration present only "
+ "where a render VISIBLY shows it, and name the view.")
+ return head
+
+
def connectivity_error_pairs(gates: list[GateReport]) -> list[tuple[str, str]]:
"""The connectivity gate's ERROR-level penetration part pairs — the D48 slice
channel's hatch targets. The pair is read the way the measured batteries read it:
@@ -821,6 +1122,9 @@ RIG_RULES: dict[str, str] = {
"poses": "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.",
"scene_cams": "Views named overview_* and eye_* are harness cameras fitted to the scene bounds (layout X-ray); every other view is one of the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.",
"scene_craft": "On the authored cameras also read the CRAFT of the picture, not only its contents: depth layering (is there anything within a few metres framing the shot, and anything on the horizon), ground variation (blended materials, paths, dressed edges vs one flat colour), variety among repeated natural elements, small-prop dressing, and aerial perspective (distant things hazier than near ones). The same camera at two times appears as separate tiles — compare them pixel-for-pixel before answering nothing_moves.",
+ # scene_v2 (2026-10-14): the high overview tiles lift room ceilings (scene_host.skyLayersBelow) and
+ # drop the fog; the low one is the contact camera; CONTACT CROPs are diagnostic close-ups
+ "scene_contact": "The high overview_* tiles (overview_front_right / overview_back_left / overview_top) are rendered with the fog removed and room ceilings lifted: a missing roof, lid or haze in them is never a defect. overview_low_front stands at ground level just outside the content, where daylight under a base shows. CONTACT CROP images are diagnostic close-ups cut from an overview tile around a placement finding the gate measured (the label names the asset, the kind and the number): judge the contact they show — base meets ground, part through neighbour — never their composition, lighting or dressing. Every floating / sunken / clipping / scale claim must name its view and its asset.",
"object": "All views show the same object. Use top + low views for symmetry, footprint and ground contact.",
}
@@ -840,6 +1144,7 @@ def view_rig_section(renders: RenderSet, montages: list[Montage], *, scene: bool
if scene:
bits.append(RIG_RULES["scene_cams"])
bits.append(RIG_RULES["scene_craft"])
+ bits.append(RIG_RULES["scene_contact"])
else:
bits.append(RIG_RULES["object"])
if renders.console_errors:
@@ -895,10 +1200,13 @@ def montage_image_parts(
detail_crops: int = MAX_DETAIL_CROPS,
max_px: int = MAX_PX,
cache_dir: Path | None = None,
+ gates: Sequence[GateReport] = (),
) -> tuple[list[tuple[str, ImagePart]], list[Montage]]:
- """(label, ImagePart) pairs for the montages of a render set, plus the montage plan (in send order)."""
+ """(label, ImagePart) pairs for the montages of a render set, plus the montage plan (in send
+ order). ``gates`` feed a scene's contact crops (``plan_contact_crops``)."""
montages = shuffle_montages(
- plan_montages(renders, geometry_views=geometry_views, scene=scene, max_montages=max_montages, detail_crops=detail_crops),
+ plan_montages(renders, geometry_views=geometry_views, scene=scene, max_montages=max_montages, detail_crops=detail_crops,
+ gates=gates),
shuffle_seed,
)
grids = [m for m in montages if not m.is_detail]
@@ -955,7 +1263,7 @@ def build_judge_messages(
("PLAN DIGEST:\n" + _clip(inp.plan_summary, 5000)) if inp.plan_summary.strip() else "PLAN DIGEST: (none)",
acceptance_section(inp.acceptance),
measurement_section(inp.measurement),
- gates_section(inp.gates),
+ gates_section(inp.gates, scene=is_scene),
previous_section(inp.previous, inp.round_index),
_clip(inp.extra_context, 2500) if inp.extra_context.strip() else "",
_clip(extra_text, 2500) if extra_text.strip() else "",
@@ -964,6 +1272,7 @@ def build_judge_messages(
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,
+ gates=inp.gates if is_scene else (),
)
slices = slice_images or []
rig = view_rig_section(inp.renders, montages, scene=is_scene)
diff --git a/harness/codeverse3d/judges/rubrics.py b/harness/codeverse3d/judges/rubrics.py
index 37221cf5..66d2633a 100644
--- a/harness/codeverse3d/judges/rubrics.py
+++ b/harness/codeverse3d/judges/rubrics.py
@@ -149,6 +149,13 @@ class CapRule(BaseModel):
default=False,
description="acceptance rules only: cap + (1 - cap) * verified_must / total_must instead of the flat cap",
)
+ veto_warn_keys: dict[str, float] = Field(
+ default_factory=dict,
+ description="gate rules only: finding.data key → magnitude at or above which a WARN of the rule's kinds "
+ "keeps the judge's claim alive (measured_absent); empty = the penetration default, "
+ "{depth_m: VETO_PENETRATION_DEPTH_M}. scene_v2 states {gap_m: 0.02} / {sunk_m: 0.10} / "
+ "{overlap: 0.20}; 0.0 = any WARN of the kind that carries the key",
+ )
note: str = ""
@model_validator(mode="after")
@@ -568,27 +575,45 @@ VETO_PENETRATION_DEPTH_M = 0.008
def _rule_gates_clean(rule: CapRule, gates: list[GateReport]) -> bool:
- """Every gate ``rule`` watches ran, passed, and has no finding of its ``kinds`` that is
- an ERROR — or a penetration WARN measured at ``VETO_PENETRATION_DEPTH_M`` or deeper.
- A report is watched when its name OR one of its findings' ``gate`` matches the rule,
- the same predicate the cap side (``_finding_matches``) uses."""
+ """Every gate ``rule`` watches ran and reports no finding of its ``kinds`` that is an
+ ERROR — or a WARN whose measured magnitude reaches the rule's veto line
+ (``CapRule.veto_warn_keys``; default: a penetration ``depth_m`` of
+ ``VETO_PENETRATION_DEPTH_M``). A report is watched when its name OR one of its findings'
+ ``gate`` matches the rule, the same predicate the cap side (``_finding_matches``) uses.
+
+ Scoped to the rule's kinds since scoring version 4 (2026-10-14): a failed report used to
+ cancel the veto whatever it failed on, and on the scene track the placement rows and the
+ plan checks share ONE report — a ``no_fog`` or ``missing_content`` ERROR let every
+ "floating asset" claim stand although the rows had measured none (scene_v2 splits the
+ placement caps per kind for the same reason). A failed report that names no ERROR finding
+ at all cannot say what failed and still counts as not clean."""
watched = [g for g in gates if fnmatch(g.gate, rule.gate) or any(fnmatch(f.gate, rule.gate) for f in g.findings)]
if not watched:
return False
+ lines = rule.veto_warn_keys or {"depth_m": VETO_PENETRATION_DEPTH_M}
for g in watched:
- if not g.passed:
+ if not g.passed and not any(f.severity == Severity.ERROR for f in g.findings):
return False
for f in g.findings:
if not any(k.lower() in _finding_tokens(f) for k in rule.kinds):
continue
if f.severity == Severity.ERROR:
return False
- depth = f.data.get("depth_m") if isinstance(f.data, dict) else None
- if f.severity == Severity.WARN and isinstance(depth, (int, float)) and depth >= VETO_PENETRATION_DEPTH_M:
+ if f.severity == Severity.WARN and _reaches_veto_line(f, lines):
return False
return True
+def _reaches_veto_line(f: GateFinding, lines: dict[str, float]) -> bool:
+ """Does a WARN's measured magnitude (any of ``lines``' keys in ``f.data``) reach its line?"""
+ data = f.data if isinstance(f.data, dict) else {}
+ for key, line in lines.items():
+ v = data.get(key)
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and float(v) >= line:
+ return True
+ return False
+
+
def veto_measured_defects(
rubric: Rubric, defects: dict[str, bool], gates: list[GateReport]
) -> tuple[dict[str, bool], list[str]]:
@@ -691,7 +716,7 @@ def _rule_hit(
# ===================================================================== scoring
-SCORING_VERSION = 3
+SCORING_VERSION = 4
"""The arithmetic downstream of the model, stamped into every ``ScoreBreakdown``.
A stored verdict is reproducible from its samples only under the version that wrote
@@ -708,6 +733,12 @@ drift to report, not a fault.
3 — 2026-09-24: a gate cap rule's ``kinds`` match the finding's typed ``data.kind`` /
``data.code``; the message only when it has neither, the target never (N50). A replay
of the 1 229 recorded judged rounds moved no cap and no veto.
+4 — 2026-10-14 (scene_v2): the measured-absent veto is scoped to the rule's ``kinds`` — a
+ watched report that failed on an unrelated kind no longer cancels it — and the WARN
+ magnitude that keeps a claim alive is the rule's ``veto_warn_keys`` (the object rubrics
+ keep the ``depth_m`` ≥ 8 mm default, so their verdicts replay unchanged unless the
+ connectivity report failed on a penetration while the judge claimed floating, or the
+ reverse).
"""
diff --git a/harness/codeverse3d/judges/rubrics/scene_v2.yaml b/harness/codeverse3d/judges/rubrics/scene_v2.yaml
new file mode 100644
index 00000000..906652bf
--- /dev/null
+++ b/harness/codeverse3d/judges/rubrics/scene_v2.yaml
@@ -0,0 +1,420 @@
+name: scene_v2
+version: 2
+track_hint: scene
+pass_threshold: 0.70
+description: >
+ Rubric for a procedural 3D SCENE (a place) judged on its authored cameras plus a
+ fitted overview rig, at one or more animation times, with a probe digest (console/shader
+ errors, census) and diagnostic CONTACT CROPS at the placement findings the gate measured.
+ The scene owns its lighting, sky and fog: grade the picture it makes, and the place it
+ depicts. v2 (2026-10-14, the argon scene-tuning program): stricter and detail-aware —
+ floating and sunken are separate measured defects, interpenetration / scale / hard-edged
+ particles / missing planned elements / hero placement join the checklist, the caps follow
+ the scene_placement gate's typed kinds, and every criterion is anchored at six levels so the
+ judge uses the whole scale. scene_v1 stays frozen for replays of the rounds it scored.
+
+extra_instructions: >
+ Views named overview_* are HARNESS cameras fitted to the scene bounds — nobody framed
+ them; use them only for layout, coverage, floating / sunken / clipping assets and scale,
+ and never as evidence that a picture is badly composed, badly lit or under-dressed. The
+ high ones (overview_front_right, overview_back_left, overview_top) are rendered with the
+ fog removed and room ceilings lifted, so a missing roof, lid or haze THERE is never a
+ defect; overview_low_front stands at ground level just outside the content and keeps both.
+ Every other view is one of the scene's OWN authored cameras (PascalCase plan names such as
+ Establishing / BridgeView) — grade composition, lighting, atmosphere and effects on those
+ alone. Views at different times (t=...) show animation, but they reach you in different
+ montage images: do NOT judge motion by comparing them — the harness measures the pixel
+ change between the two times per camera and states it in the context; that measurement
+ decides `nothing_moves` and every "it must move" acceptance item. The probe digest lists
+ console/shader errors measured by the harness; treat those as facts. A gate finding that
+ starts with "harness rig view" describes one of the harness's own cameras, not the scene:
+ never turn it into a defect against the scene.
+
+
+ CONTACT CROP images are diagnostic close-ups the harness cut from an overview tile around a
+ placement finding the gate MEASURED (the label names the asset, the kind and the number):
+ judge the contact they show — does the base meet what is under it, does the part pass
+ through its neighbour — and nothing else about them (not their composition, lighting or
+ dressing). Every claim of a floating, sunken, clipping or wrongly scaled asset must name
+ the VIEW (montage position + view name, or the crop) and the asset; a claim without a view
+ is not a claim. A dark seam under a base is contact, not daylight. The MEASURED PLACEMENT
+ line is the gate's own count over the placed assets it checked: where it reports an asset
+ floating, sunken or overlapping, confirm it in a view; where it passed, mark those defects
+ only on what a render visibly shows.
+
+
+ Use zone and asset names from the plan digest as targets.
+
+
+ CALIBRATION — fixed points on the overall scale (the harness computes the overall from
+ your criterion scores; these say where the criteria must land): a bare skeleton — ground
+ plane, a few primitives, the starter sky — scores at most 0.35 overall; a correct but plain
+ diorama (every planned zone present, boxes-and-cones assets, flat ground, no dressing, no
+ haze) sits around 0.55; a photographable place — layered detail, varied assets, dressed
+ ground, aerial perspective, no visible defect — scores 0.80 or more. A diorama and a
+ photographable place must land at least 0.3 apart: if you cannot tell which of two scenes a
+ person would screenshot, you have compressed the scale. Each criterion carries six anchors
+ (1.0 / 0.85 / 0.7 / 0.55 / 0.4 / 0.1); interpolate between them and use the whole range.
+
+
+ Craft on this track is mostly about five things, so look for each of them explicitly
+ before scoring: (1) the GROUND — is it several blended materials with paths, wear and
+ dressed edges, or one flat colour with a hard bbox line; (2) VEGETATION / repeated
+ natural elements — several silhouettes with size and hue variation in clusters, or one
+ shape stamped in a ring; (3) DEPTH — is there something in the near foreground framing
+ the shot, a subject in the midground and a horizon above, or is it a small diorama alone
+ on a big empty plane; (4) DRESSING — the small props (pebbles, leaves, tools, cups,
+ cables, litter) that make a place look used; (5) ATMOSPHERE — fog/haze giving aerial
+ perspective, coloured (sky-lit) shade, and a key light whose hue differs from the fill.
+ A scene can be entirely correct against the brief and still sit at 0.55 because it fails
+ all five; say so in the issues rather than inventing a fidelity complaint. And a scene
+ that passes all five can still lose on DETAIL: look at every asset at crop scale for a
+ floating base, a part through another part, a mismatched scale and hard-edged particles
+ before you score.
+
+criteria:
+ - id: brief_fidelity
+ weight: 0.18
+ floor: 0.30
+ title: Brief fidelity
+ description: >
+ Does the scene depict the place the brief describes, with every named element
+ (landmarks, zones, weather, time of day, activity) present and recognisable,
+ arranged as the brief implies?
+ anchors:
+ "1.0": Every named element is present, recognisable and where the brief puts it; setting, era, weather and time of day are unmistakable from the authored cameras alone.
+ "0.85": Every named element is present and recognisable; one is smaller or plainer than the brief implies, or the time of day / weather is right but understated.
+ "0.7": The place reads right; one named element is token or hard to find, or the arrangement differs from what the brief implies.
+ "0.55": The place reads right but two named elements are token, or one is missing, and the mood (weather, hour) is generic rather than the brief's.
+ "0.4": The place reads right but named elements are missing, or the time of day / weather contradicts the brief.
+ "0.1": Wrong kind of place, or an unreadable world.
+
+ - id: composition_and_camera
+ weight: 0.14
+ floor: 0.25
+ title: Composition and camera
+ description: >
+ Do the authored cameras make readable, well-framed pictures — a focal subject,
+ foreground/midground/background, horizon placed deliberately, nothing clipped by
+ the near plane, no camera inside geometry, no shot that shows only sky or ground?
+ anchors:
+ "1.0": Every authored camera is a composed shot — a foreground element within a few metres frames the edge, the subject fills the middle distance, a horizon band sits above, and the subject is what the camera is aimed at.
+ "0.85": Every shot is composed and aimed; one lacks a foreground frame or sits a little too high / too central.
+ "0.7": Shots are readable and aimed at the subject, but one layer is missing (no foreground, or a bare horizon) or one shot is flat / off-centre.
+ "0.55": The scene reads as a diorama photographed from outside — subject centred on a large empty plane, no foreground, nothing on the horizon.
+ "0.4": One authored camera shows nothing useful (sky, ground, the inside of a wall), or the establishing shot is aimed at the bounds centre rather than the subject, or a shot is badly clipped.
+ "0.1": Most shots are unusable or the camera is inside geometry.
+
+ - id: lighting_atmosphere
+ weight: 0.14
+ floor: 0.25
+ title: Lighting and atmosphere
+ description: >
+ Is the lighting readable and atmospheric — a consistent sun/moon direction,
+ present soft shadows, sky that matches the mood, aerial perspective / fog giving
+ depth, exposure neither blown nor crushed, coloured (sky-lit) shade rather than
+ black?
+ anchors:
+ "1.0": Clear mood executed consistently; warm key against a cooler fill (or the reverse); soft accurate shadows with smooth edges; fog/haze gives visible aerial perspective with distance; shade carries sky colour.
+ "0.85": The mood is clear and the key / fill / haze are all present; one of them is a notch off (shadows a little hard, haze a little thin, the sky a little flat).
+ "0.7": Good lighting with one weakness (slightly flat shadows, slightly heavy fog, or a horizon with no atmospheric falloff).
+ "0.55": Lit but airless — no haze or depth cue, key and fill share one hue so the frame is monochrome, or shadow edges are visibly stair-stepped.
+ "0.4": Flat shadowless light, or noticeably under/over-exposed, or sky contradicting the light, or black (unfilled) shadows.
+ "0.1": Near-black, blown white, or unlit.
+
+ - id: asset_quality_detail
+ weight: 0.14
+ title: Asset quality and detail
+ description: >
+ Are the individual assets refined beyond primitives and varied — buildings with
+ roofs/windows/setbacks, trees with trunk and canopy, vehicles and street
+ furniture where the place calls for them — without copy-paste monotony? Judge
+ them at crop scale, not only from the overviews.
+ anchors:
+ "1.0": Assets are crafted and varied — several silhouettes per family, per-instance size and hue variation, wear and small props everywhere; the crops hold up.
+ "0.85": Assets are crafted and varied; one family is plainer than the rest or repeats a silhouette, and the crops show a seam or two.
+ "0.7": Assets are decent with some repetition, a few plain ones, or thin set dressing.
+ "0.55": Hero assets are fine but everything around them is one repeated primitive and the place is undressed — no small props, no litter, no ground cover.
+ "0.4": Mostly plain boxes / cones, or one shape stamped everywhere, or a solid object faked as a flat coloured plane.
+ "0.1": Primitive blobs or an empty world.
+
+ - id: spatial_coherence_scale
+ weight: 0.12
+ floor: 0.25
+ title: Spatial coherence and scale
+ description: >
+ Is the layout believable as a place (streets connect, shoreline continuous,
+ buildings face roads, spacing realistic), everything sits ON the ground/terrain
+ (nothing floating, sunken or clipping through a neighbour), and relative sizes
+ agree on what a metre is? Read the MEASURED PLACEMENT line and the contact crops
+ before you score this.
+ anchors:
+ "1.0": Layout reads as a real place; every base meets its support in every crop and overview; nothing passes through anything; sizes agree.
+ "0.85": Layout reads as a real place; one base shows a hairline seam or one prop touches a neighbour, nothing you would notice without the crop.
+ "0.7": Minor oddities (a slightly floating prop, a slightly large car, two props sharing a corner) that do not break the read.
+ "0.55": One clearly floating or sunken asset, or one visible intersection, or one scale error, in a layout that otherwise reads as a place.
+ "0.4": Several floating/sunken assets, or a hero passing through a wall or the terrain, or a glaring scale error (a door taller than its house).
+ "0.1": Uniform scatter, many floating objects, or scale chaos.
+
+ - id: materials_shaders_effects
+ weight: 0.12
+ materials: true
+ title: Materials, shaders and effects
+ description: >
+ Do surfaces read as materials (water with specular life, glass, foliage,
+ concrete) and do the planned effects (custom shaders, particles, post-processing)
+ visibly exist and look intentional — not magenta, not noise, not a flat tint, not
+ hard-edged quads standing in for dust, steam or spray?
+ anchors:
+ "1.0": Materials convincing; every planned effect is visible, soft where it should be soft, and adds to the picture.
+ "0.85": Materials convincing and every planned effect present; one effect is a little crude (a slightly sharp sprite, a water surface a touch glassy).
+ "0.7": Materials sensible; effects present but subtle or slightly crude.
+ "0.55": Materials sensible but one surface the brief names is wrong (dull water, foliage one flat green), or one planned effect is missing while the rest are present.
+ "0.4": A planned effect is missing or broken (flat water, no particles, a black shader, hard-edged discs for smoke), or a placeholder material is visible.
+ "0.1": Placeholder surfaces throughout or broken shaders dominate.
+
+ - id: animation_life
+ weight: 0.08
+ title: Animation and life
+ description: >
+ Comparing frames at different times, does something move as the plan says
+ (water, foliage, vehicles, lights, characters) in a plausible way, and is the
+ scene alive rather than frozen? The MEASURED MOTION line decides whether a camera
+ changed; the pictures decide whether the motion is plausible.
+ anchors:
+ "1.0": Planned motion is visible and natural across the time samples.
+ "0.85": Planned motion is visible on every camera the plan says should move; one movement is stiff or small.
+ "0.7": Some planned motion visible; subtle or partial.
+ "0.55": Motion is measured on one camera only, or only one of several planned movements shows.
+ "0.4": Frames are identical although motion was planned, or motion is implausible (rigid glide, clipping).
+ "0.1": Nothing moves and/or motion breaks the scene.
+
+ - id: technical_cleanliness
+ weight: 0.08
+ floor: 0.30
+ title: Technical cleanliness
+ description: >
+ No z-fighting, no magenta/default materials, no missing faces, no visible world
+ edge cliff, no console or shader errors in the probe digest.
+ anchors:
+ "1.0": Clean renders, zero console/shader errors.
+ "0.85": Clean renders with one small artefact you had to look for (a far z-fight, one flickering seam), zero errors.
+ "0.7": A minor artefact or a single non-fatal warning.
+ "0.55": Two or three visible artefacts (a z-fight on a floor, a missing back face, a world edge seen from one camera), or a warning per round.
+ "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). The
+# placement items are also what the scene_placement gate MEASURES (caps below): a gate that
+# ran and found nothing of the kind vetoes the claim (judges/rubrics.measured_absent).
+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: >
+ One of the SCENE'S OWN authored cameras shows only sky / ground / the inside of a wall,
+ or is clipped by the near plane. (Never answer this for an overview_* harness view.)
+ penalty: 0.08
+ cap: 0.60
+ - id: unlit_or_blown
+ text: >
+ One of the SCENE'S OWN authored cameras is near-black, blown to white, or lit from a
+ direction that contradicts the sky. (Never answer this for an overview_* harness view:
+ a rig shot taken at street level under a rooftop, or from above a night scene, is dark
+ because of where the harness put it.)
+ penalty: 0.08
+ cap: 0.60
+ - id: floating_asset
+ text: >
+ An asset visibly hovers above the ground / terrain / its support — daylight under its
+ base — in a view you name (an overview_* tile or a CONTACT CROP). A dark seam under a
+ base is contact, not daylight; a hanging lantern, a bird or a boat on water is not this.
+ penalty: 0.10
+ cap: 0.60
+ - id: sunken_asset
+ text: >
+ An asset is visibly buried in the ground / terrain / a floor — its base or a good part
+ of its body below the surface it should stand on — in a view you name. A rock, a post
+ or a root the plan means to be partly buried is not this.
+ penalty: 0.08
+ cap: 0.65
+ - id: interpenetration
+ text: >
+ Parts of one asset pass through another asset, or through terrain / walls (a bench
+ through a wall, a trunk through a roof, a hull through a jetty, a figure in a table) —
+ cite the view. Two props merely touching are not this.
+ penalty: 0.08
+ cap: 0.70
+ - id: wrong_scale
+ text: >
+ An asset is obviously too large or too small for its neighbours or for the size the plan
+ gives it (a door taller than its house, a car the size of a bench, a person two storeys
+ high, a lantern as big as a hut) — cite the view.
+ penalty: 0.06
+ cap: 0.75
+ - id: hard_edged_particles
+ text: >
+ Dust, steam, smoke, sparks, rain, snow, fireflies or spray are drawn as sharp-edged
+ quads, flat discs, hexagons or squares instead of soft sprites / blurred points — cite
+ the view.
+ penalty: 0.04
+ - id: missing_planned_element
+ text: >
+ A zone, asset, effect or animation the plan digest names is absent from EVERY view —
+ not merely small, hidden behind something or hard to find.
+ penalty: 0.06
+ - id: hero_misplaced
+ text: >
+ A hero asset (a GLB / the plan's featured object) is not on its planned support or
+ place — on the wrong side of the scene, on the water instead of the jetty, in the
+ middle of a path, or clipped into a wall.
+ penalty: 0.06
+ - 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: >
+ The harness's MEASURED MOTION line says no authored camera changed between the animation
+ times although motion was planned. Answer this from that measurement only — never from
+ comparing tiles by eye, and never because you cannot see what moved.
+ 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
+ - id: flat_ground
+ text: The ground is one flat untextured colour — no material blending, no paths or worn areas, and where objects meet it the seam is a hard undressed line.
+ penalty: 0.04
+ - id: monotonous_vegetation
+ text: A repeated natural element (trees, rocks, plants, crowd) is one shape stamped many times — no variation in silhouette, size or hue, and placed in a ring or a grid rather than clusters.
+ penalty: 0.04
+ - id: empty_midground
+ text: An authored camera has no depth layering — nothing in the near foreground and/or nothing on the horizon, so the subject sits alone on a large empty plane.
+ penalty: 0.04
+ - id: undressed_scene
+ text: The place has no small props or clutter (pebbles, leaves, tools, cups, cables, litter, ground cover) — it looks like a showroom of a few large objects.
+ penalty: 0.03
+ - id: thin_atmosphere
+ text: No visible aerial perspective — distant things are as saturated and contrasty as near things, there is no haze/fog falloff, and the key and fill light share one hue.
+ penalty: 0.03
+
+# The scene_placement gate (spatial/scene_placement.py) measures every placed asset's foot
+# columns against what is under it and every pair's box overlap; its findings carry a typed
+# data.kind, and each rule below watches ONE kind so a veto is scoped to what was measured
+# (an unrelated ERROR in the same report — no_fog, missing_content — no longer cancels it;
+# scoring version 4). veto_warn_keys: a WARN of the rule's kind whose measured magnitude
+# reaches the line keeps the judge's claim alive (the picture decides); under it the gate's
+# "seated / weld / within tolerance" verdict stands. Each line is a Settings.placement default
+# of 2026-10-14 (config.Placement; tests/judges/test_scene_judge.py pins them), stated here as
+# data because a rubric is data: gap_m 0.02 = floating_indoor_m, the tolerance the gate measures
+# an interior against (and = contact_m, so every floating / unsupported WARN it raises, indoors
+# or out, carries a larger gap and is never vetoed — the OUTDOOR 0.05 stood here until 2026-10-15
+# and vetoed a 2-5 cm indoor hover the gate itself had flagged); sunk_m 0.10 = sunk_m, where a
+# sunken WARN starts; overlap 0.20 is deliberately above overlap_warn 0.10, where a box
+# intersection becomes visible; `factor: 0.0` means any scale WARN (the factor can be < 1 for
+# too small).
+caps:
+ - id: floating_asset
+ when: gate
+ gate: "scene_placement"
+ severity: error
+ kinds: [floating, unsupported]
+ measures: [floating_asset]
+ cap: 0.60
+ veto_warn_keys: {gap_m: 0.02} # = Placement.floating_indoor_m (= contact_m): a WARN of the kind always reaches it
+ note: a gap over 0.08 m, or more than two floaters, is an ERROR (Settings.placement, D105)
+ - id: sunken_asset
+ when: gate
+ gate: "scene_placement"
+ severity: error
+ kinds: [sunken]
+ measures: [sunken_asset]
+ cap: 0.65
+ veto_warn_keys: {sunk_m: 0.10} # = Placement.sunk_m, where a sunken WARN starts: a WARN of the kind always reaches it
+ - id: interpenetration
+ when: gate
+ gate: "scene_placement"
+ severity: error
+ kinds: [interpenetration]
+ measures: [interpenetration]
+ cap: 0.70
+ veto_warn_keys: {overlap: 0.20} # above Placement.overlap_warn 0.10 by design: where a box intersection shows
+ - id: wrong_scale
+ when: gate
+ gate: "scene_placement"
+ severity: error
+ kinds: [scale]
+ measures: [wrong_scale]
+ cap: 0.75
+ veto_warn_keys: {factor: 0.0}
+ - id: free_exempt
+ when: gate
+ gate: "scene_placement"
+ severity: error
+ kinds: [free_exempt]
+ cap: 0.75
+ note: more than half the placed assets tagged placement='free' — the author hid them from the gate
+ - id: build_error
+ when: gate
+ gate: "build*"
+ severity: error
+ cap: 0.0
+ - id: shader_error
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [shader, glsl, webgl, compile]
+ cap: 0.5
+ - id: console_error
+ when: console
+ cap: 0.6
+ note: runtime JS errors seen while rendering
+ - id: camera_in_geometry
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [camera_in_geometry, camera_underground, camera_blocked]
+ cap: 0.5
+ note: the kinds the scene_frames gate really emits (frame_metrics.py); the v1 list named five that nothing emitted
+ # scene_frames gate (codeverse3d.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: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
+ graded: true
+ note: >
+ 0.6 + 0.4 * verified/total over the must items, as on the object tracks since
+ 2026-08-30; the verdict still FAILS on any unverified must item.
diff --git a/harness/codeverse3d/judges/vlm_judge.py b/harness/codeverse3d/judges/vlm_judge.py
index 696ef6b1..3a0cbe6b 100644
--- a/harness/codeverse3d/judges/vlm_judge.py
+++ b/harness/codeverse3d/judges/vlm_judge.py
@@ -77,6 +77,17 @@ SLICE_LABELS = {
"left_right": "cross-section left-right · interior view",
}
+#: the judge's thinking levels (``ChatRequest.thinking``); the run default is ``Settings.judge.thinking``
+THINKING_LEVELS: tuple[str, ...] = ("off", "low", "medium", "high")
+
+#: Per-track montage ceilings under the ``Settings.judge.montages`` dial. D47's 3 → 5 was
+#: measured on the OBJECT rig only (docs/DECISIONS.md D47); graphics keeps the pre-D47 3 until a
+#: battery measures it. The scene rig moved 3 → 4 with scene_v2 (2026-10-14): the fourth
+#: overview (``overview_low_front``, the contact camera) plus the t=1.5 tiles need a third
+#: grid on a three-camera plan and a fourth on a four-camera one — a cap of 3 silently
+#: dropped the low tile the contact crops are cut from. An explicit ``max_montages`` wins.
+TRACK_MONTAGE_CAP: dict[str, int] = {"scene": 4, "graphics": 3}
+
@dataclass
class JudgeContext:
@@ -102,7 +113,7 @@ class VlmJudge:
n_samples: int = 1,
temperature: float = 0.2,
*,
- thinking: Literal["off", "low", "medium", "high"] = "low",
+ thinking: Literal["off", "low", "medium", "high"] | None = None,
max_attempts: int = 3,
max_montages: int | None = None,
detail_crops: int | None = None,
@@ -128,11 +139,17 @@ class VlmJudge:
"acceptance item follows the representative sample (rubrics.aggregate_samples); an odd n "
"gives a true majority", self.n_samples)
self.temperature = temperature
- self.thinking = thinking
+ # payload size and thinking: the profile's dial (Settings.judge) unless the caller states one
+ jd = get_settings().judge
+ # ``thinking=None`` reads ``Settings.judge.thinking`` (C3D_JUDGE__THINKING) — the one place a run,
+ # a replay (`3dcode judge --thinking`) and the calibration tool take the level from (D105:
+ # gemini-4-argon thinks only from 'medium')
+ level = str(jd.thinking if thinking is None else thinking)
+ if level not in THINKING_LEVELS:
+ raise ValueError(f"judge thinking must be one of {' | '.join(THINKING_LEVELS)}, not {level!r}")
+ self.thinking: str = level
self.max_attempts = max(1, int(max_attempts))
self.sample_budget_s = SAMPLE_BUDGET_S if sample_budget_s is None else float(sample_budget_s)
- # payload size: the profile's dial (Settings.judge) unless the caller states one
- jd = get_settings().judge
self.max_montages = max(1, int(jd.montages if max_montages is None else max_montages))
self._montages_explicit = max_montages is not None
self.detail_crops = max(0, int(jd.detail_crops if detail_crops is None else detail_crops))
@@ -142,13 +159,12 @@ class VlmJudge:
self.label = label
def _montages_for(self, inp: JudgeInput) -> int:
- """Per-track montage cap: the 3→5 default was measured ONLY on the D47 object
- rig (docs/DECISIONS.md D47); scene and graphics keep the pre-D47 ceiling of 3
- until a battery measures them at 5 (review of PR #3). An explicit
- ``max_montages`` from the caller always wins."""
- if self._montages_explicit or inp.spec.track.value in SLICE_TRACKS:
+ """Per-track montage cap (``TRACK_MONTAGE_CAP``: scene 4, graphics 3; the object rig takes
+ the dial, D47). An explicit ``max_montages`` from the caller always wins."""
+ cap = TRACK_MONTAGE_CAP.get(inp.spec.track.value)
+ if self._montages_explicit or cap is None:
return self.max_montages
- return min(self.max_montages, 3)
+ return min(self.max_montages, cap)
# ------------------------------------------------------------------ provenance
@property
@@ -188,9 +204,11 @@ class VlmJudge:
)
reqs.append(ChatRequest(
messages=messages, system=system, response_schema=schema, temperature=self.temperature,
- thinking=self.thinking,
- # the label is the ledger's attribution when the sample runs in a worker
- # thread (fan_out does not carry context vars): keep stage + round in it
+ thinking=self.thinking, # type: ignore[arg-type] # validated against THINKING_LEVELS in __init__
+ # proc.fan_out copies the caller's contextvars into every sample thread, so the ledger's
+ # ambient attribution reaches a worker; it is bound per STAGE (the track's call_context
+ # around a round), so the label stays explicit with what only this call knows — the judge
+ # job (self-describing: cost/context.SELF_DESCRIBING), its rubric, round and sample
label=f"{self.label}:{self.rubric.name}:r{inp.round_index:02d}:s{k}",
))
if len(reqs) == 1: # serial path: no pool, no thread hop
diff --git a/harness/codeverse3d/languages/_js_lint.py b/harness/codeverse3d/languages/_js_lint.py
index 0b5b9ad7..12d2d839 100644
--- a/harness/codeverse3d/languages/_js_lint.py
+++ b/harness/codeverse3d/languages/_js_lint.py
@@ -14,6 +14,13 @@ symlink/``..`` hop out of ``src/`` is reported as an escape, never as "missing".
Syntax is ``runtime_js/lib/syntax_check.mjs`` (export_glb's checker too) in ONE node
process per lint, skipping files whose bytes already parsed — it was one ``node --check``
per file: 51 on a scene, 44 of them unchanged ``src/lib`` modules, ≈ 2.5 s a build call.
+
+:func:`check_named_imports` is the second half of the import policy: ``check_imports`` only
+asks whether the TARGET exists, so ``import { concrete } from '../lib/materials.js'`` passed
+the lint and died at module link ("does not provide an export named 'concrete'") — the
+argon loop's iteration 0 lost two whole zones to it at assembly (run
+``it00_scene_threejs_r1_18``, scored 0.47). Exports are read from the target's source
+text (:func:`module_exports`), once per file per lint through the caller's cache.
"""
from __future__ import annotations
@@ -169,3 +176,122 @@ def check_imports(
else:
findings.append(make_finding(verdict, spec, line))
return findings, targets
+
+
+# ===================================================================== named imports
+_IDENT = r"[A-Za-z_$][\w$]*"
+_IDENT_RE = re.compile(rf"^{_IDENT}$")
+# ``import { a, b as c } from '…'``, ``import x, { a } from '…'``, braces over several lines;
+# ``import * as m`` and a bare default import have no brace and never match. Group 1 is the
+# ``import`` keyword (the finding's line), 2 the brace body, 3 the specifier.
+_NAMED_IMPORT_RE = re.compile(
+ rf"""(?:^|\n)\s*(import)(?:\s+{_IDENT}\s*,)?\s*\{{([^}}]*)\}}\s*from\s*['"]([^'"]+)['"]"""
+)
+# ``export [async] function[*] NAME`` / ``export class|const|let|var NAME``
+_EXPORT_DECL_RE = re.compile(
+ rf"\bexport\s+(?:async\s+)?(?:function\s*\*?\s*|(?:class|const|let|var)\s+)({_IDENT})"
+)
+# ``export { a, b as c }`` and ``export { a as b } from '…'``: the exported name is the LAST token
+_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
+# ``export * as ns from '…'`` exports exactly ``ns``; a bare ``export * from '…'`` exports another
+# module's surface (group 1 empty)
+_EXPORT_STAR_RE = re.compile(rf"\bexport\s*\*\s*(?:as\s+({_IDENT})\s+)?from\b")
+_EXPORT_DEFAULT_RE = re.compile(r"\bexport\s+default\b")
+# ``export const { a, b } = …`` / ``export const [x] = …``: names inside a pattern
+_EXPORT_PATTERN_RE = re.compile(r"\bexport\s+(?:const|let|var)\s*[\[{]")
+
+#: ``{resolved target: its exports}`` — one lint reads each ``src/lib`` module once, not once
+#: per importer (a scene has ~50 files importing the same dozen modules)
+ExportsCache = dict[Path, frozenset[str] | None]
+
+
+@dataclass(frozen=True)
+class NamedImport:
+ """One static ``import { a, b as c } from '<spec>'``: ``names`` are the IMPORTED names
+ (``a`` and ``b`` — what the target module must export, not the local aliases)."""
+
+ spec: str
+ names: tuple[str, ...]
+ line: int
+
+
+def named_import_specs(src: str) -> list[NamedImport]:
+ """Every static named import of ``src`` (comments blanked first, so a commented-out
+ import is not parsed); ``import * as m`` and default-only imports yield nothing."""
+ code = strip_js(src, strings=False) # the specifier is a string literal: keep strings
+ out: list[NamedImport] = []
+ for m in _NAMED_IMPORT_RE.finditer(code):
+ names = tuple(n for n in (item.split()[0] for item in m.group(2).split(",") if item.strip())
+ if _IDENT_RE.match(n))
+ if names:
+ out.append(NamedImport(m.group(3), names, line_of(code, m.start(1))))
+ return out
+
+
+def module_exports(src: str) -> frozenset[str] | None:
+ """The names an ES module's source text exports, or ``None`` when its surface cannot be
+ enumerated from the text alone: a bare ``export * from '…'`` (another module's surface —
+ not resolved transitively, so nothing is reported against such a module) or a
+ destructuring ``export const { a } = …`` pattern. ``export default`` exports ``default``."""
+ code = strip_js(src)
+ if _EXPORT_PATTERN_RE.search(code):
+ return None
+ names = {m.group(1) for m in _EXPORT_DECL_RE.finditer(code)}
+ for m in _EXPORT_LIST_RE.finditer(code):
+ names |= {last for last in (item.split()[-1] for item in m.group(1).split(",") if item.strip())
+ if _IDENT_RE.match(last)}
+ for m in _EXPORT_STAR_RE.finditer(code):
+ if not m.group(1):
+ return None
+ names.add(m.group(1))
+ if _EXPORT_DEFAULT_RE.search(code):
+ names.add("default")
+ return frozenset(names)
+
+
+def exported_names(path: Path) -> frozenset[str] | None:
+ """:func:`module_exports` of the file at ``path`` (``None`` when it cannot be read)."""
+ try:
+ return module_exports(path.read_text(errors="replace"))
+ except OSError:
+ return None
+
+
+def describe_exports(names: frozenset[str], *, limit: int = 12) -> str:
+ """``it exports: a, b, …`` (sorted, at most ``limit`` named) or ``it exports nothing``."""
+ if not names:
+ return "it exports nothing"
+ shown = sorted(names)[:limit]
+ return "it exports: " + ", ".join(shown) + (", …" if len(names) > limit else "")
+
+
+def check_named_imports(
+ src: str,
+ path: Path,
+ src_root: Path,
+ *,
+ make_finding: Callable[[str, str, int, frozenset[str]], GateFinding],
+ exports: ExportsCache | None = None,
+) -> list[GateFinding]:
+ """A finding per imported name that its target module does not export, for every named
+ import of ``src`` whose specifier resolves to an existing ``.js`` / ``.mjs`` file under
+ ``src_root`` (``'three'`` and the non-allowed kinds are :func:`check_imports`'s business).
+
+ ``make_finding(spec, name, line, exports)`` builds the finding — the caller owns message,
+ severity and hint; ``exports`` is the target's surface, for an "it exports: …" listing.
+ Pass one ``exports`` cache for the whole lint so each target is read once.
+ """
+ cache: ExportsCache = {} if exports is None else exports
+ findings: list[GateFinding] = []
+ for imp in named_import_specs(src):
+ verdict = classify_import(imp.spec, path, src_root)
+ target = verdict.target
+ if verdict.kind is not ImportKind.ALLOWED or target is None or target.suffix not in (".js", ".mjs"):
+ continue
+ if target not in cache:
+ cache[target] = exported_names(target)
+ surface = cache[target]
+ if surface is None:
+ continue
+ findings.extend(make_finding(imp.spec, name, imp.line, surface) for name in imp.names if name not in surface)
+ return findings
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.py
index 902781de..309f9bfa 100644
--- a/harness/codeverse3d/languages/base.py
+++ b/harness/codeverse3d/languages/base.py
@@ -61,6 +61,11 @@ class SceneRuntime(LanguageRuntime, Protocol):
entry is assembled from the zones, how the built scene is probed and rendered. The scene
stages, ``Services`` and the scene tools reach a scene language only through this."""
+ #: the environment module the env stage writes (``src/env.js`` / ``src/env.py``): the one
+ #: file a scene session owns besides the zones and assets, named by the runtime so no track
+ #: code tests a path for ``.js`` / ``.py``
+ env_file: str
+
def zone_file(self, name: str) -> str:
"""The module that builds zone ``name`` (``src/zones/<snake>.<ext>``)."""
...
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index 3aba16c7..ebd3b98d 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -64,7 +64,8 @@ WARN_CALL_PREFIXES: tuple[tuple[str, str, LintKind], ...] = (
("sys.exit", "do not exit; let the script fall off the end", LintKind.SANDBOX),
)
# 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).
+# Verified against Blender 5.2.2 LTS (2026-10-14): 'Anisotropic' and 'Specular Tint' STILL EXIST (do not
+# list them); 5.2.2 also has 'Thin Wall', 'Thin Film Thickness' and 'Thin Film IOR'.
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)",
@@ -89,6 +90,7 @@ class BpyCollector(ast.NodeVisitor):
self._guarded: list[frozenset[str]] = [] # keys the enclosing if/elif tests are membership checks of
self.names_assigned: list[str] = [] # string constants assigned to .name / name=
self.constants: list[tuple[str, int]] = []
+ self.gn_item_stores: list[tuple[str, int]] = [] # (key, line) of <x>["Socket_N"] = … (pre-5.2 GN inputs)
self.has_temp_override = False
self.keywords: list[tuple[str, int]] = []
@@ -192,6 +194,9 @@ class BpyCollector(ast.NodeVisitor):
if node.value.attr == "inputs" and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str):
key = node.slice.value
self.bsdf_inputs.append((key, node.lineno, any(key in g for g in self._guarded)))
+ if (isinstance(node.ctx, ast.Store) and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str)
+ and node.slice.value.startswith(("Socket_", "Input_"))):
+ self.gn_item_stores.append((node.slice.value, node.lineno))
self.generic_visit(node)
def visit_Constant(self, node: ast.Constant) -> None:
@@ -252,10 +257,29 @@ def store_traps(target: str, line: int) -> list[GateFinding]:
def use_nodes_trap(target: str, line: int) -> list[GateFinding]:
if target.endswith(".use_nodes"):
- return [_f(LintKind.API_TRAP, Severity.INFO, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, "")]
+ return [_f(LintKind.API_TRAP, Severity.INFO, "`use_nodes = True` is deprecated in Blender 5.x (removed in 6.0): materials, worlds and lights "
+ "always have a node tree; harmless", line, "delete the line")]
return []
+def gn_input_traps(c: BpyCollector) -> list[GateFinding]:
+ """Geometry-nodes modifier inputs set the pre-5.2 way: ``mod["Socket_2"] = v`` raises TypeError
+ ("id properties not supported for this type") since Blender 5.2 (verified on 5.2.2)."""
+ return [_f(LintKind.API_TRAP, Severity.ERROR, f"`[...][{key!r}] = ...`: geometry-nodes modifier inputs are RNA properties in Blender 5.2 "
+ "(TypeError at runtime)", line,
+ f"getattr(mod.properties.inputs, {key!r}).value = <value> (identifiers: mod.properties.inputs.keys(); "
+ "an attribute-driven input: `.type = 'ATTRIBUTE'` + `.attribute_name = ...`)")
+ for key, line in c.gn_item_stores]
+
+
+def solver_traps(c: BpyCollector, source: str) -> list[GateFinding]:
+ """``solver = 'FAST'``: the boolean solver was renamed — Blender 5.2.2 has FLOAT / EXACT / MANIFOLD."""
+ lines = source.splitlines()
+ return [_f(LintKind.API_TRAP, Severity.ERROR, "boolean solver 'FAST' does not exist in Blender 5.x (TypeError at runtime)", line,
+ "solver = 'MANIFOLD' (closed meshes) or 'EXACT'; 'FLOAT' is the old FAST")
+ for const, line in c.constants if const == "FAST" and 0 < line <= len(lines) and ".solver" in lines[line - 1]]
+
+
def source_traps(c: BpyCollector, source: str) -> list[GateFinding]:
"""Whole-file traps: removed Principled inputs, bmesh lookup tables, undefined names, the
background-mode selection, invalid engine ids."""
@@ -286,7 +310,9 @@ def source_traps(c: BpyCollector, source: str) -> list[GateFinding]:
"keep references to the objects you create (`obj = bpy.context.object` right after primitive_*_add) instead of re-reading the selection"))
for const, line in c.constants:
if const == "BLENDER_EEVEE_NEXT":
- out.append(_f(LintKind.HARNESS_OWNED, 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"))
+ out.append(_f(LintKind.HARNESS_OWNED, W, "'BLENDER_EEVEE_NEXT' is not a valid engine id in Blender 5.x", line, "render settings are owned by the harness; delete the line"))
+ out.extend(gn_input_traps(c))
+ out.extend(solver_traps(c, source))
return out
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
index 2668a7b6..1cafadad 100644
--- a/harness/codeverse3d/languages/scene_blender/__init__.py
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -83,7 +83,7 @@ def frame_of(t: float) -> int:
# ===================================================================== layout
#: what a whole-scene session edits: the entry and the environment (zones and assets have their own)
-SCENE_FILES: tuple[str, ...] = (ENTRY_REL, "src/env.py")
+SCENE_FILES: tuple[str, ...] = (ENTRY_REL, "src/env.py") # == (ENTRY_REL, ENV_FILE); ENV_FILE is defined with the starter tree
#: refine targets that are the environment's, whatever the plan calls its zones
ENV_WORDS = frozenset({"env", "environment", "lighting", "sky", "fog", "ground", "water", "light", "world", "sun"})
@@ -407,6 +407,51 @@ def lint(ws: Workspace) -> GateReport:
return GateReport.of(GATE, findings, duration_ms=int((time.monotonic() - t0) * 1000))
+# ===================================================================== starter tree
+STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
+#: the harness-owned bpy library (``src/lib/*.py``, D51 for this language): shipped into EVERY
+#: workspace by both skeleton paths; the model's index of it is prompts/scene_blender/effects_catalog.md
+#: (tests/scene_runtime/test_skeleton.py pins the two to each other)
+LIB_DIR = STARTER_DIR / "lib"
+ENV_FILE = "src/env.py"
+
+
+def lib_files() -> list[Path]:
+ """The library modules shipped into a workspace, sorted (the package's ``__init__.py`` ships
+ too but names no calls, so the catalog does not list it)."""
+ return sorted(p for p in LIB_DIR.glob("*.py") if p.name != "__init__.py")
+
+
+def _put(path: Path, text: str, written: list[Path]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ written.append(path)
+
+
+def _write_lib(ws: Workspace, written: list[Path]) -> None:
+ for src in sorted(LIB_DIR.glob("*.py")):
+ _put(ws.src / "lib" / src.name, src.read_text(), written)
+
+
+def write_example(ws: Workspace) -> list[Path]:
+ """The complete plan-less starter scene (``starter/src/**/*.py``: entry, env, zones, assets
+ and the library) into ``ws.src`` — scene_threejs's ``write_example`` twin. Raises when the
+ starter tree is missing: an rglob over an absent directory writes nothing and reports
+ success, which is how a wheel without package data once shipped empty scenes
+ (tests/core/test_portability.py)."""
+ if not STARTER_DIR.is_dir():
+ raise FileNotFoundError(
+ f"scene_blender starter tree missing: {STARTER_DIR} — this install has no package data "
+ f"(a non-editable install needs [tool.setuptools.package-data] to ship languages/**/starter/**/*)")
+ written: list[Path] = []
+ for src in sorted(STARTER_DIR.rglob("*.py")):
+ _put(ws.src / src.relative_to(STARTER_DIR), src.read_text(), written)
+ if not written:
+ raise FileNotFoundError(f"scene_blender starter tree at {STARTER_DIR} contains no .py files")
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ return written
+
+
# ===================================================================== skeleton
def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, float]:
"""A plan (GLB-frame) vector in this language's frame (D12: prompts and skeleton convert)."""
@@ -414,11 +459,17 @@ def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, floa
def _env_source(plan: ScenePlan) -> str:
+ """``src/env.py`` built FROM the library: the ground function, the sky, the sun, the ground
+ mesh, the fog box and — for an interior — the room shell and its ceiling light."""
c, e = _v(plan.bounds.center), _v(plan.bounds.extents, extents=True)
span = max(e[0], e[1], 40.0)
ground = round(max(120.0, span * 2.5), 1)
+ # level ground wherever the plan put its cameras (z ≈ 0 inside the bounds), gentle hills beyond
+ flat = round(max(45.0, span / 2 + 15.0), 1)
fog_h = round(max(e[2] * 2.0, 20.0), 1)
interior = "True" if plan.interior else "False"
+ glazed = bool(getattr(plan, "glazed", False))
+ room_energy = round(40.0 * e[0] * e[1], 1)
return f'''"""src/env.py — the environment: world (sky), sun, ground, atmosphere{", enclosure" if plan.interior else ""}.
ENV PLAN: {plan.environment.strip()}
@@ -427,130 +478,42 @@ Frame: Z up, -Y front, metres. BOUNDS below are the plan's, in this frame.
CONTRACT: height_at(x, y) -> z is THE ground: the terrain mesh and every zone's seat use it.
build_env(ctx) -> dict builds the world, lamps, ground and atmosphere into ctx.collection and returns
what zones may share (materials, water level, sun direction ...) — they read it as ctx.env.
- Rewrite the sky / sun / ground / fog below to match the plan; keep build_env and height_at.
+ Everything below is built from src/lib (lib.terrain / lib.sky / lib.lighting / lib.materials /
+ lib.architecture — see the effects catalog): rewrite the sky / sun / ground / fog to match the
+ plan; keep build_env and height_at.
"""
-import math
-
-import bmesh
-import bpy
-from mathutils import Vector
+from lib import architecture, lighting, materials, sky, terrain
BOUNDS = {{"center": ({fmt3(c)}), "extents": ({fmt3(e)})}}
INTERIOR = {interior}
+GLAZED = {glazed} # a glass house: the shell's walls and lid are panes on an iron frame
GROUND_SIZE = {ground}
-SUN_AZIMUTH_DEG = 45.0 # compass angle of the sun: 0 = +X, 90 = +Y
+FLAT_RADIUS = {flat} # level ground for the plan's cameras (z = 0); the hills start beyond it
+SUN_AZIMUTH_DEG = 45.0 # compass angle of the sun: 0 = +X, 90 = +Y (the sky and the lamp share it)
SUN_ELEVATION_DEG = 35.0
+SEED = 0
+_RELIEF = terrain.make_height_at(seed=SEED, relief=0.0 if INTERIOR else 2.5, scale=60.0, flat_radius=FLAT_RADIUS)
def height_at(x, y):
- """z of the ground at (x, y) — flat until you shape it (then the ground mesh follows)."""
- return 0.0
-
-
-def _material(name, rgb, roughness=0.8, metallic=0.0):
- mat = bpy.data.materials.new(name)
- bsdf = mat.node_tree.nodes["Principled BSDF"]
- bsdf.inputs["Base Color"].default_value = (rgb[0], rgb[1], rgb[2], 1.0)
- bsdf.inputs["Roughness"].default_value = roughness
- bsdf.inputs["Metallic"].default_value = metallic
- return mat
-
-
-def _ground(ctx, material):
- me = bpy.data.meshes.new("Ground")
- bm = bmesh.new()
- bmesh.ops.create_grid(bm, x_segments=96, y_segments=96, size=GROUND_SIZE / 2)
- for v in bm.verts:
- v.co.z = height_at(v.co.x, v.co.y)
- bm.to_mesh(me)
- bm.free()
- me.materials.append(material)
- ob = bpy.data.objects.new("Ground", me)
- ctx.collection.objects.link(ob)
- return ob
-
-
-def _sky(ctx):
- world = bpy.data.worlds.new("Sky")
- ctx.scene.world = world
- nodes, links = world.node_tree.nodes, world.node_tree.links
- sky = nodes.new("ShaderNodeTexSky")
- sky.sky_type = "MULTIPLE_SCATTERING"
- sky.sun_elevation = math.radians(SUN_ELEVATION_DEG)
- sky.sun_rotation = math.radians(SUN_AZIMUTH_DEG)
- links.new(sky.outputs["Color"], nodes["Background"].inputs["Color"])
- nodes["Background"].inputs["Strength"].default_value = 0.4
-
-
-def _sun(ctx):
- az, el = math.radians(SUN_AZIMUTH_DEG), math.radians(SUN_ELEVATION_DEG)
- towards_sun = Vector((math.cos(el) * math.cos(az), math.cos(el) * math.sin(az), math.sin(el)))
- lamp = bpy.data.lights.new("Sun", "SUN")
- lamp.energy = 3.0
- ob = bpy.data.objects.new("Sun", lamp)
- ob.rotation_euler = (-towards_sun).to_track_quat("-Z", "Y").to_euler()
- ctx.collection.objects.link(ob)
- return towards_sun
-
-
-def _atmosphere(ctx):
- """A bounded fog volume over the scene (a world volume over a large scene swallows the sun)."""
- cx, cy, _ = BOUNDS["center"]
- me = bpy.data.meshes.new("Atmosphere")
- bm = bmesh.new()
- bmesh.ops.create_cube(bm, size=1.0)
- bmesh.ops.scale(bm, vec=(GROUND_SIZE, GROUND_SIZE, {fog_h}), verts=bm.verts)
- bmesh.ops.translate(bm, vec=(cx, cy, {fog_h / 2}), verts=bm.verts)
- bm.to_mesh(me)
- bm.free()
- mat = bpy.data.materials.new("AtmosphereFog")
- nodes, links = mat.node_tree.nodes, mat.node_tree.links
- nodes.remove(nodes["Principled BSDF"])
- fog = nodes.new("ShaderNodeVolumePrincipled")
- fog.inputs["Density"].default_value = {0.001 if plan.interior else 0.002}
- links.new(fog.outputs["Volume"], nodes["Material Output"].inputs["Volume"])
- me.materials.append(mat)
- ctx.collection.objects.link(bpy.data.objects.new("Atmosphere", me))
-
-
-def _enclosure(ctx, material):
- """Floor, walls and ceiling on the bounds' faces (an interior's shell; cut the openings)."""
- (cx, cy, cz), (ex, ey, ez) = BOUNDS["center"], BOUNDS["extents"]
- t = 0.2
- slabs = {{
- "Floor": ((cx, cy, cz - ez / 2 - t / 2), (ex, ey, t)),
- "Ceiling": ((cx, cy, cz + ez / 2 + t / 2), (ex, ey, t)),
- "WallBack": ((cx, cy + ey / 2 + t / 2, cz), (ex, t, ez)),
- "WallLeft": ((cx - ex / 2 - t / 2, cy, cz), (t, ey, ez)),
- "WallRight": ((cx + ex / 2 + t / 2, cy, cz), (t, ey, ez)),
- }}
- for name, (centre, size) in slabs.items():
- me = bpy.data.meshes.new(name)
- bm = bmesh.new()
- bmesh.ops.create_cube(bm, size=1.0)
- bmesh.ops.scale(bm, vec=size, verts=bm.verts)
- bmesh.ops.translate(bm, vec=centre, verts=bm.verts)
- bm.to_mesh(me)
- bm.free()
- me.materials.append(material)
- ctx.collection.objects.link(bpy.data.objects.new(name, me))
- lamp = bpy.data.lights.new("CeilingLight", "AREA")
- lamp.energy = 40.0 * ex * ey
- lamp.size = max(0.5, min(ex, ey) * 0.5)
- ob = bpy.data.objects.new("CeilingLight", lamp)
- ob.location = (cx, cy, cz + ez / 2 - 0.05)
- ctx.collection.objects.link(ob)
+ """z of the ground at (x, y) — level inside FLAT_RADIUS, rolling beyond (the ground mesh follows)."""
+ return _RELIEF(x, y)
def build_env(ctx):
- _sky(ctx)
- sun = _sun(ctx)
- ground_mat = _material("GroundMat", (0.28, 0.33, 0.22))
- _ground(ctx, ground_mat)
+ sky.sun_world(ctx.scene, elevation_deg=SUN_ELEVATION_DEG, azimuth_deg=SUN_AZIMUTH_DEG, strength=0.4, dust=1.5)
+ _, towards_sun = lighting.sun(ctx.collection, azimuth_deg=SUN_AZIMUTH_DEG, elevation_deg=SUN_ELEVATION_DEG, energy=3.0)
+ ground_mat = materials.material("GroundMat", "4A5A3A", roughness=0.9, noise_scale=6.0)
+ terrain.ground("Ground", ctx.collection, size=GROUND_SIZE, segments=96, height_at=height_at, material=ground_mat)
+ (cx, cy, cz), (ex, ey, ez) = BOUNDS["center"], BOUNDS["extents"]
if INTERIOR:
- _enclosure(ctx, _material("WallMat", (0.72, 0.68, 0.6)))
- _atmosphere(ctx)
- return {{"ground_material": ground_mat, "sun_direction": tuple(sun)}}
+ # the shell sits 1 cm above the ground so its floor never z-fights the terrain
+ architecture.room_shell(ctx.collection, materials.material("WallMat", "B8AE9A", roughness=0.85),
+ center=(cx, cy, cz + 0.01), extents=(ex, ey, ez), glazed=GLAZED)
+ lighting.area_light(ctx.collection, "CeilingLight", (cx, cy, cz + ez / 2 - 0.05), "FFF1DC", {room_energy},
+ size=max(0.5, min(ex, ey) * 0.5), target=(cx, cy, cz - ez / 2))
+ sky.haze(ctx.collection, (cx, cy, {fog_h / 2}), (GROUND_SIZE, GROUND_SIZE, {fog_h}), density={0.001 if plan.interior else 0.002})
+ return {{"ground_material": ground_mat, "sun_direction": tuple(towards_sun)}}
'''
@@ -565,26 +528,17 @@ CONTRACT: build_{snake}(ctx, variant=0) -> bpy.types.Collection — link every p
(named '{pascal}'), built ONCE at the origin with its base on z = 0, front facing -Y. Zones place
collection instances of it (ctx.assets['{snake}']); never link it anywhere else.
"""
-import bmesh
-import bpy
+from lib.materials import material
+from lib.mesh import Batch
def build_{snake}(ctx, variant=0):
- mat = bpy.data.materials.new("{pascal}Mat")
- bsdf = mat.node_tree.nodes["Principled BSDF"]
- bsdf.inputs["Base Color"].default_value = ({fmt3(rgb)}, 1.0)
- bsdf.inputs["Roughness"].default_value = {rough}
- bsdf.inputs["Metallic"].default_value = {metal}
- # PLACEHOLDER blockout at the planned size — REPLACE with the real construction (several parts).
- me = bpy.data.meshes.new("{pascal}Body")
- bm = bmesh.new()
- bmesh.ops.create_cube(bm, size=1.0)
- bmesh.ops.scale(bm, vec=({w:g}, {d:g}, {h:g}), verts=bm.verts)
- bmesh.ops.translate(bm, vec=(0.0, 0.0, {h / 2:g}), verts=bm.verts)
- bm.to_mesh(me)
- bm.free()
- me.materials.append(mat)
- ctx.collection.objects.link(bpy.data.objects.new("{pascal}Body", me))
+ mat = material("{pascal}Mat", ({fmt3(rgb)}), roughness={rough}, metal={metal})
+ # PLACEHOLDER blockout at the planned size — REPLACE with the real construction: several parts
+ # in a Batch (one mesh per material, lib.mesh), base on z = 0, front facing -Y.
+ b = Batch("{pascal}")
+ b.box(mat, (0.0, 0.0, {h / 2:g}), ({w:g}, {d:g}, {h:g}))
+ b.finish(ctx.collection, parent=False)
return ctx.collection
'''
@@ -608,27 +562,21 @@ def _zone_source(z: ZonePlan, assets: dict[str, AssetPlan], counters: dict[str,
return f'''"""src/zones/{snake}.py — zone "{pascal}": {z.description.strip()}
PLAN bbox (Z up, -Y front, metres): centre ({fmt3(c)}) extents ({fmt3(e)}). Contents: {", ".join(z.contents) or "-"}
-CONTRACT: build(ctx) -> bpy.types.Collection — ctx.collection is this zone's (named '{pascal}', active,
- so bpy.ops primitives land in it); every PLACED thing is ONE root object in it, named <Name>_<i>
- (object names are global in Blender: never reuse one another zone uses). Seat things on
- ctx.height_at(x, y); keep them inside the bbox. Assets: a collection-instance Empty of
- ctx.assets['<snake>']. Animation is data: keyframes, or simple drivers on `frame`.
+CONTRACT: build(ctx) -> bpy.types.Collection — ctx.collection is this zone's (named '{pascal}', active);
+ every PLACED thing is ONE root object in it, named <Name>_<i> (object names are global in
+ Blender: never reuse one another zone uses). Seat things on ctx.height_at(x, y) — lib.scatter
+ instances and lib.place.seat do — and keep them inside the bbox. Assets: a collection-instance
+ Empty of ctx.assets['<snake>'] (lib.scatter.instance). Animation is data: lib.motion.
"""
-import bpy
+from lib.scatter import instance
def place(ctx, key, name, x, y, rot_z=0.0):
- """One placed copy of asset `key`: a collection-instance Empty seated on the ground."""
+ """One placed copy of asset `key`: a collection-instance Empty seated on ctx.height_at."""
source = ctx.assets.get(key)
if source is None:
return None
- ob = bpy.data.objects.new(name, None)
- ob.instance_type = "COLLECTION"
- ob.instance_collection = source
- ob.location = (x, y, ctx.height_at(x, y))
- ob.rotation_euler[2] = rot_z
- ctx.collection.objects.link(ob)
- return ob
+ return instance(ctx.collection, source, name, x, y, height_at=ctx.height_at, rot_z=rot_z)
def build(ctx):
@@ -667,30 +615,27 @@ CAMERAS = [
'''
-def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
- """Starter files for a scene plan (env, one module per zone and per procedural asset, the
- assembled entry); ``public/assets/`` for the heroes."""
+def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
+ """Starter files for a scene plan (the library, env, one module per zone and per procedural
+ asset, the assembled entry); ``public/assets/`` for the heroes. Without a plan the complete
+ example scene is the skeleton (``write_example``)."""
+ if plan is None:
+ return write_example(ws)
if not isinstance(plan, ScenePlan):
raise TypeError(f"scene_blender needs a ScenePlan, got {type(plan).__name__}")
written: list[Path] = []
-
- def put(rel: str, text: str) -> None:
- path = ws.root / rel
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(text)
- written.append(path)
-
- put("src/env.py", _env_source(plan))
+ _write_lib(ws, written)
+ _put(ws.root / ENV_FILE, _env_source(plan), written)
assets = {to_snake(a.name): a for a in plan.assets}
for a in plan.assets:
if a.kind != "blender_glb":
- put(asset_file(a), _asset_source(a))
+ _put(ws.root / asset_file(a), _asset_source(a), written)
counters: dict[str, int] = {}
for z in plan.zones:
- put(zone_file(z.name), _zone_source(z, assets, counters))
- put(ENTRY_REL, render_scene_py([to_snake(z.name) for z in plan.zones],
- [to_snake(a.name) for a in plan.assets if a.kind != "blender_glb"], [],
- list(plan.cameras[:6]), title=plan.title, summary=plan.summary))
+ _put(ws.root / zone_file(z.name), _zone_source(z, assets, counters), written)
+ _put(ws.root / ENTRY_REL, render_scene_py([to_snake(z.name) for z in plan.zones],
+ [to_snake(a.name) for a in plan.assets if a.kind != "blender_glb"], [],
+ list(plan.cameras[:6]), title=plan.title, summary=plan.summary), written)
(ws.public / "assets").mkdir(parents=True, exist_ok=True)
return written
@@ -739,6 +684,12 @@ class SceneBlenderRuntime:
zone_file = staticmethod(zone_file)
asset_file = staticmethod(asset_file)
+ @property
+ def env_file(self) -> str:
+ """The environment module (``src/env.py``): what an env session edits, the file the
+ scene track hints for the whole-scene stage (``SceneRuntime.env_file``)."""
+ return ENV_FILE
+
def __init__(self, *, blender: str | None = None, settings: Settings | None = None) -> None:
self._settings = settings or get_settings()
self._blender = blender
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/assets/crate.py b/harness/codeverse3d/languages/scene_blender/starter/src/assets/crate.py
new file mode 100644
index 00000000..74fd4274
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/assets/crate.py
@@ -0,0 +1,30 @@
+"""src/assets/crate.py — asset "Crate": a slatted wooden crate, 0.9 m, corner posts and boards.
+
+CONTRACT: build_crate(ctx, variant=0) -> bpy.types.Collection — link every part into ctx.collection
+ (named 'Crate'), built ONCE at the origin with its base on z = 0, front facing -Y. Zones place
+ collection instances of it (ctx.assets['crate']); never link it anywhere else.
+"""
+from lib.materials import material, woodgrain
+from lib.mesh import Batch
+
+SIZE = 0.9
+
+
+def build_crate(ctx, variant=0):
+ wood = woodgrain(material("CrateWood", "8A6A3F", roughness=0.8), dark="3A2A18", light="9A7A4A")
+ s = SIZE * (1.0 + 0.08 * (variant % 3))
+ post, slat = 0.06, 0.05
+ rim = s * 0.87 + 0.14 # the top slat's top: the posts reach it, so a stacked crate rests on all four corners
+ b = Batch("Crate")
+ for sx in (-1, 1):
+ for sy in (-1, 1):
+ b.box(wood, (sx * (s / 2 - post / 2), sy * (s / 2 - post / 2), rim / 2), (post, post, rim))
+ for k in range(4): # three slats per side, a gap between them
+ z = s * (0.12 + 0.25 * k) + 0.07
+ for sy in (-1, 1):
+ b.box(wood, (0.0, sy * (s / 2 - slat / 2), z), (s - 2 * post, slat, 0.14))
+ for sx in (-1, 1):
+ b.box(wood, (sx * (s / 2 - slat / 2), 0.0, z), (slat, s - 2 * post, 0.14))
+ b.box(wood, (0.0, 0.0, 0.025), (s - 0.02, s - 0.02, 0.05)) # the floor board
+ b.finish(ctx.collection, parent=False)
+ return ctx.collection
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/assets/lantern_post.py b/harness/codeverse3d/languages/scene_blender/starter/src/assets/lantern_post.py
new file mode 100644
index 00000000..830753dd
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/assets/lantern_post.py
@@ -0,0 +1,22 @@
+"""src/assets/lantern_post.py — asset "LanternPost": a 2.4 m timber post with a bracket arm and a
+glowing paper lantern, plus the light it throws.
+
+CONTRACT: build_lantern_post(ctx, variant=0) -> bpy.types.Collection — built ONCE at the origin
+ with its base on z = 0; zones place collection instances (ctx.assets['lantern_post']). A lamp
+ inside the collection is instanced with it, so every post lights its own patch.
+"""
+from lib import architecture, lighting, materials
+from lib.mesh import Batch
+
+
+def build_lantern_post(ctx, variant=0):
+ wood = materials.woodgrain(materials.material("PostWood", "3A2A1A", roughness=0.85))
+ glow = materials.emissive("LanternGlow", "FFB270", 5.0)
+ b = Batch("LanternPost")
+ b.beam(wood, (0.0, 0.0, 0.0), (0.0, 0.0, 2.4), 0.06, sides=8)
+ b.beam(wood, (0.0, 0.0, 2.3), (0.45, 0.0, 2.3), 0.035, sides=6)
+ b.beam(wood, (0.0, 0.0, 1.95), (0.42, 0.0, 2.28), 0.025, sides=6)
+ architecture.lantern(b, glow, wood, (0.45, 0.0, 1.85), radius=0.17)
+ b.finish(ctx.collection, parent=False)
+ lighting.practical(ctx.collection, "LanternPostLight", (0.45, 0.0, 1.72), color="FFB270", energy=25.0, size=0.25)
+ return ctx.collection
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/env.py b/harness/codeverse3d/languages/scene_blender/starter/src/env.py
new file mode 100644
index 00000000..28134f45
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/env.py
@@ -0,0 +1,41 @@
+"""src/env.py — the environment of the example scene: a low warm sun, rolling meadow beyond a
+level play area, a lake basin, haze.
+
+Frame: Z up, -Y front, metres.
+CONTRACT: height_at(x, y) -> z is THE ground: the terrain mesh and every zone's seat use it.
+ build_env(ctx) -> dict builds the world, lamps, ground and atmosphere into ctx.collection and
+ returns what zones may share (materials, water level, sun direction ...) — they read it as
+ ctx.env. Everything here comes from src/lib (lib.terrain / lib.sky / lib.lighting /
+ lib.materials); keep build_env and height_at when you rewrite it.
+"""
+import math
+
+from lib import lighting, materials, sky, terrain
+
+GROUND_SIZE = 160.0
+FLAT_RADIUS = 48.0 # level ground under the cameras (z = 0); gentle hills beyond
+SUN_AZIMUTH_DEG = 215.0 # compass angle of the sun: 0 = +X, 90 = +Y (the sky and the lamp share it)
+SUN_ELEVATION_DEG = 22.0
+BASIN = (-24.0, 2.0, 15.0, 1.2) # the lake's (x, y, radius, depth): zones/lakeside.py fills it to WATER_LEVEL
+WATER_LEVEL = -0.3
+SEED = 5
+_RELIEF = terrain.make_height_at(seed=SEED, relief=2.5, scale=60.0, flat_radius=FLAT_RADIUS)
+
+
+def height_at(x, y):
+ """z of the ground at (x, y): the relief minus a smooth-rimmed bowl under the lake."""
+ bx, by, br, bd = BASIN
+ d = math.hypot(x - bx, y - by) / br
+ t = max(0.0, min(1.0, (d - 0.3) / 0.7)) # a wide rim: banks under 15 % so props seat on them
+ bowl = bd * (1.0 - t * t * (3.0 - 2.0 * t))
+ return _RELIEF(x, y) - bowl
+
+
+def build_env(ctx):
+ sky.sun_world(ctx.scene, elevation_deg=SUN_ELEVATION_DEG, azimuth_deg=SUN_AZIMUTH_DEG, strength=0.35, dust=2.5)
+ _, towards_sun = lighting.sun(ctx.collection, azimuth_deg=SUN_AZIMUTH_DEG, elevation_deg=SUN_ELEVATION_DEG,
+ color="FFC98A", energy=3.5, angle_deg=1.5)
+ ground_mat = materials.material("GroundMat", "4F5E39", roughness=0.92, noise_scale=5.0)
+ terrain.ground("Ground", ctx.collection, size=GROUND_SIZE, segments=112, height_at=height_at, material=ground_mat)
+ sky.haze(ctx.collection, (0.0, 0.0, 12.0), (GROUND_SIZE, GROUND_SIZE, 24.0), density=0.0025, color="D9C7A8")
+ return {"ground_material": ground_mat, "sun_direction": tuple(towards_sun), "water_level": WATER_LEVEL}
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/__init__.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/__init__.py
new file mode 100644
index 00000000..892bb227
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/__init__.py
@@ -0,0 +1,7 @@
+"""src/lib — the harness-owned bpy starter library (D51 for scene_blender).
+
+Shipped into every scene_blender workspace; an agent CALLS it (``from lib.mesh import Batch``)
+and never edits it (writes under src/lib/ are reverted). The index is the effects catalog the
+prompts carry (``prompts/scene_blender/effects_catalog.md``); the lint reads these files for
+syntax only. Blender 5.2 LTS API only.
+"""
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/architecture.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/architecture.py
new file mode 100644
index 00000000..03cae71d
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/architecture.py
@@ -0,0 +1,499 @@
+"""lib/architecture.py — buildings, bridges, roofs, paving, room shells and signs.
+
+Batch recipes stand on the ground z you pass (``center`` = (x, y, ground z), pass
+``height_at(x, y)``); the ridge / long axis runs along +X unless a ``direction`` says
+otherwise (compass degrees: 0 = +X, 90 = +Y, for a window's outward normal). Paving is 2 cm
+thick so a prop seated on ``height_at`` still reads as resting on it (the gate's contact
+tolerance). ``room_shell`` is for ``src/env.py``: it names the lid ``Ceiling`` under a
+``RoomShell`` root so the overview rig can lift it; ``glazed=True`` makes it a glass house (glass
+panes on an iron-frame grid, the sun coming through).
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+import bpy
+from mathutils import Matrix, Vector
+
+from lib.materials import glass
+from lib.mesh import box_geometry, mesh_object
+from lib.noise import hash01
+
+Vec3 = tuple[float, float, float]
+_WALLS = ("front", "back", "left", "right")
+_BAY, _BAR, _PANE = (1.6, 1.6, 2.4), 0.08, 0.02 # a glazed shell's frame spacing per world axis, bar section, glass (m)
+
+
+def _yaw(direction_deg: float) -> Matrix:
+ """The rotation that turns a -Y-facing thing to face compass ``direction_deg``."""
+ return Matrix.Rotation(math.radians(direction_deg) + math.pi / 2, 4, "Z")
+
+
+def arched_opening(batch: Any, mat: Any, center: Sequence[float], width: float, height: float, *, depth: float = 0.28,
+ thickness: float = 0.2) -> None:
+ """A round arch surround in a wall along X: two jambs ``thickness`` wide and an arch ring
+ over an opening ``width`` wide and ``height`` tall (to the crown), ``depth`` through the
+ wall, standing on ``center`` (x, y, ground z)."""
+ cx, cy, cz = (float(v) for v in center)
+ r_in, r_out = width / 2, width / 2 + thickness
+ jamb_h = max(0.1, height - r_in)
+ for sx in (-1, 1):
+ batch.box(mat, (cx + sx * (r_in + thickness / 2), cy, cz + jamb_h / 2), (thickness, depth, jamb_h))
+ n = 14
+ verts: list[Vec3] = []
+ faces: list[tuple[int, ...]] = []
+ for k in range(n + 1):
+ a = math.pi * k / n
+ ca, sa = math.cos(a), math.sin(a)
+ for yy in (cy - depth / 2, cy + depth / 2):
+ verts.append((cx + r_in * ca, yy, cz + jamb_h + r_in * sa))
+ verts.append((cx + r_out * ca, yy, cz + jamb_h + r_out * sa))
+ for k in range(n):
+ a = 4 * k
+ faces.append((a, a + 4, a + 5, a + 1)) # front face (-y)
+ faces.append((a + 2, a + 3, a + 7, a + 6)) # back face (+y)
+ faces.append((a + 1, a + 5, a + 7, a + 3)) # outer (extrados)
+ faces.append((a, a + 2, a + 6, a + 4)) # inner (intrados)
+ batch.add(mat, verts, faces)
+
+
+def _slope(batch: Any, mats: Any, center: Sequence[float], width: float, depth: float, rise: float, side: int, rng_: Any,
+ *, style: str) -> None:
+ """One roof slope: a plank underlay plus tiles, built flat then tilted about X."""
+ tile, trim = mats
+ half = depth / 2
+ run = math.hypot(half, rise)
+ pitch = math.atan2(rise, half)
+ cx, cy, cz = (float(v) for v in center)
+ # local frame: x along the ridge, y from the eave (0) up the slope to the ridge (run), z the
+ # slope's outward normal; the +Y slope is the -Y one yawed 180° about the ridge's foot
+ flip = Matrix.Rotation(math.pi, 4, "Z") if side > 0 else Matrix.Identity(4)
+ m = Matrix.Translation((cx, cy + side * half, cz)) @ flip @ Matrix.Rotation(pitch, 4, "X")
+ view = batch.transformed(m)
+ view.box(trim, (0.0, run / 2, 0.02), (width + 0.4, run + 0.25, 0.04))
+ if style == "tiles":
+ tw, th = 0.34, 0.3
+ if (width / tw) * (run / th) > 1400:
+ k = math.sqrt((width / tw) * (run / th) / 1400)
+ tw, th = tw * k, th * k
+ cols, rows = max(1, int(width / tw)), max(1, int(run / th))
+ for r in range(rows):
+ for c in range(cols):
+ x = -width / 2 + tw * (c + 0.5) + (tw / 2 if r % 2 else 0.0)
+ y = th * (r + 0.5) + 0.1
+ view.box(tile, (x, y, 0.065 + 0.012 * rng_.uniform(-1, 1)), (tw * 0.96, th * 1.08, 0.03), rotation=rng_.uniform(-0.03, 0.03))
+ else:
+ pitch_w = 0.2
+ n = max(1, int(width / pitch_w))
+ for c in range(n + 1):
+ x = -width / 2 + pitch_w * c
+ view.beam(tile, (x, 0.0, 0.07), (x, run, 0.07), 0.08, sides=8)
+ if c < n:
+ view.beam(tile, (x + pitch_w / 2, 0.0, 0.0), (x + pitch_w / 2, run, 0.0), 0.08, sides=8)
+
+
+def tiled_roof(batch: Any, tile: Any, trim: Any, center: Sequence[float], width: float, depth: float, rise: float, rng_: Any) -> None:
+ """A pitched roof with its ridge along X: eaves ``width`` x ``depth`` resting on ``center``
+ (x, y, eave z), ridge ``rise`` higher. Flat tiles (≤ 1 400 per slope: 17 k triangles)
+ over a plank underlay in ``trim``, a ridge beam on top."""
+ for side in (-1, 1):
+ _slope(batch, (tile, trim), center, width, depth, rise, side, rng_, style="tiles")
+ cx, cy, cz = (float(v) for v in center)
+ batch.box(trim, (cx, cy, cz + rise + 0.08), (width + 0.4, 0.22, 0.14))
+
+
+def clay_roof(batch: Any, frame: Any, tiles: Any, timber: Any, center: Sequence[float], width: float, depth: float, rise: float,
+ rng_: Any) -> None:
+ """A pantile roof: half-round ``tiles`` rows over a ``frame`` underlay, rafter ends in
+ ``timber`` showing under the eaves; same footprint rule as ``tiled_roof``."""
+ for side in (-1, 1):
+ _slope(batch, (tiles, frame), center, width, depth, rise, side, rng_, style="clay")
+ cx, cy, cz = (float(v) for v in center)
+ batch.box(timber, (cx, cy, cz + rise + 0.1), (width + 0.5, 0.26, 0.16))
+ for i in range(max(2, int(width / 0.9)) + 1):
+ x = cx - width / 2 + width * i / max(1, int(width / 0.9))
+ for side in (-1, 1):
+ batch.box(timber, (x, cy + side * (depth / 2 + 0.05), cz - 0.12), (0.12, 0.5, 0.14))
+
+
+def fret_window(batch: Any, wood: Any, paper: Any, x: float, y: float, z: float, width: float, height: float, direction: float, *,
+ pattern: int = 0) -> None:
+ """A latticed window ``width`` x ``height`` whose sill centre is at (x, y, z), facing
+ compass ``direction``: a frame and a fret in ``wood`` (``pattern`` 0 grid, 1 diagonal, 2
+ nested) over a ``paper`` pane."""
+ view = batch.transformed(Matrix.Translation((x, y, z)) @ _yaw(direction))
+ f, d = 0.06, 0.08
+ view.box(wood, (0.0, 0.0, f / 2), (width, d, f))
+ view.box(wood, (0.0, 0.0, height - f / 2), (width, d, f))
+ for sx in (-1, 1):
+ view.box(wood, (sx * (width / 2 - f / 2), 0.0, height / 2), (f, d, height))
+ bar = 0.025
+ if pattern == 1:
+ n = 4
+ for k in range(1, n):
+ t = k / n
+ view.beam(wood, (-width / 2 + width * t, 0.0, f), (width / 2, 0.0, height - f * (1.0 - t)), bar / 2, sides=4)
+ view.beam(wood, (-width / 2, 0.0, f + (height - 2 * f) * t), (width / 2 - width * t, 0.0, height - f), bar / 2, sides=4)
+ elif pattern == 2:
+ for k in range(1, 4):
+ w, h = width * (1.0 - k * 0.22), height * (1.0 - k * 0.22)
+ for sx in (-1, 1):
+ view.box(wood, (sx * w / 2, 0.0, height / 2), (bar, bar, h))
+ view.box(wood, (0.0, 0.0, height / 2 - h / 2), (w, bar, bar))
+ view.box(wood, (0.0, 0.0, height / 2 + h / 2), (w, bar, bar))
+ else:
+ for k in range(1, 3):
+ view.box(wood, (-width / 2 + width * k / 3, 0.0, height / 2), (bar, bar, height - 2 * f))
+ for k in range(1, 4):
+ view.box(wood, (0.0, 0.0, f + (height - 2 * f) * k / 4), (width - 2 * f, bar, bar))
+ verts, faces = box_geometry((0.0, d * 0.3, height / 2), (width - 2 * f, 0.004, height - 2 * f))
+ view.add(paper, verts, faces)
+
+
+def timber_house(batch: Any, roofs: Any, x: float, y: float, width: float, depth: float, floors: int, mats: Any, rng_: Any,
+ index: int) -> float:
+ """A half-timbered house ``width`` (along X) x ``depth`` with ``floors`` storeys (2.8 m
+ each, upper ones jettied 0.2 m) on ground point (x, y, 0): walls, timber frame, a door and
+ fret windows on the front (-Y), a ``tiled_roof``. ``mats`` = {"wall", "timber", "door",
+ "window"}, ``roofs`` = {"tile", "trim"}; ``index`` varies the door side and the fret.
+ Returns the ridge height above the ground. ~6-12 k triangles."""
+ wall, timber, door, pane = mats["wall"], mats["timber"], mats["door"], mats["window"]
+ storey = 2.8
+ z0 = 0.0
+ for fl in range(max(1, int(floors))):
+ jetty = 0.2 * fl
+ w, dd = width + 2 * jetty, depth + 2 * jetty
+ zb = z0 + storey * fl
+ batch.box(wall, (x, y, zb + storey / 2), (w, dd, storey))
+ # sill beam and posts
+ batch.box(timber, (x, y - dd / 2 - 0.04, zb + 0.08), (w + 0.1, 0.1, 0.16))
+ batch.box(timber, (x, y - dd / 2 - 0.04, zb + storey - 0.08), (w + 0.1, 0.1, 0.16))
+ n_posts = max(2, int(w / 1.4))
+ for k in range(n_posts + 1):
+ px = x - w / 2 + w * k / n_posts
+ batch.box(timber, (px, y - dd / 2 - 0.04, zb + storey / 2), (0.14, 0.1, storey))
+ for sy in (-1, 1):
+ batch.box(timber, (x + sy * (w / 2 + 0.04), y - dd / 2 + dd * k / n_posts, zb + storey / 2), (0.1, 0.14, storey))
+ if fl == 0:
+ for k in range(n_posts):
+ ax = x - w / 2 + w * k / n_posts
+ bx = ax + w / n_posts
+ batch.beam(timber, (ax, y - dd / 2 - 0.04, zb + 0.16), (bx, y - dd / 2 - 0.04, zb + storey * 0.45), 0.05, sides=4)
+ # windows on the front, one per bay but the door bay on the ground floor
+ door_bay = index % n_posts
+ for k in range(n_posts):
+ wx = x - w / 2 + w * (k + 0.5) / n_posts
+ if fl == 0 and k == door_bay:
+ batch.box(door, (wx, y - dd / 2 - 0.02, zb + 1.05), (0.95, 0.06, 2.1))
+ continue
+ fret_window(batch, timber, pane, wx, y - dd / 2 - 0.02, zb + 0.9, 0.9, 1.2, -90.0, pattern=(index + k) % 3)
+ for sy in (-1, 1):
+ fret_window(batch, timber, pane, x + sy * (w / 2 + 0.02), y + dd * 0.15, zb + 0.9, 0.8, 1.1, 0.0 if sy > 0 else 180.0, pattern=index % 3)
+ top = z0 + storey * floors
+ jetty = 0.2 * (floors - 1)
+ rise = (depth + 2 * jetty) * 0.48
+ tiled_roof(batch, roofs["tile"], roofs["trim"], (x, y, top), width + 2 * jetty + 0.4, depth + 2 * jetty + 0.4, rise, rng_)
+ # gable infill under the roof at both ends
+ for sx in (-1, 1):
+ gx = x + sx * (width / 2 + jetty)
+ verts = [(gx, y - (depth / 2 + jetty), top), (gx, y + (depth / 2 + jetty), top), (gx, y, top + rise)]
+ batch.add(wall, verts, [(0, 1, 2) if sx > 0 else (0, 2, 1)])
+ return top + rise + 0.15
+
+
+def _footing(batch: Any, mat: Any, center: Sequence[float], size: Sequence[float], height_at: Any) -> None:
+ """A foundation block of ``size`` (x, y, height) whose top is at ``center`` z: its bottom
+ meets the LOWEST of the ground under its four corners (``height_at``) so no corner floats on
+ a slope — the gate samples the corners; without ``height_at`` it is ``size[2]`` tall."""
+ cx, cy, cz = (float(v) for v in center)
+ sx, sy, h = (float(v) for v in size)
+ corners = ((-sx / 2, -sy / 2), (sx / 2, -sy / 2), (sx / 2, sy / 2), (-sx / 2, sy / 2))
+ if height_at is None:
+ bottoms = [cz - h] * 4
+ else: # a wedge: every corner 2 cm under its own ground, so a bank buries nothing deeper
+ bottoms = [min(float(height_at(cx + dx, cy + dy)) - 0.02, cz - 0.05) for dx, dy in corners]
+ verts = [(cx + dx, cy + dy, zb) for (dx, dy), zb in zip(corners, bottoms, strict=True)]
+ verts += [(cx + dx, cy + dy, cz) for dx, dy in corners]
+ batch.add(mat, verts, [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
+
+
+def stone_bridge(batch: Any, stone: Any, dark: Any, *, center: Sequence[float], span: float = 27.6, width: float = 4.7,
+ rise: float = 3.9, height_at: Any = None) -> None:
+ """A hump-backed stone bridge along X over ``center`` (x, y, water / ground z): a barrel
+ arch (intrados in ``dark``) rising ``rise`` m, spandrels, a cambered deck and parapets in
+ ``stone``; the abutments' feet stand on the ``center`` z, or follow ``height_at`` under
+ their corners when given. ~2.6 k triangles."""
+ cx, cy, cz = (float(v) for v in center)
+ n = 24
+ ha = span * 0.36 # the arch's half-span
+ deck_h = rise + 0.9 # deck centre height above z
+ verts: list[Vec3] = []
+ faces: list[tuple[int, ...]] = []
+ # arch barrel: intrados (dark) as a strip of quads, spandrel walls as the strip up to the deck
+ for k in range(n + 1):
+ a = math.pi * k / n
+ xi, zi = cx - ha * math.cos(a), cz + rise * math.sin(a)
+ for yy in (cy - width / 2, cy + width / 2):
+ verts.append((xi, yy, zi))
+ for k in range(n):
+ a = 2 * k
+ faces.append((a, a + 1, a + 3, a + 2))
+ batch.add(dark, verts, faces, smooth=True)
+ sv: list[Vec3] = []
+ sf: list[tuple[int, ...]] = []
+ for yy in (cy - width / 2, cy + width / 2):
+ base = len(sv)
+ for k in range(n + 1):
+ a = math.pi * k / n
+ xi = cx - ha * math.cos(a)
+ sv.append((xi, yy, cz + rise * math.sin(a)))
+ sv.append((xi, yy, cz + deck_h - 0.35 * (xi - cx) ** 2 / (span / 2) ** 2 * deck_h))
+ for k in range(n):
+ a = base + 2 * k
+ sf.append((a, a + 2, a + 3, a + 1) if yy < cy else (a, a + 1, a + 3, a + 2))
+ batch.add(stone, sv, sf)
+ # deck (cambered), parapets and abutment blocks
+ m = 16
+ for k in range(m):
+ t0, t1 = k / m, (k + 1) / m
+ x0, x1 = cx - span / 2 + span * t0, cx - span / 2 + span * t1
+ h0 = cz + deck_h - 0.35 * (x0 - cx) ** 2 / (span / 2) ** 2 * deck_h
+ h1 = cz + deck_h - 0.35 * (x1 - cx) ** 2 / (span / 2) ** 2 * deck_h
+ slab = [(x0, cy - width / 2, h0), (x1, cy - width / 2, h1), (x1, cy + width / 2, h1), (x0, cy + width / 2, h0)]
+ batch.add(stone, slab, [(0, 1, 2, 3)])
+ for sy in (-1, 1):
+ yy = cy + sy * (width / 2 - 0.18)
+ batch.add(stone, [(x0, yy - 0.18, h0), (x1, yy - 0.18, h1), (x1, yy + 0.18, h1), (x0, yy + 0.18, h0),
+ (x0, yy - 0.18, h0 + 1.0), (x1, yy - 0.18, h1 + 1.0), (x1, yy + 0.18, h1 + 1.0), (x0, yy + 0.18, h0 + 1.0)],
+ [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
+ for sx in (-1, 1):
+ ax = cx + sx * (span / 2 - (span / 2 - ha) / 2)
+ _footing(batch, stone, (ax, cy, cz + deck_h * 0.65), (span / 2 - ha, width + 0.3, deck_h * 0.65), height_at)
+
+
+def arched_footbridge(batch: Any, wood: Any, stone: Any, *, start: Sequence[float], end: Sequence[float], rise: float = 1.5,
+ height_at: Any = None) -> None:
+ """A wooden footbridge arching ``rise`` m from ``start`` to ``end`` (x, y, ground z): planks,
+ rails on posts, stone abutments standing on the two ground points (their corners follow
+ ``height_at`` when given — a bank is never level). ~1.5 k triangles."""
+ a, b = Vector(tuple(float(v) for v in start)), Vector(tuple(float(v) for v in end))
+ d = b - a
+ L = max(0.5, d.length)
+ along = d.normalized()
+ side = Vector((-along.y, along.x, 0.0)).normalized()
+ n = max(4, int(L / 0.3))
+ w = 1.6
+ for k in range(n):
+ t = (k + 0.5) / n
+ p = a + d * t + Vector((0.0, 0.0, rise * math.sin(math.pi * t) + 0.08))
+ tangent = (along + Vector((0.0, 0.0, rise * math.pi * math.cos(math.pi * t) / L))).normalized()
+ m = Matrix.Translation(p) @ Matrix((side, tangent, side.cross(tangent))).transposed().to_4x4()
+ batch.transformed(m).box(wood, (0.0, 0.0, 0.0), (w, L / n * 0.92, 0.05))
+ for k in range(5):
+ t = k / 4
+ p = a + d * t + Vector((0.0, 0.0, rise * math.sin(math.pi * t) + 0.1))
+ for sy in (-1, 1):
+ foot = p + side * (sy * w / 2)
+ batch.beam(wood, foot, foot + Vector((0.0, 0.0, 1.0)), 0.04, sides=6)
+ for sy in (-1, 1):
+ pts = [a + d * (k / 12) + side * (sy * w / 2) + Vector((0.0, 0.0, rise * math.sin(math.pi * k / 12) + 1.1)) for k in range(13)]
+ for k in range(12):
+ batch.beam(wood, pts[k], pts[k + 1], 0.035, sides=6)
+ for p in (a, b):
+ _footing(batch, stone, (p.x, p.y, p.z + 0.3), (w + 0.4, 1.2, 0.3), height_at)
+
+
+def tower(batch: Any, mat: Any, center: Sequence[float], radius: float, low: float, high: float, windows: Any, *, count: int = 8) -> None:
+ """A round tower about ``center`` (x, y) from z = ``low`` to ``high``: a tapering drum with
+ a battered base, ``count`` window insets in ``windows`` on two levels, and merlons on top."""
+ cx, cy = float(center[0]), float(center[1])
+ h = high - low
+ batch.lathe(mat, (cx, cy), [(radius * 1.15, low), (radius * 1.05, low + h * 0.12), (radius, low + h * 0.9), (radius * 1.08, high - 0.4),
+ (radius * 1.08, high), (0.0, high)], sides=24)
+ for level in (0.42, 0.72):
+ for k in range(max(1, int(count))):
+ a = math.tau * (k + 0.5 * (level > 0.5)) / count
+ m = Matrix.Translation((cx + math.cos(a) * radius * 0.98, cy + math.sin(a) * radius * 0.98, low + h * level)) @ Matrix.Rotation(a + math.pi / 2, 4, "Z")
+ batch.transformed(m).box(windows, (0.0, 0.0, 0.0), (0.35, 0.12, 0.9))
+ for k in range(max(6, int(count) * 2)):
+ a = math.tau * k / max(6, int(count) * 2)
+ m = Matrix.Translation((cx + math.cos(a) * radius * 1.0, cy + math.sin(a) * radius * 1.0, high + 0.3)) @ Matrix.Rotation(a, 4, "Z")
+ batch.transformed(m).box(mat, (0.0, 0.0, 0.0), (0.3, 0.45, 0.6))
+
+
+def paving(batch: Any, mats: Sequence[Any], *, center: Sequence[float], inner_r: float, rings: int, seed: int) -> None:
+ """Fan-set paving: ``rings`` concentric rings of stones 0.4 m deep from ``inner_r`` outward
+ around ``center`` (x, y, ground z), 2 cm thick, cycling ``mats``; ``seed`` varies the
+ joints. A ring of radius r holds ~2πr / 0.35 stones."""
+ cx, cy, cz = (float(v) for v in center)
+ k = 0
+ for ring in range(max(1, int(rings))):
+ r0 = inner_r + 0.4 * ring
+ rm = r0 + 0.2
+ n = max(6, int(math.tau * rm / 0.35))
+ for i in range(n):
+ a = math.tau * (i + 0.5 * (ring % 2)) / n
+ j = 0.012 * hash01(k, seed)
+ w = math.tau * rm / n - 0.025 - j
+ batch.box(mats[k % len(mats)], (cx + rm * math.cos(a), cy + rm * math.sin(a), cz + 0.01), (0.38 - j, w, 0.02), rotation=a)
+ k += 1
+
+
+def paving_grid(batch: Any, mats: Sequence[Any], center: Sequence[float], size: float | Sequence[float], stone: float | Sequence[float],
+ joint: float, rng_: Any) -> None:
+ """A rectangular grid of flagstones ``stone`` (m, or (x, y)) with ``joint`` m gaps over
+ ``size`` m around ``center`` (x, y, ground z), 2 cm thick, cycling ``mats`` with a jitter."""
+ sx, sy = (float(size), float(size)) if isinstance(size, (int, float)) else (float(size[0]), float(size[1]))
+ tx, ty = (float(stone), float(stone)) if isinstance(stone, (int, float)) else (float(stone[0]), float(stone[1]))
+ cx, cy, cz = (float(v) for v in center)
+ nx, ny = max(1, int(sx / (tx + joint))), max(1, int(sy / (ty + joint)))
+ k = 0
+ for i in range(nx):
+ for j in range(ny):
+ x = cx - sx / 2 + (tx + joint) * (i + 0.5)
+ y = cy - sy / 2 + (ty + joint) * (j + 0.5)
+ batch.box(mats[rng_.randrange(len(mats))], (x, y, cz + 0.01), (tx - rng_.uniform(0, joint * 0.5), ty - rng_.uniform(0, joint * 0.5), 0.02))
+ k += 1
+
+
+def _slab(name: str, collection: Any, mat: Any, loc: Sequence[float], size: Sequence[float], parent: Any) -> Any:
+ v, f = box_geometry(loc, size)
+ ob = mesh_object(name, v, f, mat, collection)
+ ob.parent = parent
+ return ob
+
+
+def room_shell(collection: Any, mat: Any, *, center: Sequence[float], extents: Sequence[float], thickness: float = 0.2,
+ openings: Sequence[Sequence[Any]] = (), glazed: bool = False) -> list[Any]:
+ """An interior's floor, four walls and ceiling OUTSIDE the box ``center`` / ``extents``
+ (inner faces = the box faces), under a root Empty ``RoomShell`` with the lid named
+ ``Ceiling`` (the overview rig lifts it). ``openings`` = ``(wall, offset, width, sill, head)``
+ rows — ``wall`` front/back/left/right (front = -Y), ``offset`` along the wall from its
+ centre, ``sill``/``head`` heights above the floor — cut as panels, no booleans. ``glazed``
+ makes a glass house (a conservatory, a greenhouse, a glass atrium): every wall panel and the
+ lid become a ``materials.glass`` pane that casts no shadow on an iron-frame grid of ``mat``
+ bars (the sun comes through, the frame's grid shadows the floor); the floor stays an opaque
+ slab of ``mat`` and the names stay, a pane being its panel's name + ``Glass``. Returns
+ ``[root, floor, ceiling, walls…]`` (glazed: each panel's frame then its pane); for ``src/env.py``."""
+ cx, cy, cz = (float(v) for v in center)
+ ex, ey, ez = (float(v) for v in extents)
+ t = float(thickness)
+ z0, z1 = cz - ez / 2, cz + ez / 2
+ pane = (bpy.data.materials.get("RoomShellGlass") or glass("RoomShellGlass", color="E6F2F0")) if glazed else None
+ root = bpy.data.objects.new("RoomShell", None)
+ root.empty_display_size = 0.5
+ collection.objects.link(root)
+ out = [root, _slab("RoomShellFloor", collection, mat, (cx, cy, z0 - t / 2), (ex + 2 * t, ey + 2 * t, t), root)]
+ out += _slabs("Ceiling", collection, mat, pane, (cx, cy, z1 + t / 2), (ex + 2 * t, ey + 2 * t, t), 2, root)
+ # each wall: (name, axis along the wall, centre point, length)
+ walls = {"front": ("RoomShellWallFront", "x", (cx, cy - ey / 2 - t / 2), ex + 2 * t),
+ "back": ("RoomShellWallBack", "x", (cx, cy + ey / 2 + t / 2), ex + 2 * t),
+ "left": ("RoomShellWallLeft", "y", (cx - ex / 2 - t / 2, cy), ey),
+ "right": ("RoomShellWallRight", "y", (cx + ex / 2 + t / 2, cy), ey)}
+ cuts: dict[str, list[tuple[float, float, float, float]]] = {w: [] for w in _WALLS}
+ for row in openings:
+ wall, offset, width, sill, head = str(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4])
+ # clamped into the wall: a head above the lid would invert the lintel into a slab ABOVE it (gate ERROR)
+ sill, head = max(0.0, min(sill, ez)), max(0.0, min(head, ez))
+ if wall in cuts and width > 0 and head > sill:
+ cuts[wall].append((offset, width, sill, head))
+ for wall in _WALLS:
+ name, axis, (wx, wy), length = walls[wall]
+ spec = (collection, mat, root, name, axis, wx, wy, t, pane)
+ segs = sorted(cuts[wall], key=lambda c: c[0])
+ edge = -length / 2
+ k = 0
+ for offset, width, sill, head in segs:
+ a, b = max(edge, offset - width / 2), min(length / 2, offset + width / 2)
+ _panel(out, spec, edge, a, z0, z1, f"_{k}")
+ if sill > 0:
+ _panel(out, spec, a, b, z0, z0 + sill, f"_{k}Sill")
+ if head < ez:
+ _panel(out, spec, a, b, z0 + head, z1, f"_{k}Lintel")
+ edge = b
+ k += 1
+ _panel(out, spec, edge, length / 2, z0, z1, "" if k == 0 else f"_{k}")
+ return out
+
+
+def _panel(out: list[Any], spec: tuple[Any, ...], a: float, b: float, zb: float, zt: float, tag: str) -> None:
+ """One wall panel between ``a`` and ``b`` along the wall, ``zb``..``zt`` tall (skipped when
+ degenerate); ``spec`` = (collection, material, root, name, axis, wx, wy, thickness, pane)."""
+ collection, mat, root, name, axis, wx, wy, t, pane = spec
+ if b - a <= 1e-3 or zt - zb <= 1e-3:
+ return
+ mid = (a + b) / 2
+ loc = (wx + mid, wy, (zb + zt) / 2) if axis == "x" else (wx, wy + mid, (zb + zt) / 2)
+ size = (b - a, t, zt - zb) if axis == "x" else (t, b - a, zt - zb)
+ out.extend(_slabs(f"{name}{tag}", collection, mat, pane, loc, size, 1 if axis == "x" else 0, root))
+
+
+def _slabs(name: str, collection: Any, mat: Any, pane: Any, loc: Sequence[float], size: Sequence[float], thin: int,
+ parent: Any) -> list[Any]:
+ """One opaque slab — or, with a ``pane`` material, its glazed twin: a ``_PANE`` glass sheet in
+ the slab's mid-plane that casts no shadow (the sun comes through), framed by ``mat`` bars on a
+ WORLD lattice (``_BAY`` apart: the grid runs on across neighbouring panels and around an
+ opening) plus a bar on every edge. ``thin`` = the thickness axis (0 x, 1 y, 2 z), known from
+ the face — never the smallest size: a sill can be narrower than the wall is thick."""
+ if pane is None:
+ return [_slab(name, collection, mat, loc, size, parent)]
+ c0, s0 = [float(v) for v in loc], [float(v) for v in size]
+ verts: list[Vec3] = []
+ faces: list[tuple[int, ...]] = []
+ depth = max(0.04, min(s0[thin], 0.15))
+ i, j = [k for k in range(3) if k != thin]
+ for along, across in ((i, j), (j, i)):
+ lo, hi = c0[across] - s0[across] / 2, c0[across] + s0[across] / 2
+ lines, v = [lo, hi], math.ceil((lo + 0.3) / _BAY[across]) * _BAY[across]
+ while v < hi - 0.3:
+ lines.append(v)
+ v += _BAY[across]
+ for at in lines:
+ c, s = list(c0), [0.0, 0.0, 0.0]
+ c[across] = at
+ s[thin], s[along], s[across] = depth, s0[along], _BAR
+ bv, bf = box_geometry(c, s)
+ base = len(verts)
+ verts += bv
+ faces += [tuple(base + n for n in f) for f in bf]
+ frame = mesh_object(name, verts, faces, mat, collection)
+ frame.parent = parent
+ sheet_ob = _slab(f"{name}Glass", collection, pane, c0, [_PANE if k == thin else s0[k] for k in range(3)], parent)
+ sheet_ob.visible_shadow = False
+ return [frame, sheet_ob]
+
+
+def lantern(batch: Any, silk: Any, wood: Any, center: Sequence[float], *, radius: float = 0.35, length: float | None = None) -> None:
+ """A paper lantern centred at ``center`` (it hangs: tag the finished root ``free`` or put
+ it on a post): a ``silk`` body (make it ``materials.emissive``) with ``wood`` caps and a
+ hanging loop; ``length`` defaults to 2.4 x ``radius``."""
+ cx, cy, cz = (float(v) for v in center)
+ L = float(length) if length is not None else radius * 2.4
+ batch.lathe(silk, (cx, cy), [(0.0, cz - L / 2), (radius * 0.55, cz - L / 2 + 0.03), (radius, cz - L * 0.22), (radius, cz + L * 0.22),
+ (radius * 0.55, cz + L / 2 - 0.03), (0.0, cz + L / 2)], sides=24)
+ for zz in (cz - L / 2 - 0.02, cz + L / 2 + 0.02):
+ batch.lathe(wood, (cx, cy), [(0.0, zz - 0.02), (radius * 0.4, zz - 0.02), (radius * 0.4, zz + 0.02), (0.0, zz + 0.02)], sides=12)
+ batch.ring(wood, (cx, cy, cz + L / 2 + 0.1), (0.0, 1.0, 0.0), 0.06, 0.008, segments=16)
+
+
+def text_mesh(name: str, collection: Any, body: str, loc: Sequence[float], size: float, mat: Any, *,
+ rotation: Sequence[float] = (math.pi / 2, 0.0, 0.0), align: str = "CENTER", extrude: float = 0.005) -> Any:
+ """Readable lettering: a text object saying ``body`` at ``loc``, ``size`` m tall letters,
+ standing up and facing -Y with the default ``rotation``; ``extrude`` gives it thickness.
+ Measured by the census like any mesh; a sign a camera can read."""
+ cu = bpy.data.curves.new(name, "FONT")
+ cu.body = str(body)
+ cu.size = float(size)
+ cu.extrude = float(extrude)
+ cu.align_x = align
+ if mat is not None:
+ cu.materials.append(mat)
+ ob = bpy.data.objects.new(name, cu)
+ ob.location = tuple(float(v) for v in loc)
+ ob.rotation_mode = "XYZ"
+ ob.rotation_euler = tuple(float(v) for v in rotation)
+ collection.objects.link(ob)
+ return ob
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/figure.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/figure.py
new file mode 100644
index 00000000..e3eefc5d
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/figure.py
@@ -0,0 +1,75 @@
+"""lib/figure.py — people as batch geometry: a figure, a dressed visitor, a crowd.
+
+A figure is 1.72 x ``scale`` m tall and stands on ``center`` (x, y, ground z) facing -Y, turned
+by ``heading`` (radians about Z; ``place.heading(a, b)`` gives the value that faces ``b``).
+``pose`` 0 stands, 1 is a full walking stride (legs and arms swung). About 560 triangles; a
+crowd of forty is one object.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+from mathutils import Matrix
+
+_H = 1.72
+
+
+def figure(batch: Any, cloth: Any, skin: Any, center: Sequence[float], *, scale: float = 1.0, heading: float = 0.0,
+ pose: float = 0.0) -> None:
+ """One person in ``cloth`` with ``skin`` hands and head, standing on ``center``."""
+ _person(batch, cloth, cloth, skin, center, scale=scale, heading=heading, pose=pose)
+
+
+def visitor(batch: Any, cloth: Any, mats: Sequence[Any], center: Sequence[float], *, scale: float = 1.0, heading: float = 0.0,
+ pose: float = 0.0, variant: int = 0) -> None:
+ """A dressed figure: ``cloth`` for the coat, ``mats[variant]`` for the legs (a list of
+ trouser / skirt materials, cycled), ``mats[-1]`` for the skin when it holds two or more
+ — hand ``materials.tint`` copies to vary a crowd."""
+ pool = list(mats) or [cloth]
+ legs = pool[int(variant) % len(pool)]
+ skin = pool[-1] if len(pool) > 1 else cloth
+ _person(batch, cloth, legs, skin, center, scale=scale, heading=heading, pose=pose)
+
+
+def crowd(batch: Any, mats: Sequence[Any], points: Sequence[Sequence[float]], rng_: Any, **kw: Any) -> None:
+ """A ``visitor`` at every (x, y, ground z) of ``points`` with a random heading, stride and
+ coat drawn from ``mats`` (the last is the skin); ``kw`` = ``scale``."""
+ pool = list(mats)
+ coats = pool[:-1] if len(pool) > 1 else pool
+ for i, p in enumerate(points):
+ visitor(batch, coats[rng_.randrange(len(coats))], pool, p, heading=rng_.uniform(0.0, math.tau),
+ pose=rng_.uniform(0.0, 1.0), variant=rng_.randrange(len(pool)) if pool else i, **kw)
+
+
+def _person(batch: Any, coat: Any, legs: Any, skin: Any, center: Sequence[float], *, scale: float, heading: float, pose: float) -> None:
+ H = _H * float(scale)
+ cx, cy, cz = (float(v) for v in center)
+ view = batch.transformed(Matrix.Translation((cx, cy, cz)) @ Matrix.Rotation(float(heading), 4, "Z"))
+ swing = 0.45 * max(0.0, min(1.0, float(pose)))
+ hip_z, knee_z, ankle_z = 0.5 * H, 0.27 * H, 0.04 * H
+ for side, s in ((-1, 1.0), (1, -1.0)):
+ hx = side * 0.085 * H
+ fwd = -math.sin(swing * s) * (hip_z - ankle_z) # a stride goes along -Y (the front)
+ knee = (hx, fwd * 0.55, knee_z + 0.02 * H * abs(math.sin(swing)))
+ ankle = (hx, fwd, ankle_z)
+ view.beam(legs, (hx, 0.0, hip_z), knee, 0.065 * H, end=0.05 * H, sides=8)
+ view.beam(legs, knee, ankle, 0.05 * H, end=0.04 * H, sides=8)
+ view.box(skin, (hx, fwd - 0.05 * H, 0.02 * H), (0.08 * H, 0.15 * H, 0.04 * H))
+ # torso (a flattened lathe), neck, head
+ torso = view.transformed(Matrix.Diagonal((1.0, 0.68, 1.0, 1.0)))
+ torso.lathe(coat, (0.0, 0.0), [(0.13 * H, hip_z - 0.02 * H), (0.15 * H, 0.62 * H), (0.155 * H, 0.74 * H), (0.12 * H, 0.82 * H), (0.0, 0.835 * H)], sides=14)
+ view.beam(skin, (0.0, 0.0, 0.8 * H), (0.0, 0.0, 0.87 * H), 0.035 * H, sides=8)
+ view.sphere(skin, (0.0, 0.0, 0.925 * H), (0.07 * H, 0.075 * H, 0.085 * H), subdivision=2)
+ view.sphere(coat, (0.0, 0.01 * H, 0.95 * H), (0.072 * H, 0.077 * H, 0.065 * H), subdivision=1) # hair / cap
+ # arms, swung opposite to the legs
+ for side, s in ((-1, -1.0), (1, 1.0)):
+ sx = side * 0.19 * H
+ fwd = -math.sin(swing * s * 0.8) * 0.35 * H
+ elbow = (sx * 1.1, fwd * 0.5, 0.62 * H)
+ hand = (sx * 1.05, fwd, 0.47 * H)
+ view.beam(coat, (sx * 0.9, 0.0, 0.8 * H), elbow, 0.045 * H, end=0.04 * H, sides=8)
+ view.beam(coat, elbow, hand, 0.04 * H, end=0.032 * H, sides=8)
+ view.sphere(skin, hand, 0.035 * H, subdivision=1)
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/lighting.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/lighting.py
new file mode 100644
index 00000000..f78cac99
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/lighting.py
@@ -0,0 +1,110 @@
+"""lib/lighting.py — lamps as data objects (never ``bpy.ops.object.light_add``).
+
+Units are Blender's: a Sun's ``energy`` is irradiance in W/m² (3-5 reads as daylight under AgX
+at exposure 0, 0.3-1 as dusk), point / spot / area ``energy`` is Watts (a 45 W practical lights a
+porch, 500-2000 W a hall). Compass angles: 0° = +X, 90° = +Y, like the skeleton's
+``SUN_AZIMUTH_DEG``. The harness owns exposure (0) and the view transform (AgX): light the scene,
+never the camera.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+import bpy
+from mathutils import Vector
+
+from lib.materials import rgba
+
+
+def _rgb(color: str | Sequence[float]) -> tuple[float, float, float]:
+ c = rgba(color) if isinstance(color, str) else tuple(float(v) for v in color)
+ return (c[0], c[1], c[2])
+
+
+def aim(obj: Any, target: Sequence[float]) -> None:
+ """Point ``obj``'s -Z axis (a lamp's beam, a camera's view) at ``target``."""
+ d = Vector(target) - Vector(obj.location)
+ if d.length < 1e-6:
+ return
+ obj.rotation_mode = "XYZ"
+ obj.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
+
+
+def sun(collection: Any, *, azimuth_deg: float, elevation_deg: float, color: str | Sequence[float] = "FFCF9C",
+ energy: float = 3.0, angle_deg: float = 2.0, name: str = "Sun") -> tuple[Any, Vector]:
+ """A Sun lamp shining FROM compass ``azimuth_deg`` at ``elevation_deg``; returns
+ ``(lamp, towards_sun)`` — the unit vector zones can read as ``ctx.env["sun_direction"]``.
+ ``angle_deg`` is the disc's angular size (2° = soft natural shadow edges)."""
+ az, el = math.radians(azimuth_deg), math.radians(elevation_deg)
+ towards_sun = Vector((math.cos(el) * math.cos(az), math.cos(el) * math.sin(az), math.sin(el)))
+ lamp = bpy.data.lights.new(name, "SUN")
+ lamp.energy = float(energy)
+ lamp.color = _rgb(color)
+ lamp.angle = math.radians(angle_deg)
+ ob = bpy.data.objects.new(name, lamp)
+ ob.rotation_mode = "XYZ"
+ ob.rotation_euler = (-towards_sun).to_track_quat("-Z", "Y").to_euler()
+ collection.objects.link(ob)
+ return ob, towards_sun
+
+
+def area_light(collection: Any, name: str, loc: Sequence[float], color: str | Sequence[float], energy: float, *,
+ size: float = 5.0, target: Sequence[float] | None = None, shape: str = "DISK") -> Any:
+ """An area lamp of ``size`` m (``shape`` SQUARE / RECTANGLE / DISK / ELLIPSE) at ``loc``,
+ aimed at ``target`` (straight down when None): a ceiling panel, a sky fill, a window."""
+ lamp = bpy.data.lights.new(name, "AREA")
+ lamp.shape = shape
+ lamp.size = float(size)
+ if shape in ("RECTANGLE", "ELLIPSE"):
+ lamp.size_y = float(size) * 0.5
+ lamp.energy = float(energy)
+ lamp.color = _rgb(color)
+ ob = bpy.data.objects.new(name, lamp)
+ ob.location = tuple(float(v) for v in loc)
+ collection.objects.link(ob)
+ if target is not None:
+ aim(ob, target)
+ return ob
+
+
+def point_light(collection: Any, name: str, loc: Sequence[float], color: str | Sequence[float], energy: float, *,
+ radius: float = 0.05) -> Any:
+ """A point lamp; ``radius`` (m) softens its shadows (a bulb 0.05, a lantern 0.3)."""
+ lamp = bpy.data.lights.new(name, "POINT")
+ lamp.energy = float(energy)
+ lamp.color = _rgb(color)
+ lamp.shadow_soft_size = float(radius)
+ ob = bpy.data.objects.new(name, lamp)
+ ob.location = tuple(float(v) for v in loc)
+ collection.objects.link(ob)
+ return ob
+
+
+def spot(collection: Any, name: str, loc: Sequence[float], color: str | Sequence[float], energy: float, *,
+ size_deg: float = 45.0, blend: float = 0.3, target: Sequence[float] | None = None) -> Any:
+ """A spot lamp with a ``size_deg`` cone and ``blend`` soft edge, aimed at ``target``."""
+ lamp = bpy.data.lights.new(name, "SPOT")
+ lamp.energy = float(energy)
+ lamp.color = _rgb(color)
+ lamp.spot_size = math.radians(size_deg)
+ lamp.spot_blend = float(blend)
+ lamp.shadow_soft_size = 0.1
+ ob = bpy.data.objects.new(name, lamp)
+ ob.location = tuple(float(v) for v in loc)
+ collection.objects.link(ob)
+ if target is not None:
+ aim(ob, target)
+ return ob
+
+
+def practical(collection: Any, name: str, loc: Sequence[float], color: str | Sequence[float] = "FFB270", energy: float = 300.0, *,
+ size: float = 0.42, target: Sequence[float] | None = None) -> Any:
+ """The light a visible fixture throws (a lantern, a window, a brazier): a warm disc area lamp
+ of ``size`` m — pair it with an ``emissive`` skin on the fixture so the source reads.
+ ``energy`` is what the FRAME needs, not what the fixture looks like: measured on Blender 5.2.2
+ (the harness's Cycles/AgX settings, c3d-bpy-scene-lighting), two 45 W practicals leave a night
+ frame at mean luminance 0.05 (a dark_frame ERROR); ~300-500 W each at 2.5-3 m lights it."""
+ return area_light(collection, name, loc, color, energy, size=size, target=target, shape="DISK")
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/materials.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/materials.py
new file mode 100644
index 00000000..e28b0403
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/materials.py
@@ -0,0 +1,403 @@
+"""lib/materials.py — Principled materials without texture files (Blender 5.2 socket names).
+
+Colours are sRGB hex strings (``"8A6A3F"``) converted to linear here, or an already-linear
+(r, g, b) tuple. Procedural detail reads OBJECT texture coordinates, so a pattern keeps its
+metre scale whatever the object's size. Under Cycles + AgX at exposure 0 a non-emissive
+albedo belongs in 0.02-0.8 linear: pure black or pure white reads as a hole or a blown
+surface. Never ``use_nodes`` (deprecated in 5.x: every material has a node tree).
+"""
+
+from __future__ import annotations
+
+import colorsys
+from collections.abc import Sequence
+from typing import Any
+
+import bpy
+
+RGBA = tuple[float, float, float, float]
+
+
+def _srgb_to_linear(c: float) -> float:
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
+
+
+def rgba(hex_color: str, alpha: float = 1.0) -> RGBA:
+ """``"RRGGBB"`` (sRGB, optional ``#``) → linear (r, g, b, alpha) for a colour socket."""
+ h = hex_color.strip().lstrip("#")
+ if len(h) == 3:
+ h = "".join(ch * 2 for ch in h)
+ r, g, b = (int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
+ return (_srgb_to_linear(r), _srgb_to_linear(g), _srgb_to_linear(b), float(alpha))
+
+
+def _rgb(color: str | Sequence[float]) -> RGBA:
+ """A hex string or a linear (r, g, b[, a]) tuple as RGBA."""
+ if isinstance(color, str):
+ return rgba(color)
+ vals = [float(v) for v in color]
+ return (vals[0], vals[1], vals[2], vals[3] if len(vals) > 3 else 1.0)
+
+
+def _scaled(c: RGBA, k: float) -> RGBA:
+ return (min(1.0, c[0] * k), min(1.0, c[1] * k), min(1.0, c[2] * k), c[3])
+
+
+def _tree(mat: Any) -> tuple[Any, Any, Any, Any]:
+ nt = mat.node_tree
+ return nt, nt.nodes, nt.links, nt.nodes["Principled BSDF"]
+
+
+def _coords(nodes: Any, links: Any, scale: float = 1.0) -> Any:
+ """Object-space coordinates scaled by ``scale`` (features per metre): the vector socket."""
+ tc = nodes.new("ShaderNodeTexCoord")
+ mp = nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (scale, scale, scale)
+ links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ return mp.outputs["Vector"]
+
+
+def _noise(nodes: Any, links: Any, vector: Any, scale: float = 1.0, detail: float = 4.0, roughness: float = 0.5) -> Any:
+ n = nodes.new("ShaderNodeTexNoise")
+ n.inputs["Scale"].default_value = float(scale)
+ n.inputs["Detail"].default_value = float(detail)
+ n.inputs["Roughness"].default_value = float(roughness)
+ if vector is not None:
+ links.new(vector, n.inputs["Vector"])
+ return n
+
+
+def _mix(nodes: Any, links: Any, a: RGBA, b: RGBA, factor: Any) -> Any:
+ """``ShaderNodeMix`` (RGBA) between ``a`` and ``b`` driven by ``factor``: the colour output."""
+ m = nodes.new("ShaderNodeMix")
+ m.data_type = "RGBA"
+ m.inputs[6].default_value = a
+ m.inputs[7].default_value = b
+ links.new(factor, m.inputs[0])
+ return m.outputs[2]
+
+
+def _bump(nodes: Any, links: Any, height: Any, bsdf: Any, strength: float = 0.1, distance: float = 0.05) -> None:
+ b = nodes.new("ShaderNodeBump")
+ b.inputs["Strength"].default_value = float(strength)
+ b.inputs["Distance"].default_value = float(distance)
+ links.new(height, b.inputs["Height"])
+ links.new(b.outputs["Normal"], bsdf.inputs["Normal"])
+
+
+def _ramp(nodes: Any, links: Any, factor: Any, stops: Sequence[tuple[float, RGBA]], interpolation: str = "LINEAR") -> Any:
+ r = nodes.new("ShaderNodeValToRGB")
+ r.color_ramp.interpolation = interpolation
+ els = r.color_ramp.elements
+ els[0].position, els[0].color = stops[0]
+ els[1].position, els[1].color = stops[-1]
+ for pos, col in stops[1:-1]:
+ e = els.new(pos)
+ e.color = col
+ links.new(factor, r.inputs["Fac"])
+ return r.outputs["Color"]
+
+
+def material(name: str, color: str | Sequence[float], roughness: float = 0.5, metal: float = 0.0, *,
+ noise_scale: float = 0.0, bump: float = 0.08, emission: float = 0.0) -> Any:
+ """A Principled material. ``noise_scale`` > 0 (features per metre) adds a subtle colour
+ breakup and a bump of ``bump`` strength; ``emission`` > 0 makes it glow in its own colour."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ col = _rgb(color)
+ bsdf.inputs["Base Color"].default_value = col
+ bsdf.inputs["Roughness"].default_value = float(roughness)
+ bsdf.inputs["Metallic"].default_value = float(metal)
+ if emission > 0:
+ bsdf.inputs["Emission Color"].default_value = col
+ bsdf.inputs["Emission Strength"].default_value = float(emission)
+ if noise_scale > 0:
+ vec = _coords(nodes, links, 1.0)
+ n = _noise(nodes, links, vec, scale=noise_scale, detail=5.0, roughness=0.55)
+ links.new(_mix(nodes, links, _scaled(col, 0.82), _scaled(col, 1.12), n.outputs["Fac"]), bsdf.inputs["Base Color"])
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=bump, distance=0.04)
+ return mat
+
+
+def masonry(name: str, color: str | Sequence[float], mortar: str = "625D66", scale: float = 2.0) -> Any:
+ """Bricks in ``color`` with ``mortar`` joints, ``scale`` rows per metre (Brick texture on
+ object coordinates, so a wall of any size keeps brick-sized bricks)."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ col = _rgb(color)
+ br = nodes.new("ShaderNodeTexBrick")
+ br.inputs["Color1"].default_value = _scaled(col, 0.9)
+ br.inputs["Color2"].default_value = _scaled(col, 1.1)
+ br.inputs["Mortar"].default_value = _rgb(mortar)
+ br.inputs["Scale"].default_value = float(scale)
+ br.inputs["Mortar Size"].default_value = 0.025
+ br.inputs["Mortar Smooth"].default_value = 0.1
+ links.new(_coords(nodes, links, 1.0), br.inputs["Vector"])
+ links.new(br.outputs["Color"], bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.85
+ _bump(nodes, links, br.outputs["Fac"], bsdf, strength=0.35, distance=0.02)
+ return mat
+
+
+def limestone(name: str, color: str | Sequence[float], scale: float = 1.2) -> Any:
+ """Pale blotchy stone: noise colour breakup + a fine grain bump (``scale`` blotches / m)."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ col = _rgb(color)
+ vec = _coords(nodes, links, 1.0)
+ blotch = _noise(nodes, links, vec, scale=scale, detail=3.0, roughness=0.6)
+ grain = _noise(nodes, links, vec, scale=scale * 18.0, detail=6.0, roughness=0.7)
+ links.new(_mix(nodes, links, _scaled(col, 0.78), _scaled(col, 1.08), blotch.outputs["Fac"]), bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.8
+ _bump(nodes, links, grain.outputs["Fac"], bsdf, strength=0.12, distance=0.01)
+ return mat
+
+
+def ashlar(name: str, color: str | Sequence[float]) -> Any:
+ """Dressed stone blocks 1.2 x 0.4 m with thin joints."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ col = _rgb(color)
+ br = nodes.new("ShaderNodeTexBrick")
+ br.inputs["Color1"].default_value = _scaled(col, 0.92)
+ br.inputs["Color2"].default_value = _scaled(col, 1.06)
+ br.inputs["Mortar"].default_value = _scaled(col, 0.45)
+ br.inputs["Scale"].default_value = 1.0
+ br.inputs["Mortar Size"].default_value = 0.012
+ br.inputs["Brick Width"].default_value = 1.2
+ br.inputs["Row Height"].default_value = 0.4
+ links.new(_coords(nodes, links, 1.0), br.inputs["Vector"])
+ links.new(br.outputs["Color"], bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.75
+ _bump(nodes, links, br.outputs["Fac"], bsdf, strength=0.3, distance=0.015)
+ return mat
+
+
+def woodgrain(mat: Any, dark: str = "29190F", light: str = "805939", direction: Sequence[float] = (3, 0.1, 5)) -> Any:
+ """Give ``mat`` a stretched-noise grain between ``dark`` and ``light``; ``direction`` scales
+ the noise per axis (long along the grain, short across). Returns ``mat``."""
+ _, nodes, links, bsdf = _tree(mat)
+ tc = nodes.new("ShaderNodeTexCoord")
+ mp = nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = tuple(float(v) for v in direction)
+ links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ n = _noise(nodes, links, mp.outputs["Vector"], scale=4.0, detail=6.0, roughness=0.6)
+ ramp = _ramp(nodes, links, n.outputs["Fac"], [(0.35, _rgb(dark)), (0.65, _rgb(light))])
+ links.new(ramp, bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.6
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.15, distance=0.01)
+ return mat
+
+
+def chipped_paint(mat: Any, paint: str | Sequence[float], substrate: str | Sequence[float], scale: float = 6.0) -> Any:
+ """Paint in ``paint`` worn through to ``substrate`` in noisy patches (``scale`` patches / m)."""
+ _, nodes, links, bsdf = _tree(mat)
+ vec = _coords(nodes, links, 1.0)
+ n = _noise(nodes, links, vec, scale=scale, detail=4.0, roughness=0.65)
+ mask = _ramp(nodes, links, n.outputs["Fac"], [(0.42, (0, 0, 0, 1)), (0.5, (1, 1, 1, 1))])
+ m = nodes.new("ShaderNodeMix")
+ m.data_type = "RGBA"
+ m.inputs[6].default_value = _rgb(substrate)
+ m.inputs[7].default_value = _rgb(paint)
+ links.new(mask, m.inputs[0])
+ links.new(m.outputs[2], bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.5
+ _bump(nodes, links, mask, bsdf, strength=0.25, distance=0.003)
+ return mat
+
+
+def worn_alloy(name: str, color: str | Sequence[float], *, seed: int = 0, metal: float = 0.55) -> Any:
+ """Dull metal with streaky roughness; ``seed`` shifts the streak pattern."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ bsdf.inputs["Base Color"].default_value = _rgb(color)
+ bsdf.inputs["Metallic"].default_value = float(metal)
+ tc = nodes.new("ShaderNodeTexCoord")
+ mp = nodes.new("ShaderNodeMapping")
+ mp.inputs["Scale"].default_value = (1.0, 14.0, 1.0)
+ mp.inputs["Location"].default_value = (seed * 3.7, seed * 1.3, 0.0)
+ links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ n = _noise(nodes, links, mp.outputs["Vector"], scale=3.0, detail=5.0, roughness=0.6)
+ rough = _ramp(nodes, links, n.outputs["Fac"], [(0.3, (0.25, 0.25, 0.25, 1)), (0.7, (0.7, 0.7, 0.7, 1))])
+ links.new(rough, bsdf.inputs["Roughness"])
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.05, distance=0.003)
+ return mat
+
+
+def mineral_surface(name: str, color: str | Sequence[float], *, stone: bool = False) -> Any:
+ """Rock / soil in ``color``: mottled by noise; ``stone=True`` adds Voronoi crack lines."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ col = _rgb(color)
+ vec = _coords(nodes, links, 1.0)
+ n = _noise(nodes, links, vec, scale=2.5, detail=6.0, roughness=0.6)
+ base = _mix(nodes, links, _scaled(col, 0.7), _scaled(col, 1.15), n.outputs["Fac"])
+ if stone:
+ vor = nodes.new("ShaderNodeTexVoronoi")
+ vor.inputs["Scale"].default_value = 1.6
+ links.new(vec, vor.inputs["Vector"])
+ cracks = _ramp(nodes, links, vor.outputs["Distance"], [(0.0, (0.3, 0.3, 0.3, 1)), (0.08, (1, 1, 1, 1))])
+ m = nodes.new("ShaderNodeMix")
+ m.data_type = "RGBA"
+ m.blend_type = "MULTIPLY"
+ m.inputs[0].default_value = 1.0
+ links.new(base, m.inputs[6])
+ links.new(cracks, m.inputs[7])
+ base = m.outputs[2]
+ _bump(nodes, links, vor.outputs["Distance"], bsdf, strength=0.4, distance=0.02)
+ else:
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.2, distance=0.03)
+ links.new(base, bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.9
+ return mat
+
+
+def water(name: str, color: str = "163F4A", roughness: float = 0.12, scale: float = 0.8, *,
+ flow: Sequence[float] = (0.6, 0.2), ctx: Any = None) -> Any:
+ """A refracting water surface tinted ``color`` with rippled normals (``scale`` ripples / m);
+ with ``ctx`` the ripples drift ``flow`` m/s between ``ctx.times`` (keyframes on the mapping)."""
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ bsdf.inputs["Base Color"].default_value = _rgb(color)
+ bsdf.inputs["Roughness"].default_value = float(roughness)
+ bsdf.inputs["Transmission Weight"].default_value = 0.75
+ bsdf.inputs["IOR"].default_value = 1.33
+ bsdf.inputs["Coat Weight"].default_value = 0.3
+ tc = nodes.new("ShaderNodeTexCoord")
+ mp = nodes.new("ShaderNodeMapping")
+ mp.name = "FlowMapping"
+ links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ n = _noise(nodes, links, mp.outputs["Vector"], scale=scale, detail=6.0, roughness=0.55)
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.08, distance=0.05)
+ if ctx is not None:
+ from lib.motion import scroll
+
+ scroll(mp, (float(flow[0]), float(flow[1]), 0.0), ctx)
+ return mat
+
+
+def clear_water(name: str) -> Any:
+ """Shallow, almost colourless water (a basin, a fountain bowl, a stream)."""
+ mat = water(name, color="9CC8CF", roughness=0.05, scale=1.4)
+ mat.node_tree.nodes["Principled BSDF"].inputs["Transmission Weight"].default_value = 0.95
+ return mat
+
+
+def glass(name: str, color: str = "FFFFFF", roughness: float = 0.05, ior: float = 1.5) -> Any:
+ mat = bpy.data.materials.new(name)
+ _, _, _, bsdf = _tree(mat)
+ bsdf.inputs["Base Color"].default_value = _rgb(color)
+ bsdf.inputs["Roughness"].default_value = float(roughness)
+ bsdf.inputs["Transmission Weight"].default_value = 1.0
+ bsdf.inputs["IOR"].default_value = float(ior)
+ return mat
+
+
+def foliage(name: str, color: str | Sequence[float], variants: int = 3) -> list[Any]:
+ """``variants`` leaf materials around ``color`` (hue and lightness spread, the spread a
+ photograph carries): give neighbouring trees different ones."""
+ base = _rgb(color)
+ h, l_, s = colorsys.rgb_to_hls(*base[:3])
+ out = []
+ n = max(1, int(variants))
+ for i in range(n):
+ t = (i / (n - 1) - 0.5) if n > 1 else 0.0
+ r, g, b = colorsys.hls_to_rgb((h + 0.045 * t) % 1.0, max(0.02, min(0.8, l_ * (1.0 + 0.35 * t))), max(0.0, min(1.0, s * (1.0 + 0.2 * t))))
+ mat = bpy.data.materials.new(f"{name}_{i}")
+ _, nodes, links, bsdf = _tree(mat)
+ bsdf.inputs["Base Color"].default_value = (r, g, b, 1.0)
+ bsdf.inputs["Roughness"].default_value = 0.6
+ bsdf.inputs["Specular IOR Level"].default_value = 0.3
+ n_ = _noise(nodes, links, _coords(nodes, links, 1.0), scale=30.0, detail=2.0, roughness=0.5)
+ links.new(_mix(nodes, links, (r * 0.75, g * 0.75, b * 0.75, 1.0), (min(1.0, r * 1.2), min(1.0, g * 1.2), min(1.0, b * 1.2), 1.0),
+ n_.outputs["Fac"]), bsdf.inputs["Base Color"])
+ out.append(mat)
+ return out
+
+
+def snow(name: str = "Snow") -> Any:
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ bsdf.inputs["Base Color"].default_value = (0.86, 0.88, 0.92, 1.0)
+ bsdf.inputs["Roughness"].default_value = 0.55
+ bsdf.inputs["Subsurface Weight"].default_value = 0.2
+ bsdf.inputs["Subsurface Radius"].default_value = (0.3, 0.3, 0.35)
+ n = _noise(nodes, links, _coords(nodes, links, 1.0), scale=25.0, detail=5.0, roughness=0.6)
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.1, distance=0.01)
+ return mat
+
+
+def ice(name: str = "Ice") -> Any:
+ mat = bpy.data.materials.new(name)
+ _, nodes, links, bsdf = _tree(mat)
+ bsdf.inputs["Base Color"].default_value = (0.8, 0.9, 0.97, 1.0)
+ bsdf.inputs["Roughness"].default_value = 0.18
+ bsdf.inputs["Transmission Weight"].default_value = 0.8
+ bsdf.inputs["IOR"].default_value = 1.31
+ n = _noise(nodes, links, _coords(nodes, links, 1.0), scale=3.0, detail=7.0, roughness=0.7)
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.3, distance=0.02)
+ return mat
+
+
+def emissive(name: str, color: str | Sequence[float], strength: float) -> Any:
+ """A light-giving skin (a lantern paper, a sign, a window pane): ``strength`` 3-8 READS as a lit
+ fixture, 20+ as sun-bright — but it does not light a frame: measured on Blender 5.2.2 two
+ fixture-sized emitters at strength 5-80 left a night frame at mean luminance 0.03-0.05
+ (dark_frame). Pair every emissive fixture with ``lighting.practical`` for the light itself."""
+ mat = bpy.data.materials.new(name)
+ _, _, _, bsdf = _tree(mat)
+ col = _rgb(color)
+ bsdf.inputs["Base Color"].default_value = (0.02, 0.02, 0.02, 1.0)
+ bsdf.inputs["Emission Color"].default_value = col
+ bsdf.inputs["Emission Strength"].default_value = float(strength)
+ return mat
+
+
+def volume(name: str, color: str | Sequence[float], density: float = 0.4, *, anisotropy: float = 0.3,
+ noise_scale: float = 0.0, emission: float = 0.0) -> Any:
+ """A Principled VOLUME with no surface: the only soft steam, smoke, dust, mist or spark haze
+ Cycles can draw. A sphere wearing it renders as a puff with no silhouette — a translucent
+ Principled BSDF skin, a metaball or a disc always has one (``hard_edged_particles``, 8 of 30
+ argon Blender scenes on 2026-10-15). Measured on Blender 5.2.2: 40 subdivision-3 puffs add
+ 0.7 s to a 32-spp GPU frame. ``density`` per metre — 0.15-0.35 steam and dust, 0.5-0.8 smoke;
+ ``noise_scale`` features / m breaks a plume up (3-6); ``emission`` > 0 lights sparks or a haze
+ from inside. A volume is lit like everything else: white steam under a dim world comes out
+ grey, so raise the world or give it ``emission`` 0.2-0.5."""
+ mat = bpy.data.materials.new(name)
+ nt = mat.node_tree
+ nodes, links = nt.nodes, nt.links
+ out = nodes["Material Output"]
+ for n in [n for n in nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"]:
+ nodes.remove(n)
+ vol = nodes.new("ShaderNodeVolumePrincipled")
+ col = _rgb(color)
+ vol.inputs["Color"].default_value = col
+ vol.inputs["Density"].default_value = float(density)
+ vol.inputs["Anisotropy"].default_value = float(anisotropy)
+ if emission > 0:
+ vol.inputs["Emission Color"].default_value = col
+ vol.inputs["Emission Strength"].default_value = float(emission)
+ if noise_scale > 0:
+ n = _noise(nodes, links, _coords(nodes, links, 1.0), scale=float(noise_scale), detail=4.0, roughness=0.6)
+ mul = nodes.new("ShaderNodeMath")
+ mul.operation = "MULTIPLY"
+ mul.inputs[1].default_value = float(density) * 2.0
+ links.new(n.outputs["Fac"], mul.inputs[0])
+ links.new(mul.outputs[0], vol.inputs["Density"])
+ links.new(vol.outputs["Volume"], out.inputs["Volume"])
+ return mat
+
+
+def tint(mat: Any, variant: float) -> Any:
+ """A copy of ``mat`` whose base colour is shifted by ``variant`` (-1..1: darker / lighter
+ and a touch of hue) — a crowd's coats, a street's shutters."""
+ out = mat.copy()
+ out.name = f"{mat.name}_v{variant:+.2f}"
+ bsdf = out.node_tree.nodes.get("Principled BSDF")
+ if bsdf is None or bsdf.inputs["Base Color"].is_linked:
+ return out
+ r, g, b, a = bsdf.inputs["Base Color"].default_value
+ h, l_, s = colorsys.rgb_to_hls(r, g, b)
+ r, g, b = colorsys.hls_to_rgb((h + 0.03 * variant) % 1.0, max(0.02, min(0.85, l_ * (1.0 + 0.3 * variant))), s)
+ bsdf.inputs["Base Color"].default_value = (r, g, b, a)
+ return out
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/mesh.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/mesh.py
new file mode 100644
index 00000000..e30ff2fe
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/mesh.py
@@ -0,0 +1,339 @@
+"""lib/mesh.py — a Batch of geometry → a few mesh objects under ONE root.
+
+Why a Batch: the placement census is per OBJECT and Cycles syncs per object — a prop built as
+sixty bpy primitives is sixty placement rows and sixty objects, a prop built as one Batch is
+ONE row (its root Empty) and one mesh per material. Nothing here touches ``bpy.ops``: vertices
+and faces stay plain lists until ``finish`` writes them with ``from_pydata``.
+
+Frame: Z up, -Y front, metres. Primitive ``loc`` is the CENTRE (``cone`` / ``lathe``: the base
+on the axis); every finished object gets its origin at its base centre, so ``place.seat`` and
+``place.face_toward`` act about the foot of the prop.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+import bmesh
+import bpy
+from mathutils import Matrix, Vector
+
+Vec3 = tuple[float, float, float]
+_SPHERES: dict[int, tuple[list[Vec3], list[tuple[int, ...]]]] = {}
+
+
+def sphere_template(level: int) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ """A unit icosphere's (vertices, triangles): level 1 = 20 faces, 2 = 80, 3 = 320, 4 = 1280
+ (cached; copy before mutating)."""
+ level = max(1, min(5, int(level)))
+ if level not in _SPHERES:
+ bm = bmesh.new()
+ bmesh.ops.create_icosphere(bm, subdivisions=level, radius=1.0)
+ bm.verts.ensure_lookup_table()
+ bm.faces.ensure_lookup_table()
+ verts = [(v.co.x, v.co.y, v.co.z) for v in bm.verts]
+ faces = [tuple(v.index for v in f.verts) for f in bm.faces]
+ bm.free()
+ _SPHERES[level] = (verts, faces)
+ return _SPHERES[level]
+
+
+def _axes(d: Vector) -> tuple[Vector, Vector]:
+ """Two unit vectors orthogonal to ``d`` (right-handed with it)."""
+ d = d.normalized()
+ helper = Vector((0.0, 0.0, 1.0)) if abs(d.z) < 0.9 else Vector((1.0, 0.0, 0.0))
+ u = d.cross(helper).normalized()
+ return u, d.cross(u).normalized()
+
+
+def _ring(center: Vector, u: Vector, v: Vector, radius: float, sides: int, phase: float = 0.0) -> list[Vec3]:
+ out = []
+ for j in range(sides):
+ a = phase + math.tau * j / sides
+ p = center + u * (radius * math.cos(a)) + v * (radius * math.sin(a))
+ out.append((p.x, p.y, p.z))
+ return out
+
+
+def _band(a: int, b: int, sides: int) -> list[tuple[int, ...]]:
+ """Quads between ring ``a`` and ring ``b`` (vertex offsets), outward for CCW rings."""
+ return [(a + j, a + (j + 1) % sides, b + (j + 1) % sides, b + j) for j in range(sides)]
+
+
+def box_geometry(loc: Sequence[float], size: float | Sequence[float], rotation: float = 0.0) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ """A box centred at ``loc`` (yaw ``rotation`` radians about Z); 8 vertices, 6 quads."""
+ sx, sy, sz = (size, size, size) if isinstance(size, (int, float)) else size
+ hx, hy, hz = sx / 2, sy / 2, sz / 2
+ c, s = math.cos(rotation), math.sin(rotation)
+ verts = []
+ for x, y, z in ((-hx, -hy, -hz), (hx, -hy, -hz), (hx, hy, -hz), (-hx, hy, -hz),
+ (-hx, -hy, hz), (hx, -hy, hz), (hx, hy, hz), (-hx, hy, hz)):
+ verts.append((loc[0] + x * c - y * s, loc[1] + x * s + y * c, loc[2] + z))
+ faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
+ return verts, faces
+
+
+def lathe_geometry(xy: Sequence[float], profile: Sequence[Sequence[float]], sides: int = 32,
+ phase: float = 0.0) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ """``profile`` = [(radius, z), ...] revolved about the vertical axis through ``xy``; a radius
+ of 0 collapses to a point, an open end is capped."""
+ sides = max(3, int(sides))
+ verts: list[Vec3] = []
+ faces: list[tuple[int, ...]] = []
+ starts: list[int | None] = [] # ring start index, or the apex vertex index when r == 0
+ apex: list[bool] = []
+ for r, z in profile:
+ if r <= 1e-6:
+ starts.append(len(verts))
+ apex.append(True)
+ verts.append((float(xy[0]), float(xy[1]), float(z)))
+ else:
+ starts.append(len(verts))
+ apex.append(False)
+ verts.extend(_ring(Vector((xy[0], xy[1], z)), Vector((1, 0, 0)), Vector((0, 1, 0)), float(r), sides, phase))
+ for i in range(len(profile) - 1):
+ a, b = starts[i], starts[i + 1]
+ if apex[i] and apex[i + 1]:
+ continue
+ if apex[i]:
+ faces.extend((a, b + (j + 1) % sides, b + j) for j in range(sides))
+ elif apex[i + 1]:
+ faces.extend((a + j, a + (j + 1) % sides, b) for j in range(sides))
+ else:
+ faces.extend(_band(a, b, sides))
+ if not apex[0]:
+ faces.append(tuple(starts[0] + j for j in reversed(range(sides))))
+ if not apex[-1]:
+ faces.append(tuple(starts[-1] + j for j in range(sides)))
+ return verts, faces
+
+
+def beam_geometry(a: Sequence[float], b: Sequence[float], radius: float, end: float | None = None,
+ sides: int = 8) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ """A capped cylinder from ``a`` to ``b`` (radius ``end`` at ``b`` for a taper)."""
+ sides = max(3, int(sides))
+ pa, pb = Vector(a), Vector(b)
+ d = pb - pa
+ if d.length < 1e-6:
+ d = Vector((0, 0, 1e-3))
+ u, v = _axes(d)
+ verts = _ring(pa, u, v, radius, sides) + _ring(pb, u, v, radius if end is None else end, sides)
+ faces = _band(0, sides, sides)
+ faces.append(tuple(reversed(range(sides))))
+ faces.append(tuple(range(sides, 2 * sides)))
+ return verts, faces
+
+
+def torus_geometry(loc: Sequence[float], radius: float, tube: float, major: int = 64, minor: int = 8,
+ axis: Sequence[float] = (0.0, 0.0, 1.0)) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ """A torus centred at ``loc`` with its hole along ``axis``."""
+ major, minor = max(3, int(major)), max(3, int(minor))
+ rot = Vector((0.0, 0.0, 1.0)).rotation_difference(Vector(axis).normalized()).to_matrix()
+ centre = Vector(loc)
+ verts: list[Vec3] = []
+ for i in range(major):
+ a = math.tau * i / major
+ ring_c = Vector((radius * math.cos(a), radius * math.sin(a), 0.0))
+ radial = Vector((math.cos(a), math.sin(a), 0.0))
+ for j in range(minor):
+ t = math.tau * j / minor
+ p = ring_c + radial * (tube * math.cos(t)) + Vector((0.0, 0.0, tube * math.sin(t)))
+ p = centre + rot @ p
+ verts.append((p.x, p.y, p.z))
+ faces = []
+ for i in range(major):
+ i2 = (i + 1) % major
+ for j in range(minor):
+ j2 = (j + 1) % minor
+ faces.append((i * minor + j, i2 * minor + j, i2 * minor + j2, i * minor + j2))
+ return verts, faces
+
+
+def sphere_geometry(loc: Sequence[float], scale: float | Sequence[float], subdivision: int = 1) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ sx, sy, sz = (scale, scale, scale) if isinstance(scale, (int, float)) else scale
+ verts, faces = sphere_template(subdivision)
+ return [(loc[0] + x * sx, loc[1] + y * sy, loc[2] + z * sz) for x, y, z in verts], list(faces)
+
+
+class _Part:
+ __slots__ = ("faces", "material", "smooth", "verts")
+
+ def __init__(self, material: Any) -> None:
+ self.material = material
+ self.verts: list[Vec3] = []
+ self.faces: list[tuple[int, ...]] = []
+ self.smooth: list[bool] = []
+
+
+class Batch:
+ """Geometry accumulated per material; ``finish`` writes the objects.
+
+ ``Batch("Oak_3")`` then ``b.box(...)``, ``b.beam(...)`` …; ``b.transformed(matrix)`` is a view
+ that transforms what is added through it (a figure facing ``heading``, a lantern hung at an
+ angle); ``b.finish(ctx.collection)`` returns ``[root, mesh, …]`` — the root is the placement
+ row and the thing to ``place.seat`` / tag ``root["placement"] = "free"``.
+ """
+
+ def __init__(self, name: str) -> None:
+ self.name = str(name)
+ self._parts: dict[str, _Part] = {}
+ self._matrix: Matrix | None = None
+ self._root: Batch = self
+
+ # ------------------------------------------------------------------ accumulation
+ def add(self, mat: Any, vertices: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], smooth: bool | Sequence[bool] = False) -> int:
+ """Append raw geometry under material ``mat``; returns the part's vertex count before."""
+ key = mat.name if mat is not None else ""
+ part = self._root._parts.get(key)
+ if part is None:
+ part = self._root._parts[key] = _Part(mat)
+ base = len(part.verts)
+ if self._matrix is not None:
+ m = self._matrix
+ part.verts.extend(tuple(m @ Vector(v)) for v in vertices)
+ else:
+ part.verts.extend((float(v[0]), float(v[1]), float(v[2])) for v in vertices)
+ part.faces.extend(tuple(int(i) + base for i in f) for f in faces)
+ if isinstance(smooth, bool):
+ part.smooth.extend([smooth] * len(faces))
+ else:
+ flags = list(smooth)
+ part.smooth.extend(bool(flags[i]) if i < len(flags) else False for i in range(len(faces)))
+ return base
+
+ def transformed(self, matrix: Matrix | Sequence[Sequence[float]]) -> Batch:
+ """A view of this batch whose additions are transformed by ``matrix`` first."""
+ view = Batch.__new__(Batch)
+ view.name = self.name
+ view._parts = self._root._parts
+ view._root = self._root
+ m = Matrix(matrix)
+ view._matrix = (self._matrix @ m) if self._matrix is not None else m
+ return view
+
+ def box(self, mat: Any, loc: Sequence[float], size: float | Sequence[float], rotation: float = 0.0) -> None:
+ self.add(mat, *box_geometry(loc, size, rotation))
+
+ def sphere(self, mat: Any, loc: Sequence[float], scale: float | Sequence[float], subdivision: int = 1) -> None:
+ self.add(mat, *sphere_geometry(loc, scale, subdivision), smooth=True)
+
+ def lathe(self, mat: Any, xy: Sequence[float], profile: Sequence[Sequence[float]], sides: int = 32, phase: float = 0.0) -> None:
+ self.add(mat, *lathe_geometry(xy, profile, sides, phase), smooth=True)
+
+ def cone(self, mat: Any, loc: Sequence[float], radius: float, height: float, top: float = 0.0, sides: int = 24) -> None:
+ """A cone / frustum standing on its base centre ``loc``."""
+ self.lathe(mat, (loc[0], loc[1]), [(radius, loc[2]), (top, loc[2] + height)], sides)
+
+ def beam(self, mat: Any, a: Sequence[float], b: Sequence[float], radius: float, end: float | None = None, sides: int = 8) -> None:
+ self.add(mat, *beam_geometry(a, b, radius, end, sides), smooth=sides >= 12)
+
+ def torus(self, mat: Any, loc: Sequence[float], radius: float, tube: float, major: int = 64, minor: int = 8) -> None:
+ self.add(mat, *torus_geometry(loc, radius, tube, major, minor), smooth=True)
+
+ def ring(self, mat: Any, center: Sequence[float], normal: Sequence[float], radius: float, tube: float, segments: int = 96) -> None:
+ """A hoop of radius ``radius`` whose axis is ``normal`` (an arch rib, a wheel rim)."""
+ self.add(mat, *torus_geometry(center, radius, tube, segments, 8, axis=normal), smooth=True)
+
+ # ------------------------------------------------------------------ output
+ def bounds(self) -> tuple[Vector, Vector] | None:
+ lo = Vector((math.inf, math.inf, math.inf))
+ hi = Vector((-math.inf, -math.inf, -math.inf))
+ seen = False
+ for part in self._root._parts.values():
+ for x, y, z in part.verts:
+ seen = True
+ lo.x, lo.y, lo.z = min(lo.x, x), min(lo.y, y), min(lo.z, z)
+ hi.x, hi.y, hi.z = max(hi.x, x), max(hi.y, y), max(hi.z, z)
+ return (lo, hi) if seen else None
+
+ def finish(self, collection: Any, *, bevel: float = 0.0, parent: bool = True, name_prefix: str = "") -> list[Any]:
+ """Write one mesh object per material into ``collection``: under ONE root Empty named
+ after the batch (``parent=True``, the default — one placement row however many
+ materials), else the meshes alone. Every object's origin is the batch's base centre.
+ ``bevel`` > 0 adds a Bevel modifier (angle-limited) to each mesh."""
+ parts = [p for p in self._root._parts.values() if p.faces]
+ if not parts:
+ return []
+ lo, hi = self.bounds() # type: ignore[misc]
+ origin = Vector(((lo.x + hi.x) / 2, (lo.y + hi.y) / 2, lo.z))
+ base_name = f"{name_prefix}{self.name}"
+ out: list[Any] = []
+ root = None
+ if parent:
+ root = bpy.data.objects.new(base_name, None)
+ root.empty_display_size = 0.25
+ root.location = origin
+ collection.objects.link(root)
+ out.append(root)
+ for part in parts:
+ mat_tag = part.material.name.replace(" ", "") if part.material is not None else "Mesh"
+ name = f"{base_name}_{mat_tag}" if (parent or len(parts) > 1) else base_name
+ me = bpy.data.meshes.new(name)
+ me.from_pydata([(x - origin.x, y - origin.y, z - origin.z) for x, y, z in part.verts], [], part.faces)
+ me.update()
+ if len(me.polygons) == len(part.smooth):
+ me.polygons.foreach_set("use_smooth", part.smooth)
+ if part.material is not None:
+ me.materials.append(part.material)
+ ob = bpy.data.objects.new(name, me)
+ if root is not None:
+ ob.parent = root
+ else:
+ ob.location = origin
+ collection.objects.link(ob)
+ if bevel > 0:
+ mod = ob.modifiers.new("Bevel", "BEVEL")
+ mod.width = float(bevel)
+ mod.segments = 2
+ mod.limit_method = "ANGLE"
+ mod.angle_limit = math.radians(40.0)
+ out.append(ob)
+ return out
+
+
+def mesh_object(name: str, vertices: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], mat: Any, collection: Any,
+ *, smooth: bool = False) -> Any:
+ """One mesh object from raw lists, linked into ``collection`` (origin at the world origin)."""
+ me = bpy.data.meshes.new(name)
+ me.from_pydata([tuple(float(c) for c in v) for v in vertices], [], [tuple(int(i) for i in f) for f in faces])
+ me.update()
+ if smooth:
+ me.shade_smooth()
+ if mat is not None:
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ collection.objects.link(ob)
+ return ob
+
+
+def curve_object(name: str, points: Sequence[Sequence[float]], radius: float, mat: Any, collection: Any,
+ *, cyclic: bool = False) -> Any:
+ """A tube along ``points`` (a POLY spline with a round bevel) — a rope, a cable, a vine."""
+ cu = bpy.data.curves.new(name, "CURVE")
+ cu.dimensions = "3D"
+ cu.bevel_depth = float(radius)
+ cu.bevel_resolution = 3
+ cu.use_fill_caps = True
+ sp = cu.splines.new("POLY")
+ sp.points.add(len(points) - 1)
+ for i, p in enumerate(points):
+ sp.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)
+ sp.use_cyclic_u = bool(cyclic)
+ if mat is not None:
+ cu.materials.append(mat)
+ ob = bpy.data.objects.new(name, cu)
+ collection.objects.link(ob)
+ return ob
+
+
+def parent_under(objects: Sequence[Any], collection: Any, name: str) -> Any:
+ """An Empty named ``name`` in ``collection`` that becomes the parent of ``objects`` (their
+ world poses kept): several objects as ONE placement row."""
+ root = bpy.data.objects.new(name, None)
+ root.empty_display_size = 0.25
+ collection.objects.link(root)
+ for ob in objects:
+ ob.parent = root
+ return root
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/motion.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/motion.py
new file mode 100644
index 00000000..63591ec0
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/motion.py
@@ -0,0 +1,121 @@
+"""lib/motion.py — animation as DATA: keyframes on ``ctx.frame(t)`` and simple drivers.
+
+The harness samples frame ``ctx.frame(t)`` for every ``t`` in ``ctx.times`` (0 and 1.5 s at 30
+fps = frames 1 and 46) and reads the result off the saved .blend: nothing here runs Python at
+render time. A driver expression must be in Blender's simple-expression subset (``frame``,
+``sin`` / ``cos`` / ``min`` / ``max`` / ``clamp``, + - * /) — a Python driver evaluates to 0
+under ``--factory-startup`` and fails the build census. Actions are slotted in 5.2: the
+f-curves live in ``action.layers[0].strips[0].channelbag(slot)``.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+_AXES = {"X": 0, "Y": 1, "Z": 2}
+
+
+def _frames(ctx: Any, t0: float | None = None, t1: float | None = None) -> tuple[int, int]:
+ times = tuple(ctx.times) if ctx is not None else (0.0, 1.5)
+ a = float(times[0] if t0 is None else t0)
+ b = float(times[-1] if t1 is None else t1)
+ return ctx.frame(a), ctx.frame(b)
+
+
+def fcurves(id_data: Any) -> list[Any]:
+ """Every f-curve animating ``id_data`` (an object, a node tree, a shape key block)."""
+ ad = getattr(id_data, "animation_data", None)
+ act = ad.action if ad is not None else None
+ if act is None:
+ return []
+ out: list[Any] = []
+ for layer in act.layers:
+ for strip in layer.strips:
+ bag = strip.channelbag(ad.action_slot)
+ if bag is not None:
+ out.extend(bag.fcurves)
+ return out
+
+
+def set_interpolation(id_data: Any, interpolation: str = "LINEAR") -> None:
+ """``LINEAR`` / ``BEZIER`` / ``CONSTANT`` on every keyframe of ``id_data``."""
+ for fc in fcurves(id_data):
+ for kp in fc.keyframe_points:
+ kp.interpolation = interpolation
+
+
+def keyframe_path(obj: Any, points: Sequence[Sequence[float]], ctx: Any, *, t0: float = 0.0, t1: float | None = None,
+ interpolation: str = "LINEAR") -> None:
+ """Move ``obj`` through ``points`` (world positions of its origin) evenly between ``t0`` and
+ ``t1`` (default: the last of ``ctx.times``)."""
+ f0, f1 = _frames(ctx, t0, t1)
+ n = len(points)
+ for i, p in enumerate(points):
+ frame = f0 if n == 1 else round(f0 + (f1 - f0) * i / (n - 1))
+ obj.location = (float(p[0]), float(p[1]), float(p[2]))
+ obj.keyframe_insert("location", frame=frame)
+ obj.location = (float(points[0][0]), float(points[0][1]), float(points[0][2]))
+ set_interpolation(obj, interpolation)
+
+
+def drift(obj: Any, delta: Sequence[float], ctx: Any) -> None:
+ """Translate ``obj`` by ``delta`` (m) over ``ctx.times``: a drifting boat, a rising balloon,
+ a falling leaf — linear."""
+ start = (float(obj.location[0]), float(obj.location[1]), float(obj.location[2]))
+ end = (start[0] + float(delta[0]), start[1] + float(delta[1]), start[2] + float(delta[2]))
+ keyframe_path(obj, [start, end], ctx)
+
+
+def spin(obj: Any, axis: str = "Z", turns_per_s: float = 0.25, ctx: Any = None) -> None:
+ """Rotate ``obj`` about its ``axis`` forever: a simple driver ``frame * k`` (a windmill, a
+ waterwheel, a weather vane). Positive = counter-clockwise seen from +axis."""
+ fps = float(ctx.fps) if ctx is not None else 30.0
+ k = math.tau * float(turns_per_s) / fps
+ obj.rotation_mode = "XYZ"
+ fc = obj.driver_add("rotation_euler", _AXES[axis.upper()])
+ fc.driver.type = "SCRIPTED"
+ fc.driver.expression = f"frame*{k:.6f}"
+
+
+def sway(obj: Any, axis: str, amplitude: float, period_s: float, ctx: Any) -> None:
+ """Rock ``obj`` ± ``amplitude`` radians about ``axis`` with period ``period_s``: a simple
+ driver ``sin(frame * w) * a`` around the current rotation (a hanging lantern, a mast)."""
+ fps = float(ctx.fps) if ctx is not None else 30.0
+ w = math.tau / (max(0.05, float(period_s)) * fps)
+ i = _AXES[axis.upper()]
+ obj.rotation_mode = "XYZ"
+ base = float(obj.rotation_euler[i])
+ fc = obj.driver_add("rotation_euler", i)
+ fc.driver.type = "SCRIPTED"
+ fc.driver.expression = f"{base:.6f}+sin(frame*{w:.6f})*{float(amplitude):.6f}"
+
+
+def scroll(mapping_node: Any, velocity: Sequence[float], ctx: Any) -> None:
+ """Slide a Mapping node's Location by ``velocity`` (texture units per second) over
+ ``ctx.times``: moving water, drifting clouds, a flowing aurora — keyframes on the node
+ tree, linear."""
+ f0, f1 = _frames(ctx)
+ t0, t1 = float(ctx.times[0]), float(ctx.times[-1])
+ sock = mapping_node.inputs["Location"]
+ start = tuple(float(v) for v in sock.default_value)
+ sock.keyframe_insert("default_value", frame=f0)
+ sock.default_value = tuple(start[k] + float(velocity[k]) * (t1 - t0) for k in range(3))
+ sock.keyframe_insert("default_value", frame=f1)
+ sock.default_value = start
+ set_interpolation(mapping_node.id_data, "LINEAR")
+
+
+def shape_key_sweep(obj: Any, key_name: str, ctx: Any, *, from_value: float = 0.0, to_value: float = 1.0) -> None:
+ """Drive shape key ``key_name`` of ``obj`` from ``from_value`` to ``to_value`` over
+ ``ctx.times`` (a sail filling, a flower opening) — linear keyframes on the key block."""
+ f0, f1 = _frames(ctx)
+ keys = obj.data.shape_keys
+ key = keys.key_blocks[key_name]
+ key.value = float(from_value)
+ key.keyframe_insert("value", frame=f0)
+ key.value = float(to_value)
+ key.keyframe_insert("value", frame=f1)
+ key.value = float(from_value)
+ set_interpolation(keys, "LINEAR")
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/noise.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/noise.py
new file mode 100644
index 00000000..9fe54877
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/noise.py
@@ -0,0 +1,145 @@
+"""lib/noise.py — seeded noise on the CPU: hills, scatter masks, jitter. Pure python.
+
+Deterministic in (coordinates, seed) on every machine, so a zone can seat on the env's
+``height_at`` without reading the terrain mesh back. Gradient (Perlin) noise on a hashed
+lattice: ``fbm2`` / ``fbm3`` return about -1..1, ``ridged`` 0..1. Cost: a 96 x 96 height
+field with four octaves is ~60 ms — fine for the env's ground, too slow for a per-blade
+query (use ``hash01`` for that).
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from collections.abc import Callable, Sequence
+
+_MASK = 0xFFFFFFFF
+#: the twelve Perlin gradient directions (edge midpoints of a cube)
+_GRAD3: tuple[tuple[float, float, float], ...] = (
+ (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0), (1, 0, 1), (-1, 0, 1),
+ (1, 0, -1), (-1, 0, -1), (0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1),
+)
+
+
+def rng(seed: int = 0) -> random.Random:
+ """THE seeded generator (``ctx.rng(seed)`` is the same object): never module-level random."""
+ return random.Random(seed)
+
+
+def hash01(i: int, seed: int = 0) -> float:
+ """A uniform [0, 1) value from an integer and a seed — the lattice hash, also the cheapest
+ per-item jitter (``hash01(index, seed)`` costs nothing and never drifts between runs)."""
+ x = (int(i) * 0x27D4EB2D + int(seed) * 0x165667B1 + 0x9E3779B9) & _MASK
+ x = ((x ^ (x >> 15)) * 0x2C1B3C6D) & _MASK
+ x = ((x ^ (x >> 12)) * 0x297A2D39) & _MASK
+ return (x ^ (x >> 15)) / 4294967296.0
+
+
+def _lattice(ix: int, iy: int, iz: int = 0) -> int:
+ return (ix * 1619 + iy * 31337 + iz * 6971) & _MASK
+
+
+def _fade(t: float) -> float:
+ return t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
+
+
+def _grad2(ix: int, iy: int, seed: int, fx: float, fy: float) -> float:
+ a = hash01(_lattice(ix, iy), seed) * math.tau
+ return math.cos(a) * fx + math.sin(a) * fy
+
+
+def _grad3(ix: int, iy: int, iz: int, seed: int, fx: float, fy: float, fz: float) -> float:
+ g = _GRAD3[int(hash01(_lattice(ix, iy, iz), seed) * 12.0) % 12]
+ return g[0] * fx + g[1] * fy + g[2] * fz
+
+
+def noise2(x: float, y: float, seed: int = 0) -> float:
+ """One octave of 2-D gradient noise, about -1..1, period-free."""
+ x0, y0 = math.floor(x), math.floor(y)
+ fx, fy = x - x0, y - y0
+ u, v = _fade(fx), _fade(fy)
+ n00 = _grad2(x0, y0, seed, fx, fy)
+ n10 = _grad2(x0 + 1, y0, seed, fx - 1.0, fy)
+ n01 = _grad2(x0, y0 + 1, seed, fx, fy - 1.0)
+ n11 = _grad2(x0 + 1, y0 + 1, seed, fx - 1.0, fy - 1.0)
+ nx0 = n00 + u * (n10 - n00)
+ nx1 = n01 + u * (n11 - n01)
+ return max(-1.0, min(1.0, (nx0 + v * (nx1 - nx0)) * 1.4142))
+
+
+def noise3(x: float, y: float, z: float, seed: int = 0) -> float:
+ """One octave of 3-D gradient noise, about -1..1 (boulder displacement, cloud density)."""
+ x0, y0, z0 = math.floor(x), math.floor(y), math.floor(z)
+ fx, fy, fz = x - x0, y - y0, z - z0
+ u, v, w = _fade(fx), _fade(fy), _fade(fz)
+
+ def corner(dx: int, dy: int, dz: int) -> float:
+ return _grad3(x0 + dx, y0 + dy, z0 + dz, seed, fx - dx, fy - dy, fz - dz)
+
+ x00 = corner(0, 0, 0) + u * (corner(1, 0, 0) - corner(0, 0, 0))
+ x10 = corner(0, 1, 0) + u * (corner(1, 1, 0) - corner(0, 1, 0))
+ x01 = corner(0, 0, 1) + u * (corner(1, 0, 1) - corner(0, 0, 1))
+ x11 = corner(0, 1, 1) + u * (corner(1, 1, 1) - corner(0, 1, 1))
+ y0v = x00 + v * (x10 - x00)
+ y1v = x01 + v * (x11 - x01)
+ return max(-1.0, min(1.0, (y0v + w * (y1v - y0v)) * 1.15))
+
+
+def fbm2(x: float, y: float, *, octaves: int = 4, lacunarity: float = 2.0, gain: float = 0.5,
+ seed: int = 0) -> float:
+ """Fractal sum of ``octaves`` gradient octaves, normalised to about -1..1. Feature size is
+ 1 unit: call with ``x / scale_m``."""
+ total, amp, freq, norm = 0.0, 1.0, 1.0, 0.0
+ for o in range(max(1, int(octaves))):
+ total += amp * noise2(x * freq + o * 17.31, y * freq - o * 11.07, seed + o)
+ norm += amp
+ amp *= gain
+ freq *= lacunarity
+ return total / norm
+
+
+def fbm3(x: float, y: float, z: float, *, octaves: int = 4, lacunarity: float = 2.0, gain: float = 0.5,
+ seed: int = 0) -> float:
+ """``fbm2`` in three dimensions (about -1..1)."""
+ total, amp, freq, norm = 0.0, 1.0, 1.0, 0.0
+ for o in range(max(1, int(octaves))):
+ total += amp * noise3(x * freq + o * 5.17, y * freq - o * 3.71, z * freq + o * 7.03, seed + o)
+ norm += amp
+ amp *= gain
+ freq *= lacunarity
+ return total / norm
+
+
+def ridged(x: float, y: float, *, seed: int = 0, octaves: int = 5) -> float:
+ """Ridged multifractal, 0..1: sharp crests and rounded valleys (mountains, dune crests)."""
+ total, amp, freq, norm, weight = 0.0, 1.0, 1.0, 0.0, 1.0
+ for o in range(max(1, int(octaves))):
+ n = 1.0 - abs(noise2(x * freq + o * 13.7, y * freq + o * 9.1, seed + o))
+ n = n * n * weight
+ weight = max(0.0, min(1.0, n * 2.0))
+ total += n * amp
+ norm += amp
+ amp *= 0.5
+ freq *= 2.1
+ return max(0.0, min(1.0, total / norm))
+
+
+def mountain_height(x: float, y: float, *, seed: int = 0, amplitude: float = 45.0, frequency: float = 0.013) -> float:
+ """A horizon ridge's height (m) at (x, y): ``amplitude`` x ridged noise of wavelength
+ ``1 / frequency`` m (the defaults give 45 m peaks about 80 m apart) — for a backdrop range
+ BEYOND the play area, never under the cameras."""
+ r = ridged(x * frequency, y * frequency, seed=seed)
+ return amplitude * r * r
+
+
+def height_field(size: float | Sequence[float], segments: int, fn: Callable[[float, float], float]) -> list[float]:
+ """``fn(x, y)`` sampled on a ``(segments + 1)²`` grid centred at the origin, row-major
+ (y outer, x inner) — the order ``terrain.ground`` and ``mesh.mesh_object`` grids use."""
+ sx, sy = (float(size), float(size)) if isinstance(size, (int, float)) else (float(size[0]), float(size[1]))
+ n = max(1, int(segments))
+ out: list[float] = []
+ for iy in range(n + 1):
+ y = -sy / 2 + sy * iy / n
+ for ix in range(n + 1):
+ out.append(float(fn(-sx / 2 + sx * ix / n, y)))
+ return out
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/place.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/place.py
new file mode 100644
index 00000000..84d17138
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/place.py
@@ -0,0 +1,260 @@
+"""lib/place.py — seating, facing and the zone's own placement self-check.
+
+The placement gate (``runtime_js/lib/host_placement.mjs``, run on the census GLB) samples up to
+five FOOT COLUMNS per placed thing — the lowest vertex and the ±x / ±y extremes of the band
+within max(2 cm, 5 %) of its height above its minimum — and reports a gap > 0.05 m outdoors
+(0.02 m indoors) as floating, a burial > 0.10 m as sunk and AABB overlaps > 10 % of the
+smaller box as interpenetration. ``seat`` uses the SAME columns, so what it seats the gate
+reads as supported. World matrices are composed here from ``matrix_basis`` because
+``obj.matrix_world`` is stale until the depsgraph evaluates (an object just given a
+``location`` still reports the identity).
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from typing import Any
+
+import bpy
+import numpy as np
+from mathutils import Matrix, Vector
+
+#: the gate's foot band: max(FOOT_BAND_MIN_M, FOOT_BAND_FRAC x height) above the lowest vertex
+FOOT_BAND_MIN_M = 0.02
+FOOT_BAND_FRAC = 0.05
+CONTACT_M = 0.02
+_EVALUATED_TYPES = ("CURVE", "FONT", "SURFACE", "META")
+
+
+def world_matrix(obj: Any) -> Matrix:
+ """``obj``'s world matrix NOW (parent chain x ``matrix_basis``), not the depsgraph's last."""
+ m = obj.matrix_basis.copy()
+ if obj.parent is not None:
+ return world_matrix(obj.parent) @ obj.matrix_parent_inverse @ m
+ return m
+
+
+def _mesh_points(obj: Any, matrix: Matrix, *, evaluated: bool) -> np.ndarray:
+ """World-space vertices of one object's own geometry (empty for a non-geometric object)."""
+ me = None
+ owner = None
+ if obj.type == "MESH" and (not evaluated or not obj.modifiers):
+ me = obj.data
+ elif obj.type == "MESH" or obj.type in _EVALUATED_TYPES:
+ owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
+ try:
+ me = owner.to_mesh()
+ except RuntimeError:
+ me = None
+ if me is None or len(me.vertices) == 0:
+ if owner is not None:
+ owner.to_mesh_clear()
+ return np.empty((0, 3), np.float64)
+ co = np.empty(len(me.vertices) * 3, np.float32)
+ me.vertices.foreach_get("co", co)
+ if owner is not None:
+ owner.to_mesh_clear()
+ pts = co.reshape(-1, 3).astype(np.float64)
+ m = np.array(matrix, np.float64)
+ return pts @ m[:3, :3].T + m[:3, 3]
+
+
+def _collection_points(coll: Any, matrix: Matrix, *, evaluated: bool) -> list[np.ndarray]:
+ off = Vector(coll.instance_offset)
+ out = []
+ for o in coll.all_objects:
+ if o.type == "EMPTY" or o.hide_render:
+ continue
+ local = world_matrix(o)
+ local.translation = local.translation - off
+ out.append(_mesh_points(o, matrix @ local, evaluated=evaluated))
+ return out
+
+
+def world_points(obj: Any, *, evaluated: bool = True) -> np.ndarray:
+ """World-space vertices of ``obj``, its children and (for a collection instance) its
+ source — the point set the gate measures as this placement row."""
+ parts: list[np.ndarray] = []
+ stack = [obj]
+ while stack:
+ o = stack.pop()
+ m = world_matrix(o)
+ if o.type == "EMPTY" and o.instance_type == "COLLECTION" and o.instance_collection is not None:
+ parts.extend(_collection_points(o.instance_collection, m, evaluated=evaluated))
+ else:
+ parts.append(_mesh_points(o, m, evaluated=evaluated))
+ stack.extend(o.children)
+ parts = [p for p in parts if len(p)]
+ return np.concatenate(parts) if parts else np.empty((0, 3), np.float64)
+
+
+def bbox_world(obj: Any, *, evaluated: bool = True) -> tuple[Vector, Vector]:
+ """(min, max) corners of ``obj``'s geometry in world space (children and instances included);
+ a thing with no geometry answers its own location twice."""
+ pts = world_points(obj, evaluated=evaluated)
+ if not len(pts):
+ p = world_matrix(obj).translation
+ return Vector(p), Vector(p)
+ lo, hi = pts.min(axis=0), pts.max(axis=0)
+ return Vector(lo.tolist()), Vector(hi.tolist())
+
+
+def foot_columns(points: np.ndarray, columns: int = 5) -> list[tuple[float, float, float]]:
+ """The gate's foot columns of a point set: lowest, min x, max x, min y, max y of the foot
+ band, deduplicated within 1 cm, up to ``columns``."""
+ if not len(points):
+ return []
+ zmin, zmax = float(points[:, 2].min()), float(points[:, 2].max())
+ band = points[points[:, 2] <= zmin + max(FOOT_BAND_MIN_M, FOOT_BAND_FRAC * (zmax - zmin))]
+
+ def lowest_at(axis: int, sign: float) -> np.ndarray:
+ """The lowest band vertex at the band's extreme along ``axis`` (a sill beam's top and
+ bottom share an x: the top is not the foot)."""
+ extreme = (sign * band[:, axis]).max()
+ cand = band[sign * band[:, axis] >= extreme - 1e-4]
+ return cand[cand[:, 2].argmin()]
+
+ picks = [band[band[:, 2].argmin()], lowest_at(0, -1.0), lowest_at(0, 1.0), lowest_at(1, -1.0), lowest_at(1, 1.0)]
+ out: list[tuple[float, float, float]] = []
+ for p in picks:
+ x, y, z = (float(v) for v in p)
+ if any(math.hypot(q[0] - x, q[1] - y) < 0.01 for q in out):
+ continue
+ out.append((x, y, z))
+ if len(out) >= max(1, int(columns)):
+ break
+ return out
+
+
+def _drop(points: np.ndarray, height_at: Callable[[float, float], float], *, sink: float, columns: int) -> float:
+ """The vertical move that puts the first foot on the ground (every other column at or below
+ it): ``min`` over the columns of (ground - foot) - sink."""
+ cols = foot_columns(points, columns)
+ if not cols:
+ return 0.0
+ return min(float(height_at(x, y)) - z for x, y, z in cols) - float(sink)
+
+
+def seat(obj: Any, height_at: Callable[[float, float], float], *, sink: float = 0.0, columns: int = 5) -> float:
+ """Move ``obj`` vertically so its lowest foot column rests on ``height_at`` (``sink`` m
+ deeper: an embedded rock, a driven post). Returns the move in metres. Seat the ROOT of a
+ prop (the Empty ``Batch.finish`` returns), whose z is a world z."""
+ dz = _drop(world_points(obj), height_at, sink=sink, columns=columns)
+ obj.location.z += dz
+ return dz
+
+
+def seat_instance(empty: Any, source: Any, height_at: Callable[[float, float], float], *, sink: float = 0.0) -> float:
+ """``seat`` for a collection-instance Empty of ``source`` (its rotation and scale applied to
+ the source's geometry before the foot columns are read). Returns the move in metres."""
+ m = world_matrix(empty)
+ parts = [p for p in _collection_points(source, m, evaluated=True) if len(p)]
+ if not parts:
+ return 0.0
+ dz = _drop(np.concatenate(parts), height_at, sink=sink, columns=5)
+ empty.location.z += dz
+ return dz
+
+
+def rest_on(obj: Any, support: Any, *, offset: float = 0.0) -> float:
+ """Seat ``obj`` on ``support`` (a table, a shelf, a wall top): its lowest point meets the
+ highest point of ``support`` under ``obj``'s footprint (+ ``offset``). Returns the move."""
+ pts = world_points(obj)
+ sup = world_points(support)
+ if not len(pts) or not len(sup):
+ return 0.0
+ lo, hi = pts.min(axis=0), pts.max(axis=0)
+ pad = 0.02
+ under = sup[(sup[:, 0] >= lo[0] - pad) & (sup[:, 0] <= hi[0] + pad) & (sup[:, 1] >= lo[1] - pad) & (sup[:, 1] <= hi[1] + pad)]
+ top = float(under[:, 2].max()) if len(under) else float(sup[:, 2].max())
+ dz = top + float(offset) - float(lo[2])
+ obj.location.z += dz
+ return dz
+
+
+def heading(a: Sequence[float], b: Sequence[float]) -> float:
+ """The Z rotation (radians) that points a -Y-front object standing at ``a`` toward ``b``."""
+ return math.atan2(float(b[1]) - float(a[1]), float(b[0]) - float(a[0])) + math.pi / 2
+
+
+def face_toward(obj: Any, target: Sequence[float]) -> float:
+ """Yaw ``obj`` (front = -Y) toward ``target``; returns the angle set."""
+ pos = world_matrix(obj).translation
+ ang = heading((pos.x, pos.y), target)
+ obj.rotation_mode = "XYZ"
+ obj.rotation_euler[2] = ang
+ return ang
+
+
+def clear_of(objs: Sequence[Any], min_gap: float = CONTACT_M, *, overlap: float = 0.10) -> list[tuple[str, str, float]]:
+ """The zone's self-check: pairs of ``objs`` whose world AABBs overlap by more than
+ ``overlap`` of the smaller box (the gate's interpenetration threshold) as
+ ``(name_a, name_b, fraction)``; boxes merely within ``min_gap`` are contact, not reported."""
+ boxes = []
+ for o in objs:
+ lo, hi = bbox_world(o)
+ boxes.append((o.name, np.array(lo), np.array(hi)))
+ out: list[tuple[str, str, float]] = []
+ for i in range(len(boxes)):
+ na, la, ha = boxes[i]
+ for j in range(i + 1, len(boxes)):
+ nb, lb, hb = boxes[j]
+ if np.any(la - min_gap > hb) or np.any(lb - min_gap > ha):
+ continue
+ ov = np.minimum(ha, hb) - np.maximum(la, lb)
+ if np.any(ov <= 0):
+ continue
+ va = float(np.prod(np.maximum(ha - la, 0.01)))
+ vb = float(np.prod(np.maximum(hb - lb, 0.01)))
+ frac = float(np.prod(ov)) / min(va, vb)
+ if frac > overlap:
+ out.append((na, nb, round(frac, 3)))
+ return out
+
+
+def clear_mask(objs: Sequence[Any], margin: float = 0.3) -> Callable[[float, float], float]:
+ """A ``scatter.poisson(mask=…)`` filter that keeps scatter points OUT of the footprints of
+ ``objs`` — their world AABBs grown by ``margin`` m: 0.0 inside one, 1.0 clear. Build it from
+ the roots placed by hand BEFORE the small stuff is scattered: 9 of the 13 Blender zones that
+ shipped an interpenetration ERROR in the argon loop's iteration 0 (2026-10-15) had scattered
+ a small prop into a cart, a rack, a shrub or a mound (100 % of the smaller box)."""
+ boxes: list[tuple[float, float, float, float]] = []
+ for o in objs:
+ lo, hi = bbox_world(o)
+ boxes.append((lo.x - margin, lo.y - margin, hi.x + margin, hi.y + margin))
+
+ def mask(x: float, y: float) -> float:
+ for x0, y0, x1, y1 in boxes:
+ if x0 <= x <= x1 and y0 <= y <= y1:
+ return 0.0
+ return 1.0
+
+ return mask
+
+
+def keep_inside(obj: Any, bbox: tuple[Sequence[float], Sequence[float]]) -> Vector:
+ """Slide ``obj`` horizontally so its AABB stays within ``bbox`` = (centre, extents) — the
+ zone's plan box, in this frame. Returns the move."""
+ (cx, cy, _), (ex, ey, _) = bbox
+ lo, hi = bbox_world(obj)
+ move = Vector((0.0, 0.0, 0.0))
+ for k, c, e in ((0, cx, ex), (1, cy, ey)):
+ if lo[k] < c - e / 2:
+ move[k] = (c - e / 2) - lo[k]
+ elif hi[k] > c + e / 2:
+ move[k] = (c + e / 2) - hi[k]
+ obj.location.x += move.x
+ obj.location.y += move.y
+ return move
+
+
+def unique_name(base: str, i: int) -> str:
+ """``Base_i`` — or the next free index when that object already exists (names are global
+ in Blender: a second ``Lantern_0`` would silently become ``Lantern_0.001``)."""
+ i = int(i)
+ name = f"{base}_{i}"
+ while name in bpy.data.objects:
+ i += 1
+ name = f"{base}_{i}"
+ return name
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/scatter.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/scatter.py
new file mode 100644
index 00000000..15079ce6
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/scatter.py
@@ -0,0 +1,183 @@
+"""lib/scatter.py — placing copies: collection instances and geometry-nodes clouds.
+
+Two kinds of copy, and the gate treats them differently. ``instance`` / ``scatter`` make a
+collection-instance Empty per copy, seated on ``height_at``: ONE placement row each (named,
+measured for floating / sunk / interpenetration — what a bench, a cart or a tree deserves).
+``gn_scatter`` makes an instance CLOUD on a surface (blades, pebbles, tufts: hundreds to tens
+of thousands): one object, counted as instances in the census and EXEMPT from per-asset
+placement because its copies ride the surface by construction. Blender 5.2 API: node inputs
+are set with ``getattr(mod.properties.inputs, identifier).value``.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from typing import Any
+
+import bpy
+
+from lib.place import seat_instance, unique_name, world_matrix
+
+HeightFn = Callable[[float, float], float]
+
+
+def instance(collection: Any, source: Any, name: str, x: float, y: float, *, height_at: HeightFn, rot_z: float = 0.0,
+ scale: float = 1.0, sink: float = 0.0) -> Any:
+ """One placed copy of the Collection ``source`` (``ctx.assets["<snake>"]``): an instance
+ Empty named ``name`` at (x, y), yawed ``rot_z`` radians, seated on ``height_at`` (``sink``
+ m deeper). Returns the Empty — the placement row."""
+ ob = bpy.data.objects.new(name, None)
+ ob.instance_type = "COLLECTION"
+ ob.instance_collection = source
+ ob.empty_display_size = 0.25
+ ob.location = (float(x), float(y), 0.0)
+ ob.rotation_mode = "XYZ"
+ ob.rotation_euler = (0.0, 0.0, float(rot_z))
+ ob.scale = (float(scale), float(scale), float(scale))
+ collection.objects.link(ob)
+ seat_instance(ob, source, height_at, sink=sink)
+ return ob
+
+
+def scatter(collection: Any, source: Any, prefix: str, points: Sequence[Sequence[float]], *, height_at: HeightFn, rng: Any,
+ rot: str | float = "random", scale: Sequence[float] = (1.0, 1.0)) -> list[Any]:
+ """``instance`` at every (x, y) of ``points``, named ``<prefix>_<i>``; ``rot`` ``"random"``
+ or a fixed yaw, ``scale`` a (min, max) range drawn per copy."""
+ out = []
+ for i, p in enumerate(points):
+ yaw = rng.uniform(0.0, math.tau) if rot == "random" else float(rot)
+ s = rng.uniform(float(scale[0]), float(scale[1])) if scale[0] != scale[1] else float(scale[0])
+ out.append(instance(collection, source, unique_name(prefix, i), float(p[0]), float(p[1]), height_at=height_at,
+ rot_z=yaw, scale=s))
+ return out
+
+
+def poisson(rng: Any, *, area: Sequence[float], min_dist: float, max_count: int,
+ mask: Callable[[float, float], float] | None = None) -> list[tuple[float, float]]:
+ """Up to ``max_count`` points in ``area`` = (x0, y0, x1, y1) at least ``min_dist`` apart
+ (dart throwing); ``mask(x, y)`` 0..1 is the chance a candidate is kept (a shoreline, a
+ clearing). Deterministic for a seeded ``rng``."""
+ x0, y0, x1, y1 = (float(v) for v in area)
+ cell = max(1e-3, float(min_dist)) / math.sqrt(2.0)
+ grid: dict[tuple[int, int], tuple[float, float]] = {}
+ out: list[tuple[float, float]] = []
+ tries = max(1, int(max_count)) * 30
+ for _ in range(tries):
+ if len(out) >= max_count:
+ break
+ x, y = rng.uniform(x0, x1), rng.uniform(y0, y1)
+ if mask is not None and rng.uniform(0.0, 1.0) > float(mask(x, y)):
+ continue
+ gx, gy = int(math.floor((x - x0) / cell)), int(math.floor((y - y0) / cell))
+ ok = True
+ for i in range(gx - 2, gx + 3):
+ for j in range(gy - 2, gy + 3):
+ q = grid.get((i, j))
+ if q is not None and math.hypot(q[0] - x, q[1] - y) < min_dist:
+ ok = False
+ break
+ if not ok:
+ break
+ if ok:
+ grid[(gx, gy)] = (x, y)
+ out.append((x, y))
+ return out
+
+
+def along_path(points: Sequence[Sequence[float]], n: int, *, jitter: float = 0.0, rng: Any = None) -> list[tuple[float, ...]]:
+ """``n`` points evenly spaced by arc length along the polyline ``points`` (2-D or 3-D,
+ returned the same way), each pushed up to ``jitter`` m sideways when ``rng`` is given."""
+ pts = [tuple(float(v) for v in p) for p in points]
+ if len(pts) == 1 or n <= 0:
+ return pts[:1] * max(0, n)
+ seg = [math.dist(pts[i], pts[i + 1]) for i in range(len(pts) - 1)]
+ total = sum(seg)
+ out: list[tuple[float, ...]] = []
+ for k in range(n):
+ d = total * (k / (n - 1) if n > 1 else 0.5)
+ i = 0
+ while i < len(seg) - 1 and d > seg[i]:
+ d -= seg[i]
+ i += 1
+ t = d / seg[i] if seg[i] > 0 else 0.0
+ a, b = pts[i], pts[i + 1]
+ p = [a[j] + (b[j] - a[j]) * t for j in range(len(a))]
+ if jitter > 0 and rng is not None:
+ dx, dy = b[0] - a[0], b[1] - a[1]
+ L = math.hypot(dx, dy) or 1.0
+ s = rng.uniform(-jitter, jitter)
+ p[0] += -dy / L * s
+ p[1] += dx / L * s
+ out.append(tuple(p))
+ return out
+
+
+def grid(center: Sequence[float], size: float | Sequence[float], spacing: float, rng: Any, *, jitter: float = 0.3) -> list[tuple[float, float]]:
+ """A grid of (x, y) points ``spacing`` m apart over ``size`` m around ``center``, each moved
+ up to ``jitter`` x spacing (an orchard, a car park, a crowd that is not a lattice)."""
+ sx, sy = (float(size), float(size)) if isinstance(size, (int, float)) else (float(size[0]), float(size[1]))
+ cx, cy = float(center[0]), float(center[1])
+ nx, ny = max(1, int(sx / spacing)), max(1, int(sy / spacing))
+ out = []
+ for i in range(nx):
+ for j in range(ny):
+ x = cx - sx / 2 + spacing * (i + 0.5) + rng.uniform(-jitter, jitter) * spacing
+ y = cy - sy / 2 + spacing * (j + 0.5) + rng.uniform(-jitter, jitter) * spacing
+ out.append((x, y))
+ return out
+
+
+def gn_scatter(name: str, collection: Any, surface: Any, instance_obj: Any, *, density: float, seed: int = 0,
+ align_normal: bool = True, scale_range: Sequence[float] = (0.8, 1.2)) -> Any:
+ """An instance cloud of ``instance_obj`` on the mesh of ``surface`` (a hidden patch that
+ follows the terrain, or any mesh): ``density`` copies per m², random yaw, ``scale_range``
+ per copy, aligned to the surface normal when ``align_normal``. Returns the host object
+ (named ``name``; it renders ONLY the instances — the surface stays the distribution
+ domain). ``instance_obj`` may be hidden: its geometry is copied, not its visibility."""
+ ng = bpy.data.node_groups.new(f"{name}Scatter", "GeometryNodeTree")
+ ng.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")
+ dens = ng.interface.new_socket("Density", in_out="INPUT", socket_type="NodeSocketFloat")
+ sd = ng.interface.new_socket("Seed", in_out="INPUT", socket_type="NodeSocketInt")
+ ng.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")
+ n, links = ng.nodes, ng.links
+ gi, go = n.new("NodeGroupInput"), n.new("NodeGroupOutput")
+ dist = n.new("GeometryNodeDistributePointsOnFaces")
+ dist.distribute_method = "RANDOM"
+ links.new(gi.outputs["Geometry"], dist.inputs["Mesh"])
+ links.new(gi.outputs["Density"], dist.inputs["Density"])
+ links.new(gi.outputs["Seed"], dist.inputs["Seed"])
+ info = n.new("GeometryNodeObjectInfo")
+ info.inputs["Object"].default_value = instance_obj
+ inst = n.new("GeometryNodeInstanceOnPoints")
+ links.new(dist.outputs["Points"], inst.inputs["Points"])
+ links.new(info.outputs["Geometry"], inst.inputs["Instance"])
+ yaw = n.new("FunctionNodeRandomValue")
+ yaw.data_type = "FLOAT_VECTOR"
+ yaw.inputs["Min"].default_value = (0.0, 0.0, 0.0)
+ yaw.inputs["Max"].default_value = (0.0, 0.0, math.tau)
+ links.new(gi.outputs["Seed"], yaw.inputs["Seed"])
+ euler = n.new("FunctionNodeEulerToRotation")
+ links.new(yaw.outputs["Value"], euler.inputs["Euler"])
+ if align_normal:
+ rot = n.new("FunctionNodeRotateRotation")
+ links.new(dist.outputs["Rotation"], rot.inputs["Rotation"])
+ links.new(euler.outputs["Rotation"], rot.inputs["Rotate By"])
+ links.new(rot.outputs["Rotation"], inst.inputs["Rotation"])
+ else:
+ links.new(euler.outputs["Rotation"], inst.inputs["Rotation"])
+ size = n.new("FunctionNodeRandomValue")
+ size.data_type = "FLOAT"
+ size.inputs["Min"].default_value = float(scale_range[0])
+ size.inputs["Max"].default_value = float(scale_range[1])
+ links.new(gi.outputs["Seed"], size.inputs["Seed"])
+ links.new(size.outputs["Value"], inst.inputs["Scale"])
+ links.new(inst.outputs["Instances"], go.inputs["Geometry"])
+ host = bpy.data.objects.new(name, surface.data)
+ host.matrix_world = world_matrix(surface)
+ collection.objects.link(host)
+ mod = host.modifiers.new("Scatter", "NODES")
+ mod.node_group = ng
+ getattr(mod.properties.inputs, dens.identifier).value = float(density)
+ getattr(mod.properties.inputs, sd.identifier).value = int(seed)
+ return host
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/sky.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/sky.py
new file mode 100644
index 00000000..70a6524d
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/sky.py
@@ -0,0 +1,214 @@
+"""lib/sky.py — the world (sky), fog volumes and sky dressing. ENV ONLY for the world setters:
+``scene.world`` belongs to ``src/env.py``'s ``build_env`` (the lint rejects it in a zone).
+
+The census reads the world's background kind (``sky:MULTIPLE_SCATTERING`` / a hex colour / a
+node) and the fog from either the world's Volume output or the largest volume-only box
+(``haze``); a scene with neither reads as thin_atmosphere. Blender 5.2 facts: the physical
+sky is ``MULTIPLE_SCATTERING`` (the old name raises), its dust knob is ``aerosol_density``, and
+the sun disc is ON by default — ``sun_world`` turns it off because ``lighting.sun`` is the sun.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+import bpy
+
+from lib.materials import rgba
+from lib.mesh import mesh_object
+from lib.noise import fbm2, rng
+
+
+def _rgb(color: str | Sequence[float]) -> tuple[float, float, float, float]:
+ if isinstance(color, str):
+ return rgba(color)
+ v = [float(c) for c in color]
+ return (v[0], v[1], v[2], v[3] if len(v) > 3 else 1.0)
+
+
+def _fresh_world(scene: Any, name: str) -> tuple[Any, Any, Any, Any]:
+ world = bpy.data.worlds.new(name)
+ scene.world = world
+ nt = world.node_tree
+ bg = nt.nodes.get("Background") or nt.nodes.new("ShaderNodeBackground")
+ out = nt.nodes.get("World Output") or nt.nodes.new("ShaderNodeOutputWorld")
+ if not out.inputs["Surface"].is_linked:
+ nt.links.new(bg.outputs["Background"], out.inputs["Surface"])
+ return world, nt.nodes, nt.links, bg
+
+
+def sun_world(scene: Any, *, elevation_deg: float = 12.0, azimuth_deg: float = 125.0, strength: float = 0.2,
+ dust: float = 2.0) -> Any:
+ """A physical sky (MULTIPLE_SCATTERING) lit from compass ``azimuth_deg`` (0 = +X, 90 = +Y —
+ pass the same numbers to ``lighting.sun``) at ``elevation_deg``; ``strength`` is the world's
+ Background strength (0.2-0.5 by day: the sky is bright), ``dust`` the aerosol density
+ (1 = clear, 2-4 hazy, warm low sun). The sun disc is off: the Sun lamp casts the shadows."""
+ world, nodes, links, bg = _fresh_world(scene, "Sky")
+ sky = nodes.new("ShaderNodeTexSky")
+ sky.sky_type = "MULTIPLE_SCATTERING"
+ sky.sun_disc = False
+ sky.sun_elevation = math.radians(elevation_deg)
+ sky.sun_rotation = math.radians(azimuth_deg - 90.0) # Blender: rotation 0 puts the sun at +Y
+ sky.aerosol_density = float(dust)
+ links.new(sky.outputs["Color"], bg.inputs["Color"])
+ bg.inputs["Strength"].default_value = float(strength)
+ return world
+
+
+def night_world(scene: Any, color: str | Sequence[float] = "17273F", strength: float = 0.3) -> Any:
+ """A flat night sky in ``color`` (a deep blue, never black: AgX needs something to lift)."""
+ world, _, _, bg = _fresh_world(scene, "NightSky")
+ bg.inputs["Color"].default_value = _rgb(color)
+ bg.inputs["Strength"].default_value = float(strength)
+ return world
+
+
+def gradient_world(scene: Any, stops: Sequence[tuple[float, str | Sequence[float]]], *, clouds: bool = True,
+ strength: float = 0.7) -> Any:
+ """A sky graded from the horizon (position 0) to the zenith (1) through ``stops`` =
+ ``[(0.0, "F2C9A0"), (0.35, "7FA7D6"), (1.0, "1F4A8E")]``; ``clouds`` mottles the upper half
+ with noise. For dusk / dawn / stylised skies where the physical sky is wrong."""
+ world, nodes, links, bg = _fresh_world(scene, "GradientSky")
+ tc = nodes.new("ShaderNodeTexCoord")
+ sep = nodes.new("ShaderNodeSeparateXYZ")
+ links.new(tc.outputs["Generated"], sep.inputs["Vector"])
+ ramp = nodes.new("ShaderNodeValToRGB")
+ els = ramp.color_ramp.elements
+ ordered = sorted(((float(p), _rgb(c)) for p, c in stops), key=lambda s: s[0])
+ els[0].position, els[0].color = max(0.0, ordered[0][0]), ordered[0][1]
+ els[1].position, els[1].color = min(1.0, ordered[-1][0]), ordered[-1][1]
+ for pos, col in ordered[1:-1]:
+ e = els.new(max(0.0, min(1.0, pos)))
+ e.color = col
+ links.new(sep.outputs["Z"], ramp.inputs["Fac"]) # Generated z = 0 at the horizon, 1 at the zenith
+ colour = ramp.outputs["Color"]
+ if clouds:
+ n = nodes.new("ShaderNodeTexNoise")
+ n.inputs["Scale"].default_value = 2.5
+ n.inputs["Detail"].default_value = 6.0
+ n.inputs["Roughness"].default_value = 0.6
+ links.new(tc.outputs["Generated"], n.inputs["Vector"])
+ mask = nodes.new("ShaderNodeValToRGB")
+ mask.color_ramp.elements[0].position = 0.55
+ mask.color_ramp.elements[1].position = 0.75
+ links.new(n.outputs["Fac"], mask.inputs["Fac"])
+ math_node = nodes.new("ShaderNodeMath")
+ math_node.operation = "MULTIPLY"
+ links.new(mask.outputs["Color"], math_node.inputs[0])
+ links.new(sep.outputs["Z"], math_node.inputs[1])
+ mix = nodes.new("ShaderNodeMix")
+ mix.data_type = "RGBA"
+ mix.inputs[7].default_value = (0.9, 0.9, 0.92, 1.0)
+ links.new(colour, mix.inputs[6])
+ links.new(math_node.outputs["Value"], mix.inputs[0])
+ colour = mix.outputs[2]
+ links.new(colour, bg.inputs["Color"])
+ bg.inputs["Strength"].default_value = float(strength)
+ return world
+
+
+def haze(collection: Any, loc: Sequence[float], size: float | Sequence[float], density: float = 0.003,
+ color: str | Sequence[float] = "ADC9E1", name: str = "Atmosphere") -> Any:
+ """A bounded fog volume: a box centred at ``loc`` of ``size`` m whose only material is a
+ Principled Volume (``density`` per metre: 0.002 clear valley air, 0.01 morning mist, 0.03
+ a dense fog bank). Volume-only, so the census reports it as fog, not matter; a world
+ volume over a large scene swallows the sun — this stays over the play area."""
+ sx, sy, sz = (size, size, size) if isinstance(size, (int, float)) else size
+ hx, hy, hz = sx / 2, sy / 2, sz / 2
+ cx, cy, cz = (float(v) for v in loc)
+ verts = [(cx + x, cy + y, cz + z) for x, y, z in ((-hx, -hy, -hz), (hx, -hy, -hz), (hx, hy, -hz), (-hx, hy, -hz),
+ (-hx, -hy, hz), (hx, -hy, hz), (hx, hy, hz), (-hx, hy, hz))]
+ faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
+ mat = bpy.data.materials.new(f"{name}Fog")
+ nt = mat.node_tree
+ nt.nodes.remove(nt.nodes["Principled BSDF"])
+ fog = nt.nodes.new("ShaderNodeVolumePrincipled")
+ fog.inputs["Density"].default_value = float(density)
+ fog.inputs["Color"].default_value = _rgb(color)
+ fog.inputs["Anisotropy"].default_value = 0.3
+ nt.links.new(fog.outputs["Volume"], nt.nodes["Material Output"].inputs["Volume"])
+ return mesh_object(name, verts, faces, mat, collection)
+
+
+def aurora(name: str, collection: Any, center: Sequence[float], *, span: float = 560.0, height: float = 72.0, seed: int = 0,
+ strength: float = 0.24, ctx: Any = None) -> Any:
+ """A curtain of aurora: a wavy emissive ribbon ``span`` m long and ``height`` m tall hung at
+ ``center`` (x, y, altitude). Tagged ``placement = "free"`` (it is in the sky); with ``ctx``
+ the glow drifts along the ribbon between ``ctx.times``."""
+ n = 48
+ verts: list[tuple[float, float, float]] = []
+ faces: list[tuple[int, ...]] = []
+ cx, cy, cz = (float(v) for v in center)
+ for i in range(n + 1):
+ t = i / n
+ x = cx - span / 2 + span * t
+ y = cy + 18.0 * fbm2(t * 3.0, seed * 0.37, octaves=3, seed=seed)
+ lift = 6.0 * fbm2(t * 5.0 + 11.0, seed * 0.11, octaves=2, seed=seed + 1)
+ verts.append((x, y, cz + lift))
+ verts.append((x, y, cz + height + lift * 1.5))
+ for i in range(n):
+ a = 2 * i
+ faces.append((a, a + 2, a + 3, a + 1))
+ mat = bpy.data.materials.new(f"{name}Glow")
+ nt = mat.node_tree
+ nodes, links = nt.nodes, nt.links
+ bsdf = nodes["Principled BSDF"]
+ nodes.remove(bsdf)
+ emit = nodes.new("ShaderNodeEmission")
+ emit.inputs["Strength"].default_value = float(strength) * 8.0
+ tc = nodes.new("ShaderNodeTexCoord")
+ mp = nodes.new("ShaderNodeMapping")
+ mp.name = "FlowMapping"
+ mp.inputs["Scale"].default_value = (0.02, 0.02, 0.05)
+ links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ noise = nodes.new("ShaderNodeTexNoise")
+ noise.inputs["Scale"].default_value = 1.0
+ noise.inputs["Detail"].default_value = 4.0
+ links.new(mp.outputs["Vector"], noise.inputs["Vector"])
+ ramp = nodes.new("ShaderNodeValToRGB")
+ els = ramp.color_ramp.elements
+ els[0].position, els[0].color = 0.35, (0.05, 0.9, 0.45, 1.0)
+ els[1].position, els[1].color = 0.75, (0.5, 0.2, 0.9, 1.0)
+ links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
+ links.new(ramp.outputs["Color"], emit.inputs["Color"])
+ # fade to nothing along the bottom edge and where the noise is dark
+ sep = nodes.new("ShaderNodeSeparateXYZ")
+ links.new(tc.outputs["Generated"], sep.inputs["Vector"])
+ fade = nodes.new("ShaderNodeMath")
+ fade.operation = "MULTIPLY"
+ links.new(sep.outputs["Z"], fade.inputs[0])
+ links.new(noise.outputs["Fac"], fade.inputs[1])
+ transparent = nodes.new("ShaderNodeBsdfTransparent")
+ mix = nodes.new("ShaderNodeMixShader")
+ links.new(fade.outputs["Value"], mix.inputs["Fac"])
+ links.new(transparent.outputs["BSDF"], mix.inputs[1])
+ links.new(emit.outputs["Emission"], mix.inputs[2])
+ links.new(mix.outputs["Shader"], nodes["Material Output"].inputs["Surface"])
+ mat.surface_render_method = "BLENDED"
+ ob = mesh_object(name, verts, faces, mat, collection)
+ ob["placement"] = "free"
+ if ctx is not None:
+ from lib.motion import scroll
+
+ scroll(mp, (0.6, 0.0, 0.0), ctx)
+ return ob
+
+
+def stars(batch: Any, mat: Any, *, seed: int = 0, count: int = 900, radius: float = 600.0) -> None:
+ """``count`` star quads on a dome of ``radius`` m above the horizon, added to ``batch`` with
+ an ``emissive`` ``mat``. Name the batch ``Stars…`` (sky-named and 1 km wide, so the census
+ files it as sky) and tag its root ``["placement"] = "free"``."""
+ r = rng(seed)
+ for _ in range(max(0, int(count))):
+ az = r.uniform(0.0, math.tau)
+ el = math.asin(r.uniform(0.08, 1.0))
+ size = r.uniform(0.6, 1.8)
+ cx, cy, cz = radius * math.cos(el) * math.cos(az), radius * math.cos(el) * math.sin(az), radius * math.sin(el)
+ # a quad facing the origin: span two directions orthogonal to the radial line
+ ux, uy = -math.sin(az), math.cos(az)
+ vx, vy, vz = -math.sin(el) * math.cos(az), -math.sin(el) * math.sin(az), math.cos(el)
+ verts = [(cx + (ux * a + vx * b) * size, cy + (uy * a + vy * b) * size, cz + vz * b * size)
+ for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
+ batch.add(mat, verts, [(0, 1, 2, 3)])
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/terrain.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/terrain.py
new file mode 100644
index 00000000..ef5c22fb
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/terrain.py
@@ -0,0 +1,180 @@
+"""lib/terrain.py — the ground and the rock that sits on it.
+
+``make_height_at`` is THE ground function: the env's ``height_at`` returns it, the ground mesh
+samples it, every zone seats on it (``place.seat`` / ``scatter.instance``). Level inside
+``flat_radius`` (the plan's cameras were written for z ≈ 0 there), rolling beyond, so nothing
+in the play area tilts. Batch recipes (``boulder``, ``talus``, ``basalt_column`` …) stand
+their lowest vertex ON the ``center`` z you pass — pass ``height_at(x, y)``.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from typing import Any
+
+from lib.mesh import mesh_object, sphere_template
+from lib.noise import fbm2, fbm3, hash01, rng
+
+HeightFn = Callable[[float, float], float]
+
+
+def _smoothstep(e0: float, e1: float, x: float) -> float:
+ t = max(0.0, min(1.0, (x - e0) / (e1 - e0))) if e1 > e0 else (1.0 if x >= e1 else 0.0)
+ return t * t * (3.0 - 2.0 * t)
+
+
+def make_height_at(*, seed: int = 0, relief: float = 3.0, scale: float = 60.0, flat_radius: float = 45.0,
+ base: float = 0.0) -> HeightFn:
+ """A ground function: ``base`` within ``flat_radius`` m of the origin, hills of up to
+ ``relief`` m with features ``scale`` m wide beyond it (blended in over ``scale`` m, so the
+ rim slopes under 5 % at the defaults)."""
+ blend = max(1.0, scale)
+
+ def height_at(x: float, y: float) -> float:
+ r = math.hypot(x, y)
+ if r <= flat_radius:
+ return base
+ t = _smoothstep(flat_radius, flat_radius + blend, r)
+ n = 0.5 + 0.5 * fbm2(x / scale, y / scale, octaves=4, seed=seed)
+ return base + t * relief * n
+
+ return height_at
+
+
+def ground(name: str, collection: Any, *, size: float | Sequence[float], segments: int, height_at: HeightFn,
+ material: Any, center: Sequence[float] = (0.0, 0.0), smooth: bool = True) -> Any:
+ """The terrain mesh: a ``size`` m grid of ``segments`` cells (96 for a 120-200 m ground)
+ following ``height_at``. Name it ``Ground…`` / ``Terrain…``: the census classifies the
+ ground by name and shape, and the placement gate seats on it."""
+ sx, sy = (float(size), float(size)) if isinstance(size, (int, float)) else (float(size[0]), float(size[1]))
+ n = max(1, int(segments))
+ cx, cy = float(center[0]), float(center[1])
+ verts = []
+ for iy in range(n + 1):
+ y = cy - sy / 2 + sy * iy / n
+ for ix in range(n + 1):
+ x = cx - sx / 2 + sx * ix / n
+ verts.append((x, y, float(height_at(x, y))))
+ faces = []
+ for iy in range(n):
+ for ix in range(n):
+ a = iy * (n + 1) + ix
+ faces.append((a, a + 1, a + n + 2, a + n + 1))
+ return mesh_object(name, verts, faces, material, collection, smooth=smooth)
+
+
+def cliff(name: str, collection: Any, *, length: float, height: float, height_at: HeightFn, material: Any,
+ seed: int = 0) -> Any:
+ """A rock face ``length`` m long along +X (centred on the origin, facing -Y) and ``height``
+ m tall, its foot on ``height_at`` and its face broken by ledges; move / rotate the object
+ to place it. ~2 400 triangles."""
+ nx, nz = max(2, int(length / 1.5)), max(2, int(height / 1.2))
+ verts = []
+ for iz in range(nz + 1):
+ v = iz / nz
+ for ix in range(nx + 1):
+ u = ix / nx
+ x = -length / 2 + length * u
+ bulge = 1.4 * fbm2(u * 6.0, v * 4.0, octaves=4, seed=seed) + 0.6 * (1.0 - v)
+ ledge = 0.35 * math.sin(v * 9.0 + fbm2(u * 3.0, 7.0, octaves=2, seed=seed) * 2.0)
+ z = float(height_at(x, 0.0)) + height * v + (0.0 if iz == 0 else 0.4 * fbm2(u * 9.0, v * 9.0, octaves=2, seed=seed + 3))
+ verts.append((x, -bulge - ledge, z))
+ # a back wall and a top so the face is a closed slab
+ top = len(verts)
+ for ix in range(nx + 1):
+ x = -length / 2 + length * ix / nx
+ verts.append((x, 2.5, float(height_at(x, 2.5)) + height + 0.3))
+ faces = []
+ for iz in range(nz):
+ for ix in range(nx):
+ a = iz * (nx + 1) + ix
+ faces.append((a, a + nx + 1, a + nx + 2, a + 1))
+ for ix in range(nx):
+ a = nz * (nx + 1) + ix
+ faces.append((a, a + 1, top + ix + 1, top + ix))
+ return mesh_object(name, verts, faces, material, collection, smooth=True)
+
+
+def _sphere_cloud(center: Sequence[float], scale: Sequence[float], seed: int, detail: int, *, rough: float = 0.28, squash: float = 0.6
+ ) -> tuple[list[tuple[float, float, float]], list[tuple[int, ...]]]:
+ """An icosphere displaced by fbm3, flattened underneath, standing on ``center`` z."""
+ verts, faces = sphere_template(detail)
+ out = []
+ sx, sy, sz = scale
+ for x, y, z in verts:
+ d = 1.0 + rough * fbm3(x * 1.7 + seed, y * 1.7, z * 1.7 - seed, octaves=3, seed=seed)
+ out.append((x * d * sx, y * d * sy, (z * d * sz) if z >= 0 else z * d * sz * squash))
+ zmin = min(v[2] for v in out)
+ cx, cy, cz = (float(c) for c in center)
+ return [(cx + x, cy + y, cz + (z - zmin)) for x, y, z in out], list(faces)
+
+
+def boulder(batch: Any, mat: Any, center: Sequence[float], scale: float | Sequence[float], *, seed: int = 0, detail: int = 3) -> None:
+ """A rock of ``scale`` m (a number, or (x, y, z) extents) standing on ``center`` z;
+ ``detail`` 2 = 80 triangles (a field), 3 = 320 (near the camera), 4 = 1 280 (a hero)."""
+ s = (scale, scale, scale * 0.8) if isinstance(scale, (int, float)) else tuple(float(v) for v in scale)
+ v, f = _sphere_cloud(center, (s[0] / 2, s[1] / 2, s[2] / 2), seed, detail)
+ batch.add(mat, v, f, smooth=True)
+
+
+def rock_field(batch: Any, mat: Any, center: Sequence[float], radius: float, count: int, height_at: HeightFn, rng_: Any) -> None:
+ """``count`` boulders of 0.3-1.4 m scattered within ``radius`` of ``center`` (x, y), each
+ standing on ``height_at`` — 80 triangles apiece."""
+ cx, cy = float(center[0]), float(center[1])
+ for i in range(max(0, int(count))):
+ a, r = rng_.uniform(0.0, math.tau), radius * math.sqrt(rng_.uniform(0.0, 1.0))
+ x, y = cx + r * math.cos(a), cy + r * math.sin(a)
+ s = rng_.uniform(0.3, 1.4)
+ boulder(batch, mat, (x, y, float(height_at(x, y))), (s, s * rng_.uniform(0.7, 1.2), s * rng_.uniform(0.5, 0.8)),
+ seed=int(rng_.uniform(0, 10_000)) + i, detail=2)
+
+
+def talus(batch: Any, mat: Any, center: Sequence[float], scale: float, seed: int) -> None:
+ """A scree heap ``scale`` m across standing on ``center`` z: ~40 small rocks piled in a cone
+ (the lower ones on the ground, the upper ones on the heap) — ~800 triangles."""
+ r = rng(seed)
+ cx, cy, cz = (float(c) for c in center)
+ heap_h = scale * 0.45
+ for i in range(40):
+ a, d = r.uniform(0.0, math.tau), math.sqrt(r.uniform(0.0, 1.0))
+ x, y = cx + d * scale / 2 * math.cos(a), cy + d * scale / 2 * math.sin(a)
+ surface = heap_h * max(0.0, 1.0 - d) ** 1.3
+ s = scale * r.uniform(0.08, 0.2)
+ boulder(batch, mat, (x, y, cz + surface * 0.85), (s, s * r.uniform(0.6, 1.0), s * 0.7), seed=seed * 7 + i, detail=1)
+
+
+def basalt_column(batch: Any, materials: Sequence[Any], center: Sequence[float], radius: float, height: float, rng_: Any,
+ lean: Sequence[float] = (0.0, 0.0)) -> None:
+ """A cluster of hexagonal basalt columns within ``radius`` of ``center`` (x, y, ground z),
+ the tallest ``height`` m, cycling ``materials``; ``lean`` (dx, dy per metre of height) tilts
+ the whole cluster. Each column is 8 quads."""
+ cx, cy, cz = (float(c) for c in center)
+ step = max(0.3, radius / 2.6)
+ k = 0
+ for i in range(-3, 4):
+ for j in range(-3, 4):
+ x = cx + step * (i + 0.5 * (j % 2))
+ y = cy + step * 0.866 * j
+ if math.hypot(x - cx, y - cy) > radius:
+ continue
+ h = height * (0.35 + 0.65 * (1.0 - math.hypot(x - cx, y - cy) / radius)) * rng_.uniform(0.75, 1.0)
+ r = step * 0.52
+ top = [(x + r * math.cos(a) + lean[0] * h, y + r * math.sin(a) + lean[1] * h, cz + h) for a in
+ (math.tau * s / 6 for s in range(6))]
+ bottom = [(x + r * math.cos(a), y + r * math.sin(a), cz) for a in (math.tau * s / 6 for s in range(6))]
+ verts = bottom + top
+ faces = [(s, (s + 1) % 6, 6 + (s + 1) % 6, 6 + s) for s in range(6)] + [tuple(range(6, 12))]
+ batch.add(materials[k % len(materials)], verts, faces)
+ k += 1
+
+
+def shoreline_mask(x: float, y: float, water_level: float, height_at: HeightFn) -> float:
+ """0 under water, 1 half a metre above it, smooth between — a scatter mask that keeps
+ reeds on the bank and trees off the beach."""
+ return _smoothstep(0.0, 0.5, float(height_at(x, y)) - float(water_level))
+
+
+def jitter(i: int, seed: int = 0) -> float:
+ """-1..1 from an index: the cheap per-item variation (``hash01``) in signed form."""
+ return hash01(i, seed) * 2.0 - 1.0
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.py
new file mode 100644
index 00000000..92123ce0
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.py
@@ -0,0 +1,236 @@
+"""lib/vegetation.py — trees, shrubs, ferns, grass and flower beds as batch geometry.
+
+A crown is LEAVES: hundreds of small leaf cards in a volume, never one displaced ball — a
+closed blob has no silhouette, lets no light through and carries one hue. Every recipe stands
+on the z you pass (``loc`` / ``center`` = the ground point: pass ``height_at(x, y)``); counts
+are capped so a tree costs 3-9 k triangles (``max_leaves``). Ground cover that must be dense
+(blades, tufts) goes through ``grass_patch`` = a geometry-nodes instance cloud, which the
+census counts as instances and the placement gate leaves alone.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from typing import Any
+
+import bpy
+from mathutils import Vector
+
+from lib.materials import material
+from lib.mesh import mesh_object, sphere_template
+from lib.noise import rng
+from lib.scatter import gn_scatter
+
+HeightFn = Callable[[float, float], float]
+Vec3 = tuple[float, float, float]
+_CROWN = { # kind: (trunk share of the height, crown rx / height, crown rz / height, leaf size, crown lift)
+ "broadleaf": (0.40, 0.30, 0.32, 0.17, 0.0),
+ "oak": (0.33, 0.44, 0.30, 0.20, 0.02),
+ "cypress": (0.08, 0.13, 0.46, 0.12, 0.0),
+ "pine": (0.30, 0.26, 0.35, 0.14, 0.0),
+}
+
+
+def _leaf(center: Vector, normal: Vector, size: float, base: int) -> tuple[list[Vec3], list[tuple[int, ...]]]:
+ n = normal.normalized()
+ helper = Vector((0.0, 0.0, 1.0)) if abs(n.z) < 0.9 else Vector((1.0, 0.0, 0.0))
+ u = n.cross(helper).normalized() * size
+ v = n.cross(u).normalized() * size
+ pts = [center - u - v, center + u - v, center + u + v, center - u + v]
+ return [(p.x, p.y, p.z) for p in pts], [(base, base + 1, base + 2, base + 3)]
+
+
+def _leaf_cloud(batch: Any, mat: Any, center: Vector, radii: Sequence[float], count: int, size: float, r: Any,
+ *, shell: float = 0.55) -> None:
+ """``count`` leaf cards inside the ellipsoid ``radii`` about ``center``, biased to the
+ outer ``shell`` (the inside of a crown is never seen); one ``add`` for the whole cloud."""
+ verts: list[Vec3] = []
+ faces: list[tuple[int, ...]] = []
+ rx, ry, rz = radii
+ for _ in range(max(0, int(count))):
+ d = Vector((r.gauss(0.0, 1.0), r.gauss(0.0, 1.0), r.gauss(0.0, 1.0)))
+ if d.length < 1e-6:
+ continue
+ d.normalize()
+ rad = shell + (1.0 - shell) * r.uniform(0.0, 1.0) ** 0.5
+ p = center + Vector((d.x * rx * rad, d.y * ry * rad, d.z * rz * rad))
+ normal = d + Vector((r.uniform(-0.6, 0.6), r.uniform(-0.6, 0.6), r.uniform(-0.6, 0.6)))
+ v, f = _leaf(p, normal, size * 0.5 * r.uniform(0.7, 1.3), len(verts)) # size = the card's full side
+ verts.extend(v)
+ faces.extend(f)
+ batch.add(mat, verts, faces)
+
+
+def tree(batch: Any, loc: Sequence[float], height: float, bark: Any, foliage: Any, *, seed: int = 0, kind: str = "broadleaf",
+ max_leaves: int = 4000) -> None:
+ """A tree ``height`` m tall standing on ``loc`` (x, y, ground z): a tapered trunk, 4-7
+ branches and a crown of leaf cards (``broadleaf`` / ``oak`` / ``cypress``) or tiered
+ needle cones (``pine``). 3-9 k triangles; ``max_leaves`` caps the crown."""
+ r = rng(seed)
+ x, y, z = (float(v) for v in loc)
+ kind = kind if kind in _CROWN else "broadleaf"
+ trunk_share, krx, krz, leaf, lift = _CROWN[kind]
+ trunk_h = height * trunk_share
+ r0 = max(0.04, height * (0.028 if kind == "cypress" else 0.036))
+ batch.lathe(bark, (x, y), [(r0 * 1.3, z), (r0, z + 0.25), (r0 * 0.72, z + trunk_h), (r0 * 0.3, z + trunk_h + height * 0.28)], sides=10)
+ crown_c = Vector((x, y, z + trunk_h + height * krz * (1.0 + lift)))
+ radii = (height * krx, height * krx * r.uniform(0.85, 1.0), height * krz)
+ if kind == "pine":
+ tiers = 5
+ for k in range(tiers):
+ t = k / (tiers - 1)
+ base_z = z + trunk_h * 0.7 + (height - trunk_h * 0.7) * t * 0.78
+ rad = height * krx * (1.0 - 0.75 * t) * r.uniform(0.9, 1.1)
+ batch.cone(foliage, (x, y, base_z), rad, height * 0.28 * (1.0 - 0.3 * t), top=rad * 0.08, sides=14)
+ return
+ for _ in range(r.randint(4, 7)):
+ a = r.uniform(0.0, math.tau)
+ start = Vector((x, y, z + trunk_h * r.uniform(0.75, 1.0)))
+ end = crown_c + Vector((math.cos(a) * radii[0] * 0.55, math.sin(a) * radii[1] * 0.55, r.uniform(-0.2, 0.5) * radii[2]))
+ batch.beam(bark, start, end, r0 * 0.35, end=r0 * 0.12, sides=6)
+ count = min(int(max_leaves), int(height * height * (34 if kind != "cypress" else 48)))
+ _leaf_cloud(batch, foliage, crown_c, radii, count, leaf, r)
+
+
+def shrub(batch: Any, bark: Any, foliage: Any, center: Sequence[float], *, scale: float = 1.0, seed: int = 0) -> None:
+ """A bush ~1.1 x ``scale`` m tall standing on ``center``: a few stems and 140 leaf cards."""
+ r = rng(seed)
+ x, y, z = (float(v) for v in center)
+ for _ in range(4):
+ a, d = r.uniform(0.0, math.tau), r.uniform(0.1, 0.4) * scale
+ batch.beam(bark, (x, y, z), (x + math.cos(a) * d, y + math.sin(a) * d, z + r.uniform(0.6, 0.9) * scale), 0.02 * scale, end=0.008, sides=5)
+ _leaf_cloud(batch, foliage, Vector((x, y, z + 0.62 * scale)), (0.55 * scale, 0.5 * scale, 0.5 * scale), 140, 0.11 * scale, r, shell=0.45)
+
+
+def leaf_spray(batch: Any, foliage: Any, center: Sequence[float], rng_: Any, *, radius: float = 0.32, count: int = 35) -> None:
+ """``count`` leaf cards within ``radius`` of ``center`` (a vine knot, a creeper on a wall)."""
+ _leaf_cloud(batch, foliage, Vector(tuple(float(v) for v in center)), (radius, radius, radius), count, radius * 0.35, rng_, shell=0.2)
+
+
+def _strip(batch: Any, mat: Any, spine: Sequence[Vector], widths: Sequence[float], up: Vector) -> None:
+ """A ribbon of quads along ``spine`` (its width across ``up`` x direction)."""
+ verts: list[Vec3] = []
+ faces: list[tuple[int, ...]] = []
+ for i, p in enumerate(spine):
+ d = (spine[min(i + 1, len(spine) - 1)] - spine[max(i - 1, 0)])
+ side = d.cross(up).normalized() * (widths[i] / 2) if d.length > 1e-6 else Vector((widths[i] / 2, 0, 0))
+ verts.append((p.x - side.x, p.y - side.y, p.z - side.z))
+ verts.append((p.x + side.x, p.y + side.y, p.z + side.z))
+ for i in range(len(spine) - 1):
+ a = 2 * i
+ faces.append((a, a + 1, a + 3, a + 2))
+ batch.add(mat, verts, faces, smooth=True)
+
+
+def fern(batch: Any, mat: Any, center: Sequence[float], *, scale: float = 1.0, seed: int = 0) -> None:
+ """A fern of 7 arching fronds, ~0.8 x ``scale`` m across, standing on ``center``."""
+ r = rng(seed)
+ x, y, z = (float(v) for v in center)
+ for k in range(7):
+ a = math.tau * k / 7 + r.uniform(-0.2, 0.2)
+ L = scale * r.uniform(0.55, 0.85)
+ spine = []
+ widths = []
+ for i in range(9):
+ t = i / 8
+ spine.append(Vector((x + math.cos(a) * L * t, y + math.sin(a) * L * t, z + 0.02 + L * 0.7 * t * (1.25 - t))))
+ widths.append(0.22 * scale * math.sin(math.pi * min(1.0, t + 0.08)) ** 0.6)
+ _strip(batch, mat, spine, widths, Vector((0.0, 0.0, 1.0)))
+
+
+def tropical(batch: Any, leaves: Any, stem: Any, center: Sequence[float], *, scale: float = 1.0, seed: int = 0) -> None:
+ """A banana-like plant ~2.3 x ``scale`` m tall standing on ``center``: a stem and seven
+ broad arching leaves."""
+ r = rng(seed)
+ x, y, z = (float(v) for v in center)
+ top = z + 1.4 * scale
+ batch.beam(stem, (x, y, z), (x, y, top), 0.07 * scale, end=0.05 * scale, sides=8)
+ for k in range(7):
+ a = math.tau * k / 7 + r.uniform(-0.25, 0.25)
+ L = scale * r.uniform(1.1, 1.5)
+ spine = []
+ widths = []
+ for i in range(10):
+ t = i / 9
+ spine.append(Vector((x + math.cos(a) * L * t, y + math.sin(a) * L * t, top + L * (0.55 * t - 0.75 * t * t))))
+ widths.append(0.42 * scale * math.sin(math.pi * min(1.0, t * 0.85 + 0.1)) ** 0.7)
+ _strip(batch, leaves, spine, widths, Vector((0.0, 0.0, 1.0)))
+
+
+def grass_clump(batch: Any, mats: Any, x: float, y: float, z: float, rng_: Any) -> None:
+ """A tuft of 12 leaning blades 0.25-0.45 m tall at (x, y, z); ``mats`` a material or a
+ list (one picked per blade). 24 triangles."""
+ pool = list(mats) if isinstance(mats, (list, tuple)) else [mats]
+ for _ in range(12):
+ a, lean, h = rng_.uniform(0.0, math.tau), rng_.uniform(0.15, 0.5), rng_.uniform(0.25, 0.45)
+ w = 0.014
+ bx, by = x + rng_.uniform(-0.08, 0.08), y + rng_.uniform(-0.08, 0.08)
+ tip = (bx + math.cos(a) * lean * h, by + math.sin(a) * lean * h, z + h)
+ mid = (bx + math.cos(a) * lean * h * 0.35, by + math.sin(a) * lean * h * 0.35, z + h * 0.55)
+ px, py = -math.sin(a) * w, math.cos(a) * w
+ verts = [(bx - px, by - py, z), (bx + px, by + py, z), (mid[0] + px * 0.6, mid[1] + py * 0.6, mid[2]),
+ (mid[0] - px * 0.6, mid[1] - py * 0.6, mid[2]), tip]
+ batch.add(pool[rng_.randrange(len(pool))], verts, [(0, 1, 2, 3), (3, 2, 4)])
+
+
+def perennial_bed(batch: Any, center: Sequence[float], radius: float, height_at: HeightFn, foliage: Any, petals: Any, rng_: Any) -> None:
+ """A flower bed within ``radius`` of ``center`` (x, y): 20 grass clumps and 30 flower heads
+ on stems, each standing on ``height_at``. ~1 100 triangles."""
+ cx, cy = float(center[0]), float(center[1])
+ for _ in range(20):
+ a, d = rng_.uniform(0.0, math.tau), radius * math.sqrt(rng_.uniform(0.0, 1.0))
+ x, y = cx + d * math.cos(a), cy + d * math.sin(a)
+ grass_clump(batch, foliage, x, y, float(height_at(x, y)), rng_)
+ sv, sf = sphere_template(1)
+ for _ in range(30):
+ a, d = rng_.uniform(0.0, math.tau), radius * math.sqrt(rng_.uniform(0.0, 1.0))
+ x, y = cx + d * math.cos(a), cy + d * math.sin(a)
+ z = float(height_at(x, y))
+ h = rng_.uniform(0.25, 0.5)
+ batch.beam(foliage, (x, y, z), (x, y, z + h), 0.006, sides=4)
+ s = rng_.uniform(0.03, 0.05)
+ batch.add(petals, [(x + vx * s, y + vy * s, z + h + vz * s * 0.6) for vx, vy, vz in sv], list(sf), smooth=True)
+
+
+def _blade(name: str, collection: Any, height: float, color: str) -> Any:
+ """The hidden blade a grass cloud copies: three tapered quads leaning +Y, base at z = 0."""
+ h, w = float(height), 0.02
+ verts = [(-w, 0, 0), (w, 0, 0), (w * 0.7, h * 0.12, h * 0.45), (-w * 0.7, h * 0.12, h * 0.45),
+ (w * 0.35, h * 0.3, h * 0.8), (-w * 0.35, h * 0.3, h * 0.8), (0, h * 0.5, h)]
+ faces = [(0, 1, 2, 3), (3, 2, 4, 5), (5, 4, 6)]
+ blade = mesh_object(name, verts, faces, material(f"{name}Mat", color, roughness=0.65), collection)
+ blade.location = (0.0, 0.0, -200.0)
+ blade.hide_render = True
+ blade.hide_viewport = True
+ return blade
+
+
+def grass_patch(name: str, collection: Any, surface: Any, *, blade: Any = None, density: float = 5.0, seed: int = 0,
+ height: float = 0.3, color: str = "4A6B2A") -> Any:
+ """Grass over ``surface`` (a mesh object — make a hidden ground patch with
+ ``terrain.ground(..., center=…, size=…)`` and ``hide_render = True`` so it follows the
+ terrain without drawing a second ground): ``density`` blades per m², ``height`` m tall in
+ ``color``, or your own ``blade`` object. One geometry-nodes instance cloud (exempt from
+ per-asset placement); 3 quads per blade — a 12 x 12 m patch at density 5 is ~720 blades."""
+ src = blade if blade is not None else _blade(f"{name}Blade", collection, height, color)
+ return gn_scatter(name, collection, surface, src, density=density, seed=seed, align_normal=True, scale_range=(0.7, 1.3))
+
+
+def tree_stand(collection: Any, batch: Any, positions: Sequence[Sequence[float]], height_at: HeightFn, rng_: Any, **tree_kw: Any) -> list[Any]:
+ """Trees at every (x, y) of ``positions`` standing on ``height_at``, added to ``batch`` and
+ finished into ``collection`` as ONE object (a copse, a treeline): returns the objects.
+ ``tree_kw`` = ``bark`` and ``foliage`` (required), ``height`` (varied ±20 %), ``kind``,
+ ``max_leaves``."""
+ bark, foliage = tree_kw.pop("bark"), tree_kw.pop("foliage")
+ base_h = float(tree_kw.pop("height", 7.0))
+ for x, y in ((float(p[0]), float(p[1])) for p in positions):
+ tree(batch, (x, y, float(height_at(x, y))), base_h * rng_.uniform(0.8, 1.2), bark, foliage,
+ seed=rng_.randrange(1_000_000), **tree_kw)
+ return batch.finish(collection)
+
+
+def plant_count(obj: Any) -> int:
+ """How many instances a ``grass_patch`` host places (its modifier's evaluated instances)."""
+ dg = bpy.context.evaluated_depsgraph_get()
+ return sum(1 for inst in dg.object_instances if inst.is_instance and inst.parent is not None and inst.parent.original == obj)
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/water.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/water.py
new file mode 100644
index 00000000..631657b4
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/water.py
@@ -0,0 +1,191 @@
+"""lib/water.py — water surfaces, falls, jets and spray.
+
+A water surface is ONE refracting plane (``materials.water``); the renderer refracts the bed
+through it, so give it a bed (the ground, a basin). Name water things ``…Water`` / ``…Pond``
+/ ``…Lake``: the census files a water-named surface as a backdrop and a foot in it as
+"on water" (a boat, a jetty post), never floating or sunk. Falls and jets are foam sheets
+and thin tubes — no fluid solver; with ``ctx`` their texture drifts between ``ctx.times``.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Sequence
+from typing import Any
+
+import bpy
+
+from lib.materials import _bump, _noise, _ramp
+from lib.materials import water as water_material
+from lib.mesh import Batch, mesh_object
+from lib.motion import drift, scroll
+from lib.noise import fbm2, rng
+from lib.place import unique_name
+
+G = 9.81
+
+
+def foam_shader(name: str) -> Any:
+ """White water: a rough, slightly translucent surface with noisy alpha (edges thin out)."""
+ mat = bpy.data.materials.new(name)
+ nt = mat.node_tree
+ nodes, links, bsdf = nt.nodes, nt.links, nt.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (0.9, 0.94, 0.97, 1.0)
+ bsdf.inputs["Roughness"].default_value = 0.75
+ bsdf.inputs["Transmission Weight"].default_value = 0.2
+ tc = nodes.new("ShaderNodeTexCoord")
+ mp = nodes.new("ShaderNodeMapping")
+ mp.name = "FlowMapping"
+ mp.inputs["Scale"].default_value = (2.0, 2.0, 0.6)
+ links.new(tc.outputs["Object"], mp.inputs["Vector"])
+ n = _noise(nodes, links, mp.outputs["Vector"], scale=3.0, detail=5.0, roughness=0.6)
+ alpha = _ramp(nodes, links, n.outputs["Fac"], [(0.3, (0.15, 0.15, 0.15, 1)), (0.7, (0.95, 0.95, 0.95, 1))])
+ links.new(alpha, bsdf.inputs["Alpha"])
+ _bump(nodes, links, n.outputs["Fac"], bsdf, strength=0.3, distance=0.02)
+ mat.surface_render_method = "BLENDED"
+ return mat
+
+
+def water_surface(name: str, collection: Any, *, size: float | Sequence[float], level: float, material: Any = None,
+ ripple: float = 0.045, seed: int = 0, height_fn: Callable[[float, float], float] | None = None) -> Any:
+ """A ``size`` m water plane at z = ``level`` with ``ripple`` m of gentle swell, centred on
+ the origin (move the object to place it). With ``height_fn`` the cells where the ground
+ stands more than 0.25 m above the water are dropped, so a lake never pokes through its
+ banks. Default material: ``materials.water``. ~4 600 triangles."""
+ sx, sy = (float(size), float(size)) if isinstance(size, (int, float)) else (float(size[0]), float(size[1]))
+ n = 48
+ verts = []
+ keep = []
+ for iy in range(n + 1):
+ y = -sy / 2 + sy * iy / n
+ for ix in range(n + 1):
+ x = -sx / 2 + sx * ix / n
+ verts.append((x, y, float(level) + ripple * fbm2(x * 0.35, y * 0.35, octaves=3, seed=seed)))
+ keep.append(height_fn is None or float(height_fn(x, y)) <= level + 0.25)
+ faces = []
+ for iy in range(n):
+ for ix in range(n):
+ a = iy * (n + 1) + ix
+ quad = (a, a + 1, a + n + 2, a + n + 1)
+ if any(keep[i] for i in quad):
+ faces.append(quad)
+ used = sorted({i for f in faces for i in f})
+ remap = {old: new for new, old in enumerate(used)}
+ mat = material if material is not None else water_material(f"{name}Mat")
+ return mesh_object(name, [verts[i] for i in used], [tuple(remap[i] for i in f) for f in faces], mat, collection, smooth=True)
+
+
+def pool_height(x: float, y: float, *, level: float = -0.25) -> float:
+ """A ``height_at`` for things that float: the water ``level`` everywhere (seat a boat, a
+ lily pad or a lantern with ``place.seat(obj, lambda x, y: pool_height(x, y, level=-0.25))``)."""
+ return float(level)
+
+
+def _sheet(name: str, collection: Any, mat: Any, origin: Sequence[float], across: Sequence[float], along: Sequence[float],
+ width: float, height: float, *, seed: int, speed: float, offset: float) -> Any:
+ """One falling sheet: top edge ``width`` wide at ``origin`` (centre of the lip), falling
+ ``height`` with a parabolic throw along ``along``; rows wobble with noise."""
+ rows, cols = 24, 8
+ ax, ay = float(across[0]), float(across[1])
+ lx, ly = float(along[0]), float(along[1])
+ ox, oy, oz = (float(v) for v in origin)
+ verts = []
+ for r in range(rows + 1):
+ drop = height * r / rows
+ throw = speed * math.sqrt(2.0 * drop / G) + offset
+ for c in range(cols + 1):
+ u = c / cols - 0.5
+ wob = 0.05 * height * fbm2(u * 4.0 + seed, r / rows * 3.0, octaves=2, seed=seed)
+ x = ox + ax * u * width + lx * (throw + wob)
+ y = oy + ay * u * width + ly * (throw + wob)
+ verts.append((x, y, oz - drop))
+ faces = [(r * (cols + 1) + c, r * (cols + 1) + c + 1, (r + 1) * (cols + 1) + c + 1, (r + 1) * (cols + 1) + c)
+ for r in range(rows) for c in range(cols)]
+ return mesh_object(name, verts, faces, mat, collection, smooth=True)
+
+
+def waterfall(name: str, collection: Any, center: Sequence[float], *, width: float, height: float, seed: int = 0,
+ ctx: Any = None, layers: int = 4) -> list[Any]:
+ """A fall ``width`` m wide dropping ``height`` m onto ``center`` (x, y, z of the impact —
+ the pool level), the lip ``height`` above it; ``layers`` foam sheets staggered outward,
+ all under one root Empty (one placement row, its foot at the impact). Flow is toward -Y.
+ With ``ctx`` the foam streams down between ``ctx.times``. ~400 triangles per layer."""
+ cx, cy, cz = (float(v) for v in center)
+ root = bpy.data.objects.new(name, None)
+ root.empty_display_size = 0.25
+ root.location = (cx, cy, cz)
+ collection.objects.link(root)
+ mat = foam_shader(f"{name}Foam")
+ out = [root]
+ for k in range(max(1, int(layers))):
+ sheet = _sheet(f"{name}Sheet_{k}", collection, mat, (cx, cy, cz + height), (1.0, 0.0), (0.0, -1.0), width * (1.0 + 0.06 * k),
+ height, seed=seed + k, speed=0.9 + 0.25 * k, offset=0.08 * k)
+ sheet.parent = root
+ sheet.matrix_parent_inverse = root.matrix_basis.inverted()
+ out.append(sheet)
+ if ctx is not None:
+ scroll(mat.node_tree.nodes["FlowMapping"], (0.0, 0.0, -2.5), ctx)
+ return out
+
+
+def hanging_fall(name: str, collection: Any, outlet: Sequence[float], along: Sequence[float], across: Sequence[float], *,
+ width: float, height: float, seed: int = 0, ctx: Any = None) -> list[Any]:
+ """A single sheet from an ``outlet`` (x, y, z of a spout, a gutter, a broken aqueduct)
+ thrown along the unit direction ``along`` (x, y) and ``width`` m wide along ``across``,
+ falling ``height`` m. Root Empty at the outlet; tag it ``["placement"] = "free"`` when it
+ hangs over nothing. With ``ctx`` the foam streams down."""
+ ox, oy, oz = (float(v) for v in outlet)
+ root = bpy.data.objects.new(name, None)
+ root.empty_display_size = 0.25
+ root.location = (ox, oy, oz)
+ collection.objects.link(root)
+ mat = foam_shader(f"{name}Foam")
+ sheet = _sheet(f"{name}Sheet", collection, mat, (ox, oy, oz), across, along, width, height, seed=seed, speed=1.2, offset=0.0)
+ sheet.parent = root
+ sheet.matrix_parent_inverse = root.matrix_basis.inverted()
+ if ctx is not None:
+ scroll(mat.node_tree.nodes["FlowMapping"], (0.0, 0.0, -2.5), ctx)
+ return [root, sheet]
+
+
+def droplets(batch: Any, mat: Any, center: Sequence[float], width: float, bottom: float, rng_: Any, count: int = 260) -> None:
+ """``count`` tiny tetrahedra (spray, drips, sparks) in a cloud ``width`` m wide centred on
+ ``center`` (x, y, z), its lowest at z = ``bottom``; 4 triangles each."""
+ cx, cy, cz = (float(v) for v in center)
+ top = cz + (cz - float(bottom))
+ s = 0.012
+ for _ in range(max(0, int(count))):
+ x, y = cx + rng_.uniform(-width / 2, width / 2), cy + rng_.uniform(-width / 2, width / 2)
+ z = rng_.uniform(float(bottom) + s, top)
+ verts = [(x + s, y + s, z + s), (x - s, y - s, z + s), (x - s, y + s, z - s), (x + s, y - s, z - s)]
+ batch.add(mat, verts, [(0, 1, 2), (0, 3, 1), (0, 2, 3), (1, 3, 2)])
+
+
+def fountain_jets(batch: Any, collection: Any, water_mat: Any, *, center: Sequence[float], nozzle_r: float, landing_r: float,
+ count: int = 14, rise: float = 1.85, ctx: Any = None, seed: int = 0) -> Any:
+ """``count`` parabolic jets from a ring of radius ``nozzle_r`` to one of ``landing_r``
+ around ``center`` (x, y, z of the basin's water level), peaking ``rise`` m up, as thin
+ tubes in ``batch`` plus a spray cloud at the landing ring. With ``ctx`` a second spray
+ cloud is finished into ``collection`` (tagged free) and falls between ``ctx.times``;
+ returned, else None. ~220 triangles per jet."""
+ cx, cy, cz = (float(v) for v in center)
+ r = rng(seed)
+ for i in range(max(1, int(count))):
+ a = math.tau * i / count + r.uniform(-0.05, 0.05)
+ pts = []
+ for k in range(13):
+ t = k / 12
+ rad = nozzle_r + (landing_r - nozzle_r) * t
+ z = cz + 4.0 * rise * t * (1.0 - t)
+ pts.append((cx + rad * math.cos(a), cy + rad * math.sin(a), z))
+ for k in range(12):
+ batch.beam(water_mat, pts[k], pts[k + 1], 0.02, sides=6)
+ droplets(batch, water_mat, (cx, cy, cz + 0.22), landing_r * 2.2, cz + 0.01, r, count=140)
+ if ctx is None:
+ return None
+ spray = Batch(unique_name(f"{batch.name}Spray", 0))
+ droplets(spray, water_mat, (cx, cy, cz + rise * 0.55), landing_r * 1.6, cz + rise * 0.2, r, count=160)
+ objs = spray.finish(collection)
+ objs[0]["placement"] = "free"
+ drift(objs[0], (0.0, 0.0, -rise * 0.3), ctx)
+ return objs[0]
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/scene.py b/harness/codeverse3d/languages/scene_blender/starter/src/scene.py
new file mode 100644
index 00000000..33de7429
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/scene.py
@@ -0,0 +1,26 @@
+"""src/scene.py — ASSEMBLED BY THE HARNESS (codeverse3d assembler). Edit env / zones / assets
+instead; re-assembly overwrites this file.
+EXAMPLE: a lakeside hamlet at golden hour — the plan-less starter scene (every zone and asset is
+built from src/lib; read them as worked examples of the library).
+
+The harness builds the scene in one Blender process: env.build_env(ctx); every hero GLB and asset
+module (build_<snake>(ctx)); then every zone's build(ctx) — each on its own (a zone that raises is
+dropped and reported with its file:line); then the CAMERAS below (Z up, -Y front, metres; fov is
+the VERTICAL field of view in degrees). The census is the t = 0 pose, frame 1.
+"""
+
+ZONES = {
+ "hamlet": "Hamlet",
+ "lakeside": "Lakeside",
+ "orchard": "Orchard",
+}
+ASSETS = {
+ "crate": "Crate",
+ "lantern_post": "LanternPost",
+}
+HEROES = {}
+CAMERAS = [
+ {"name": "village_street", "location": (1.0, -22.0, 1.8), "look_at": (3.0, 10.0, 1.6), "fov": 42},
+ {"name": "lake_shore", "location": (-4.0, -24.0, 2.4), "look_at": (-24.0, 4.0, 0.2), "fov": 48},
+ {"name": "orchard_walk", "location": (36.0, -30.0, 2.2), "look_at": (20.0, -10.0, 1.2), "fov": 45},
+]
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/zones/hamlet.py b/harness/codeverse3d/languages/scene_blender/starter/src/zones/hamlet.py
new file mode 100644
index 00000000..d094ac4e
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/zones/hamlet.py
@@ -0,0 +1,60 @@
+"""src/zones/hamlet.py — zone "Hamlet": two half-timbered houses around a paved yard, lantern
+posts, a signpost and a few villagers.
+
+CONTRACT: build(ctx) -> bpy.types.Collection — ctx.collection is this zone's; every PLACED thing
+is ONE root object in it (a Batch root, an instance Empty), named <Name>_<i>, seated on
+ctx.height_at. Assets are collection instances of ctx.assets['<snake>'] (lib.scatter.instance).
+"""
+from lib import architecture, figure, materials, mesh, place, scatter
+
+SEED = 11
+HOUSES = ((-2.0, 14.0, 7.0, 5.5, 2), (9.5, 15.0, 6.0, 5.0, 1)) # x, y, width, depth, floors
+YARD = (4.0, 7.0)
+
+
+def build(ctx):
+ rng = ctx.rng(SEED)
+ h = ctx.height_at
+ wall = materials.limestone("HamletWall", "D8CDB4")
+ timber = materials.woodgrain(materials.material("HamletTimber", "4A3220", roughness=0.75))
+ tile = materials.material("HamletTile", "7A4A3A", roughness=0.85, noise_scale=4.0)
+ pane = materials.glass("HamletPane", "DDE6EE", roughness=0.1)
+ door = materials.chipped_paint(materials.material("HamletDoor", "2F5F8F", roughness=0.5), "2F5F8F", "6B5A48")
+ stones = [materials.limestone("YardStone", "A79F8E", scale=3.0), materials.limestone("YardStoneDark", "8E867A", scale=3.0)]
+ mats = {"wall": wall, "timber": timber, "door": door, "window": pane}
+ roofs = {"tile": tile, "trim": timber}
+
+ for i, (x, y, w, d, floors) in enumerate(HOUSES):
+ b = mesh.Batch(place.unique_name("House", i))
+ architecture.timber_house(b, roofs, x, y, w, d, floors, mats, rng, i)
+ root = b.finish(ctx.collection)[0]
+ place.seat(root, h) # built at z = 0; the ground may not be exactly there
+
+ yard = mesh.Batch("Yard_0")
+ architecture.paving(yard, stones, center=(YARD[0], YARD[1], h(*YARD)), inner_r=0.8, rings=7, seed=SEED)
+ yard.finish(ctx.collection)
+
+ post = mesh.Batch("Signpost_0")
+ post.beam(timber, (10.0, 6.0, h(10.0, 6.0)), (10.0, 6.0, h(10.0, 6.0) + 2.3), 0.06, sides=8)
+ post.box(timber, (10.0, 6.0, h(10.0, 6.0) + 2.0), (1.6, 0.06, 0.45))
+ root = post.finish(ctx.collection)[0]
+ sign = architecture.text_mesh("SignText_0", ctx.collection, "OLD MILL INN", (10.0, 5.95, h(10.0, 6.0) + 1.85), 0.22,
+ materials.material("SignPaint", "F2E6C8", roughness=0.6))
+ sign.parent = root # the text rides the post: one placement row
+ sign.matrix_parent_inverse = place.world_matrix(root).inverted()
+
+ coats = [materials.material("CoatRed", "7A2E2E", roughness=0.85), materials.material("CoatBlue", "2E4A7A", roughness=0.85),
+ materials.material("CoatGreen", "4A6A3A", roughness=0.85), materials.material("Skin", "D9A880", roughness=0.6)]
+ folk = mesh.Batch("Villagers_0")
+ spots = [(2.5, 4.0), (6.0, 3.0), (7.5, 9.5), (-1.0, 9.0)]
+ figure.crowd(folk, coats, [(x, y, h(x, y)) for x, y in spots], rng)
+ folk.finish(ctx.collection)
+
+ lantern = ctx.assets.get("lantern_post")
+ if lantern is not None:
+ scatter.scatter(ctx.collection, lantern, "LanternPost", [(-1.0, 4.5), (9.0, 3.5), (12.5, 10.5)], height_at=h, rng=rng, rot=0.0)
+ crate = ctx.assets.get("crate")
+ if crate is not None:
+ for i, (x, y, yaw) in enumerate(((3.6, 14.5, 0.3), (4.5, 15.2, 1.2), (13.2, 13.5, 0.0))):
+ scatter.instance(ctx.collection, crate, place.unique_name("Crate", i), x, y, height_at=h, rot_z=yaw)
+ return ctx.collection
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/zones/lakeside.py b/harness/codeverse3d/languages/scene_blender/starter/src/zones/lakeside.py
new file mode 100644
index 00000000..d518fabd
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/zones/lakeside.py
@@ -0,0 +1,49 @@
+"""src/zones/lakeside.py — zone "Lakeside": the lake in the env's basin, a wooden footbridge over
+its edge, shore rocks, reeds and a willow.
+
+CONTRACT: build(ctx) -> bpy.types.Collection — every placed thing is ONE root object seated on
+ctx.height_at; the water is a water-named surface (the census files it as a backdrop and a foot
+in it as on water).
+"""
+from lib import architecture, materials, mesh, terrain, vegetation, water
+
+SEED = 21
+LAKE = (-24.0, 2.0) # == env.BASIN's centre
+
+
+def build(ctx):
+ rng = ctx.rng(SEED)
+ h = ctx.height_at
+ level = float(ctx.env.get("water_level", -0.3))
+
+ lake = water.water_surface("LakeWater", ctx.collection, size=(34.0, 34.0), level=level,
+ material=materials.water("LakeWaterMat", color="1A3F4A", ctx=ctx),
+ height_fn=lambda x, y: h(x + LAKE[0], y + LAKE[1]))
+ lake.location = (LAKE[0], LAKE[1], 0.0)
+
+ rock = materials.mineral_surface("ShoreRock", "6F6A60", stone=True)
+ rocks = mesh.Batch("ShoreRocks_0")
+ terrain.rock_field(rocks, rock, (LAKE[0] + 13.0, LAKE[1] - 7.0), 4.5, 14, h, rng)
+ terrain.boulder(rocks, rock, (LAKE[0] + 11.0, LAKE[1] + 10.0, h(LAKE[0] + 11.0, LAKE[1] + 10.0)), 1.6, seed=3)
+ rocks.finish(ctx.collection)
+
+ wood = materials.woodgrain(materials.material("BridgeWood", "5A4330", roughness=0.8))
+ stone = materials.ashlar("BridgeStone", "9A9080")
+ bridge = mesh.Batch("Footbridge_0")
+ start, end = (LAKE[0] + 12.7, LAKE[1] - 12.7), (LAKE[0] + 8.5, LAKE[1] - 8.5) # bank top → the shallows
+ architecture.arched_footbridge(bridge, wood, stone, start=(*start, h(*start)), end=(*end, h(*end)), rise=1.1, height_at=h)
+ bridge.finish(ctx.collection)
+
+ reed_bed = terrain.ground("ReedSurface", ctx.collection, size=(9.0, 6.0), segments=6, height_at=h, material=None,
+ center=(LAKE[0] + 13.5, LAKE[1] + 5.0))
+ reed_bed.hide_render = True # the distribution domain only: the cloud draws
+ reed_bed.hide_viewport = True
+ vegetation.grass_patch("Reeds_0", ctx.collection, reed_bed, density=5.0, seed=SEED, height=1.2, color="6B7A3A")
+
+ bark = materials.material("WillowBark", "4A3A2A", roughness=0.9, noise_scale=6.0)
+ leaves = materials.foliage("WillowLeaf", "6A8A3A", variants=2)
+ willow = mesh.Batch("Willow_0")
+ wx, wy = LAKE[0] + 16.5, LAKE[1] + 1.0
+ vegetation.tree(willow, (wx, wy, h(wx, wy)), 7.5, bark, leaves[0], seed=SEED, kind="broadleaf", max_leaves=1800)
+ willow.finish(ctx.collection)
+ return ctx.collection
diff --git a/harness/codeverse3d/languages/scene_blender/starter/src/zones/orchard.py b/harness/codeverse3d/languages/scene_blender/starter/src/zones/orchard.py
new file mode 100644
index 00000000..e81c087b
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/starter/src/zones/orchard.py
@@ -0,0 +1,37 @@
+"""src/zones/orchard.py — zone "Orchard": a stand of apple trees, a hedge, a flower bed and
+harvest crates (instances of the crate asset).
+
+CONTRACT: build(ctx) -> bpy.types.Collection — every placed thing is ONE root object seated on
+ctx.height_at (lib.vegetation recipes stand on the z you pass; lib.scatter seats instances).
+"""
+from lib import materials, mesh, scatter, vegetation
+
+SEED = 31
+CENTER = (20.0, -12.0)
+
+
+def build(ctx):
+ rng = ctx.rng(SEED)
+ h = ctx.height_at
+ bark = materials.material("OrchardBark", "4A3524", roughness=0.9, noise_scale=6.0)
+ leaves = materials.foliage("OrchardLeaf", "4F7A2E", variants=3)
+
+ rows = scatter.grid(CENTER, (16.0, 12.0), 4.5, rng, jitter=0.2)
+ vegetation.tree_stand(ctx.collection, mesh.Batch("AppleTrees_0"), rows, h, rng, bark=bark, foliage=leaves[1],
+ height=4.5, kind="broadleaf", max_leaves=700)
+
+ hedge = mesh.Batch("Hedge_0")
+ for i, (x, y) in enumerate(scatter.along_path([(10.0, -3.5), (30.0, -3.5)], 10)):
+ vegetation.shrub(hedge, bark, leaves[i % 3], (x, y, h(x, y)), scale=1.1, seed=SEED + i)
+ hedge.finish(ctx.collection)
+
+ petals = materials.material("Petals", "D94A6A", roughness=0.7)
+ bed = mesh.Batch("FlowerBed_0")
+ vegetation.perennial_bed(bed, (12.5, -19.0), 2.0, h, leaves[0], petals, rng)
+ bed.finish(ctx.collection)
+
+ crate = ctx.assets.get("crate")
+ if crate is not None:
+ spots = scatter.poisson(rng, area=(24.0, -22.0, 30.0, -16.0), min_dist=1.6, max_count=5)
+ scatter.scatter(ctx.collection, crate, "HarvestCrate", spots, height_at=h, rng=rng, scale=(0.85, 1.1))
+ return ctx.collection
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index 0b96086a..5d6c9ddc 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -23,10 +23,13 @@ from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, Z
from codeverse3d.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake
from codeverse3d.languages._common import line_of, missing_entry, target_file, target_line, ws_rel
from codeverse3d.languages._js_lint import (
+ ExportsCache,
ImportKind,
ImportVerdict,
SyntaxProblem,
check_imports,
+ check_named_imports,
+ describe_exports,
js_sources,
node_check_syntax,
strip_js,
@@ -85,7 +88,12 @@ def _syntax_finding(p: SyntaxProblem, rel: str) -> GateFinding:
hint="fix the syntax error at the quoted line (node --check)", line=p.line, detail=p.stderr_tail)
-def _check_imports(rel: str, text: str, ws: Workspace, path: Path) -> list[GateFinding]:
+def _check_imports(rel: str, text: str, ws: Workspace, path: Path, export_cache: ExportsCache) -> list[GateFinding]:
+ """The import policy on one agent file: the specifier kinds, then — for a relative target
+ that exists — every imported name against what the target exports. ``src/lib`` modules
+ are never linted as agent code, but they ARE read here as targets (``export_cache`` holds
+ each one's surface for the whole lint): a name the catalog does not list is a SyntaxError
+ at module link, which drops the whole zone at assembly."""
def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
tgt = f"{rel}:{line}"
if v.kind is ImportKind.ESCAPES:
@@ -98,7 +106,14 @@ def _check_imports(rel: str, text: str, ws: Workspace, path: Path) -> list[GateF
return _f(LintKind.BAD_IMPORT, Severity.ERROR, f"import '{spec}' is not allowed (only 'three', 'three/addons/*', relative files)", target=tgt,
hint="no CDN / npm packages; write the helper yourself in src/")
- return check_imports(text, path, ws.src, make_finding=make_finding)[0]
+ def missing_name(spec: str, name: str, line: int, names: frozenset[str]) -> GateFinding:
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR,
+ f"import {{ {name} }} from '{spec}': that module exports no '{name}' ({describe_exports(names)})",
+ target=f"{rel}:{line}",
+ hint="import only names the module actually exports (for src/lib modules: the names the effects catalog lists)")
+
+ findings = check_imports(text, path, ws.src, make_finding=make_finding)[0]
+ return findings + check_named_imports(text, path, ws.src, make_finding=missing_name, exports=export_cache)
def lint(ws: Workspace) -> GateReport:
@@ -112,6 +127,7 @@ def lint(ws: Workspace) -> GateReport:
hint="create src/scene.js exporting createScene({THREE, renderer, loaders})"))
big: list[str] = []
syntax = node_check_syntax(files)
+ export_cache: ExportsCache = {}
for path in files:
rel = ws_rel(ws, path)
text = path.read_text(errors="replace")
@@ -120,7 +136,7 @@ def lint(ws: Workspace) -> GateReport:
continue
if _is_lib(path, ws):
continue
- findings.extend(_check_imports(rel, text, ws, path))
+ findings.extend(_check_imports(rel, text, ws, path, export_cache))
code = strip_js(text, strings=False) # a comment quoting the contract is not a call
for pat, sev, msg, hint, kind in _PATTERNS:
m = pat.search(code)
@@ -702,6 +718,8 @@ def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "de
class SceneThreeJsRuntime:
language = Language.SCENE_THREEJS
entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.SCENE_THREEJS], "src/zones/*.js", "src/assets/*.js", "src/env.js", "src/shaders/*.js")
+ #: ``SceneRuntime.env_file``: the module the env stage writes (``SCENE_FILES[1]``)
+ env_file: str = SCENE_FILES[1]
zone_file = staticmethod(zone_file)
asset_file = staticmethod(asset_file)
diff --git a/harness/codeverse3d/languages/threejs/__init__.py b/harness/codeverse3d/languages/threejs/__init__.py
index 38d2677c..1ddba696 100644
--- a/harness/codeverse3d/languages/threejs/__init__.py
+++ b/harness/codeverse3d/languages/threejs/__init__.py
@@ -14,10 +14,14 @@ from codeverse3d.contracts.plan import Plan, StaticPlan
from codeverse3d.conventions import to_pascal, to_snake
from codeverse3d.languages._common import BUILD_TIMEOUT, line_of, missing_entry, ws_rel
from codeverse3d.languages._js_lint import (
+ ExportsCache,
ImportKind,
ImportVerdict,
check_imports,
+ check_named_imports,
+ describe_exports,
js_sources,
+ module_exports,
strip_js,
)
from codeverse3d.languages._js_lint import (
@@ -96,9 +100,6 @@ PLACEHOLDER_COLORS = ("0x9aa5b1", "0xb08968", "0x7f8c8d", "0xc0a080", "0x6c7a89"
# ===================================================================== lint
GATE = "lint:threejs"
-_EXPORT_BUILD_RE = re.compile(r"\bexport\s+(?:async\s+)?function\s+(build[A-Za-z0-9_]*)\s*\(")
-_EXPORT_CONST_BUILD_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+(build[A-Za-z0-9_]*)\s*=")
-_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
# token -> (severity, message, fix hint, kind)
_FORBIDDEN: dict[str, tuple[Severity, str, str, LintKind]] = {
r"\bfetch\s*\(": (Severity.ERROR, "network access (fetch) is not allowed in object code", "build geometry procedurally; no downloads", LintKind.SANDBOX),
@@ -124,8 +125,9 @@ def _f(kind: LintKind, sev: Severity, target: str, message: str, hint: str) -> G
return GateFinding(gate=GATE, severity=sev, target=target, message=message, fix_hint=hint, data={"kind": kind.value})
-def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> set[Path]:
- """Validate import specifiers; return the set of resolved relative targets."""
+def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding], export_cache: ExportsCache) -> set[Path]:
+ """Validate import specifiers and, on a relative target, the imported names (a name the
+ part does not export is a SyntaxError at link); return the set of resolved relative targets."""
rel = ws_rel(ws, path)
def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
@@ -140,8 +142,14 @@ def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFindin
return _f(LintKind.BAD_IMPORT, Severity.ERROR, rel, f"{rel}:{line}: import of {kind} '{spec}' is not allowed",
"only 'three', 'three/addons/...' and relative './' imports are available")
+ def missing_name(spec: str, name: str, line: int, names: frozenset[str]) -> GateFinding:
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, rel,
+ f"{rel}:{line}: import {{ {name} }} from '{spec}': that module exports no '{name}' ({describe_exports(names)})",
+ "import only names the module actually exports (a part file exports build<Pascal>(THREE))")
+
new, targets = check_imports(src, path, ws.src, make_finding=make_finding)
findings.extend(new)
+ findings.extend(check_named_imports(src, path, ws.src, make_finding=missing_name, exports=export_cache))
return targets
@@ -155,17 +163,8 @@ def _lint_forbidden(ws: Workspace, path: Path, src: str, findings: list[GateFind
def _exports(src: str) -> set[str]:
- names = {m.group(1) for m in _EXPORT_BUILD_RE.finditer(src)}
- names |= {m.group(1) for m in _EXPORT_CONST_BUILD_RE.finditer(src)}
- for m in _EXPORT_LIST_RE.finditer(src):
- for item in m.group(1).split(","):
- item = item.strip()
- if not item:
- continue
- alias = item.split(" as ")[-1].strip()
- if alias.startswith("build"):
- names.add(alias)
- return names
+ """The ``build*`` names ``src`` exports (what the entry and every part file must provide)."""
+ return {n for n in module_exports(src) or () if n.startswith("build")}
def lint_workspace(ws: Workspace) -> GateReport:
@@ -175,6 +174,7 @@ def lint_workspace(ws: Workspace) -> GateReport:
entry = ws.src / "object.js"
sources = js_sources(ws.src)
syntax = check_syntax(sources)
+ export_cache: ExportsCache = {}
if not entry.is_file():
findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, "src/object.js",
@@ -189,7 +189,7 @@ def lint_workspace(ws: Workspace) -> GateReport:
findings.append(_f(LintKind.SYNTAX, Severity.ERROR, rel, f"{rel}:{syn.line or '?'}: {syn.message}",
"fix the syntax error at that line"))
continue # other checks are noise on a file that does not parse
- imported |= _lint_imports(ws, path, src, findings)
+ imported |= _lint_imports(ws, path, src, findings, export_cache)
_lint_forbidden(ws, path, src, findings)
exports = _exports(src)
if path == entry:
diff --git a/harness/codeverse3d/languages/wrappers/_census_glb.py b/harness/codeverse3d/languages/wrappers/_census_glb.py
index 398bc6c6..2577ee92 100644
--- a/harness/codeverse3d/languages/wrappers/_census_glb.py
+++ b/harness/codeverse3d/languages/wrappers/_census_glb.py
@@ -308,6 +308,12 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
host = inst.parent.original if inst.parent is not None else None
if host is None or host.hide_render or is_volume_only(ob):
continue
+ if host.type in MEASURABLE_TYPES and host.type != "MESH":
+ # a bevelled curve / a text object: the depsgraph lists the owner's own evaluated
+ # mesh component as an instance OF the owner (Blender 5.2.2, measured 2026-10-14:
+ # is_instance, parent = the curve, original = the curve) — written once, from the
+ # owner, by _write_other_types; a cloud here would be a phantom second copy
+ continue
ix = w.mesh(ob.data.as_pointer(), ob.data, [s.material for s in ob.material_slots])
if ix is None:
continue
diff --git a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
index 053e6522..dc3da7cf 100644
--- a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
+++ b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
@@ -8,12 +8,13 @@ the BLENDER frame (Z-up, -Y front, metres — the harness converts, ``convention
{"out": "/abs/dir", "result": "/abs/dir/blender_frames.json",
"engine": "cycles" | "eevee" | "workbench", "samples": 32, "device": "GPU" | "CPU",
- "width": 1024, "height": 576, "times": [0.0, 1.5], "authored": true,
- "cameras": [{"name", "kind", "position", "look_at", "fov", "no_fog", "times"}]}
+ "frame_time_limit_s": 20.0, "width": 1024, "height": 576, "times": [0.0, 1.5],
+ "authored": true, "cameras": [{"name", "kind", "position", "look_at", "fov", "no_fog", "times"}]}
What it does:
1. render settings — ALL harness-owned, whatever the .blend carries: engine, samples,
- device (Cycles CUDA; no CUDA device → CPU, recorded), adaptive sampling + OIDN, a fixed
+ device (Cycles CUDA; no CUDA device → CPU, recorded), adaptive sampling + OIDN on the GPU,
+ persistent data (the scene is synced once for all cameras), a per-frame time cap, a fixed
seed, AgX / look None / exposure 0 on the sRGB display, RGB 8-bit PNG, no transparent film;
2. cameras: with ``authored`` the .blend's own camera objects (``scene["c3d_cameras"]`` gives
their order, else the scene camera first then by name; ``cam["c3d_look_at"]`` their target,
@@ -21,7 +22,11 @@ What it does:
per job spec (vertical ``fov`` like three.js), at the spec's own times;
3. per time (ascending): ``frame_set(1 + round(t * fps))``, then every camera renders one PNG
``<name>_<tag>.png`` (the three.js driver's file names); ``no_fog`` views render with the
- world volume unlinked (the overview rig reads structure, not atmosphere);
+ world volume unlinked AND a room shell's lid lifted — every mesh named ``Ceiling…`` under
+ a ``RoomShell…`` parent whose evaluated world bbox top is below the camera is render-hidden
+ for that frame (the three.js host's ``skyLayersBelow`` rule, scene_host.mjs; the rubric
+ tells the judge the high overviews show interiors with the lid off) and named in the
+ frame's ``hidden`` (the overview rig reads structure, not atmosphere);
4. writes the result json atomically: the frames (Blender-frame poses, per-frame wall ms),
the device actually used, the GL renderer (EEVEE / Workbench) and every per-frame error.
@@ -100,6 +105,8 @@ def setup_render(scene: Any, job: dict[str, Any]) -> dict[str, Any]:
if engine == "cycles":
c = scene.cycles
if want == "GPU":
+ # CUDA only — OptiX is never probed: on this WSL2 box Blender 5.2.2 has no libnvoptix
+ # (init error 7804) and setting compute_device_type to OPTIX and back crashes Blender.
prefs = bpy.context.preferences.addons["cycles"].preferences
try:
prefs.compute_device_type = "CUDA"
@@ -122,6 +129,14 @@ def setup_render(scene: Any, job: dict[str, Any]) -> dict[str, Any]:
c.denoising_use_gpu = info["device"] == "GPU"
c.seed = 0
c.use_animated_seed = False
+ # The fast path (Blender 5.2.2 LTS, RTX 5090, 1024x576, 460 objects, 32 spp): persistent
+ # data keeps the synced scene + BVH across the cameras of one job — 8 frames 5.3 s → 2.2 s
+ # (0.64 → 0.21 s per frame after the first). The per-frame time cap bounds a heavy
+ # scene's sampling (0 = none); the job's render timeout is the outer wall.
+ r.use_persistent_data = True
+ c.time_limit = max(0.0, float(job.get("frame_time_limit_s") or 0.0))
+ info["persistent_data"] = True
+ info["frame_time_limit_s"] = c.time_limit
elif engine == "eevee":
scene.eevee.taa_render_samples = samples
info["device"] = want # the GL context decides; the harness picks the env (d3d12 = GPU)
@@ -191,7 +206,7 @@ def harness_camera(spec: dict[str, Any]) -> Any:
def unlink_world_volume(scene: Any) -> list[tuple[Any, Any]]:
"""Remove the world output's Volume links; returns them for ``relink``."""
w = scene.world
- if w is None or not w.use_nodes or w.node_tree is None:
+ if w is None or w.node_tree is None: # 5.x: a world always has a node tree (use_nodes is deprecated)
return []
removed = []
for n in w.node_tree.nodes:
@@ -207,6 +222,35 @@ def relink(scene: Any, links: list[tuple[Any, Any]]) -> None:
scene.world.node_tree.links.new(a, b)
+# --------------------------------------------------------------------------- room shells
+ROOM_SHELL_PREFIX, LID_PREFIX = "RoomShell", "Ceiling"
+
+
+def lift_lids(scene: Any, camera: Any) -> list[Any]:
+ """Render-hide every room shell lid under ``camera`` and return those objects (restore with
+ ``hide_render = False``). A lid is a mesh object named ``Ceiling…`` whose parent is named
+ ``RoomShell…`` (what ``lib.architecture.room_shell`` builds — the prompts promise the author
+ the rig lifts it by name) and whose evaluated world-space bbox top is below the camera's
+ z: ``scene_host.skyLayersBelow``'s rule, so both languages' overview tiles show the same
+ interior. An author's own roof, a lid the camera is under, an already hidden lid and
+ linked library data (never written) stay."""
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ eye_z = camera.evaluated_get(depsgraph).matrix_world.translation.z
+ lids = []
+ for ob in scene.objects:
+ if ob.type != "MESH" or ob.hide_render or ob.parent is None or ob.library is not None:
+ continue
+ if not (ob.name.startswith(LID_PREFIX) and ob.parent.name.startswith(ROOM_SHELL_PREFIX)):
+ continue
+ ev = ob.evaluated_get(depsgraph)
+ top = max((ev.matrix_world @ Vector(corner)).z for corner in ev.bound_box)
+ if top < eye_z:
+ lids.append(ob)
+ for ob in lids:
+ ob.hide_render = True
+ return lids
+
+
def gl_renderer() -> str:
try:
import gpu
@@ -260,6 +304,7 @@ def main() -> int:
scene.camera = s["object"]
scene.render.filepath = os.path.join(out, path)
fog = unlink_world_volume(scene) if s.get("no_fog") else []
+ lids = lift_lids(scene, s["object"]) if s.get("no_fog") else []
t0 = time.perf_counter()
try:
bpy.ops.render.render(write_still=True)
@@ -269,6 +314,8 @@ def main() -> int:
finally:
if fog:
relink(scene, fog)
+ for ob in lids:
+ ob.hide_render = False
ms = int((time.perf_counter() - t0) * 1000)
if not os.path.isfile(os.path.join(out, path)):
result["errors"].append(f"render of '{s['name']}' at t={t:g} wrote no image")
@@ -276,7 +323,7 @@ def main() -> int:
result["frames"].append({
"name": s["name"], "kind": s["kind"], "path": path, "time_s": t, "frame": frame,
"position": s["position"], "look_at": s["look_at"], "fov": s["fov"],
- "no_fog": bool(s.get("no_fog")), "render_ms": ms,
+ "no_fog": bool(s.get("no_fog")), "hidden": sorted(ob.name for ob in lids), "render_ms": ms,
})
if result["engine"] in ("eevee", "workbench"):
result["gl_renderer"] = gl_renderer()
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy.py b/harness/codeverse3d/languages/wrappers/run_bpy.py
index 5576f506..1d9729e8 100644
--- a/harness/codeverse3d/languages/wrappers/run_bpy.py
+++ b/harness/codeverse3d/languages/wrappers/run_bpy.py
@@ -128,7 +128,7 @@ def select_exportables(bpy: Any) -> list[Any]:
def export_glb(bpy: Any, path: str) -> None:
- """Kwargs verified on Blender 5.0.1 (io_scene_gltf2)."""
+ """Kwargs verified on Blender 5.2.2 LTS (io_scene_gltf2; the offline suite exercises this call)."""
bpy.ops.export_scene.gltf(
filepath=path,
export_format="GLB",
@@ -151,10 +151,8 @@ def export_glb(bpy: Any, path: str) -> None:
def export_stl(bpy: Any, path: str) -> None:
- if hasattr(bpy.ops.wm, "stl_export"): # Blender 4.2+ native exporter (Z-up, -Y... forward 'Y' default)
- bpy.ops.wm.stl_export(filepath=path, export_selected_objects=True, apply_modifiers=True, ascii_format=False, global_scale=1.0)
- else: # legacy add-on
- bpy.ops.export_mesh.stl(filepath=path, use_selection=True, use_mesh_modifiers=True, ascii=False)
+ """The native exporter (forward 'Y' default, Z-up); Blender 5.2 LTS only (D104)."""
+ bpy.ops.wm.stl_export(filepath=path, export_selected_objects=True, apply_modifiers=True, ascii_format=False, global_scale=1.0)
# ----------------------------------------------------------------------------- main
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
index 4681d2e0..608b962c 100644
--- a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
+++ b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
@@ -408,6 +408,8 @@ def scene_facts(bpy: Any, handlers_before: dict[str, int]) -> dict[str, Any]:
continue
if ob.type not in ("MESH", "CURVE", "SURFACE", "FONT", "META") or (inst.is_instance and ob.type != "MESH"):
continue
+ if inst.is_instance and inst.parent is not None and inst.parent.original.type in ("CURVE", "SURFACE", "FONT", "META"):
+ continue # a curve / text's own evaluated mesh component (counted from the owner; _census_glb skips it too)
src = ob if inst.is_instance else ob.original
if is_volume_only(src):
if not inst.is_instance:
diff --git a/harness/codeverse3d/prompts/__init__.py b/harness/codeverse3d/prompts/__init__.py
index 0ee4a008..2b84ce44 100644
--- a/harness/codeverse3d/prompts/__init__.py
+++ b/harness/codeverse3d/prompts/__init__.py
@@ -1,4 +1,11 @@
-"""Prompt loader: markdown + jinja2 templates, content-hashed for provenance."""
+"""Prompt loader: markdown + jinja2 templates, content-hashed for provenance.
+
+Every name resolves through the ACTIVE VARIANT first (``prompts/variants.py``, D105): a file
+``variants/<name>/<rel>`` shadows ``<rel>``, a missing overlay file falls back to the base, and
+with no variant active nothing here changes — the base environment is the single
+``FileSystemLoader`` it always was, so base rendering is byte-identical (the manifest pins it).
+Callers do not change: ``load_text`` / ``render`` / ``catalog.language_text`` take the same names.
+"""
from __future__ import annotations
@@ -8,36 +15,66 @@ from functools import lru_cache
from pathlib import Path
from typing import Any
-from jinja2 import ChainableUndefined, Environment, FileSystemLoader, StrictUndefined
+from jinja2 import ChainableUndefined, ChoiceLoader, Environment, FileSystemLoader, StrictUndefined
from jinja2.exceptions import UndefinedError
+from codeverse3d.prompts.variants import active_variant, variant_root
+
log = logging.getLogger(__name__)
PROMPTS_DIR = Path(__file__).resolve().parent
-_env = Environment(
- loader=FileSystemLoader(str(PROMPTS_DIR)),
- undefined=StrictUndefined,
- trim_blocks=True,
- lstrip_blocks=True,
- keep_trailing_newline=True,
- autoescape=False,
-)
+#: the flags every prompt environment renders with — the base one and each variant's
+_FLAGS: dict[str, Any] = {"undefined": StrictUndefined, "trim_blocks": True, "lstrip_blocks": True,
+ "keep_trailing_newline": True, "autoescape": False}
+
+_env = Environment(loader=FileSystemLoader(str(PROMPTS_DIR)), **_FLAGS)
#: same environment (loader + flags; its own template cache), but an unknown name renders
#: empty instead of raising — used only as the fallback in :func:`render`, never as the default.
_lenient_env = _env.overlay(undefined=ChainableUndefined)
-@lru_cache(maxsize=256)
-def load_text(rel_path: str) -> str:
- """Raw prompt text, e.g. ``load_text("blender/cookbook.md")``."""
- p = PROMPTS_DIR / rel_path
+@lru_cache(maxsize=16)
+def _env_for(variant: str) -> tuple[Environment, Environment]:
+ """``(strict, lenient)`` environments: the base pair for ``""``; for a variant a ``ChoiceLoader``
+ pair — the overlay directory first, the base second, so an overlay template may ``{% include %}``
+ or ``{% extends %}`` a base file, and a name the overlay does not ship renders from the base."""
+ if not variant:
+ return _env, _lenient_env
+ env = Environment(loader=ChoiceLoader([FileSystemLoader(str(variant_root(variant))),
+ FileSystemLoader(str(PROMPTS_DIR))]), **_FLAGS)
+ return env, env.overlay(undefined=ChainableUndefined)
+
+
+def _resolve(variant: str, rel_path: str) -> Path:
+ """The file ``rel_path`` reads from under ``variant``: its overlay copy when one exists, else the
+ base path (which may not exist either — the caller decides what a missing file means)."""
+ if variant:
+ overlay = variant_root(variant) / rel_path
+ if overlay.is_file():
+ return overlay
+ return PROMPTS_DIR / rel_path
+
+
+def prompt_root(rel_path: str) -> Path:
+ """The file a prompt name resolves to right now (the active variant's overlay, else the base)."""
+ return _resolve(active_variant(), rel_path)
+
+
+@lru_cache(maxsize=512)
+def _load(variant: str, rel_path: str) -> str:
+ p = _resolve(variant, rel_path)
if not p.is_file():
raise FileNotFoundError(f"prompt not found: {rel_path}")
return p.read_text()
+def load_text(rel_path: str) -> str:
+ """Raw prompt text, e.g. ``load_text("blender/cookbook.md")`` — the active variant's copy first."""
+ return _load(active_variant(), rel_path)
+
+
def render(rel_path: str, **ctx: Any) -> str:
"""Render a jinja template under prompts/ with ``ctx``.
@@ -48,13 +85,14 @@ def render(rel_path: str, **ctx: Any) -> str:
So a missing name degrades the prompt (that one section renders empty) instead of
killing the task, and says so in the log. Everything else still raises.
"""
- template = _env.get_template(rel_path)
+ env, lenient = _env_for(active_variant())
+ template = env.get_template(rel_path)
try:
return template.render(**ctx)
except UndefinedError as e:
log.error("prompt %s wants a variable this caller does not pass (%s); rendering it "
"leniently — the prompt loses that section, the run continues", rel_path, e)
- return _lenient_env.get_template(rel_path).render(**ctx)
+ return lenient.get_template(rel_path).render(**ctx)
def prompt_hash(text: str) -> str:
diff --git a/harness/codeverse3d/prompts/_claims.toml b/harness/codeverse3d/prompts/_claims.toml
index 2422b687..c90695de 100644
--- a/harness/codeverse3d/prompts/_claims.toml
+++ b/harness/codeverse3d/prompts/_claims.toml
@@ -58,3 +58,181 @@ text = "0, 1.5"
python = "codeverse3d.tracks.scene:SCENE_TIMES"
sep = ", "
context = "scene_views(times=["
+
+# ---- scene_blender (prompts/scene_blender/*, DESIGN 2026-10-14 lane B1). The placement thresholds
+# are Settings defaults (config.Placement — no module constant since lane G deleted them): `python`
+# names the class and `format` reads the field's default through str.format's attribute / item
+# syntax; a tightened default fails the claim until the prompt agrees.
+
+[[claim]]
+key = "scene_times"
+file = "scene_blender/cookbook.md"
+text = "0 and t = 1.5"
+python = "codeverse3d.tracks.scene:SCENE_TIMES"
+sep = " and t = "
+context = "renders every camera at t ="
+
+[[claim]]
+key = "scene_fps"
+file = "scene_blender/contract.md"
+text = "30"
+python = "codeverse3d.languages.scene_blender:FPS"
+context = "fps="
+
+[[claim]]
+key = "asset_max_tris"
+file = "scene_blender/cookbook.md"
+text = "15000"
+python = "codeverse3d.tracks.scene_assets:ASSET_MAX_TRIS"
+context = "per asset"
+
+[[claim]]
+key = "hero_max_tris"
+file = "scene_blender/cookbook.md"
+text = "40000"
+python = "codeverse3d.tracks.scene_assets:HERO_MAX_TRIS"
+context = "for a hero"
+
+[[claim]]
+key = "scene_max_tris"
+file = "scene_blender/contract.md"
+text = "3,000,000"
+python = "codeverse3d.conventions:MAX_TRIS_SCENE"
+format = "{:,}"
+context = "scene ceiling"
+
+[[claim]]
+key = "placement_floating_outdoor_m"
+file = "scene_blender/contract.md"
+text = "0.05"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[floating_outdoor_m].default:.2f}"
+context = "outdoors"
+
+[[claim]]
+key = "placement_floating_indoor_m"
+file = "scene_blender/contract.md"
+text = "0.02"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[floating_indoor_m].default:.2f}"
+context = "indoors"
+
+[[claim]]
+key = "placement_floating_error_m"
+file = "scene_blender/contract.md"
+text = "0.08"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[floating_error_m].default:.2f}"
+context = "ERROR at"
+
+[[claim]]
+key = "placement_floating_error_count"
+file = "scene_blender/contract.md"
+text = "2"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[floating_error_count].default}"
+context = "things float"
+
+[[claim]]
+key = "placement_sunk_m"
+file = "scene_blender/contract.md"
+text = "0.10"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[sunk_m].default:.2f}"
+context = "buried deeper than"
+
+[[claim]]
+key = "placement_sunk_error_m"
+file = "scene_blender/contract.md"
+text = "0.20"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[sunk_error_m].default:.2f}"
+context = "ERROR at"
+
+[[claim]]
+key = "placement_overlap_warn"
+file = "scene_blender/contract.md"
+text = "10%"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[overlap_warn].default:.0%}"
+context = "interpenetration"
+
+[[claim]]
+key = "placement_overlap_error"
+file = "scene_blender/contract.md"
+text = "35%"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[overlap_error].default:.0%}"
+context = "ERROR at"
+
+[[claim]]
+key = "placement_contact_m"
+file = "scene_blender/contract.md"
+text = "0.02"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[contact_m].default:.2f}"
+context = "gap ≤"
+
+[[claim]]
+key = "placement_free_exempt_warn"
+file = "scene_blender/contract.md"
+text = "25%"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[free_exempt_warn].default:.0%}"
+context = "warns past"
+
+[[claim]]
+key = "placement_free_exempt_error"
+file = "scene_blender/contract.md"
+text = "50%"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[free_exempt_error].default:.0%}"
+context = "errors past"
+
+[[claim]]
+key = "placement_floating_error_m"
+file = "scene_blender/system.md"
+text = "0.08"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[floating_error_m].default:.2f}"
+context = "ERRORS at"
+
+[[claim]]
+key = "placement_sunk_error_m"
+file = "scene_blender/system.md"
+text = "0.20"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[sunk_error_m].default:.2f}"
+context = "ERRORS at"
+
+[[claim]]
+key = "placement_overlap_error"
+file = "scene_blender/system.md"
+text = "35%"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[overlap_error].default:.0%}"
+context = "ERRORS at"
+
+[[claim]]
+key = "placement_floating_error_m"
+file = "scene_blender/cookbook.md"
+text = "0.08"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[floating_error_m].default:.2f}"
+context = "ERROR at"
+
+[[claim]]
+key = "placement_sunk_error_m"
+file = "scene_blender/cookbook.md"
+text = "0.20"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[sunk_error_m].default:.2f}"
+context = "ERROR at"
+
+[[claim]]
+key = "placement_overlap_error"
+file = "scene_blender/cookbook.md"
+text = "35%"
+python = "codeverse3d.config:Placement"
+format = "{0.model_fields[overlap_error].default:.0%}"
+context = "ERROR at"
diff --git a/harness/codeverse3d/prompts/blender/contract.md b/harness/codeverse3d/prompts/blender/contract.md
index fa68d927..a209c47f 100644
--- a/harness/codeverse3d/prompts/blender/contract.md
+++ b/harness/codeverse3d/prompts/blender/contract.md
@@ -38,7 +38,7 @@
network, file writes; never touch `bpy.context.scene.render` / `scene.world` (harness-owned).
* Prefer modifiers (bevel / array / mirror) over dense meshes.
-## COMPLETE minimal example A — multi-file (verified with Blender 5.0 headless)
+## COMPLETE minimal example A — multi-file (verified with Blender 5.2.2 LTS headless)
`src/parts/seat.py`
```py
import bpy, bmesh
@@ -102,7 +102,7 @@ def main() -> None:
main()
```
-## COMPLETE minimal example B — single file (small objects; verified with Blender 5.0)
+## COMPLETE minimal example B — single file (small objects; verified with Blender 5.2.2 LTS)
```python
import bpy, bmesh, math
diff --git a/harness/codeverse3d/prompts/blender/cookbook.md b/harness/codeverse3d/prompts/blender/cookbook.md
index 0729dd61..f7b3e456 100644
--- a/harness/codeverse3d/prompts/blender/cookbook.md
+++ b/harness/codeverse3d/prompts/blender/cookbook.md
@@ -1,4 +1,4 @@
-# Blender (bpy) cookbook — static objects, Blender 4.2–5.x headless
+# Blender (bpy) cookbook — static objects, Blender 5.2 LTS headless
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.
@@ -205,13 +205,13 @@ def add_bevel(obj, width=0.003, segments=3, angle_deg=30.0):
return b
def boolean_cut(obj, cutter, solver='MANIFOLD') -> None:
- """obj -= cutter, applied, cutter deleted. MANIFOLD (5.0+) is fast + robust on closed
- meshes; fall back to EXACT when inputs are not watertight. Cutter must overshoot the
- face it pierces by ≥ 5 mm, never be coplanar with it."""
+ """obj -= cutter, applied, cutter deleted. MANIFOLD is fast + robust on closed meshes;
+ fall back to EXACT when inputs are not watertight (solvers: MANIFOLD / EXACT / FLOAT —
+ there is no 'FAST'). Cutter must overshoot the face it pierces by ≥ 5 mm, never be
+ coplanar with it."""
m = obj.modifiers.new("Cut", 'BOOLEAN')
m.operation = 'DIFFERENCE'; m.object = cutter
- solvers = m.bl_rna.properties["solver"].enum_items.keys() # 4.2: FAST/EXACT; 5.0: +MANIFOLD
- m.solver = solver if solver in solvers else 'EXACT'
+ m.solver = solver
try:
apply_modifiers(obj)
except RuntimeError: # MANIFOLD refused (non-manifold input)
@@ -930,7 +930,8 @@ def build_sail_rotor() -> bpy.types.Object:
`bpy.ops.object.shade_smooth_by_angle(angle=math.radians(30))` under `temp_override`.
9. **`bsdf.inputs["Specular"]` KeyError** → 4.x names: `"Specular IOR Level"`,
`"Transmission Weight"`, `"Emission Color"`/`"Emission Strength"`, `"Coat Weight"`.
-10. **`mat.use_nodes = True`** is a no-op/deprecated in 5.0 — the node tree already exists.
+10. **`mat.use_nodes = True`** is deprecated in 5.x (removed in 6.0) — every new material, world
+ and light already has a node tree; never write it.
11. **Object scaled with `obj.scale` looks right but exports wrong / bevels uneven** → bake
with `apply_transforms(obj)` before bevel/boolean; keep scale (1,1,1) on export.
12. **`bpy.ops.mesh.primitive_cube_add(size=1, scale=(…))`** — default size is 2 m; with
@@ -941,10 +942,14 @@ def build_sail_rotor() -> bpy.types.Object:
14. **Units**: the scene is in meters; a 450 mm seat is `0.45`, never `450`. If you see a
bbox of 450 × 500 × 900 the plan numbers were typed in mm.
15. **`bpy.context.object` is None in background** → do not rely on it; keep your own refs.
-16. **Deprecated in 4.x/5.x (do not use)**: `mesh.calc_normals()`, `mesh.calc_normals_split()`,
+16. **Gone in 5.2 (do not use)**: `mesh.calc_normals()`, `mesh.calc_normals_split()`,
`edge.crease` / `edge.bevel_weight` (use attributes `crease_edge`, `bevel_weight_edge`),
`bpy.ops.*({'object': o})` dict overrides, `mat.blend_method`, `scene.node_tree`,
- `BLENDER_EEVEE_NEXT` (5.0 is `BLENDER_EEVEE`), `bgl`, `gpu.types.GPUShader(...)`.
+ `BLENDER_EEVEE_NEXT` (5.x is `BLENDER_EEVEE`), `bgl`, `gpu.types.GPUShader(...)`,
+ the boolean solver `'FAST'` (now `'FLOAT'`; prefer `'MANIFOLD'` / `'EXACT'`), and
+ geometry-nodes inputs by item access — `mod["Socket_2"] = v` raises TypeError in 5.2:
+ `getattr(mod.properties.inputs, "Socket_2").value = v` (identifiers:
+ `mod.properties.inputs.keys()`).
17. **`bmesh.ops.create_cone` with `radius2=0`** makes a cone with a degenerate cap — fine
for visuals; for booleans use `radius2=1e-4`.
18. **A curve object left un-converted** exports nothing (the harness converts meshes
diff --git a/harness/codeverse3d/prompts/scene_blender/asset.md b/harness/codeverse3d/prompts/scene_blender/asset.md
new file mode 100644
index 00000000..e619a064
--- /dev/null
+++ b/harness/codeverse3d/prompts/scene_blender/asset.md
@@ -0,0 +1,21 @@
+You write ONE self-contained Blender bpy asset module for a larger scene — a factory
+`build_<snake>(ctx, variant=0)` that builds every part of the prop into `ctx.collection` (a
+Collection the harness created for it, active, and the value it returns) at the origin, base
+on z = 0, front facing −Y, metres. Raw bpy / bmesh / mathutils only: no file IO, no image
+loading, no `bpy.ops` in loops, no lights, no cameras, no world. Imports: `bpy`, `bmesh`,
+`mathutils`, `math`, and the scene's shipped bpy library `from lib.<module> import …` when the
+task sheet names one of its calls — it is harness code that ships with every scene, not an
+outside package.
+
+The module is built once by the harness in an isolated Blender process (a raise is reported
+with its line and the asset is NOT AVAILABLE to the zones), then placed by the zones as
+collection instances of `ctx.assets['<snake>']` — so the task sheet's exact function name, size
+and `variant` contract outrank everything else: zone code places your Collection sight unseen
+by its origin, and a wrong name or an off-origin footprint fails every placement, not just
+this file. It is judged as a prop at scene distance: silhouette first, then the 2-3
+recognisable features a person would name, then wear that makes it look used; several parts
+with distinct materials (Principled BSDF: `Base Color`, `Roughness`, `Metallic`), never one
+grey box. Keep it under the triangle budget the sheet states and give every part a unique
+PascalCase name.
+
+Write the one file completely and stop. No commentary, no extra files.
diff --git a/harness/codeverse3d/prompts/scene_blender/contract.md b/harness/codeverse3d/prompts/scene_blender/contract.md
new file mode 100644
index 00000000..87b3abea
--- /dev/null
+++ b/harness/codeverse3d/prompts/scene_blender/contract.md
@@ -0,0 +1,187 @@
+# Scene (multi-file Blender bpy) authoring contract — track `scene`, language `scene_blender`
+
+## Files (Blender 5.2 LTS python; Z up, −Y front, metres)
+```
+src/scene.py ASSEMBLED BY THE HARNESS — data only (ZONES / ASSETS / HEROES / CAMERAS); never edit it
+src/env.py def height_at(x, y) -> z def build_env(ctx) -> dict (world, sun, ground, atmosphere; the enclosure of an interior)
+src/zones/<snake>.py def build(ctx) -> bpy.types.Collection (everything linked into ctx.collection, the zone's own Collection)
+src/assets/<snake>.py def build_<snake>(ctx, variant=0) -> bpy.types.Collection (built ONCE at the origin, base on z = 0, front facing −Y)
+src/lib/*.py HARNESS-OWNED bpy library — import and call, never edit (a write to it is reverted; the catalog ships with every brief)
+public/assets/<snake>.glb heroes the harness built as objects — imported for you into ctx.assets['<snake>']
+```
+
+The harness builds the scene in ONE Blender 5.2 process (`--factory-startup`, an emptied scene,
+metric units, fps=30, the frame range 1..46, every random source seeded) in this order, each
+builder in its own try/except: `env.build_env(ctx)`; every hero GLB imported; every
+`assets.<snake>.build_<snake>(ctx)`; every `zones.<snake>.build(ctx)`. A builder that raises
+is DROPPED with its `file:line` and everything it created is removed — the rest of the scene
+still builds and is measured, so one bad zone costs that zone, not the round. Then the
+harness adds the plan's cameras, hides the asset sources (they render only through their
+collection instances), writes the census and the `.blend`, and renders every camera at
+t = 0 and t = 1.5 s (frames 1 and 46) with Cycles (32 samples + OpenImageDenoise, AgX view
+transform, exposure 0). Render settings, colour management, cameras, the frame clock and
+file IO are the harness's: the lint rejects code that touches them.
+
+## The `ctx` every builder receives (data, never verbs)
+| field | what it is |
+| --- | --- |
+| `ctx.scene` | the bpy Scene (read it; its render settings are harness-owned) |
+| `ctx.collection` | the Collection THIS builder links into — a zone's own (named after the zone, active, so `bpy.ops` primitives land in it), an asset's own, the scene root for `build_env` |
+| `ctx.height_at(x, y)` | the ground: `env.height_at` once the env built, else flat 0. Seat every placed thing on it or on the surface it stands on |
+| `ctx.env` | the dict `build_env` returned (shared materials, the water level, the sun direction…); `{}` before the env builds |
+| `ctx.assets` | `{snake: Collection}` — every procedural asset the harness built and every hero it imported, at the origin, base on z = 0 |
+| `ctx.rng(seed)` | `random.Random(seed)` — THE randomness a scene may use (`random.*` and unseeded numpy are lint ERRORS) |
+| `ctx.fps`, `ctx.times` | 30 and (0.0, 1.5): the frame clock |
+| `ctx.frame(t)` | `1 + round(t * fps)`: the frame that shows animation time t — keyframe on `ctx.frame(0.0)` and `ctx.frame(1.5)` |
+
+## Frame and units
+Z is UP, −Y is the FRONT, +X is the right; metres; the ground is `height_at(x, y)` around
+z = 0. The PLAN you are handed was written in the Y-up GLB frame (the three.js convention) —
+every number the harness prints in your brief (bounds, zone bboxes, camera positions,
+layouts) is already converted to this frame; the plan's prose is not: where it says
+"y = 1.2 m up" read z = 1.2, and where it says "+z towards the camera" read −y. Sizes are
+width × depth × height here (the plan's width × height × depth, reordered).
+
+## Allowed imports
+`bpy`, `bmesh`, `mathutils` (Vector, Matrix, Euler, noise), `math`, `numpy` (only through
+`numpy.random.default_rng(seed)` for randomness), `itertools`, `functools`, `collections`,
+`dataclasses`, `colorsys`, and the workspace's own packages: `from lib.<module> import …`,
+`from env import …` (zones may read env constants). Nothing else resolves in the build.
+
+## FORBIDDEN (the lint's policy table; each is an ERROR that fails the build gate)
+`bpy.ops.render.*`, `bpy.ops.wm.*` (open/save/append/link), `bpy.ops.export_*`,
+`bpy.ops.import_*` (a hero is already imported), `bpy.ops.image.save`, `bpy.data.libraries`,
+`bpy.data.cameras.new` / `bpy.ops.object.camera_add` (cameras are the plan's), any
+`scene.render.*` / `scene.cycles.*` / `scene.eevee.*` / `scene.view_settings.*` /
+`scene.display_settings.*` / `scene.camera` / `scene.frame_*` assignment, `frame_set`,
+`bpy.app.handlers`, `bpy.app.timers`, a driver whose expression needs Python
+(`driver.use_self`, attribute access, `**`, `%`, `noise.*` in an expression), the world
+outside `src/env.py` (`bpy.data.worlds.new`, `scene.world =`), `random.*` and unseeded numpy,
+`open()`, `os` / `sys` / `pathlib` / `time` / `datetime` / `subprocess` / `shutil` / `tempfile`
+/ `glob` / `io`. Blender 5.2 removed: `use_nodes` (deprecated — materials, worlds and lights
+always have a node tree), `sky_type = 'NISHITA'` (it is `'MULTIPLE_SCATTERING'`), the boolean
+solver `'FAST'` (`FLOAT` / `EXACT` / `MANIFOLD`), `mod["Socket_2"] = v` for geometry-nodes
+inputs (`getattr(mod.properties.inputs, "Socket_2").value = v`), `Action.fcurves`
+(`action.layers[0].strips[0].channelbag(action.slots[0]).fcurves`), `Mesh.calc_normals()`,
+`use_auto_smooth`, the Principled inputs `Specular` / `Subsurface` / `Transmission` /
+`Emission` (now `Specular IOR Level`, `Subsurface Weight`, `Transmission Weight`,
+`Emission Color` + `Emission Strength`), `ShaderNodeMixRGB` (it is `ShaderNodeMix` with
+`data_type = 'RGBA'`: inputs 6 / 7 are the colours, output 2 the result).
+
+## Motion
+Animation is DATA in the `.blend`: keyframes on `ctx.frame(t)` for the two times in
+`ctx.times` (`lib.motion.keyframe_path`, `drift`, `sway`, `shape_key_sweep`), or a SIMPLE
+driver of `frame` (`lib.motion.spin`: `frame * 0.1` — sin / cos / min / max / clamp / lerp,
+`+ - * /`, comparisons; nothing that needs Python, which a `--factory-startup` build silently
+evaluates to 0). Set `keyframe_points[].interpolation = 'LINEAR'` for motion that should
+read at t = 1.5 as a travel, not an ease. Amplitudes that read in a 1024 × 576 frame: ≥ 0.10
+rad of rotation, ≥ 0.05 m of travel per 1.5 s, a particle / leaf / boat ≥ 0.6 m. A hero
+GLB's own keyframed clip plays in every instance by itself.
+
+## Naming
+PascalCase object names, globally unique — a Blender object name is global, so a second
+`Lantern_0` becomes `Lantern_0.001` and the placement table then reports a prop nobody
+planned: number every placed copy with `lib.place.unique_name(base, i)` (`Lantern_0`,
+`Lantern_1`…) and never reuse a base another zone uses. Name the terrain and the backdrop
+`Ground…` / `Terrain…` / `Water…` / `Sky…` (`SkyRidge`: the census classifies by name — a sky-named
+mesh wider than 50 m is backdrop, not content);
+an interior's shell `RoomShell…` / `Ceiling…` (the overview rig lifts the lid by name).
+
+## Placement (the scene_placement gate, run on every build)
+Every root object you link into a zone (a mesh, a parent Empty with children, a
+collection-instance Empty) is ONE placement row. From its lowest evaluated vertices the gate
+looks down for the nearest surface and up for one passing through it: a gap under the foot
+larger than 0.05 m outdoors / 0.02 m indoors is `floating` (an ERROR at 0.08 m, or when more
+than 2 things float); a foot buried deeper than 0.10 m is `sunken` (an ERROR at 0.20 m and a
+fifth of the thing's height — rocks, posts and bushes may sit partly in; stairs and ramps may
+follow the slope; a foot at or under water is fine); a bbox touching nothing is `unsupported`;
+two boxes sharing more than 10% of the smaller one's volume is `interpenetration` (an ERROR at 35%).
+Seat with `lib.place.seat(obj, ctx.height_at)` (the same foot columns the gate samples: gap ≤ 0.02 m
+after) or `lib.scatter.instance(..., height_at=ctx.height_at)`, and check your pairs with
+`lib.place.clear_of(objs)` before you finish. `obj["placement"] = "free"` exempts
+a thing MEANT to hang in the air (a bird, a lantern on a chain, a kite) — nothing else: the
+gate reports the share of placed things tagged free and warns past 25%, errors past 50%.
+Geometry-nodes instance clouds (`lib.vegetation.grass_patch`, `lib.scatter.gn_scatter`) are
+counted as instances and exempt per asset, like scatter is.
+
+## What else the gates measure
+`scene_frames`: every authored camera's frame at both times — too dark, blown out, mostly
+sky / ground, the camera inside geometry or below the ground. `scene_probe` (from the census
+GLB and the bpy facts): unique triangles over the scene ceiling (3,000,000), a Python driver
+or an app handler, no world / no atmosphere, render settings touched. A hero that would not
+import is a WARN on its file; a zone / asset / env that raised is an ERROR on its line.
+
+## COMPLETE minimal examples (the harness builds exactly these; copy their shape)
+`src/env.py`
+```python
+"""src/env.py — the environment of `Harbour at dusk`: world, sun, ground, atmosphere."""
+import bpy
+
+from lib.lighting import sun
+from lib.materials import material
+from lib.sky import haze, sun_world
+from lib.terrain import ground, make_height_at
+
+BOUNDS = {"center": (0.0, 0.0, 5.0), "extents": (120.0, 120.0, 30.0)} # the plan's, in this frame
+SUN_AZIMUTH_DEG = 250.0 # compass angle of the sun: 0 = +X, 90 = +Y
+SUN_ELEVATION_DEG = 8.0
+_terrain = make_height_at(seed=3, relief=1.2, scale=40.0, flat_radius=60.0)
+
+
+def height_at(x, y):
+ """THE ground (z at x, y): level inside the content radius, rolling beyond; every seat reads it."""
+ return _terrain(x, y)
+
+
+def build_env(ctx):
+ sun_world(ctx.scene, elevation_deg=SUN_ELEVATION_DEG, azimuth_deg=SUN_AZIMUTH_DEG, strength=0.25, dust=3.0)
+ _, towards_sun = sun(ctx.collection, azimuth_deg=SUN_AZIMUTH_DEG, elevation_deg=SUN_ELEVATION_DEG,
+ color="FFB070", energy=2.5)
+ ground_mat = material("GroundMat", "4A5A33", roughness=1.0, noise_scale=0.35)
+ ground("Ground", ctx.collection, size=320.0, segments=160, height_at=height_at, material=ground_mat)
+ haze(ctx.collection, (0.0, 0.0, 15.0), (320.0, 320.0, 30.0), density=0.004, color="D9703A")
+ return {"ground_material": ground_mat, "sun_direction": tuple(towards_sun), "water_level": 0.0}
+```
+`src/zones/quay.py`
+```python
+"""src/zones/quay.py — zone "Quay": L-shaped granite quay with bollards and crates."""
+import bmesh
+import bpy
+
+from lib.materials import material
+from lib.place import clear_of, seat, unique_name
+from lib.scatter import instance
+
+CENTRE = (-20.0, 0.0) # the plan's zone centre, in this frame
+DECK_TOP = 1.2 # the quay stands 1.2 m above the water
+
+
+def _slab(name, mat, size, loc, collection):
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+ bmesh.ops.translate(bm, vec=loc, verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ collection.objects.link(ob)
+ return ob
+
+
+def build(ctx):
+ rng = ctx.rng(11)
+ granite = material("QuayGranite", "6E6A63", roughness=0.9, noise_scale=0.6)
+ deck = _slab("QuayDeck", granite, (40.0, 60.0, DECK_TOP), (CENTRE[0], CENTRE[1], DECK_TOP / 2), ctx.collection)
+ seat(deck, ctx.height_at) # its lowest vertices meet the ground
+ placed = [deck]
+ for i in range(6): # bollards along the water edge, ON the deck
+ x = CENTRE[0] + 18.0 + rng.uniform(-0.2, 0.2)
+ y = CENTRE[1] - 25.0 + i * 10.0
+ placed.append(instance(ctx.collection, ctx.assets["bollard"], unique_name("Bollard", i), x, y,
+ height_at=lambda px, py: DECK_TOP, rot_z=rng.uniform(0.0, 6.283)))
+ for a, b, frac in clear_of(placed): # [] here — nothing shares more than 10 % of the smaller box
+ print("quay: fix the overlap", a, "x", b, f"{frac:.0%}")
+ return ctx.collection
+```
diff --git a/harness/codeverse3d/prompts/scene_blender/cookbook.md b/harness/codeverse3d/prompts/scene_blender/cookbook.md
new file mode 100644
index 00000000..bbec2b86
--- /dev/null
+++ b/harness/codeverse3d/prompts/scene_blender/cookbook.md
@@ -0,0 +1,1365 @@
+# Scene cookbook — multi-file Blender bpy scenes (5.2 LTS), built and rendered headless by the harness
+
+Every `python` snippet runs as-is INSIDE a zone's `build(ctx)`: the harness test suite writes
+each one into `src/zones/<n>.py` under `import math · import bmesh · import bpy ·
+from mathutils import Euler, Matrix, Vector, noise` with `rng = ctx.rng(7)` in scope, builds
+the workspace in Blender 5.2.2 and lints it as a zone. A block whose first line is `# role: env` is
+module-level code of `src/env.py` instead (the world is only ever built there). Z up, −Y
+front, metres. Materials, lights and worlds always have a node tree (no `use_nodes`). The
+shipped `src/lib/` does most of what is below in one call — its catalog is in your brief;
+these snippets show the raw construction so you can read, extend or replace a call. The
+harness inlines the relevant chapters into your prompts; the full file is at
+`.3dcode/cookbook.md` in your workspace.
+
+**The chapters that decide the score.** Scenes on this track lose most of their points to
+a few repeatable defects, one chapter each:
+
+| the judge / gate writes | read this chapter |
+|---|---|
+| "flat ground plane", "one colour", "no paths" | Ground that reads real |
+| "a hard world edge is visible against the sky" | Horizon: the world must not end |
+| `floating` / `sunken` / `interpenetration` (the placement gate) | Placement self-check |
+| "monotonous / identical cones", "primitive stacked shapes" | Vegetation that reads real · Rocks, cliffs and boulders |
+| "sparse", "a diorama on an empty plane", "no midground" | Scene layering · Set dressing |
+| "flat light", "too dark", "monochrome", `dark_frame` | Atmosphere: time-of-day triads · Dusk / night lighting recipe · Lighting for Cycles + AgX |
+| "frames at t=0 and t=1.5 are identical", `nothing_moves` | Motion you can SEE between t = 0 and t = 1.5 s |
+| "plastic", "one grey material", "untextured" | Materials: Principled recipes and the lib palette |
+
+## Environment (`src/env.py`): world + sun + ground + atmosphere — the scene's floor comes first
+
+```python
+# role: env
+import math
+
+import bmesh
+import bpy
+from mathutils import Vector, noise
+
+BOUNDS = {"center": (0.0, 0.0, 5.0), "extents": (120.0, 120.0, 30.0)} # the plan's, in this frame
+MOOD = "dusk" # the brief's time of day, decided ONCE (the time-of-day table below)
+SUN_AZIMUTH_DEG = 250.0 # compass angle of the sun: 0 = +X, 90 = +Y
+SUN_ELEVATION_DEG = 8.0
+GROUND_SIZE = 320.0 # >= 2.5 x the plan span: the ground must reach past the haze
+GROUND_SEGMENTS = 160 # ~1 vertex per 2 m over 320 m; fine enough for a carved path
+PATH = [(-26.0, 20.0), (-9.0, 7.0), (4.0, -2.0), (17.0, -15.0), (26.0, -26.0)] # (x, y) polyline
+PATH_HALF_W = 0.9 # a 1.8 m path, carved INTO the height so props on it sit on it
+
+
+def _clamp(v, lo=0.0, hi=1.0):
+ return lo if v < lo else hi if v > hi else v
+
+
+def _smooth(x, a, b):
+ t = _clamp((x - a) / (b - a))
+ return t * t * (3.0 - 2.0 * t)
+
+
+def _mix(c1, c2, t):
+ return tuple(a + (b - a) * t for a, b in zip(c1, c2))
+
+
+def _dist_to_path(x, y):
+ best = 1e9
+ for (ax, ay), (bx, by) in zip(PATH, PATH[1:]):
+ vx, vy, wx, wy = bx - ax, by - ay, x - ax, y - ay
+ t = _clamp((wx * vx + wy * vy) / (vx * vx + vy * vy))
+ best = min(best, math.hypot(wx - t * vx, wy - t * vy))
+ return best
+
+
+def height_at(x, y):
+ """THE ground: rolling relief within +/-1.5 m (the plan's cameras are absolute heights), flat on
+ the path. Every zone seats on this; the ground mesh IS this function sampled."""
+ base = 1.1 * noise.fractal(Vector((x * 0.035, y * 0.035, 0.0)), 1.0, 2.0, 3) + 0.25 * math.sin(x * 0.08) * math.cos(y * 0.06)
+ flat = 1.0 - _clamp((_dist_to_path(x, y) - PATH_HALF_W) / 2.2) # 1 on the path -> 0 at 3.1 m
+ return base * (1.0 - 0.85 * flat) - 0.05 * flat # the path is flat and slightly sunken
+
+
+def _ground_material():
+ """Base colour from the mesh's 'Blend' colour attribute (one material, four blended colours), plus a
+ noise bump so a flat area still catches the light."""
+ mat = bpy.data.materials.new("GroundMat")
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ bsdf = nodes["Principled BSDF"]
+ bsdf.inputs["Roughness"].default_value = 1.0
+ attr = nodes.new("ShaderNodeAttribute")
+ attr.attribute_name = "Blend"
+ links.new(attr.outputs["Color"], bsdf.inputs["Base Color"])
+ tex = nodes.new("ShaderNodeTexNoise")
+ tex.inputs["Scale"].default_value = 6.0
+ tex.inputs["Detail"].default_value = 6.0
+ bump = nodes.new("ShaderNodeBump")
+ bump.inputs["Strength"].default_value = 0.25
+ links.new(tex.outputs["Factor"], bump.inputs["Height"])
+ links.new(bump.outputs["Normal"], bsdf.inputs["Normal"])
+ return mat
+
+
+def _ground(ctx, mat):
+ """The terrain mesh displaced by height_at, colour-blended by height, slope, noise and the path."""
+ me = bpy.data.meshes.new("Ground")
+ bm = bmesh.new()
+ bmesh.ops.create_grid(bm, x_segments=GROUND_SEGMENTS, y_segments=GROUND_SEGMENTS, size=GROUND_SIZE / 2)
+ for v in bm.verts:
+ v.co.z = height_at(v.co.x, v.co.y)
+ for f in bm.faces:
+ f.smooth = True
+ bm.to_mesh(me)
+ bm.free()
+ grass, dry, dirt, rock, path = (0.33, 0.44, 0.18), (0.54, 0.51, 0.28), (0.42, 0.33, 0.20), (0.43, 0.42, 0.39), (0.66, 0.60, 0.49)
+ blend = me.color_attributes.new("Blend", "FLOAT_COLOR", "POINT")
+ e = GROUND_SIZE / GROUND_SEGMENTS
+ for v, c in zip(me.vertices, blend.data):
+ x, y, z = v.co
+ slope = min(1.0, (abs(height_at(x + e, y) - z) + abs(height_at(x, y + e) - z)) / (e * 1.2))
+ n = 0.5 + 0.5 * noise.noise(Vector((x * 0.35, y * 0.35, 0.0))) # breaks every band into patches
+ col = _mix(grass, dry, _clamp(0.35 + z * 0.5 + (n - 0.5) * 0.9))
+ col = _mix(col, dirt, _smooth(slope, 0.12, 0.45))
+ col = _mix(col, rock, _smooth(slope, 0.45, 0.9))
+ col = _mix(col, path, (1.0 - _smooth(_dist_to_path(x, y), PATH_HALF_W, PATH_HALF_W + 1.4)) * (0.75 + 0.25 * n))
+ c.color = (col[0], col[1], col[2], 1.0)
+ me.materials.append(mat)
+ ob = bpy.data.objects.new("Ground", me)
+ ctx.collection.objects.link(ob)
+ return ob
+
+
+def _sun(ctx, color, energy):
+ """ONE Sun lamp from the compass angle + elevation; returns the unit vector TOWARDS the sun."""
+ az, el = math.radians(SUN_AZIMUTH_DEG), math.radians(SUN_ELEVATION_DEG)
+ towards_sun = Vector((math.cos(el) * math.cos(az), math.cos(el) * math.sin(az), math.sin(el)))
+ lamp = bpy.data.lights.new("Sun", "SUN")
+ lamp.energy = energy # W/m^2: 2-5 for day, 0.05-0.3 for a moon (AgX, exposure 0)
+ lamp.color = color
+ lamp.angle = math.radians(2.0) # soft-edged shadows; 0.5 deg is the real sun, too crisp for a diorama
+ ob = bpy.data.objects.new("Sun", lamp)
+ ob.rotation_euler = (-towards_sun).to_track_quat("-Z", "Y").to_euler()
+ ctx.collection.objects.link(ob)
+ return towards_sun
+
+
+def _atmosphere(ctx, density, color):
+ """A BOUNDED fog volume over the scene (a world volume over a large scene swallows the sun). The
+ census reads a volume-only mesh as fog, never as matter, so it is no placement row."""
+ me = bpy.data.meshes.new("Atmosphere")
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=(GROUND_SIZE, GROUND_SIZE, 40.0), verts=bm.verts)
+ bmesh.ops.translate(bm, vec=(BOUNDS["center"][0], BOUNDS["center"][1], 18.0), verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ mat = bpy.data.materials.new("AtmosphereFog")
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ nodes.remove(nodes["Principled BSDF"])
+ fog = nodes.new("ShaderNodeVolumePrincipled")
+ fog.inputs["Density"].default_value = density
+ fog.inputs["Color"].default_value = (color[0], color[1], color[2], 1.0)
+ links.new(fog.outputs["Volume"], nodes["Material Output"].inputs["Volume"])
+ me.materials.append(mat)
+ ctx.collection.objects.link(bpy.data.objects.new("Atmosphere", me))
+
+
+def build_env(ctx):
+ tod = apply_time_of_day(ctx, MOOD) # the world (sky texture + strength) from the table below
+ towards_sun = _sun(ctx, tod["sun_color"], tod["sun_energy"])
+ mat = _ground_material()
+ _ground(ctx, mat)
+ _atmosphere(ctx, tod["fog_density"], tod["fog_color"])
+ return {"ground_material": mat, "sun_direction": tuple(towards_sun), "mood": MOOD, "palette": tod}
+```
+
+Numbers: ground ≥ 2.5 × the plan span at ~1 vertex per 2 m (the path needs the resolution,
+the far field does not); `height_at` within ±1.5 m of 0 inside the bounds; the fog box 40 m
+tall over the whole ground; sun angle 2° (soft, readable shadows). `build_env` returns what
+zones share — the ground material, the sun direction, the palette — and zones read it as
+`ctx.env`.
+
+## The exact contract the harness wrapper enforces
+
+`src/scene.py` is **written by the harness**: a data file naming the zones, assets, heroes
+and the plan's cameras, regenerated by the assembler and overwritten after your stages. The
+wrapper then runs, in one Blender process, each in its own try/except:
+
+```text
+ctx.collection = scene root; out = env.build_env(ctx); ctx.env = out (a dict) ; ctx.height_at = env.height_at
+for each hero: import public/assets/<snake>.glb into a Collection -> ctx.assets[snake]
+for each asset: ctx.collection = its own Collection; assets.<snake>.build_<snake>(ctx) -> ctx.assets[snake]
+for each zone: ctx.collection = its own Collection (active); zones.<snake>.build(ctx)
+ a raise = that zone DROPPED with file:line, everything it made removed; the rest builds
+then: the plan's cameras, the asset sources excluded from the view layer, frame 1 set, the census written,
+ scene.blend saved, every camera rendered at frames 1 and 46 (t = 0 and t = 1.5 s)
+```
+
+So `build_env(ctx)`, `build(ctx)` and `build_<snake>(ctx, variant=0)` are the whole interface:
+`build_<zone>(ctx)`, `create()`, `main()` and `register()` are NEVER called, and a module that
+raises on import (a bad top-level statement) is gone from the scene. Link every object into
+`ctx.collection`; an object linked into `ctx.scene.collection` instead belongs to no zone and is
+graded as the harness's.
+
+## Ground that reads real (blend, paths, edges — never one flat colour)
+
+A single-colour plane is the #1 reason a scene reads as a toy. Real ground is **three or four
+colours blended by height, slope and noise** (the `_ground` recipe above: a `FLOAT_COLOR`
+attribute read by an Attribute node), with the path carved into `height_at` itself and dressed
+edges where anything meets it. `lib.terrain.ground(...)` builds exactly that; `lib.terrain.
+make_height_at(...)` the relief. Where a built thing meets the ground, sink it 3–5 cm AND
+scatter 6–15 small pieces along the seam:
+
+```python
+def seam_dressing(ctx, name, points, count, rng, radius=0.18, color=(0.31, 0.42, 0.17)):
+ """Tufts / pebbles hugging a seam polyline [(x, y), ...] as ONE mesh (one placement row, exempt-free)."""
+ mat = bpy.data.materials.new(name + "Mat")
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = 1.0
+ bm = bmesh.new()
+ for i in range(count):
+ u = (i + 0.5) / count * (len(points) - 1)
+ k = min(len(points) - 2, int(u))
+ f = u - k
+ x = points[k][0] + (points[k + 1][0] - points[k][0]) * f + rng.uniform(-0.5, 0.5)
+ y = points[k][1] + (points[k + 1][1] - points[k][1]) * f + rng.uniform(-0.5, 0.5)
+ r = radius * rng.uniform(0.5, 1.4)
+ new = bmesh.ops.create_icosphere(bm, subdivisions=1, radius=r)
+ bmesh.ops.scale(bm, vec=(1.0, 1.0, 0.6), verts=new["verts"])
+ bmesh.ops.translate(bm, vec=(x, y, ctx.height_at(x, y) - r * 0.35), verts=new["verts"]) # sunk a third
+ me = bpy.data.meshes.new(name)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ ctx.collection.objects.link(ob)
+ return ob
+
+seam = seam_dressing(ctx, "SeamTufts", [(-6.0, -6.0), (6.0, -6.0), (6.0, 6.0)], 24, rng)
+print("seam tufts", len(seam.data.polygons))
+```
+
+Numbers: ≥ 3 blended colours, each with ≥ 8 % of the visible area; path 1.2–2.0 m wide; a
+ground plane that is one flat colour, or a raised bed that is a sharp box on top of grass, are
+both graded as defects (`flat_ground`, `undressed_scene`). A raised platform gets a chamfered
+kerb (`bmesh.ops.bevel` on its top edges, offset 0.03), never a naked box edge.
+
+## Horizon: the world must not end (closing the frame in Cycles)
+
+The single most repeated judge complaint on this track is *"a hard world edge is visible
+against the sky"*. Five rules kill it for good:
+
+1. **Ground reaches past the haze.** Ground size ≥ 2.5 × the plan span, the fog box over all
+ of it; detail only needs to exist inside the bounds.
+2. **The fog's colour is the sky's horizon colour.** Then the ground fades into the sky
+ instead of ending at it (the time-of-day table pairs them).
+3. **A silhouette ring** at `radius ≈ 0.6 × (1 / fog density)` and ≥ 2 × the bounds
+ half-diagonal: 24–40 low-poly hills / treeline / rooftops / mesas, height 0.06–0.12 ×
+ radius. Measured on a 45 m garden: a ring at 46 m reads as distant hills, the same ring
+ at 95 m as a crater wall, at 20 m as a stone circle.
+4. **Never tint the backdrop toward the fog colour.** The volume already hazes it by
+ distance; a pre-tinted ridge reads as pale cardboard (`placeholder_material`). Give it
+ its natural colour DARKENED (× 0.6–0.8) and let the fog do the haze.
+5. **Solid geometry, never flat cut-outs.** A ring of planes reads as cardboard from every
+ oblique and overview camera, and its base floats.
+
+```python
+def horizon_ring(ctx, radius, rng, count=30, shape="hill", color=(0.17, 0.24, 0.16), darken=0.72):
+ """Build this from build_env (an env object is not a placement row): ONE mesh of low hills / blocks /
+ mesas around the content, each base at the ground. Named Sky... (SkyRidge, SkyHills): a sky-named
+ mesh wider than 50 m is BACKDROP to the census, so the overview cameras frame the content, not the ring."""
+ mat = bpy.data.materials.new("SkyRidgeMat")
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0] * darken, color[1] * darken, color[2] * darken, 1.0)
+ bsdf.inputs["Roughness"].default_value = 1.0
+ bm = bmesh.new()
+ for i in range(count):
+ a = (i + 0.35 * rng.random()) / count * math.tau
+ rr = radius * rng.uniform(0.82, 1.12)
+ hgt = radius * rng.uniform(0.06, 0.12)
+ wid = hgt * rng.uniform(1.1, 2.7)
+ x, y = math.cos(a) * rr, math.sin(a) * rr
+ if shape == "hill":
+ new = bmesh.ops.create_cone(bm, cap_ends=True, segments=7, radius1=wid, radius2=0.0, depth=hgt)
+ elif shape == "mesa":
+ new = bmesh.ops.create_cone(bm, cap_ends=True, segments=6, radius1=wid, radius2=wid * 0.75, depth=hgt)
+ else:
+ new = bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=(wid, wid * 0.8, hgt), verts=new["verts"])
+ bmesh.ops.rotate(bm, cent=(0.0, 0.0, 0.0), matrix=Matrix.Rotation(rng.uniform(0.0, math.tau), 3, "Z"), verts=new["verts"])
+ bmesh.ops.translate(bm, vec=(x, y, ctx.height_at(x, y) + hgt / 2 - 1.5), verts=new["verts"]) # base 1.5 m under the ground
+ me = bpy.data.meshes.new("SkyRidge")
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(mat)
+ ob = bpy.data.objects.new("SkyRidge", me)
+ ctx.collection.objects.link(ob)
+ return ob
+
+ring = horizon_ring(ctx, 60.0, rng, shape="block", color=(0.17, 0.19, 0.25))
+print("sky ridge pieces", len(ring.data.polygons))
+```
+
+Interiors (a greenhouse, a cabin) need no ring — but the *outside* seen through the glass must
+still be something: the sky world plus 5–10 silhouette shapes beyond the windows.
+
+## 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; a frame that is too dark is a gate ERROR (`scene_frames:
+dark_frame`) capping the score at 0.55. Exposure is fixed at 0 and you cannot touch it: take
+the `dusk` / `night` row of the time-of-day table for the world, the sun (or moon) and the
+fog, then add **practicals** — every lantern, window and fire near a camera is an emissive
+surface (the lamp you SEE, Emission Strength 5–10, it blooms) plus its own Point light with a
+radius (the light that reaches the ground: 30–60 W within ~3 m). `lib.lighting.practical(...)`
+is this in one call; the raw version, as ONE placed thing (post → bulb → light, parented, one
+placement row seated on the ground):
+
+```python
+def practical(ctx, name, x, y, height=2.3, color=(1.0, 0.70, 0.44), energy=45.0, radius=0.42, rng=None):
+ wood = bpy.data.materials.new(name + "Post")
+ wood.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.16, 0.12, 0.08, 1.0)
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=10, radius1=0.045, radius2=0.035, depth=height)
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, height / 2), verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(wood)
+ post = bpy.data.objects.new(name, me)
+ post.location = (x, y, ctx.height_at(x, y) - 0.03) # 3 cm into the ground: the seam reads planted
+ ctx.collection.objects.link(post)
+ glow = bpy.data.materials.new(name + "Glow")
+ bsdf = glow.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Emission Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Emission Strength"].default_value = 8.0
+ bme = bpy.data.meshes.new(name + "Bulb")
+ bm = bmesh.new()
+ bmesh.ops.create_icosphere(bm, subdivisions=2, radius=0.09)
+ bm.to_mesh(bme)
+ bm.free()
+ bme.materials.append(glow)
+ bulb = bpy.data.objects.new(name + "Bulb", bme)
+ bulb.parent = post # a child: the post is the ONE placement row
+ bulb.location = (0.0, 0.0, height + 0.05) # relative to the post
+ ctx.collection.objects.link(bulb)
+ lamp = bpy.data.lights.new(name + "Light", "POINT")
+ lamp.energy = energy
+ lamp.color = color
+ lamp.shadow_soft_size = radius # a radius: soft, physical falloff
+ light = bpy.data.objects.new(name + "Light", lamp)
+ light.parent = bulb
+ ctx.collection.objects.link(light)
+ return post
+
+for i, (x, y) in enumerate([(4.0, 2.0), (-3.0, 5.0)]):
+ practical(ctx, f"Lantern_{i}", x, y)
+print("practicals", 2)
+```
+
+Rules of thumb: the moon is a Sun lamp at 0.05–0.3 W/m², cool (0.66, 0.75, 1.0), elevation
+30–50°; the night world is a deep blue Background (never black) at strength 0.05–0.15; ground
+albedo ≥ 0.25; every practical near a camera path gets its own light, the far ones share ONE
+emissive material and light nothing. **Exposure self-check (after each build):** `scene_views`
+→ the frame table (`camera_checks`) for every authored camera: read `mean_lum` / `dark_frac` /
+`blown_frac` / `content_frac`. If a frame is dark, raise the world strength by +0.05 and the
+practicals by +15 W and re-render — never add a second Sun.
+
+## Atmosphere: time-of-day triads with numbers
+
+Pick the row, hand its numbers to the world and the sun, then only tune the practicals. Cycles
+reads physical units and AgX compresses the top: a day scene is a Sun of 3–5 W/m² under a sky
+world at strength 0.3–0.5; dusk is a low warm sun at 1–2 with a strong dusty sky; night is a
+moon at 0.1 with a blue world at 0.1. The fog colour is always the sky's **horizon** colour —
+never white, never grey unless the brief says overcast.
+
+| time of day | world | strength | sun W/m² | sun colour | sun elev | air density | fog density | fog colour |
+|---|---|---|---|---|---|---|---|---|
+| dawn | sky texture | 0.25 | 2.0 | (1.00, 0.69, 0.45) | 8° | 1.6 | 0.006 | (0.91, 0.63, 0.42) |
+| morning | sky texture | 0.40 | 3.5 | (1.00, 0.95, 0.82) | 35° | 1.0 | 0.004 | (0.74, 0.84, 0.92) |
+| noon | sky texture | 0.50 | 5.0 | (1.00, 0.98, 0.94) | 70° | 0.8 | 0.003 | (0.81, 0.89, 0.95) |
+| golden | sky texture | 0.30 | 2.5 | (1.00, 0.76, 0.48) | 12° | 1.8 | 0.006 | (0.94, 0.66, 0.38) |
+| overcast | flat colour (0.78, 0.81, 0.84) | 0.60 | 1.2 | (0.85, 0.87, 0.90) | 45° | — | 0.008 | (0.76, 0.79, 0.82) |
+| dusk | sky texture | 0.20 | 1.2 | (1.00, 0.63, 0.38) | 6° | 2.0 | 0.006 | (0.85, 0.44, 0.23) |
+| night (moon) | flat colour (0.05, 0.08, 0.19) | 0.10 | 0.12 | (0.66, 0.75, 1.00) | 40° | — | 0.004 | (0.13, 0.19, 0.35) |
+
+```python
+# role: env
+TIME_OF_DAY = {
+ "dawn": {"sky": "texture", "world_strength": 0.25, "sun_energy": 2.0, "sun_color": (1.0, 0.69, 0.45), "sun_elevation": 8.0, "air": 1.6, "fog_density": 0.006, "fog_color": (0.91, 0.63, 0.42)},
+ "morning": {"sky": "texture", "world_strength": 0.40, "sun_energy": 3.5, "sun_color": (1.0, 0.95, 0.82), "sun_elevation": 35.0, "air": 1.0, "fog_density": 0.004, "fog_color": (0.74, 0.84, 0.92)},
+ "noon": {"sky": "texture", "world_strength": 0.50, "sun_energy": 5.0, "sun_color": (1.0, 0.98, 0.94), "sun_elevation": 70.0, "air": 0.8, "fog_density": 0.003, "fog_color": (0.81, 0.89, 0.95)},
+ "golden": {"sky": "texture", "world_strength": 0.30, "sun_energy": 2.5, "sun_color": (1.0, 0.76, 0.48), "sun_elevation": 12.0, "air": 1.8, "fog_density": 0.006, "fog_color": (0.94, 0.66, 0.38)},
+ "overcast": {"sky": (0.78, 0.81, 0.84), "world_strength": 0.60, "sun_energy": 1.2, "sun_color": (0.85, 0.87, 0.90), "sun_elevation": 45.0, "air": 1.0, "fog_density": 0.008, "fog_color": (0.76, 0.79, 0.82)},
+ "dusk": {"sky": "texture", "world_strength": 0.20, "sun_energy": 1.2, "sun_color": (1.0, 0.63, 0.38), "sun_elevation": 6.0, "air": 2.0, "fog_density": 0.006, "fog_color": (0.85, 0.44, 0.23)},
+ "night": {"sky": (0.05, 0.08, 0.19), "world_strength": 0.10, "sun_energy": 0.12, "sun_color": (0.66, 0.75, 1.0), "sun_elevation": 40.0, "air": 1.0, "fog_density": 0.004, "fog_color": (0.13, 0.19, 0.35)},
+}
+
+
+def apply_time_of_day(ctx, key):
+ """The world of the brief's time of day (env.py only: the world is the env's). A physical sky texture
+ by day (MULTIPLE_SCATTERING — 'NISHITA' no longer exists; its knobs are sun_elevation / sun_rotation /
+ air_density / ozone_density / altitude), a flat deep colour for overcast / night; the sun disc is off
+ because the Sun LAMP is the sun. Returns the row for the lamp and the fog."""
+ t = TIME_OF_DAY.get(key, TIME_OF_DAY["morning"])
+ world = bpy.data.worlds.new("Sky")
+ ctx.scene.world = world
+ nodes, links = world.node_tree.nodes, world.node_tree.links
+ bg = nodes["Background"]
+ if t["sky"] == "texture":
+ sky = nodes.new("ShaderNodeTexSky")
+ sky.sky_type = "MULTIPLE_SCATTERING"
+ sky.sun_disc = False
+ sky.sun_elevation = math.radians(t["sun_elevation"])
+ sky.sun_rotation = math.radians(SUN_AZIMUTH_DEG)
+ sky.air_density = t["air"] # hazier, warmer at a low sun
+ links.new(sky.outputs["Color"], bg.inputs["Color"])
+ else:
+ bg.inputs["Color"].default_value = (t["sky"][0], t["sky"][1], t["sky"][2], 1.0)
+ bg.inputs["Strength"].default_value = t["world_strength"]
+ return t
+```
+
+**Colour temperature contrast is the whole trick**: the key (sun) is warm, the fill (the sky
+world) is cool — a sky texture gives you that for free; a flat warm world under a warm sun is
+the monochrome-orange soup scenes are marked down for. Shade must carry sky colour, never
+black: with the sun under 25° keep the world strength ≥ 0.2.
+
+## Lighting for Cycles + AgX: sun, sky and area numbers (exposure stays 0)
+
+The harness renders with Cycles at 32 samples + denoise, AgX, exposure 0, and you cannot
+change any of it — so the NUMBERS are the lighting. Sun 1–5 W/m² (table above); the world
+0.1–0.6; an Area light for a window or a studio key: 200–800 W at 1–2 m size (`shape =
+'DISK'` or `'RECTANGLE'`, aimed with `to_track_quat('-Z', 'Y')`); a Spot 100–400 W, `spot_size`
+45–60°, `spot_blend` 0.3; a practical Point 30–60 W with `shadow_soft_size` 0.3–0.5. Never a
+light at 1000 W "to be safe": AgX rolls the highlights off and the frame reads blown
+(`blown_frac`). Soft shadows come from the light's SIZE (`angle` on a Sun, `shadow_soft_size`
+on a Point, `size` on an Area), not from a second light.
+
+```python
+def area_light(ctx, name, loc, target, color=(1.0, 0.93, 0.80), energy=400.0, size=1.5, shape="DISK"):
+ """An Area light aimed at `target` — a window, a studio key, a street lamp's throw."""
+ data = bpy.data.lights.new(name, "AREA")
+ data.energy = energy
+ data.color = color
+ data.size = size
+ data.shape = shape
+ ob = bpy.data.objects.new(name, data)
+ ob.location = loc
+ ob.rotation_euler = (Vector(target) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
+ ctx.collection.objects.link(ob)
+ return ob
+
+key = area_light(ctx, "WindowKey", (6.0, -4.0, 3.2), (0.0, 0.0, 0.8))
+print("area light", key.data.energy)
+```
+
+Zones add lights only for practicals and the odd window; the Sun and the world are
+`src/env.py`'s (the lint rejects a world built anywhere else).
+
+## Atmosphere volume: the fog box, local mist and light shafts
+
+The env's fog box (`_atmosphere` above, density 0.003–0.008, the horizon colour) is the depth
+cue that makes distance read. A local MIST — over a pond, in a hollow, under a lantern — is a
+second, denser, lower box: a volume-only mesh is fog to the census (no placement row), so it
+can sit anywhere. Light shafts are the same box with a higher `Anisotropy` (0.4–0.6) placed
+where the sun crosses an opening; never a cone mesh with an emissive material.
+
+```python
+def mist(ctx, name, center, size, density=0.02, color=(0.80, 0.84, 0.88), anisotropy=0.0):
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+ bmesh.ops.translate(bm, vec=center, verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ mat = bpy.data.materials.new(name + "Vol")
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ nodes.remove(nodes["Principled BSDF"])
+ vol = nodes.new("ShaderNodeVolumePrincipled")
+ vol.inputs["Density"].default_value = density
+ vol.inputs["Color"].default_value = (color[0], color[1], color[2], 1.0)
+ vol.inputs["Anisotropy"].default_value = anisotropy
+ links.new(vol.outputs["Volume"], nodes["Material Output"].inputs["Volume"])
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ ctx.collection.objects.link(ob)
+ return ob
+
+pond_mist = mist(ctx, "PondMist", (12.0, -8.0, 0.6), (16.0, 12.0, 1.2), density=0.03)
+print("mist", pond_mist.name)
+```
+
+## Water
+
+Water is a subdivided plane with a Principled BSDF that TRANSMITS (Transmission Weight 1, IOR
+1.33, Roughness 0.05–0.15, a dark teal Base Color) over a bed carved BELOW the water level in
+`height_at` (a radial depression — or the shore z-fights and the shallows never read), plus a
+noise bump for ripples whose Mapping node scrolls between the two frames (the motion the judge
+diffs). `lib.water.water_surface(...)` and `lib.materials.water(...)` are this in two calls;
+`lib.water.pool_height` the bed. Name it `Water…` (the census classifies it; a foot at or
+under the water is never "sunken").
+
+```python
+def water_plane(ctx, name, center, radius, level, color=(0.09, 0.25, 0.29), segments=48):
+ mat = bpy.data.materials.new(name + "Mat")
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ bsdf = nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = 0.10
+ bsdf.inputs["IOR"].default_value = 1.33
+ bsdf.inputs["Transmission Weight"].default_value = 1.0
+ coords = nodes.new("ShaderNodeTexCoord")
+ mapping = nodes.new("ShaderNodeMapping")
+ ripple = nodes.new("ShaderNodeTexNoise")
+ ripple.inputs["Scale"].default_value = 0.8
+ ripple.inputs["Detail"].default_value = 8.0
+ bump = nodes.new("ShaderNodeBump")
+ bump.inputs["Strength"].default_value = 0.12
+ links.new(coords.outputs["Object"], mapping.inputs["Vector"])
+ links.new(mapping.outputs["Vector"], ripple.inputs["Vector"])
+ links.new(ripple.outputs["Factor"], bump.inputs["Height"])
+ links.new(bump.outputs["Normal"], bsdf.inputs["Normal"])
+ # the ripples travel 0.6 m / 0.2 m between the two sampled times: a still mirror reads as static
+ loc = mapping.inputs["Location"]
+ loc.default_value = (0.0, 0.0, 0.0)
+ loc.keyframe_insert("default_value", frame=ctx.frame(0.0))
+ loc.default_value = (0.6, 0.2, 0.0)
+ loc.keyframe_insert("default_value", frame=ctx.frame(1.5))
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_circle(bm, cap_ends=True, segments=segments, radius=radius)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ ob.location = (center[0], center[1], level)
+ ctx.collection.objects.link(ob)
+ return ob
+
+pond = water_plane(ctx, "WaterPond", (12.0, -8.0), 6.0, -0.25)
+print("water", pond.name)
+```
+
+## Vegetation that reads real (species, jitter, clusters, ground cover)
+
+A ring of identical cones is the second most common complaint. Fix it with **three to five
+species** (`lib.vegetation.tree(...)`: broadleaf / cypress / oak / pine; `shrub`, `fern`,
+`tropical`), per-instance **scale / hue / rotation jitter**, **clustered** placement and a
+**ground-cover** layer. Raw: each tree is ONE mesh with two material slots (one placement
+row), its hue jitter through `Object Info → Color` so a dozen trees share one material and
+each still differs:
+
+```python
+def foliage_material(name, base=(0.22, 0.38, 0.14)):
+ """Base colour = the OBJECT's colour (ob.color), so one material serves every tree with its own hue."""
+ mat = bpy.data.materials.new(name)
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ bsdf = nodes["Principled BSDF"]
+ bsdf.inputs["Roughness"].default_value = 0.85
+ info = nodes.new("ShaderNodeObjectInfo")
+ links.new(info.outputs["Color"], bsdf.inputs["Base Color"])
+ return mat
+
+
+def tree_mesh(kind, k, rng):
+ """trunk + crown in one bmesh; the crown's faces get material slot 1. k = scale jitter (0.8-1.5)."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=7, radius1=0.20 * k, radius2=0.10 * k, depth=2.6 * k)
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, 1.3 * k), verts=bm.verts)
+ n_trunk = len(bm.faces)
+ if kind == "conifer":
+ crown = bmesh.ops.create_cone(bm, cap_ends=True, segments=8, radius1=1.15 * k, radius2=0.0, depth=4.4 * k)
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, 4.4 * k), verts=crown["verts"])
+ else: # broadleaf / scrub: a displaced ball, flattened
+ r = (1.7 if kind == "broadleaf" else 0.75) * k
+ crown = bmesh.ops.create_icosphere(bm, subdivisions=2, radius=r)
+ off = Vector((rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), 0.0)) # a different crown every tree
+ for v in crown["verts"]:
+ v.co *= 1.0 + 0.28 * noise.noise(v.co * 1.3 + off)
+ bmesh.ops.scale(bm, vec=(1.0, 1.0, 0.8), verts=crown["verts"])
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, (3.4 if kind == "broadleaf" else 1.0) * k), verts=crown["verts"])
+ bm.faces.ensure_lookup_table()
+ for f in bm.faces[n_trunk:]:
+ f.material_index = 1
+ for f in bm.faces:
+ f.smooth = kind != "conifer"
+ me = bpy.data.meshes.new("Tree")
+ bm.to_mesh(me)
+ bm.free()
+ return me
+
+
+def clustered_points(n, area, rng, clusters=0):
+ """area = (cx, cy, w, d); K cluster seeds, members scattered around them (Poisson-ish, never a grid)."""
+ cx, cy, w, d = area
+ k = clusters or max(2, round(n / 7))
+ seeds = [(cx + (rng.random() - 0.5) * w * 0.9, cy + (rng.random() - 0.5) * d * 0.9) for _ in range(k)]
+ sp = min(w, d) * 0.13
+ out = []
+ for i in range(n):
+ sx, sy = seeds[i % k]
+ a, r = rng.random() * math.tau, sp * math.sqrt(rng.random())
+ out.append((sx + math.cos(a) * r, sy + math.sin(a) * r))
+ return out
+
+
+def forest(ctx, name, area, mix, bark, leaves, rng, height_at):
+ """mix = {kind: count}; one mesh object per tree (ONE placement row each), seated 3 cm into the ground."""
+ objs = []
+ i = 0
+ for kind, count in mix.items():
+ for x, y in clustered_points(count, area, rng):
+ k = rng.uniform(0.8, 1.5)
+ me = tree_mesh(kind, k, rng)
+ me.materials.append(bark)
+ me.materials.append(leaves)
+ ob = bpy.data.objects.new(f"{name}{kind.capitalize()}_{i}", me)
+ ob.location = (x, y, height_at(x, y) - 0.03)
+ ob.rotation_euler = (rng.uniform(-0.05, 0.05), rng.uniform(-0.05, 0.05), rng.uniform(0.0, math.tau)) # a few degrees of lean, full yaw
+ hue = (0.22 + rng.uniform(-0.04, 0.04), 0.38 + rng.uniform(-0.08, 0.08), 0.14 + rng.uniform(-0.05, 0.05))
+ ob.color = (hue[0], hue[1], hue[2], 1.0) # hue + value jitter
+ ctx.collection.objects.link(ob)
+ objs.append(ob)
+ i += 1
+ return objs
+
+bark = bpy.data.materials.new("Bark")
+bark.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.33, 0.25, 0.17, 1.0)
+bark.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.95
+trees = forest(ctx, "Grove", (0.0, 0.0, 40.0, 40.0), {"conifer": 5, "broadleaf": 4, "scrub": 6}, bark, foliage_material("Leaves"), rng, ctx.height_at)
+print("trees", len(trees), "species", 3)
+```
+
+**Ground cover** turns "objects on a plane" into "plants growing out of the ground": a
+geometry-nodes cloud of blades over a patch (`lib.vegetation.grass_patch(...)`) — an instance
+cloud, counted as instances by the census and exempt from per-asset placement:
+
+```python
+def grass_patch(ctx, name, center, size, density, seed, height_at, color=(0.29, 0.42, 0.16)):
+ """A surface displaced by height_at + a hidden 3-sided blade instanced on it by geometry nodes."""
+ mat = bpy.data.materials.new(name + "Mat")
+ mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_grid(bm, x_segments=24, y_segments=24, size=size / 2)
+ for v in bm.verts:
+ v.co.z = height_at(center[0] + v.co.x, center[1] + v.co.y) - 0.02
+ bm.to_mesh(me)
+ bm.free()
+ patch = bpy.data.objects.new(name, me)
+ patch.location = (center[0], center[1], 0.0)
+ ctx.collection.objects.link(patch)
+ bme = bpy.data.meshes.new(name + "Blade")
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=False, segments=3, radius1=0.05, radius2=0.0, depth=0.34) # 3 faces per blade
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, 0.17), verts=bm.verts)
+ bm.to_mesh(bme)
+ bm.free()
+ bme.materials.append(mat)
+ blade = bpy.data.objects.new(name + "Blade", bme)
+ blade.hide_render = True # the source is never seen, only its instances
+ blade.hide_viewport = True
+ ctx.collection.objects.link(blade)
+ ng = bpy.data.node_groups.new(name + "Scatter", "GeometryNodeTree")
+ ng.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")
+ ng.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")
+ dens = ng.interface.new_socket("Density", in_out="INPUT", socket_type="NodeSocketFloat")
+ n = ng.nodes
+ gi, go = n.new("NodeGroupInput"), n.new("NodeGroupOutput")
+ dist = n.new("GeometryNodeDistributePointsOnFaces")
+ dist.inputs["Seed"].default_value = seed
+ scale = n.new("FunctionNodeRandomValue") # FLOAT (the default): inputs 0 / 1 are Min / Max
+ scale.inputs[0].default_value = 0.6
+ scale.inputs[1].default_value = 1.6
+ scale.inputs["Seed"].default_value = seed
+ inst = n.new("GeometryNodeInstanceOnPoints")
+ info = n.new("GeometryNodeObjectInfo")
+ info.inputs["Object"].default_value = blade
+ join = n.new("GeometryNodeJoinGeometry")
+ ng.links.new(gi.outputs["Geometry"], dist.inputs["Mesh"])
+ ng.links.new(gi.outputs["Density"], dist.inputs["Density"])
+ ng.links.new(dist.outputs["Points"], inst.inputs["Points"])
+ ng.links.new(dist.outputs["Rotation"], inst.inputs["Rotation"])
+ ng.links.new(scale.outputs["Value"], inst.inputs["Scale"])
+ ng.links.new(info.outputs["Geometry"], inst.inputs["Instance"])
+ ng.links.new(inst.outputs["Instances"], join.inputs["Geometry"])
+ ng.links.new(gi.outputs["Geometry"], join.inputs["Geometry"])
+ ng.links.new(join.outputs["Geometry"], go.inputs["Geometry"])
+ mod = patch.modifiers.new("Scatter", "NODES")
+ mod.node_group = ng
+ getattr(mod.properties.inputs, dens.identifier).value = density # Blender 5.2: inputs are RNA properties, never mod["Socket_2"]
+ return patch
+
+cover = grass_patch(ctx, "GroundCover", (0.0, -14.0), 20.0, 6.0, 9, ctx.height_at)
+print("ground cover", cover.name)
+```
+
+Density per 100 m² of planted zone: 2–5 trees, 8–20 shrubs, 250–600 blades (`density` 2.5–6
+per m²), 30–80 litter pieces. Less and the judge writes *"monotonous / undressed"*.
+
+## Rocks, cliffs and boulders that read organic (never a row of boxes)
+
+Stacked cuboids read as buildings. A rock is a **noise-displaced icosphere, flattened and
+yawed** (`lib.terrain.boulder`, `rock_field`, `talus`); a cliff is a **ridge polyline of rotated,
+non-uniformly scaled chunks with jittered strata** (`lib.terrain.cliff`), never an axis-aligned
+wall:
+
+```python
+def rock_geometry(bm, radius, rough, seed, detail=2):
+ """A displaced icosphere into `bm`; returns its verts. Flatter than tall = weathered."""
+ new = bmesh.ops.create_icosphere(bm, subdivisions=detail, radius=radius)
+ off = Vector((seed * 13.0, seed * 7.0, 0.0))
+ for v in new["verts"]:
+ d = 1.0 + rough * noise.noise(v.co * (1.7 / radius) + off)
+ v.co = Vector((v.co.x * d, v.co.y * d, v.co.z * d * 0.8))
+ return new["verts"]
+
+
+def boulder(ctx, name, x, y, radius, rng, color=(0.42, 0.40, 0.37)):
+ mat = bpy.data.materials.new(name + "Mat")
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = 0.95
+ bm = bmesh.new()
+ verts = rock_geometry(bm, radius, 0.34, rng.randrange(1000), detail=2)
+ bmesh.ops.scale(bm, vec=(rng.uniform(1.0, 1.4), rng.uniform(0.8, 1.1), 1.0), verts=verts) # non-uniform
+ for f in bm.faces:
+ f.smooth = True
+ me = bpy.data.meshes.new(name)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ ob.location = (x, y, ctx.height_at(x, y) + radius * 0.45) # a rock sits partly IN the ground (allowed)
+ ob.rotation_euler = (0.0, 0.0, rng.uniform(0.0, math.tau))
+ ctx.collection.objects.link(ob)
+ return ob
+
+
+def cliff_ridge(ctx, name, ridge, count, height, rng, strata=((0.55, 0.29, 0.18), (0.66, 0.40, 0.24), (0.75, 0.54, 0.35), (0.48, 0.23, 0.15))):
+ """Chunks straddling a polyline [(x, y), ...], stacked in strata bands, as ONE mesh with a per-vertex
+ 'Strata' colour (an Attribute node reads it)."""
+ mat = bpy.data.materials.new(name + "Mat")
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ bsdf = nodes["Principled BSDF"]
+ bsdf.inputs["Roughness"].default_value = 0.95
+ attr = nodes.new("ShaderNodeAttribute")
+ attr.attribute_name = "Strata"
+ links.new(attr.outputs["Color"], bsdf.inputs["Base Color"])
+ bm = bmesh.new()
+ bands = []
+ for i in range(count):
+ u = i / (count - 1) * (len(ridge) - 1)
+ k = min(len(ridge) - 2, int(u))
+ f = u - k
+ bx = ridge[k][0] + (ridge[k + 1][0] - ridge[k][0]) * f + rng.uniform(-1.7, 1.7)
+ by = ridge[k][1] + (ridge[k + 1][1] - ridge[k][1]) * f + rng.uniform(-1.7, 1.7)
+ layer = i % len(strata)
+ lift = height * (0.18 + 0.26 * layer) * rng.uniform(0.75, 1.25)
+ verts = rock_geometry(bm, 1.0, 0.42, rng.randrange(1000), detail=1)
+ bmesh.ops.scale(bm, vec=(rng.uniform(2.6, 6.0), rng.uniform(2.2, 5.2), lift * rng.uniform(0.7, 1.3)), verts=verts)
+ bmesh.ops.rotate(bm, cent=(0.0, 0.0, 0.0), matrix=Euler((rng.uniform(-0.25, 0.25), rng.uniform(0.0, math.tau), rng.uniform(-0.25, 0.25))).to_matrix(), verts=verts)
+ bmesh.ops.translate(bm, vec=(bx, by, ctx.height_at(bx, by) + lift * 0.55), verts=verts)
+ bands.append((len(verts), strata[layer]))
+ for f in bm.faces:
+ f.smooth = True
+ me = bpy.data.meshes.new(name)
+ bm.to_mesh(me)
+ bm.free()
+ colour = me.color_attributes.new("Strata", "FLOAT_COLOR", "POINT")
+ j = 0
+ for n, (r, g, b) in bands: # verts were appended band by band, in order
+ for _ in range(n):
+ colour.data[j].color = (r, g, b, 1.0)
+ j += 1
+ me.materials.append(mat)
+ ob = bpy.data.objects.new(name, me)
+ ctx.collection.objects.link(ob)
+ return ob
+
+rocks = [boulder(ctx, f"Boulder_{i}", -8.0 + i * 2.2, 12.0 + (i % 2) * 1.5, rng.uniform(0.4, 1.3), rng) for i in range(4)]
+cliff = cliff_ridge(ctx, "CliffRidge", [(-30.0, 14.0), (-12.0, 10.0), (2.0, 6.0), (18.0, 9.0), (30.0, 16.0)], 26, 9.0, rng)
+print("boulders", len(rocks), "cliff verts", len(cliff.data.vertices))
+```
+
+Rules: chunk yaw random over the full circle; scale non-uniform (x ≠ y ≠ z by ≥ 20 %);
+strata luminance differing by ≥ 0.08; the ridge polyline bending ≥ 15° at least twice; floor
+boulders reuse `rock_geometry` at 0.3–1.6 m and may sit a third of their height IN the ground
+(the gate allows rocks, posts and bushes partly buried).
+
+## Set dressing: how many props a place needs
+
+Judges call a scene "sparse", "token" or "undressed" long before they call it wrong. Counts
+that read as *lived in*, per zone (a zone is typically 10 × 10 m to 30 × 30 m):
+
+| scene type | hero assets | mid props (0.3–1.5 m) | small props (< 0.3 m) | ground cover / litter |
+|---|---|---|---|---|
+| garden / park | 3–5 (lantern, bridge, bench) | 12–25 (rocks, planters, pots, stumps, buckets) | 25–60 (pebbles, leaves, tools, cups, twigs) | 300–800 blades |
+| desert / canyon | 2–4 (hero boulder, arch, wreck) | 15–30 boulders in 3 size bands | 30–70 (pebbles, bones, dry brush) | 60–200 scrub clumps |
+| harbour / street | 3–6 (boat, crane, cart) | 15–30 (crates, barrels, bollards, nets, lamps) | 30–80 (ropes, buckets, bottles, fish boxes) | 100–300 weeds / litter |
+| interior | 3–6 (bench rows, a stove) | 15–30 (pots, tools, crates, stools) | 40–100 (labels, jars, gloves, cups) | n/a |
+
+Cheap rules: 3 size bands per prop family; props go **against something** (a wall base, a
+path edge, under a bench) — props alone in open ground read as scatter; never a grid or a
+ring (≥ 20 % positional jitter, full yaw jitter); repeats are collection instances of an
+asset, each with its own unique name (`lib.scatter.scatter(...)` does the names, the seating
+and the jitter):
+
+```python
+def place_asset(ctx, source, name, x, y, rot_z, height_at, scale=1.0):
+ """ONE collection-instance Empty of an asset Collection, seated: one placement row, PascalCase unique name."""
+ ob = bpy.data.objects.new(name, None)
+ ob.instance_type = "COLLECTION"
+ ob.instance_collection = source
+ ob.location = (x, y, height_at(x, y))
+ ob.rotation_euler = (0.0, 0.0, rot_z)
+ ob.scale = (scale, scale, scale)
+ ctx.collection.objects.link(ob)
+ return ob
+
+
+def along_seam(points, n, rng, offset=0.6):
+ """n (x, y, yaw) spots hugging a seam polyline, on its +side, jittered: props AGAINST a wall or a path edge."""
+ out = []
+ for i in range(n):
+ u = (i + 0.5 + rng.uniform(-0.3, 0.3)) / n * (len(points) - 1)
+ k = min(len(points) - 2, max(0, int(u)))
+ f = u - k
+ (ax, ay), (bx, by) = points[k], points[k + 1]
+ dx, dy = bx - ax, by - ay
+ length = math.hypot(dx, dy) or 1.0
+ nx, ny = -dy / length, dx / length # the seam's left normal
+ d = offset * rng.uniform(0.7, 1.4)
+ out.append((ax + dx * f + nx * d, ay + dy * f + ny * d, math.atan2(dy, dx) + rng.uniform(-0.4, 0.4)))
+ return out
+
+source = ctx.assets.get("bollard") # a planned asset: ctx.assets['<snake>']
+if source is None: # (no such plan asset: a stand-in crate)
+ cm = bpy.data.meshes.new("CrateStandIn")
+ cb = bmesh.new()
+ bmesh.ops.create_cube(cb, size=0.6)
+ bmesh.ops.translate(cb, vec=(0.0, 0.0, 0.3), verts=cb.verts)
+ cb.to_mesh(cm)
+ cb.free()
+ source = bpy.data.collections.new("CrateStandIn")
+ ctx.collection.children.link(source)
+ source.objects.link(bpy.data.objects.new("CrateStandIn", cm))
+spots = along_seam([(-10.0, -4.0), (0.0, -4.0), (8.0, 2.0)], 9, rng)
+props = [place_asset(ctx, source, f"QuayProp_{i}", x, y, yaw, ctx.height_at, scale=rng.uniform(0.85, 1.15)) for i, (x, y, yaw) in enumerate(spots)]
+print("props against the seam", len(props))
+```
+
+## Scene layering: foreground, midground, background
+
+A "diorama on an empty plane" scores ~0.5 whatever else you do. Every authored camera needs
+**three depth layers**, built on purpose:
+
+| layer | distance from camera | what lives there | how much of the frame |
+|---|---|---|---|
+| foreground frame | 1.5–5 m | a branch, a post, a parapet edge, a leaning tool, tall grass, an arch | 10–25% of the frame area, usually at an edge, may be partly cut off |
+| midground subject | 8–30 m | the hero assets: what the brief is about | fills the centre third |
+| background | 40 m–the haze | the backdrop ring, a distant treeline / skyline / mesas, the sky | the top third |
+
+```python
+CAMERAS = [((24.0, -26.0, 9.0), (0.0, 0.0, 2.0)), ((8.0, -22.0, 1.7), (0.0, 1.0, 1.4))] # the plan's, in this frame
+
+
+def frame_foreground(ctx, cam, obj, dist=3.0, side=-1.0, lift=0.0):
+ """Place `obj` just off the camera's axis at `dist` so it brackets the shot (a hand-placed framer)."""
+ eye, at = Vector(cam[0]), Vector(cam[1])
+ fwd = (at - eye)
+ fwd.z = 0.0
+ fwd.normalize()
+ right = fwd.cross(Vector((0.0, 0.0, 1.0)))
+ p = eye + fwd * dist + right * (side * dist * 0.75)
+ obj.location = (p.x, p.y, ctx.height_at(p.x, p.y) + lift)
+ obj.rotation_euler = (0.0, 0.0, math.atan2(eye.y - p.y, eye.x - p.x))
+ return obj
+
+
+def camera_mask(cameras, radius=4.0):
+ """(x, y) -> True inside a clearance disc around any camera, or on its first quarter towards the subject:
+ SKIP scattered instances there (scatter is blind; a tree 1 m in front of the lens ruins the shot)."""
+ discs = [(c[0][0], c[0][1], radius) for c in cameras]
+ for (px, py, _), (lx, ly, _) in cameras:
+ discs.append((px + (lx - px) * 0.22, py + (ly - py) * 0.22, radius * 0.6))
+ return lambda x, y: any((x - cx) ** 2 + (y - cy) ** 2 < r * r for cx, cy, r in discs)
+
+fm = bpy.data.meshes.new("Framer")
+fb = bmesh.new()
+bmesh.ops.create_cone(fb, cap_ends=True, segments=8, radius1=0.08, radius2=0.05, depth=2.4)
+bmesh.ops.translate(fb, vec=(0.0, 0.0, 1.2), verts=fb.verts)
+fb.to_mesh(fm)
+fb.free()
+framer = bpy.data.objects.new("FramerPost", fm)
+ctx.collection.objects.link(framer)
+frame_foreground(ctx, CAMERAS[1], framer, side=-1.0)
+blocked = camera_mask(CAMERAS)
+print("framer at", tuple(round(v, 2) for v in framer.location), "mask blocks (8,-22)?", blocked(8.0, -22.0), "(0,0)?", blocked(0.0, 0.0))
+```
+
+**Keep the cameras' first metres clear**, and the establishing camera sits *above the
+canopy* looking DOWN at the subject. Atmospheric perspective does the rest: with the fog the
+horizon colour, a background object loses contrast and saturation with distance for free —
+darken the distant material, never tint it.
+
+## Motion you can SEE between t = 0 and t = 1.5 s
+
+The harness renders every camera at t = 0 and t = 1.5 s (frames 1 and 46 at 30 fps) and the
+judge diffs the two frames. Sub-centimetre sway is invisible at 1024 × 576 and scores as
+`nothing_moves`. Animation is DATA: keyframes on `ctx.frame(0.0)` and `ctx.frame(1.5)`, or a
+SIMPLE driver of `frame` (`lib.motion.keyframe_path`, `drift`, `sway`, `spin`, `scroll`,
+`shape_key_sweep` are these in one call). Amplitudes that read:
+
+| what moves | amplitude | note |
+|---|---|---|
+| foliage sway | ±0.10–0.20 rad (6–11°) | rotate the crown or the whole tree about its base, not the trunk's middle |
+| grass / reeds | ±0.15 rad | phase-offset per patch |
+| water | ripples scrolling ≥ 0.15 m/s (the Mapping keyframes above) and a surface bob ≥ 0.04 m | a still mirror reads as static |
+| falling leaves / petals / snow / dust | ≥ 0.6 m of travel in 1.5 s | a small instance cloud, each with its own keyframes |
+| flags / banners / string lights | ±0.12 rad | the classic "the scene is alive" cue |
+| flame / lantern flicker | Emission Strength × 0.75…× 1.3 | keyframe the socket's `default_value` |
+| vehicles / boats / birds / a mill | ≥ 1.5 m of travel, or a visible turn | one hero mover beats ten twitchers |
+
+```python
+def keyframe_linear(ctx, obj, path, index, v0, v1):
+ """Two keys on the harness's two times, LINEAR (an eased curve barely moves by t = 1.5). Blender 5.2:
+ the curves live in the action's channelbag — Action.fcurves is gone."""
+ setattr(obj, path, _set_index(getattr(obj, path), index, v0))
+ obj.keyframe_insert(path, index=index, frame=ctx.frame(0.0))
+ setattr(obj, path, _set_index(getattr(obj, path), index, v1))
+ obj.keyframe_insert(path, index=index, frame=ctx.frame(1.5))
+ act = obj.animation_data.action
+ for fc in act.layers[0].strips[0].channelbag(act.slots[0]).fcurves:
+ for kp in fc.keyframe_points:
+ kp.interpolation = "LINEAR"
+
+
+def _set_index(vec, index, value):
+ out = list(vec)
+ out[index] = value
+ return out
+
+hull_mat = bpy.data.materials.new("HullMat")
+hull_mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.55, 0.12, 0.10, 1.0)
+hm = bpy.data.meshes.new("Boat")
+hb = bmesh.new()
+bmesh.ops.create_cube(hb, size=1.0)
+bmesh.ops.scale(hb, vec=(2.0, 6.0, 1.2), verts=hb.verts)
+bmesh.ops.translate(hb, vec=(0.0, 0.0, 0.6), verts=hb.verts)
+hb.to_mesh(hm)
+hb.free()
+hm.materials.append(hull_mat)
+boat = bpy.data.objects.new("Boat_0", hm)
+boat.location = (14.0, -6.0, -0.35) # its waterline on the water (z = -0.25)
+ctx.collection.objects.link(boat)
+keyframe_linear(ctx, boat, "location", 1, -6.0, -3.0) # drifts 3 m along +Y in 1.5 s: the hero motion
+keyframe_linear(ctx, boat, "rotation_euler", 0, -0.04, 0.04) # and rolls 4.6 degrees
+pivot = bpy.data.objects.new("MillPivot", None) # a spinning thing: a SIMPLE driver on frame
+pivot.location = (-6.0, 8.0, ctx.height_at(-6.0, 8.0) + 3.0)
+pivot["placement"] = "free" # an Empty up in the air is exempt BY DESIGN
+ctx.collection.objects.link(pivot)
+drv = pivot.driver_add("rotation_euler", 1).driver
+drv.type = "SCRIPTED"
+drv.expression = "frame * 0.12" # 5.4 rad over the 46 frames; inside the simple subset
+print("boat keys", boat.animation_data.action is not None, "driver simple", drv.is_simple_expression)
+```
+
+Give the scene **one unmistakable hero motion** (a drifting boat, turning sails, falling
+leaves, a flock) plus the ambient ones. A driver that needs Python (`noise.*`, `**`, `%`,
+attribute access, `use_self`) evaluates to 0 in this build — the lint and the census both
+reject it. Self-check: after `scene_views` compare the two sheets; if you cannot point at
+what changed, double the amplitude.
+
+## Soft particles: steam, smoke, dust, motes and sparks (never a hard-edged quad)
+
+The judge's `hard_edged_particles` defect — and the brief's "a soft particle effect … never
+hard-edged quads" must-item, which caps the whole score — fired on what 8 of 30 argon Blender
+scenes built on 2026-10-15: ico-sphere "puffs" wearing a translucent Principled BSDF, metaballs,
+stacked tori, flat discs and polygon "sparks". A SURFACE shader always has a silhouette. In
+Cycles a soft thing is a VOLUME: `lib.materials.volume` on a cloud of subdivision-3 spheres renders
+with no edge at all (measured on Blender 5.2.2: 40 puffs add 0.7 s to a 32-spp GPU frame).
+
+```python
+from lib.materials import emissive, volume
+from lib.mesh import Batch
+from lib.motion import drift
+
+# 1. steam / smoke / dust: ONE Batch of overlapping volume spheres = one placement row, tagged free
+steam = volume("KettleSteam", "ECE9E4", density=0.3, noise_scale=4.0) # dust: density .15-.25; smoke: .5-.8 and a darker colour
+rng = ctx.rng(31)
+plume = Batch("KettleSteam")
+for i in range(22):
+ r = 0.14 + 0.03 * i + rng.uniform(-0.03, 0.03) # widens as it rises
+ spread = 0.06 * (1.0 + 0.3 * i)
+ plume.sphere(steam, (rng.uniform(-spread, spread), rng.uniform(-spread, spread), 0.10 + 0.11 * i), (r, r, 0.8 * r), subdivision=3)
+steam_root = plume.finish(ctx.collection)[0] # [0] is the batch's root Empty
+steam_root.location = (4.0, -2.0, ctx.height_at(4.0, -2.0) + 0.9) # the spout / vent / chimney top
+steam_root["placement"] = "free"
+drift(steam_root, (0.0, 0.0, 0.7), ctx) # rises 0.7 m in 1.5 s: motion the frames show
+
+# 2. motes / sparks / embers: tiny EMISSIVE spheres (<= 1.5 cm): at that size subdivision 2 shows no facet
+spark = emissive("Spark", "FFB347", 30.0)
+cloud = Batch("ForgeSparks")
+for i in range(90):
+ cloud.sphere(spark, (rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5), rng.uniform(0.0, 1.6)), rng.uniform(0.006, 0.014), subdivision=2)
+spark_root = cloud.finish(ctx.collection)[0]
+spark_root.location = (-3.0, 1.0, ctx.height_at(-3.0, 1.0) + 0.6)
+spark_root["placement"] = "free"
+drift(spark_root, (0.2, 0.0, 0.9), ctx) # sparks climb; dust motes drift +/-0.3 m sideways instead
+print("particles", steam_root.name, spark_root.name)
+```
+
+Rules: a particle cloud is ONE object (a `Batch`), tagged `placement = "free"`, and it MOVES
+(`drift` / `sway`, >= 0.6 m in 1.5 s so the judge sees it); density 0.15-0.35 for steam and dust,
+0.5-0.8 for smoke; no disc, plane, cone, torus, metaball or quad is ever a particle; a volume is
+lit like everything else, so under a dim world give it `emission=0.3` or it comes out grey.
+
+## Placement self-check (`lib.place.seat`, `clear_of`)
+
+Placement is MEASURED (`check_placement`; the `scene_placement` gate runs on every build): each
+root object in your zone collection is an asset; from its lowest evaluated vertices the harness
+looks down for the nearest surface and up for one passing through it. A gap under the foot →
+`floating` (ERROR at 0.08 m or past 2 floaters); a foot buried → `sunken` (ERROR at 0.20 m and a
+fifth of the height; rocks, posts and bushes may sit partly in; stairs and ramps may follow the
+slope; a foot at/under water is fine); bbox touching nothing → `unsupported`; two boxes sharing
+more than 10% of the smaller → `interpenetration` (ERROR at 35%). `lib.place.seat(obj,
+ctx.height_at)` samples the same foot columns the gate does; `lib.place.clear_of(objs)` is the
+pair check.
+
+**Scatter clear of what you placed.** 9 of the 13 argon Blender zones that shipped an
+interpenetration ERROR in iteration 0 (2026-10-15) had scattered small props INTO a cart, a rack,
+a shrub or a salt mound (100 % of the smaller box). Place the big things first, then mask their
+footprints out of every scatter, then run `clear_of` on roots AND scattered Empties and delete
+what it still names:
+
+```python
+from lib.materials import material
+from lib.mesh import Batch
+from lib.place import bbox_world, clear_mask, clear_of
+from lib.scatter import poisson, scatter
+
+cart = Batch("HandCart") # the big thing: placed by hand FIRST
+cart.box(material("CartMat", "6B4A2B"), (0.0, 0.0, 0.5), (1.6, 2.4, 1.0))
+cart_root = cart.finish(ctx.collection)[0]
+cart_root.location = (2.0, 2.0, ctx.height_at(2.0, 2.0))
+placed_roots = [cart_root] # every hand-placed root of this zone
+rng = ctx.rng(11)
+mask = clear_mask(placed_roots, margin=0.3)
+pts = poisson(rng, area=(-1.0, -1.0, 5.0, 5.0), min_dist=0.9, max_count=40, mask=mask)
+bollards = scatter(ctx.collection, ctx.assets["bollard"], "YardBollard", pts, height_at=ctx.height_at, rng=rng)
+for a, b, frac in clear_of([*placed_roots, *bollards], overlap=0.10): # (name, name, fraction) rows
+ smaller = min((bpy.data.objects[a], bpy.data.objects[b]), key=lambda o: (lambda lo, hi: (hi - lo).length)(*bbox_world(o)))
+ bpy.data.objects.remove(smaller) # a prop you cannot move 0.3 m clear is a prop you do not need
+print("scattered", len(bollards), "clear of", cart_root.name)
+```
+
+Raw, for a thing you built yourself:
+
+```python
+def foot_and_box(obj):
+ """World-space (lowest z, bbox min, bbox max) of the EVALUATED object (modifiers and parents included)."""
+ bpy.context.view_layer.update()
+ ev = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
+ corners = [ev.matrix_world @ Vector(c) for c in ev.bound_box]
+ lo = Vector((min(c.x for c in corners), min(c.y for c in corners), min(c.z for c in corners)))
+ hi = Vector((max(c.x for c in corners), max(c.y for c in corners), max(c.z for c in corners)))
+ return lo.z, lo, hi
+
+
+def seat_on_ground(obj, height_at, sink=0.0):
+ """Lower / lift the object so its foot meets the ground under its centre (gap <= 0.02 m after)."""
+ foot, lo, hi = foot_and_box(obj)
+ cx, cy = (lo.x + hi.x) / 2, (lo.y + hi.y) / 2
+ obj.location.z += height_at(cx, cy) - sink - foot
+ return obj.location.z
+
+
+def overlapping(objs, frac=0.20):
+ """Pairs whose boxes share more than `frac` of the smaller box's volume (the gate's interpenetration)."""
+ boxes = [(o, *foot_and_box(o)[1:]) for o in objs]
+ out = []
+ for i, (a, alo, ahi) in enumerate(boxes):
+ for b, blo, bhi in boxes[i + 1:]:
+ inter = 1.0
+ for k in range(3):
+ inter *= max(0.0, min(ahi[k], bhi[k]) - max(alo[k], blo[k]))
+ small = min((ahi - alo).x * (ahi - alo).y * (ahi - alo).z, (bhi - blo).x * (bhi - blo).y * (bhi - blo).z)
+ if small > 0 and inter / small > frac:
+ out.append((a.name, b.name))
+ return out
+
+crate_mat = bpy.data.materials.new("CrateMat")
+crate_mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.5, 0.36, 0.2, 1.0)
+crates = []
+for i in range(3):
+ cm = bpy.data.meshes.new(f"Crate_{i}")
+ cb = bmesh.new()
+ bmesh.ops.create_cube(cb, size=0.8)
+ cb.to_mesh(cm)
+ cb.free()
+ cm.materials.append(crate_mat)
+ ob = bpy.data.objects.new(f"Crate_{i}", cm)
+ ob.location = (2.0 + i * 0.95, 3.0, 5.0) # dropped from the air on purpose
+ ctx.collection.objects.link(ob)
+ seat_on_ground(ob, ctx.height_at) # ...and seated
+ crates.append(ob)
+print("seated", [round(foot_and_box(c)[0] - ctx.height_at(c.location.x, c.location.y), 3) for c in crates], "overlaps", overlapping(crates))
+```
+
+A thing MEANT to hang in the air (a bird, a lantern on its chain, a kite) gets
+`obj["placement"] = "free"` — the gate reports the share of tagged things, so it is never the
+way around a seating problem. Instance clouds (geometry nodes) are not checked per asset.
+
+## Instancing and scatter (collection instances vs geometry-nodes clouds)
+
+Two ways to repeat, with different gate rows:
+
+* **A collection instance** (`lib.scatter.instance` / `scatter`): an Empty with
+ `instance_type = 'COLLECTION'` pointing at `ctx.assets['<snake>']` (or a Collection you built
+ once). ONE placement row per instance — seated, named, measured against the plan's size.
+ Use it for anything the judge will look at: props, trees near a camera, a bench.
+* **A geometry-nodes cloud** (`lib.scatter.gn_scatter`, `lib.vegetation.grass_patch`): points
+ distributed on a surface, an object instanced on them. Counted as instances by the census,
+ exempt from per-asset placement, one object. Use it for the hundreds: blades, pebbles,
+ litter, a far treeline.
+
+```python
+source = ctx.assets.get("bollard")
+if source is None: # (no such plan asset: a stand-in post)
+ pm = bpy.data.meshes.new("PostStandIn")
+ pb = bmesh.new()
+ bmesh.ops.create_cone(pb, cap_ends=True, segments=8, radius1=0.08, radius2=0.08, depth=0.9)
+ bmesh.ops.translate(pb, vec=(0.0, 0.0, 0.45), verts=pb.verts)
+ pb.to_mesh(pm)
+ pb.free()
+ source = bpy.data.collections.new("PostStandIn")
+ ctx.collection.children.link(source)
+ source.objects.link(bpy.data.objects.new("PostStandIn", pm))
+instances = []
+for i in range(6): # a row of posts along the quay edge, jittered
+ x, y = -12.0 + i * 3.0 + rng.uniform(-0.2, 0.2), -9.0 + rng.uniform(-0.15, 0.15)
+ e = bpy.data.objects.new(f"QuayPost_{i}", None)
+ e.instance_type = "COLLECTION"
+ e.instance_collection = source
+ e.location = (x, y, ctx.height_at(x, y))
+ e.rotation_euler = (0.0, 0.0, rng.uniform(0.0, math.tau))
+ ctx.collection.objects.link(e)
+ instances.append(e)
+print("instances", len(instances), "of", source.name)
+```
+
+A Collection you build for instancing (not a plan asset) lives inside your zone collection;
+its source objects at the origin are seen unless you exclude it — simplest is to instance the
+plan's assets (`ctx.assets`) and build one-offs as plain objects.
+
+## Materials: Principled recipes and the lib palette
+
+Every surface is a Principled BSDF with a COLOUR and a roughness; a grey default is graded
+`placeholder_material`. Blender 5.2 socket names: `Base Color`, `Roughness`, `Metallic`, `IOR`,
+`Alpha`, `Normal`, `Subsurface Weight`, `Specular IOR Level`, `Transmission Weight`, `Coat
+Weight`, `Sheen Weight`, `Emission Color`, `Emission Strength` (the old `Specular`,
+`Subsurface`, `Transmission`, `Emission` raise KeyError). Colour mixing is `ShaderNodeMix`
+with `data_type = 'RGBA'` (inputs 6 and 7, output 2) — `ShaderNodeMixRGB` is gone. The lib
+palette (`lib.materials`: `material`, `masonry`, `limestone`, `ashlar`, `woodgrain`,
+`chipped_paint`, `worn_alloy`, `mineral_surface`, `water`, `glass`, `foliage`, `snow`, `ice`,
+`emissive`, `tint`) builds these; the raw recipes:
+
+```python
+def material(name, color, roughness=0.5, metal=0.0, noise_scale=0.0, bump=0.08, emission=0.0):
+ """One Principled material; noise_scale > 0 adds a procedural bump so flat surfaces still catch light."""
+ mat = bpy.data.materials.new(name)
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ bsdf = nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metal
+ if emission:
+ bsdf.inputs["Emission Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Emission Strength"].default_value = emission
+ if noise_scale:
+ tex = nodes.new("ShaderNodeTexNoise")
+ tex.inputs["Scale"].default_value = noise_scale
+ tex.inputs["Detail"].default_value = 8.0
+ b = nodes.new("ShaderNodeBump")
+ b.inputs["Strength"].default_value = bump
+ links.new(tex.outputs["Factor"], b.inputs["Height"])
+ links.new(b.outputs["Normal"], bsdf.inputs["Normal"])
+ return mat
+
+
+def woodgrain(mat, dark=(0.16, 0.10, 0.06), light=(0.50, 0.35, 0.22), scale=3.0):
+ """Wave texture → Mix (RGBA) between two tones → Base Color; along the object's Y."""
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ bsdf = nodes["Principled BSDF"]
+ coords = nodes.new("ShaderNodeTexCoord")
+ wave = nodes.new("ShaderNodeTexWave")
+ wave.wave_type = "BANDS"
+ wave.bands_direction = "Y"
+ wave.inputs["Scale"].default_value = scale
+ wave.inputs["Distortion"].default_value = 4.0
+ wave.inputs["Detail"].default_value = 3.0
+ mix = nodes.new("ShaderNodeMix")
+ mix.data_type = "RGBA"
+ mix.inputs[6].default_value = (dark[0], dark[1], dark[2], 1.0)
+ mix.inputs[7].default_value = (light[0], light[1], light[2], 1.0)
+ links.new(coords.outputs["Object"], wave.inputs["Vector"])
+ links.new(wave.outputs["Factor"], mix.inputs["Factor"])
+ links.new(mix.outputs[2], bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.65
+ return mat
+
+
+def glass(name, color=(0.9, 0.95, 1.0), roughness=0.05, ior=1.5):
+ mat = material(name, color, roughness=roughness)
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Transmission Weight"].default_value = 1.0
+ bsdf.inputs["IOR"].default_value = ior
+ return mat
+
+stone = material("Granite", (0.43, 0.42, 0.39), roughness=0.9, noise_scale=12.0, bump=0.15)
+oak = woodgrain(material("Oak", (0.5, 0.35, 0.22)))
+pane = glass("Pane")
+brass = material("Brass", (0.80, 0.62, 0.30), roughness=0.35, metal=1.0)
+lamp_glow = material("Glow", (1.0, 0.72, 0.45), emission=6.0)
+sm = bpy.data.meshes.new("MaterialSampler")
+sb = bmesh.new()
+bmesh.ops.create_cube(sb, size=0.5)
+bmesh.ops.translate(sb, vec=(0.0, 0.0, 0.25), verts=sb.verts)
+sb.to_mesh(sm)
+sb.free()
+for m in (stone, oak, pane, brass, lamp_glow):
+ sm.materials.append(m)
+sampler = bpy.data.objects.new("MaterialSampler", sm)
+sampler.location = (-4.0, -4.0, ctx.height_at(-4.0, -4.0))
+ctx.collection.objects.link(sampler)
+print("materials", [m.name for m in sm.materials])
+```
+
+Albedos belong in 0.02–0.8 linear (pure black and pure white are always wrong); wood and
+stone roughness 0.6–0.95, metals `Metallic` 1 with roughness 0.2–0.5, glass transmission 1;
+an emissive at strength 5–10 blooms, 50 whites the frame out.
+
+## Assets (`src/assets/<snake>.py`): `build_<snake>` returning a Collection at the origin, base z = 0
+
+An asset module builds EVERY part into `ctx.collection` (its own, pre-made) at the origin,
+base on z = 0, front facing −Y, and returns `ctx.collection`; the harness builds it once,
+hides the source and the zones place collection instances of it. Several parts with distinct
+materials, unique names, under the triangle budget (15000 per asset); `variant` (0..n) changes
+the SILHOUETTE, not just the scale. A hero (`blender_glb`) is built by the object track instead
+and imported for you. The shape, inline (in a real asset file `build_lantern` is the module's
+top-level function):
+
+```python
+def _mat(name, color, roughness=0.5, metal=0.0, emission=0.0):
+ mat = bpy.data.materials.new(name)
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metal
+ if emission:
+ bsdf.inputs["Emission Color"].default_value = (color[0], color[1], color[2], 1.0)
+ bsdf.inputs["Emission Strength"].default_value = emission
+ return mat
+
+
+def build_lantern(ctx, variant=0):
+ iron = _mat("LanternIron", (0.12, 0.12, 0.13), roughness=0.5, metal=0.8)
+ glow = _mat("LanternGlow", (1.0, 0.78, 0.45), emission=6.0)
+ post_h = 2.2 if variant == 0 else 1.6
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=10, radius1=0.04, radius2=0.03, depth=post_h)
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, post_h / 2), verts=bm.verts)
+ cage = bmesh.ops.create_cone(bm, cap_ends=True, segments=6, radius1=0.14, radius2=0.12, depth=0.26)
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, post_h + 0.13 - 0.004), verts=cage["verts"]) # overlaps the post by 4 mm
+ me = bpy.data.meshes.new("LanternBody")
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(iron)
+ body = bpy.data.objects.new("LanternBody", me)
+ ctx.collection.objects.link(body)
+ gm = bpy.data.meshes.new("LanternGlass")
+ bm = bmesh.new()
+ bmesh.ops.create_icosphere(bm, subdivisions=2, radius=0.08)
+ bm.to_mesh(gm)
+ bm.free()
+ gm.materials.append(glow)
+ bulb = bpy.data.objects.new("LanternGlass", gm)
+ bulb.parent = body
+ bulb.location = (0.0, 0.0, post_h + 0.13)
+ ctx.collection.objects.link(bulb)
+ return ctx.collection
+
+built = build_lantern(ctx, variant=1)
+print("asset parts", [o.name for o in built.objects if o.name.startswith("Lantern")])
+```
+
+Why: a scene mixes cheap instanced props with a few hero assets; the harness hands every
+asset to the zones the same way (`ctx.assets['<snake>']`), so a zone places a procedural
+module and an imported GLB with the same four lines.
+
+## Interiors: the room shell is the env's
+
+A brief set INSIDE a built space (`interior: true` in the plan) gets its floor, walls and
+ceiling from `src/env.py` — `lib.architecture.room_shell(collection, mat, center=…,
+extents=…, thickness=0.2, openings=(…))` on the bounds' faces, named `RoomShell…` /
+`Ceiling…` so the overview rig can lift the lid — with the windows and doors cut as openings
+and the inside LIT (an Area light per window, practicals; a closed room under a sun reads
+black). Zones dress the inside and never build walls; a fixture on a wall sits flush against
+the inner face of the bounds. Measured 2026-09-07 over six interior runs: with no owner for
+walls and roof, every one was judged "not enclosed, a diorama on a flat plane" (0.0–0.3).
+
+## Traps (Blender 5.2 LTS API facts; each is a build error or a silent zero)
+
+1. **`use_nodes` is deprecated** — materials, worlds and lights always have a node tree; a
+ new material already carries `Principled BSDF` and `Material Output`.
+2. **`sky_type = 'NISHITA'` raises** — it is `'MULTIPLE_SCATTERING'`.
+3. **Principled sockets renamed** — `Specular IOR Level`, `Subsurface Weight`, `Transmission
+ Weight`, `Emission Color` + `Emission Strength`, `Coat Weight`, `Sheen Weight`.
+4. **`ShaderNodeMixRGB` is gone** — `ShaderNodeMix` with `data_type = 'RGBA'`: inputs 6 / 7,
+ output 2.
+5. **Boolean solvers are `FLOAT` / `EXACT` / `MANIFOLD`** — `'FAST'` raises.
+6. **Geometry-nodes inputs are RNA properties** — `getattr(mod.properties.inputs,
+ "Socket_2").value = v`; `mod["Socket_2"] = v` raises TypeError.
+7. **`Action.fcurves` is gone** — `action.layers[0].strips[0].channelbag(action.slots[0]).
+ fcurves` for the interpolation.
+8. **`Mesh.calc_normals()` and `use_auto_smooth` are gone** — `for f in bm.faces: f.smooth =
+ True` or `me.shade_smooth()`.
+9. **No `bpy.ops` in loops** — every operator rebuilds the scene state; build with `bmesh` and
+ `bpy.data`, place collection instances, scatter with geometry nodes.
+10. **`bpy.context.object` / `selected_objects` after `bpy.data.objects.new`** — nothing is
+ selected in background mode; keep your own references.
+11. **A driver that needs Python evaluates to 0** — only `frame`, `sin / cos / min / max /
+ clamp / lerp`, `+ - * /` and comparisons; no `noise`, `**`, `%`, attribute access,
+ `use_self`.
+12. **A Python world outside `env.py`**, a camera, `frame_set`, `scene.render.*` — lint ERRORS
+ that fail the build gate; the harness owns them.
+13. **Names are global** — `Lantern_0` twice becomes `Lantern_0.001`; number every placed
+ copy per zone family and never reuse another zone's base name.
+14. **`bm.verts[i]` before `ensure_lookup_table()`** — IndexError; call it after any topology
+ change, or iterate instead of indexing.
+15. **Triangle budgets** — 15000 per asset instance, 40000 for a hero, 3,000,000 unique
+ triangles for the whole scene (a gate ERROR past it); instance clouds count their
+ instances, so a 200-blade cloud over 400 points is 240,000 rendered triangles but 600
+ unique ones.
+16. **`matrix_world` of a fresh `bpy.data` object is identity** until the view layer updates —
+ parent with a RELATIVE `location` (the practical recipe), or call
+ `bpy.context.view_layer.update()` before reading it.
+
+## Self-check (before you call it done)
+
+Composition self-check on every authored frame (the judge grades exactly these):
+
+* three depth layers — something inside 5 m, the subject at 8–30 m, a backdrop and sky above;
+* no hard world edge anywhere against the sky; the fog the horizon's colour;
+* the ground shows ≥ 3 blended colours and at least one path / worn area;
+* vegetation shows ≥ 3 silhouettes and visible hue / scale variation, in clusters not a ring;
+* ≥ 12 mid props and ≥ 25 small props per dressed zone, placed against things, every one seated;
+* shade is coloured (the sky's), not black; the key and the world differ in hue;
+* t = 0 and t = 1.5 are visibly different.
+
+Then: `build` → `check_placement` (floating / sunken / unsupported / interpenetration + the
+fix per asset, in metres) → `scene_probe` (unique triangles, drivers, the world, console) →
+`scene_views` (authored cameras + the overview rig, with `camera_checks`) → fix the worst →
+repeat. Look at every camera's frame AND its numbers: no black frames, no white-out, the
+subject (not sky / ground) fills the establishing shot, `camera_in_geometry` false, and
+`check_placement` clean.
diff --git a/harness/codeverse3d/prompts/scene_blender/effects_catalog.md b/harness/codeverse3d/prompts/scene_blender/effects_catalog.md
new file mode 100644
index 00000000..0cb2cdf2
--- /dev/null
+++ b/harness/codeverse3d/prompts/scene_blender/effects_catalog.md
@@ -0,0 +1,99 @@
+# The shipped bpy library — call these before writing your own
+
+`src/lib/` is in your workspace already: thirteen modules of Blender 5.2 LTS bpy
+that build, seat, light and animate what a scene needs. They are not an
+outside package — they are harness code shipped into the workspace, so
+importing them is allowed where "never import a helper SDK" still forbids
+everything else (and a write to `src/lib/` is reverted).
+
+Reach for one FIRST. Write your own only for something no entry here covers,
+and then build it with `Batch` from `lib/mesh.py` — plain vertex and face lists,
+never `bpy.ops` primitives in a loop.
+
+Import with the package path from any file — `src/env.py`, `src/zones/x.py`
+and `src/assets/x.py` all say `from lib.materials import material` or
+`from lib import mesh, place` (`src/` is on the path; the modules import each
+other the same way).
+
+| Want | Call |
+| --- | --- |
+| noise on the CPU, a seeded generator, a cheap per-item jitter | `rng(seed)` (THE random: never the module-level `random`) · `hash01(i, seed=0)` 0..1 from an index · `fbm2(x, y, *, octaves=4, lacunarity=2.0, gain=0.5, seed=0)` / `fbm3(x, y, z, *, …)` gradient noise about -1..1 with 1 unit = one feature (call with `x / scale_m`) · `ridged(x, y, *, seed=0, octaves=5)` 0..1 crests · `mountain_height(x, y, *, seed=0, amplitude=45.0, frequency=0.013)` a horizon ridge in metres · `height_field(size, segments, fn)` a row-major grid of samples — `lib/noise.py`; pure python: a 96 x 96 field with four octaves is ~60 ms, so keep heavy fields to the env |
+| a prop built from parts as ONE object (one placement row, one mesh per material) | `Batch(name)` then `.box(mat, loc, size, rotation=0.0)` (loc = centre, 12 triangles) · `.sphere(mat, loc, scale, subdivision=1)` (level 1 = 20 triangles, 2 = 80, 3 = 320, 4 = 1 280) · `.lathe(mat, xy, profile, sides=32, phase=0.0)` (profile = [(radius, z), …], capped) · `.cone(mat, loc, radius, height, top=0.0, sides=24)` (loc = base centre) · `.beam(mat, a, b, radius, end=None, sides=8)` (a capped tube; `end` tapers) · `.torus(mat, loc, radius, tube, major=64, minor=8)` · `.ring(mat, center, normal, radius, tube, segments=96)` (a hoop about `normal`) · `.add(mat, vertices, faces, smooth=False)` raw lists · `.transformed(matrix)` a view whose additions are transformed (a figure turned to its heading) · `.finish(collection, *, bevel=0.0, parent=True, name_prefix="")` → `[root, mesh, …]`: ONE root Empty named after the batch (the placement row; `root["placement"] = "free"` for a hanging thing), origin at the base centre; `parent=False` for an asset's own collection · `mesh_object(name, vertices, faces, mat, collection, *, smooth=False)` · `curve_object(name, points, radius, mat, collection, *, cyclic=False)` a rope / cable / vine · `sphere_template(level)` an icosphere's lists · `parent_under(objects, collection, name)` several objects as one row — `lib/mesh.py`; metres, Z up, -Y front |
+| a textured Principled material without a texture file | `material(name, color, roughness=.5, metal=0.0, *, noise_scale=0.0, bump=.08, emission=0.0)` (hex `"8A6A3F"` or a linear tuple; `noise_scale` features / m adds breakup + bump) · `masonry(name, color, mortar="625D66", scale=2.0)` rows / m · `limestone(name, color, scale=1.2)` · `ashlar(name, color)` 1.2 x 0.4 m blocks · `woodgrain(mat, dark="29190F", light="805939", direction=(3,.1,5))` on an existing material · `chipped_paint(mat, paint, substrate, scale=6)` · `worn_alloy(name, color, *, seed=0, metal=.55)` · `mineral_surface(name, color, *, stone=False)` rock / soil, cracks when `stone` · `water(name, color="163F4A", roughness=.12, scale=.8, *, flow=(0.6,0.2), ctx=None)` ONE refracting surface (give it a bed; ripples drift with `ctx`) · `clear_water(name)` a basin · `glass(name, color="FFFFFF", roughness=.05, ior=1.5)` · `foliage(name, color, variants=3)` → a LIST of leaf materials (give neighbours different ones) · `snow(name="Snow")` · `ice(name="Ice")` · `emissive(name, color, strength)` a light-giving skin (3-8 reads as a lamp) · `tint(mat, variant)` a shifted copy (-1..1) · `volume(name, color, density=.4, *, anisotropy=.3, noise_scale=0.0, emission=0.0)` a Principled VOLUME with no surface — the ONLY soft steam / smoke / dust / spark haze in Cycles, on a `Batch` of subdivision-3 spheres (see "Soft particles" in the cookbook) — `lib/materials.py`; patterns read OBJECT coordinates so they keep their metre scale; albedos belong in 0.02-0.8 linear |
+| the ground, hills, rock | `make_height_at(*, seed=0, relief=3.0, scale=60.0, flat_radius=45.0, base=0.0)` → THE `height_at` function of (x, y) (level inside `flat_radius`, hills of `relief` m beyond; env.py returns it) · `ground(name, collection, *, size, segments, height_at, material, center=(0,0), smooth=True)` the terrain mesh (name it `Ground…`; 96 segments = 18 k triangles) · `cliff(name, collection, *, length, height, height_at, material, seed=0)` a rock face along +X (~2.4 k) · `boulder(batch, mat, center, scale, *, seed=0, detail=3)` standing on `center` z (80 / 320 / 1 280 triangles at detail 2 / 3 / 4) · `rock_field(batch, mat, center, radius, count, height_at, rng)` 80 apiece · `talus(batch, mat, center, scale, seed)` a scree heap (~800) · `basalt_column(batch, materials, center, radius, height, rng, lean=(0,0))` a hexagonal cluster (~300) · `shoreline_mask(x, y, water_level, height_at)` 0 in the water, 1 half a metre up — `lib/terrain.py`; every recipe's `center` is the GROUND point: pass `height_at` (x, y) |
+| the sky, fog, night dressing (world setters are ENV ONLY) | `sun_world(scene, *, elevation_deg=12.0, azimuth_deg=125.0, strength=.2, dust=2.0)` the physical MULTIPLE_SCATTERING sky, compass 0 = +X / 90 = +Y like the Sun lamp, disc off (the lamp is the sun) · `night_world(scene, color="17273F", strength=.3)` · `gradient_world(scene, stops, *, clouds=True, strength=.7)` stops = `[(0, "F2C9A0"), (1, "1F4A8E")]` horizon → zenith · `haze(collection, loc, size, density=.003, color="ADC9E1", name="Atmosphere")` a bounded fog box (volume-only: the census reports it as fog, never as matter; 0.002 clear, 0.01 mist, 0.03 fog) · `aurora(name, collection, center, *, span=560, height=72, seed=0, strength=.24, ctx=None)` a curtain at `center` (x, y, altitude), tagged free — NAME it with a sky word (`"AuroraSky"`) so the census files it as sky · `stars(batch, mat, *, seed=0, count=900, radius=600)` into a batch named `Stars…` with an `emissive` mat; tag its root free — `lib/sky.py`; no clouds volume, no moon disc |
+| lamps | `sun(collection, *, azimuth_deg, elevation_deg, color="FFCF9C", energy=3.0, angle_deg=2.0, name="Sun")` → `(lamp, towards_sun)`, W/m² (3-5 day, 0.3-1 dusk) · `area_light(collection, name, loc, color, energy, *, size=5.0, target=None, shape="DISK")` Watts · `point_light(collection, name, loc, color, energy, *, radius=.05)` · `spot(collection, name, loc, color, energy, *, size_deg=45.0, blend=.3, target=None)` · `practical(collection, name, loc, color="FFB270", energy=300, *, size=.42, target=None)` the light a visible fixture throws (pair it with an `emissive` skin) · `aim(obj, target)` — `lib/lighting.py`; exposure and the view transform are the harness's: light the scene, never the camera |
+| water: a lake, a fall, jets, spray | `water_surface(name, collection, *, size, level, material=None, ripple=0.045, seed=0, height_fn=None)` ONE plane at z = `level` centred on the origin — move the object; `height_fn` drops cells where the ground stands above the water (name it `…Water` / `…Lake`: a foot in it is "on water", never floating; ~4.6 k) · `pool_height(x, y, *, level=-.25)` a `height_at` for things that float · `waterfall(name, collection, center, *, width, height, seed=0, ctx=None, layers=4)` foam sheets dropping onto `center` (the impact level), flow toward -Y, ~400 per layer · `hanging_fall(name, collection, outlet, along, across, *, width, height, seed=0, ctx=None)` one sheet from a spout · `fountain_jets(batch, collection, water_mat, *, center, nozzle_r, landing_r, count=14, rise=1.85, ctx=None, seed=0)` parabolic tubes + spray (~220 per jet) · `droplets(batch, mat, center, width, bottom, rng, count=260)` 4 triangles each · `foam_shader(name)` — `lib/water.py`; no fluid solver, no caustics: a fall is sheets whose texture streams with `ctx` |
+| trees, shrubs, ferns, grass, flowers | `tree(batch, loc, height, bark, foliage, *, seed=0, kind="broadleaf", max_leaves=4000)` kinds broadleaf / oak / cypress / pine — a crown of leaf CARDS (3-9 k triangles; `max_leaves` caps it; pine ≈ 350) · `shrub(batch, bark, foliage, center, *, scale=1.0, seed=0)` (~300) · `leaf_spray(batch, foliage, center, rng, *, radius=.32, count=35)` a vine knot · `fern(batch, mat, center, *, scale=1.0, seed=0)` · `tropical(batch, leaves, stem, center, *, scale=1.0, seed=0)` · `grass_clump(batch, mats, x, y, z, rng)` 12 blades · `perennial_bed(batch, center, radius, height_at, foliage, petals, rng)` (~1.1 k) · `grass_patch(name, collection, surface, *, blade=None, density=5.0, seed=0, height=.3, color="4A6B2A")` a geometry-nodes instance CLOUD on `surface` (a hidden `terrain.ground` patch: `hide_render = True`) — exempt from per-asset placement, 3 quads per blade · `tree_stand(collection, batch, positions, height_at, rng, bark=…, foliage=…, height=7.0, kind=…)` a copse as ONE object — `lib/vegetation.py`; every `loc` / `center` is the ground point |
+| buildings, roofs, bridges, paving, a room, lettering | `timber_house(batch, roofs, x, y, width, depth, floors, mats, rng, index)` half-timbered, `mats` = {wall, timber, door, window}, `roofs` = {tile, trim}; returns the ridge height (≤ 14 k) · `tiled_roof(batch, tile, trim, center, width, depth, rise, rng)` ridge along X on `center` (x, y, eave z) · `clay_roof(batch, frame, tiles, timber, center, width, depth, rise, rng)` pantiles · `fret_window(batch, wood, paper, x, y, z, width, height, direction, *, pattern=0)` facing compass `direction` · `arched_opening(batch, mat, center, width, height, *, depth=.28, thickness=.2)` · `stone_bridge(batch, stone, dark, *, center, span=27.6, width=4.7, rise=3.9, height_at=None)` hump-backed along X (~700) · `arched_footbridge(batch, wood, stone, *, start, end, rise=1.5, height_at=None)` (~1 k; give it `height_at` on a bank) · `tower(batch, mat, center, radius, low, high, windows, *, count=8)` · `paving(batch, mats, *, center, inner_r, rings, seed)` fan-set rings, 2 cm thick (~350 per ring) · `paving_grid(batch, mats, center, size, stone, joint, rng)` flagstones · `room_shell(collection, mat, *, center, extents, thickness=.2, openings=(), glazed=False)` an interior's floor, walls and `Ceiling` under a `RoomShell` root (env.py; openings = `(wall, offset, width, sill, head)`; `glazed=True` is a glass house — a conservatory, a greenhouse, a glass atrium: every wall panel and the lid become `materials.glass` panes that cast no shadow on an iron-frame grid of `mat` bars, so the sun comes through and the frame's grid shadows the floor, which stays an opaque slab of `mat`; the names stay, a pane being its panel's name + `Glass`) · `lantern(batch, silk, wood, center, *, radius=.35, length=None)` (~550; an `emissive` silk) · `text_mesh(name, collection, body, loc, size, mat, *, rotation=(pi/2,0,0), align="CENTER", extrude=.005)` readable lettering (~300 per letter) — `lib/architecture.py`; `center` / (x, y) sit on the ground z you pass |
+| placing copies: instances and clouds | `instance(collection, source, name, x, y, *, height_at, rot_z=0.0, scale=1.0, sink=0.0)` ONE seated collection-instance Empty of `ctx.assets["<snake>"]` (the placement row) · `scatter(collection, source, prefix, points, *, height_at, rng, rot="random", scale=(1,1))` one per point, named `<prefix>_<i>` · `poisson(rng, *, area, min_dist, max_count, mask=None)` points in (x0, y0, x1, y1) at least `min_dist` apart; `mask` of (x, y) → 0..1 keeps a shoreline clear · `along_path(points, n, *, jitter=0.0, rng=None)` · `grid(center, size, spacing, rng, *, jitter=.3)` · `gn_scatter(name, collection, surface, instance_obj, *, density, seed=0, align_normal=True, scale_range=(.8,1.2))` an instance cloud (pebbles, tufts, hundreds+) — one object, exempt from per-asset placement — `lib/scatter.py`; a cloud cannot be measured per copy: anything the plan COUNTS (a bench, a cart, a tree) is an `instance` |
+| seating, facing, the zone's own placement check | `seat(obj, height_at, *, sink=0.0, columns=5)` drop a ROOT until its lowest foot column rests on the ground (the gate's own columns: lowest + ±x / ±y of the foot band) · `seat_instance(empty, source, height_at, *, sink=0.0)` · `rest_on(obj, support, *, offset=0.0)` a lantern on a table · `bbox_world(obj, *, evaluated=True)` (min, max) incl. children and instances · `face_toward(obj, target)` / `heading(a, b)` for -Y-front things · `clear_of(objs, min_gap=.02, *, overlap=0.10)` → `[(a, b, fraction)]` AABB overlaps the gate would call interpenetration: run it on your roots before returning · `clear_mask(objs, margin=.3)` → an (x, y) mask for the scatter module's poisson `mask` argument that keeps scatter points out of the placed roots' footprints (+ `margin` m): build it BEFORE you scatter the small stuff · `keep_inside(obj, bbox)` the plan's box · `unique_name(base, i)` `Base_i`, bumped past an existing name (names are global in Blender) · `world_matrix(obj)` the matrix NOW (`obj.matrix_world` is stale until the depsgraph runs) — `lib/place.py`; contact is 2 cm, floating starts at 5 cm outdoors / 2 cm indoors, sunk at 10 cm |
+| a person, a crowd | `figure(batch, cloth, skin, center, *, scale=1.0, heading=0.0, pose=0.0)` 1.72 m, facing -Y turned by `heading`, `pose` 0 standing → 1 striding (~530) · `visitor(batch, cloth, mats, center, *, scale=1.0, heading=0.0, pose=0.0, variant=0)` a coat over `mats[variant]` legs, `mats[-1]` the skin · `crowd(batch, mats, points, rng, scale=1.0)` one per (x, y, z) — `lib/figure.py`; no faces, no hands with fingers: a figure reads at 3 m and beyond |
+| motion between t = 0 and 1.5 s | `keyframe_path(obj, points, ctx, *, t0=0.0, t1=None, interpolation="LINEAR")` · `drift(obj, delta, ctx)` a boat, a balloon, a leaf · `spin(obj, axis="Z", turns_per_s=.25, ctx=None)` a SIMPLE driver `frame * k` (a wheel, a vane) · `sway(obj, axis, amplitude, period_s, ctx)` a SIMPLE driver, a sine of `frame` (a hanging lantern, a mast) · `scroll(mapping_node, velocity, ctx)` a texture that flows · `shape_key_sweep(obj, key_name, ctx, *, from_value=0.0, to_value=1.0)` a sail filling · `fcurves(id_data)` / `set_interpolation(id_data, interpolation="LINEAR")` the 5.2 slotted-action curves — `lib/motion.py`; keyframes land on `ctx.frame(t)`; a driver that needs Python evaluates to 0 in the build and fails it |
+
+## The six rules that apply to all of them
+
+**1. Collection, name, seed.** Every factory takes the collection it links into
+(`ctx.collection` — never `bpy.context.collection`), a name, and a `seed` or
+`rng` wherever it draws: the same seed gives the same scene on every machine,
+and `ctx.rng(seed)` is the ONLY randomness a zone uses. Names are global in
+Blender: `place.unique_name("Lantern", i)` — a duplicate silently becomes
+`Lantern_0.001` and reads as a stray instance.
+
+**2. Seat everything.** A placed thing is a ROOT object in the zone's
+collection: a `Batch.finish` root, a `scatter.instance` Empty, a
+`mesh_object`. The gate samples its foot columns against what is under them:
+a gap over 5 cm (2 cm indoors) is floating, a burial over 10 cm is sunk, an AABB
+overlap over 10 % of the smaller box is interpenetration, and a measured
+defect caps the score. Batch recipes stand on the ground z you pass
+(`height_at` (x, y)); instances seat themselves; anything else goes through
+`place.seat(root, ctx.height_at)`. `obj["placement"] = "free"` ONLY for a thing
+that really hangs or flies — the gate reports the share of free-tagged assets.
+
+**3. Motion is data on `ctx.frame(t)`.** Keyframes through `lib.motion`, or a
+simple driver of `frame`; never `frame_set`, handlers or Python drivers. The
+harness renders `ctx.times` = 0 and 1.5 s and reads the .blend it saved.
+
+**4. The world and the sun belong to `src/env.py`.** `sun_world` /
+`night_world` / `gradient_world` and `lighting.sun` run in `build_env` and nowhere
+else (the lint rejects a world in a zone); zones add their own practicals and
+read `ctx.env["sun_direction"]`. Give the sky and the Sun lamp the SAME
+azimuth / elevation.
+
+**5. Instances versus clouds.** A thing the plan counts (a bench, a cart, a
+tree) is a `scatter.instance` of its asset collection: one row the gate can
+name. Ground cover by the hundred (blades, pebbles, tufts) is a `gn_scatter` /
+`grass_patch` cloud: one object, counted as instances, exempt from per-asset
+placement. A prop is ONE `Batch`, not twenty primitives: the census and the
+renderer are per object.
+
+**6. Import only what you CALL.** `from lib.materials import material, woodgrain`
+— not a module's whole export list. Measured on the three.js library's first
+six scenes: 120 imported names were never used, and every later round had to
+read them.
+
+## What differs on this renderer
+
+* **Cycles, 32 samples + OpenImageDenoise, AgX at exposure 0**, 1024 x 576,
+ the harness's settings (the lint rejects `scene.render` / `scene.cycles`
+ writes). There is NO post chain and NO bloom: an `emissive` skin at
+ strength 3-8 reads as a lamp, 20+ as a sun-bright source, and a lamp beside it
+ (`lighting.practical`) is what actually lights the wall. Non-emissive albedos
+ belong in **0.02-0.8** linear.
+* **The census is the evaluated depsgraph**: modifiers, geometry nodes and
+ instances count exactly as they render; a volume-only material is fog, not
+ matter (the `haze` box never appears as a placed thing). Unique triangles
+ are capped at 3 M; a tree is 3-9 k, a two-storey house ~10 k, so a hamlet and
+ a wood fit with room to spare.
+* **Blender 5.2 API facts the library already follows** (and you must too):
+ no `use_nodes`; `ShaderNodeMix` (not MixRGB) with RGBA on inputs 6 / 7 and
+ output 2; the Principled sockets are `Emission Color` / `Emission Strength` /
+ `Transmission Weight` / `Coat Weight` / `Specular IOR Level`; the sky is
+ `MULTIPLE_SCATTERING` with `aerosol_density`; boolean solvers are MANIFOLD /
+ EXACT / FLOAT; geometry-nodes inputs are
+ `getattr(mod.properties.inputs, "Socket_2").value = v`; actions are slotted
+ (`lib.motion.fcurves`, not `action.fcurves`); `obj.matrix_world` is stale until
+ the depsgraph runs (`lib.place.world_matrix`).
+* **One refracting water plane, no planar reflector budget to spend**: Cycles
+ refracts and reflects whatever is there. Keep the ground under the water (a
+ basin in `height_at`) so there is a bed to see.
diff --git a/harness/codeverse3d/prompts/scene_blender/system.md b/harness/codeverse3d/prompts/scene_blender/system.md
new file mode 100644
index 00000000..6c398419
--- /dev/null
+++ b/harness/codeverse3d/prompts/scene_blender/system.md
@@ -0,0 +1,79 @@
+You are a Blender bpy author writing RAW python modules for a multi-file scene that a
+headless harness builds and renders in Blender 5.2 LTS (Cycles, AgX). No SDKs, no add-ons,
+no file IO, no network: `bpy`, `bmesh`, `mathutils`, `math`, `numpy` and the workspace's own
+`lib.*` / `env` modules, nothing else. The harness owns the process, the render settings,
+the cameras, the frame clock and the export — you build geometry, materials, lights, the
+world and the motion into the Collection you are handed.
+
+| file | you define | the harness calls it |
+| --- | --- | --- |
+| `src/env.py` | `height_at(x, y) -> z`, `build_env(ctx) -> dict` | first: world, sun, ground, atmosphere (an interior's shell) |
+| `src/assets/<snake>.py` | `build_<snake>(ctx, variant=0) -> Collection` | once each, at the origin, base on z = 0 → `ctx.assets['<snake>']` |
+| `src/zones/<snake>.py` | `build(ctx) -> Collection` | once each, into `ctx.collection`; a raise drops THAT zone only |
+| `src/scene.py` | nothing — harness data | the entry; re-assembly overwrites it |
+| `src/lib/*.py` | nothing — harness library | you import and call it (the catalog is in every brief) |
+
+What the gates measure — deterministically, on the census of the built scene, before any
+picture is judged:
+
+* **Placement.** Every root object you link into a zone is a row: a foot more than 0.05 m
+ above what is under it (0.02 m indoors) is `floating`, a foot buried past 0.10 m is
+ `sunken`, two boxes sharing more than 10% of the smaller one is `interpenetration`, a
+ bbox touching nothing is `unsupported` — ERRORS at 0.08 m / 0.20 m / 35%. Seat things
+ with `lib.place.seat(obj, ctx.height_at)` or `lib.scatter.instance(..., height_at=
+ ctx.height_at)` and they pass; `obj["placement"] = "free"` is for things that hang in the
+ air, and the share of tagged things is reported.
+* **Frames.** Every authored camera at t = 0 and t = 1.5 s: too dark, blown out, mostly sky or
+ ground, the camera inside geometry or below the terrain. Exposure is fixed (0): a dark
+ brief is lit by its practicals and a tinted world, never by hiding the sun.
+* **The probe.** Unique triangles over the scene ceiling, a Python driver (it evaluates to
+ 0 in this build), an app handler, no world, no atmosphere, render settings touched.
+
+{% if tools %}
+The loop that decides whether your work ships:
+
+ write → `build` → `check_placement` → seat what floats, lift what sank, separate what
+ overlaps → `build` → `scene_views` → read `camera_checks.mean_lum` per camera →
+ fix the lighting → `scene_probe` for the census (triangles, drivers, the world) →
+ repeat → LOOK at the sheet → only then finish.
+
+`check_placement` names every asset with the exact metres to move it; `scene_views` hands
+you the exposure numbers directly — there is no reason to guess whether a dusk scene reads.
+{% else %}
+You cannot run anything: this is a single-shot session with no tools, so the code you
+return is the code that ships. Budget your care accordingly: seat every object through
+`ctx.height_at` (the gate measures the gap), keep every name unique, and light the brief's
+time of day with numbers from the recipes rather than instinct — the failures below happen
+in a build you cannot see.
+{% endif %}
+
+Rules that survive every brief:
+
+* **The brief's time of day is a hard constraint, not a mood suggestion.** Decide it once,
+ write it down as constants in `src/env.py` (`SUN_AZIMUTH_DEG`, `SUN_ELEVATION_DEG`, the
+ world strength, the fog density) and make every zone read `ctx.env`. A night brief
+ rendered as noon is the wrong scene whatever is in it, and the frame gate cannot save
+ you: it only measures too-dark and too-bright.
+* **The environment IS the scene, not its backdrop.** Sky, sun, ground material and
+ atmosphere carry more of the verdict than any prop. Build them FIRST and specific to the
+ brief (snow, wet cobbles, desert haze); a default sky over a flat single-colour ground
+ reads as "unfinished" however good the props on top are.
+* **Light before colour, light before detail.** Cycles reads physical units: a Sun lamp of
+ 2–5 W/m² with a sky world at strength 0.2–0.5 for day, practicals (an emissive surface
+ plus a Point light with a radius) for dusk and night. Hue, material and geometry work are
+ invisible on near-black pixels.
+* **Things rest on things, and things stay out of each other.** `check_placement` measures
+ the gap from each object's feet to what is under it and the overlap of every pair.
+ Compute where the ground is at that (x, y) and put the object there — never at z = 0 and
+ hope the terrain is flat; give neighbours room — never let a crate's box run through a
+ wall's.
+* **One object = one thing.** A placed prop is ONE root object (a mesh, or an Empty with
+ its parts parented under it, or a collection instance of an asset) with a unique
+ PascalCase name; repeats are collection instances of `ctx.assets[...]`, fields of small
+ things are geometry-nodes clouds. Never `bpy.ops` in a loop.
+* **Split the scene across modules** as the contract says, link everything into
+ `ctx.collection`, and keep every import resolvable in the build. A module that raises
+ takes its whole zone out of the picture.
+
+A simple scene that is seated, lit and legible beats an elaborate one that floats in the
+dark. Get the floor and the light right first; spend everything after that on the brief.
diff --git a/harness/codeverse3d/prompts/scene_threejs/cookbook.md b/harness/codeverse3d/prompts/scene_threejs/cookbook.md
index 0f524684..5ccd829d 100644
--- a/harness/codeverse3d/prompts/scene_threejs/cookbook.md
+++ b/harness/codeverse3d/prompts/scene_threejs/cookbook.md
@@ -666,6 +666,28 @@ or pit never counts; a foot at/under water is fine); bbox touching nothing → `
a large share of their volume → `interpenetration`. Seat things with `heightAt(x, z)` and they pass. A thing MEANT to hang in
the air (bird, drone): `obj.userData.placement = 'free'` on it or its zone = exempt. Instanced meshes are not checked.
+Three placement rules the argon loop's iteration 0 paid for (2026-10-15: 7 of 30 zones shipped
+interpenetration ERRORs, 5 shipped sunken ones):
+
+1. **One placed thing = one direct child of the zone group.** Never wrap several props in a
+ `MidProps` / `Dressing` / `SeamDressing` Group: the gate measures that Group as ONE asset whose
+ box is the union, so every prop inside it reads as interpenetrating it (11 of 29 rows). A prop
+ built from parts is one Group; hundreds of the same thing are one `InstancedMesh`.
+2. **Scatter clear of what you placed.** Keep the boxes of the hand-placed things and skip every
+ scatter point inside them (+0.3 m); a scattered rock, fern or crate inside a placed table,
+ rockery or tower is an interpenetration at 100 % of the smaller box:
+
+```js
+const placed = []; // push after every hand placement
+function keepClear(THREE, obj, margin = 0.3) { placed.push(new THREE.Box3().setFromObject(obj).expandByScalar(margin)); }
+const isClear = (x, z) => !placed.some((b) => x >= b.min.x && x <= b.max.x && z >= b.min.z && z <= b.max.z);
+// inside a scatter loop: if (!isClear(x, z)) { m.makeScale(0, 0, 0); mesh.setMatrixAt(i, m); continue; }
+```
+
+3. **A wide flat thing on a slope** (a talus field, a long conveyor, a bench row) is measured at
+ its lowest vertices against the ground under THEM: conform each piece to `heightAt` or split it,
+ or its uphill end is `sunken` by the slope's rise (0.24-0.36 m in iteration 0).
+
## Assets (`src/assets/*.js`) and GLB assets from Blender
```js
@@ -700,14 +722,24 @@ Why: a scene mixes cheap instanced fillers with a few hero assets; GLBs come in
```js
// Rigid movers: cache a `home` Vector3 at build time, then set (never accumulate) the
// pose from t — `obj.position.y = home.y + Math.sin(t * 0.9) * 0.06` etc.
-// Particles: THREE.Points + PointsMaterial is enough for dust/fireflies/snow (custom
-// point shaders only if the plan demands). Recycle positions inside update.
+// Particles: THREE.Points with a RADIAL alpha sprite (`softDot`) — a bare PointsMaterial
+// draws SQUARES, which is the judge's `hard_edged_particles` defect (see "Soft particles").
+function softDot(THREE, size = 64) {
+ const data = new Uint8Array(size * size * 4); // no DOM: a DataTexture, not a canvas
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
+ const r = Math.min(1, Math.hypot((x + 0.5) / size - 0.5, (y + 0.5) / size - 0.5) * 2);
+ const i = (y * size + x) * 4;
+ data[i] = data[i + 1] = data[i + 2] = 255; data[i + 3] = Math.round(255 * (1 - r) * (1 - r));
+ }
+ const tex = new THREE.DataTexture(data, size, size); tex.needsUpdate = true; return tex;
+}
function buildFireflies(THREE, n = 120, area = { x: 0, z: 0, w: 30, d: 30 }) {
const pos = new Float32Array(n * 3);
const rnd = mulberry32(11);
for (let i = 0; i < n; i++) pos.set([area.x + (rnd() - 0.5) * area.w, 0.6 + rnd() * 2.2, area.z + (rnd() - 0.5) * area.d], i * 3);
const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
- const pts = new THREE.Points(geo, new THREE.PointsMaterial({ color: 0xd9f76e, size: 0.06, sizeAttenuation: true, transparent: true, opacity: 0.9 }));
+ const pts = new THREE.Points(geo, new THREE.PointsMaterial({ map: softDot(THREE), color: 0xd9f76e, size: 0.06, sizeAttenuation: true,
+ transparent: true, opacity: 0.9, depthWrite: false, alphaTest: 0.02, blending: THREE.AdditiveBlending })); // NormalBlending for dust/snow
pts.name = 'Fireflies';
const base = pos.slice();
pts.userData.update = (t) => {
@@ -768,6 +800,26 @@ console.log('sway delta (rad) over 1.5s', Math.abs(a1 - a0).toFixed(3), (Math.ab
Self-check: after `scene_views(times=[0, 1.5])` compare the two sheets. If you cannot
point at what changed, double the amplitude.
+## Soft particles: steam, smoke, dust, motes and sparks (never a hard-edged quad)
+
+The judge's `hard_edged_particles` defect — and the brief's "a soft particle effect … never
+hard-edged quads" must-item, which caps the whole score — fired on 5 of 30 argon scenes on
+2026-10-15: bare `PointsMaterial` squares for motes, a chain of opaque spheres for a steam jet,
+polygon "sparks". The library already does the soft version — prefer it:
+
+| want | call |
+|---|---|
+| steam from a vent, a cup, a chimney; rising smoke | `makeSmoke({ height, radius, wind, riseSpeed, seed })` · `makeSteam({ height, radius })` (`lib/smoke.js`) — a bounded density field, no edge anywhere |
+| dust motes, pollen, drifting sparkle | `makeMotes({ extent, height, count, size, color, seed })` (`lib/veils.js`) — glinting specks with radial falloff |
+| snow, distant rain | `makeSnowfall` · `makeRainVeil` (`lib/veils.js`) |
+| sparks and embers | `makeFire` / `makeFireField` (`lib/fire.js`, `lib/firefield.js`) — the embers ride the flame |
+| a cloud of your own | `THREE.Points` + `PointsMaterial({ map: softDot(THREE), transparent: true, depthWrite: false, alphaTest: 0.02 })` — the `softDot` sprite from the Animation chapter; `AdditiveBlending` for fireflies and sparks, `NormalBlending` for dust and snow |
+
+Rules: every point carries a radial alpha sprite or it is a square; a steam jet is ONE
+`makeSteam` / `makeSmoke`, never spheres in a row; sparks are points, never triangles or
+hexagons; the cloud MOVES (>= 0.6 m of travel in 1.5 s, see the motion table) or it is a
+static decal; keep it to 60-400 points — a fog of them reads as noise.
+
## Scene layering: foreground, midground, background
A "diorama on an empty plane" scores ~0.5 whatever else you do. Every authored camera needs
diff --git a/harness/codeverse3d/prompts/system/role_asset.j2 b/harness/codeverse3d/prompts/system/role_asset.j2
index d37e23bb..d48ecefc 100644
--- a/harness/codeverse3d/prompts/system/role_asset.j2
+++ b/harness/codeverse3d/prompts/system/role_asset.j2
@@ -8,5 +8,10 @@ deliverable. What changes:
* Stand it on the ground (lowest point at z=0) with the footprint centred on the origin —
the scene's zone code places it by its origin and assumes exactly this.
* Keep it light: it will be instanced; prefer fewer, better-shaped parts over many small ones.
+{% if language == 'scene_blender' %}
+* The Collection is instanced by the Blender zones: no lights, no cameras, no world, no render
+ or export calls, and nothing outside the asset itself (no ground plane, no environment).
+{% else %}
* The GLB is loaded by a three.js scene: no lights, no cameras, no render or export calls,
and nothing outside the asset itself (no ground plane, no environment).
+{% endif %}
diff --git a/harness/codeverse3d/prompts/tracks/plan_scene_bpy.j2 b/harness/codeverse3d/prompts/tracks/plan_scene_bpy.j2
new file mode 100644
index 00000000..f247d9a1
--- /dev/null
+++ b/harness/codeverse3d/prompts/tracks/plan_scene_bpy.j2
@@ -0,0 +1,178 @@
+You are the SCENE DIRECTOR for a Blender (bpy, Cycles) scene that several code-writing models will
+build in parallel from your plan alone (one per asset, one for every zone, one for the environment).
+Write the plan as exact numbers and concrete nouns; keep it lean (cost matters).
+
+THE PLAN'S FRAME: write every number — bounds, zone bboxes, asset sizes (width × height × depth),
+camera positions — in the Y-up GLB frame (Y up, +Z towards the viewer, metres, the ground around
+y = 0), exactly as a three.js director would. The builders author Blender Z-up modules, and the
+HARNESS converts every number it prints for them (their skeleton, their briefs, the layouts): you
+never write Z-up numbers, and `environment` prose should say "y" for up. (The language frame the
+builders see, for reference: {{ frame_doc }})
+
+LANGUAGE CONTRACT THE BUILDERS WILL FOLLOW:
+{{ contract }}
+
+SHIPPED BPY LIBRARY:
+The scene workspace already contains, under `src/lib/`: `noise.py` (`fbm2`, `ridged`,
+`mountain_height`, `height_field`), `mesh.py` (`Batch`: box / sphere / lathe / cone / beam / torus,
+`mesh_object`, `curve_object`), `materials.py` (`material`, `masonry`, `limestone`, `woodgrain`,
+`chipped_paint`, `worn_alloy`, `water`, `glass`, `foliage`, `snow`, `ice`, `emissive`),
+`terrain.py` (`make_height_at`, `ground`, `cliff`, `boulder`, `rock_field`, `talus`,
+`basalt_column`), `sky.py` (`sun_world`, `night_world`, `gradient_world`, `haze`, `aurora`,
+`stars`), `lighting.py` (`sun`, `area_light`, `point_light`, `spot`, `practical`), `water.py`
+(`water_surface`, `waterfall`, `hanging_fall`, `fountain_jets`, `droplets`), `vegetation.py`
+(`tree`: broadleaf / cypress / oak / pine, `shrub`, `fern`, `tropical`, `grass_patch`,
+`perennial_bed`, `tree_stand`), `architecture.py` (`arched_opening`, `tiled_roof`, `clay_roof`,
+`fret_window`, `timber_house`, `stone_bridge`, `arched_footbridge`, `tower`, `paving`,
+`room_shell`, `lantern`, `text_mesh`), `scatter.py` (`instance`, `scatter`, `poisson`,
+`along_path`, `grid`, `gn_scatter`), `place.py` (`seat`, `rest_on`, `clear_of`, `unique_name`),
+`figure.py` (`figure`, `visitor`, `crowd`) and `motion.py` (`keyframe_path`, `drift`, `spin`,
+`sway`, `scroll`, `shape_key_sweep`). When they cover the brief, describe their calls and
+dimensions in the owning zone description / environment / effects. Do not request an asset that
+rebuilds one of them (a Waterfall, OakTree, BoulderCluster, GrassPatch or Lantern asset); an
+element they do not cover (a carved stone, a fishing boat, a market stall) is still an asset.
+A `bpy` asset may compose a library call with its own parts (a shrine with a `tree(...)` beside it,
+a well ringed by `boulder(...)`s): name the call and its module (`tree`, `lib/vegetation.py`) in that
+asset's description. A `blender_glb` hero cannot. Zone `contents` still lists only actual asset
+names; library effects a zone places itself belong in prose, not invented asset ids.
+Water and terrain share ONE surface sampler (`height_at` from the environment; a pond is a basin
+carved into it) and every placed thing is seated on it or on what it stands on — the harness
+measures the gap.
+
+## What this track is graded on (write the plan that wins these points)
+A scene scores 0.8+ only when every authored camera makes a PICTURE: three depth layers
+(something within 5 m framing the shot, the subject at 8-30 m, a hazy horizon above), ground
+that is several blended materials with paths and worn edges, vegetation/rock in 3+ species with
+size and hue variation in clusters, a lived-in amount of small props, coloured atmosphere with a
+warm sun under a cool sky, and motion you can see between t=0 s and t=1.5 s — and NOTHING floating,
+sunken or passing through its neighbour (the placement gate measures every placed thing and caps
+the score). A correct-but-bare scene — a diorama of a few objects on one flat coloured plane,
+ringed by identical cones, under flat light — scores ~0.5 no matter how well it is coded. Your
+plan must make the bare version impossible: put the counts, the layers, the colours and the
+amplitudes in the text.
+
+WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
+1. `title`, `summary` (two sentences), `setting` (place, era, weather, time of day), `mood`.
+2. `bounds` — centre + extents in meters of the whole playable area (a garden 30 x 10 x 30 m; a
+ harbour 120 x 30 x 120 m). Keep it as small as the brief allows: detail beats acreage.
+3. `environment` — ONE paragraph, all numbers, covering IN THIS ORDER:
+ (a) the sun / moon azimuth (compass: 0 = +X, 90 = +Y) + elevation in degrees and the time of day
+ (dawn / morning / noon / golden / overcast / dusk / night — the builders' lighting table);
+ (b) the Sun lamp's colour + energy in W/m² (day 3-5, golden 2-2.5, dusk 1-1.5, a moon 0.1-0.3)
+ AND the sky world strength (day 0.4-0.5, dusk 0.2, night 0.1) — a warm sun under a cool
+ physical sky, or the frame comes out monochrome;
+ (c) the fog: density (0.003-0.008) + colour (= the sky HORIZON colour, never white or grey unless
+ overcast), as a bounded volume over the whole ground;
+ (d) ground: the terrain stays within about +/-1.5 m of y = 0 inside the bounds (camera heights
+ below are absolute, and a lifted floor puts them underground); ponds, terraces and gravel
+ beds are carved INTO the terrain, never laid on it as flat discs; the 3-4 material colours
+ that blend across it (e.g. moss (0.29, 0.38, 0.18), dry grass (0.54, 0.51, 0.28), packed
+ dirt (0.42, 0.33, 0.20), gravel (0.66, 0.60, 0.49)), what drives the blend (height, slope,
+ noise), and where the PATH runs as a polyline of 3-5 (x, z) points, 1.2-2.0 m wide;
+ (e) the BACKDROP that hides the world edge: a sky-named silhouette ring (hills / treeline /
+ rooftops / mesas) at radius ~ 0.6 x the visible range, 24-40 SOLID pieces (never flat
+ cut-out planes) in their own colour darkened 0.6-0.8x — the fog supplies the haze, so never
+ tint them toward the fog colour — or, for an interior, what is seen through the glass;
+ (f) water plane height + colour, if any.
+4. `zones` — 3 to 6 spatial regions with PascalCase names, a `bbox`, and `contents` = asset names
+ placed there. Zone bboxes tile the bounds without overlapping by more than 1 m.
+ Each zone `description` MUST state, as numbers:
+ - its DEPTH ROLE for the cameras: `foreground frame`, `midground subject` or `background`;
+ - the layout (paths, clusters, spacing in meters, what faces what, what stands ON what);
+ - DENSITY COUNTS: how many trees / shrubs / rocks / mid props (0.3-1.5 m) / small props
+ (< 0.3 m) / ground-cover blades it contains. Target per zone: 12-25 mid props, 25-60 small
+ props, 300-800 ground-cover blades for a planted zone (desert: 15-30 boulders in 3 size
+ bands, 60-200 scrub clumps; interior: 15-30 mid, 40-100 small);
+ - the VARIATION rule: at least 3 distinct silhouettes for any repeated natural element, with
+ +/-30 % scale jitter and hue jitter — never one shape stamped in a ring or grid.
+5. `assets` — 4 to 8 reusable things placed in zones. PascalCase `name`; `kind` = `bpy` for
+ procedural props (fences, lanterns, benches, boats, trees the library does not grow) built as a
+ bpy module and placed as collection instances, or `blender_glb` ONLY for 1-2 hero objects that
+ need sculpted/bevelled detail (a hero may also carry ONE 2 s keyframed motion — a swinging lamp,
+ a turning wheel — say so in its description); `description` with construction numbers and
+ colours; `approx_size_m` = width x height x depth in meters (a stone lantern 0.5 x 1.6 x 0.5; a
+ bench 1.6 x 0.9 x 0.6; a pine 3 x 7 x 3); `instances_hint` = how many appear in total. Prefer
+ FEWER asset modules with a `variant` range (say "5 variants via variant: three trunk shapes, two
+ crown shapes") over many near-duplicate modules — variation belongs inside an asset, not in the
+ asset list. Ground cover, terrain, water, backdrop and sky are NOT assets — they belong to the
+ environment / zones.
+6. `effects` — 1 to 4: `glsl_material` (a shader-node effect: water ripple, lantern glow, a
+ translucent leaf), `particles` (petals, sparks, snow — a small keyframed instance cloud),
+ `animated_geometry`, or `postprocess` (a volume: mist, light shafts); say which zone/asset.
+7. `animation` — 2 to 6 lines of what moves, each with an amplitude that is VISIBLE in a
+ 1024x576 frame after 1.5 s: foliage sway +/-0.10-0.20 rad; grass +/-0.15 rad; water ripples
+ scrolling >= 0.15 m/s plus a bob >= 0.04 m; particles travelling >= 0.6 m per 1.5 s;
+ vehicles/boats/sails >= 1.5 m or a visible turn per 1.5 s; lantern flicker x0.75-x1.3.
+ Exactly one of them is the HERO motion: the single thing a viewer cannot miss.
+8. `cameras` — 3 to 4 authored cameras. The harness uses your numbers LITERALLY, so compute them:
+ - `cameras[0]` is the establishing shot. Pick the SUBJECT (the hero asset or the zone the
+ brief is about) and its centre point S. Put the camera at distance
+ D = 1.5 x (subject radius) / tan(fov/2) from S, at height
+ y = (tallest thing between camera and subject) + 0.30 x D, looking AT S (not at the bounds
+ centre, not at the horizon). It must see 2+ zones and be mostly content rather than empty
+ sky/ground.
+ - one eye-level camera INSIDE the scene at y = ground + 1.6-1.8 m, aimed along a path or
+ across the subject so that something within 5 m frames one edge of the shot;
+ - one detail camera 2-4 m from the hero asset, slightly above its mid height.
+ - `purpose` must name the subject, the foreground framing element and what is on the horizon
+ for that shot ("establishing: the arched bridge at 14 m, framed by the maple on the right at
+ 3 m, cedar ridge on the horizon").
+ - No camera may be inside or up against geometry; fov 35-60 (vertical).
+9. `acceptance` — 6 to 12 items covering: each must-have from the brief, the hero assets visible
+ from the establishing camera, time-of-day lighting reads correctly, the hero motion is visible
+ between t=0 and t=1.5 s, no floating or sunken assets (`how: probe`), no hard world edge from
+ any authored camera.
+ **`priority` matters more than anything else in this list.** ANY unmet `must` item caps the
+ whole run's score at 0.60, however good the pictures are — one over-specified detail throws
+ away a passing scene. So:
+ - mark at most 4-6 items `must`, and only ones that restate a hard requirement of the brief
+ itself, that a person can confirm from ONE rendered frame, and that name no incidental
+ detail: "a raked gravel area is visible in the zen garden" is a `must`; "raked gravel with
+ concentric rings around each rock" is a `should`;
+ - `a1` is ALWAYS the premise: the kind of PLACE the brief describes, in the plainest words
+ that would be false if the scene were somewhere else — "the view is from inside an
+ enclosed workshop", "the courtyard is lit only by its lanterns at night". Measured
+ 2026-08-25: a brief reading "INSIDE a boatbuilder's workshop, sun raking through a dusty
+ window wall" was planned as "Coastal boatyard, clear dusk" and built faithfully as an
+ outdoor yard with no walls and no roof — it passed every gate and scored 0.4653. Write
+ the premise down and the rest of the plan stays anchored to it — and when that premise
+ is INSIDE a built space, set `interior: true`: the environment module then builds the
+ enclosure on the bounds' faces (floor, walls, ceiling, with openings where `environment`
+ puts the windows and doors) and the zones dress the inside. Measured 2026-09-07 on
+ six interior runs: with no owner for walls and roof, every one was judged "not
+ enclosed, a diorama on a flat plane" (0.0–0.3) until a refine round built them.
+ When the enclosure itself is glass on a frame (a conservatory, greenhouse, palm house,
+ glass atrium) also set `glazed: true`: the walls and roof are then glass on an iron
+ grid that the sun and the outside come through — an opaque room around a glass house
+ was judged "a solid box blocking the exterior view and lighting";
+ - mark everything else `priority: should` — craft goals, counts, specific patterns, exact
+ heights and anything needing evidence the judge may not have;
+ - never write a `must` whose wording contains a number, a named style, or the word "and"
+ joining two independent claims — split it or demote it.
+
+RULES
+- Every name in `zones[].contents` must be an asset name; asset names unique; zone names unique.
+- Realistic scale: people 1.7 m, doors 2.1 m, steps 0.17 m, benches 0.45 m seat height.
+- Prefer <= 8 assets and 3-5 zones for modest briefs. No prose outside the JSON.
+
+WORKED EXAMPLE (field SHAPE only — its prose is deliberately terse and does NOT meet the
+`environment` / zone-description / camera-purpose requirements above):
+{{ example_json }}
+
+HOW THE THREE PROSE FIELDS MUST ACTUALLY READ (style, not values):
+- environment: "Dusk: sun azimuth 250 deg elevation 8 deg, Sun lamp (1.0, 0.63, 0.38) at 1.2 W/m2
+ under a physical sky world at strength 0.2 (cool fill against the warm key); fog density 0.006,
+ colour (0.85, 0.44, 0.23) (the horizon), as a volume over the whole ground; ground blends moss
+ (0.29, 0.38, 0.18), dry grass (0.54, 0.51, 0.28), packed dirt (0.42, 0.33, 0.20) and gravel (0.66,
+ 0.60, 0.49) by slope and noise, with a 1.6 m gravel path through (-14,-11), (-5,-4), (2,1), (9,8)
+ flattened into the terrain; backdrop = 30 cedar-ridge silhouettes at radius 46 m, 3-6 m tall, in
+ their own green darkened 0.7x; pond basin carved to y=-0.35, water (0.09, 0.25, 0.29)."
+- zone description: "MIDGROUND SUBJECT. The koi pond and arched bridge on the path's east bend.
+ 1 bridge, 2 stone lanterns 4 m apart facing the path, 3 pond rocks in 3 sizes, 18 mid props
+ (potted shrubs, a water basin, a stacked-stone kerb, a bucket, a bamboo scoop), 34 small props
+ (pebbles along the pond rim, fallen maple leaves, a rope coil, moss patches), 500 ground-cover
+ blades outside the gravel. Vegetation uses 3 silhouettes (upright pine, low maple, round shrub)
+ with +/-30 % scale and hue jitter, in 4 clusters, never a ring; everything seated on the terrain."
+- camera purpose: "establishing: the arched bridge (subject centre 1.5, 0.9, -0.8, radius 4.5 m)
+ from the south-east above the maples, framed by the lantern at 3 m on the left edge, cedar ridge
+ on the horizon; sees PondBasin and ZenGarden."
diff --git a/harness/codeverse3d/prompts/tracks/scene_asset_bpy.j2 b/harness/codeverse3d/prompts/tracks/scene_asset_bpy.j2
new file mode 100644
index 00000000..aed3579f
--- /dev/null
+++ b/harness/codeverse3d/prompts/tracks/scene_asset_bpy.j2
@@ -0,0 +1,83 @@
+# Scene asset `{{ asset_name }}` ({{ asset_kind }}) — write `{{ asset_file }}`
+
+Scene: {{ spec_prompt }}
+{% if fix_instructions %}
+## FIX PASS — the asset was judged; apply exactly these changes and keep the rest
+{% for i in fix_instructions %}
+{{ i }}
+{% endfor %}
+{% endif %}
+
+## The asset
+- Name: `{{ asset_name }}`
+- Size (width × height × depth, metres — the plan's Y-up order; in Blender x = width, y = depth, z = height): {{ '%.2f' % asset_size[0] }} × {{ '%.2f' % asset_size[1] }} × {{ '%.2f' % asset_size[2] }}
+- Description: {{ asset_description }}
+- Style of the whole scene: {{ style_notes or constraints }}
+
+## Contract (raw bpy module; the harness builds it once and the zones instance it)
+{{ frame_doc }}
+{{ contract }}
+- `{{ asset_file }}` must define `def build_{{ asset_file.rsplit('/', 1)[-1][:-3] }}(ctx, variant=0)` that links
+ every part into `ctx.collection` (its own Collection, pre-made and active) and returns it: built at
+ the origin, lowest point on z = 0, footprint centred on the origin, front facing −Y, sized as stated
+ (±5 %). Zone code places collection instances of `ctx.assets['{{ asset_file.rsplit('/', 1)[-1][:-3] }}']` by
+ that origin and never calls you.
+- Build from bmesh (`create_cube` / `create_cone` / `create_icosphere` / `create_circle`, scaled and
+ translated) and Principled materials with colours (`Base Color`, `Roughness`, `Metallic`; a noise
+ bump; `lib/materials.py` has the palette) — several parts with distinct materials, each a uniquely
+ named PascalCase object (one root mesh, or children parented under it with a RELATIVE location).
+- `variant` (0..n) and `ctx.rng(seed)` may vary details deterministically; `random.*` is a lint error.
+- Segments 10–24; at most 15000 triangles for the whole asset (it is instanced).
+- No lights, no cameras, no world, no `bpy.ops` in loops, no file IO; nothing outside the asset
+ itself (no ground plane).
+- MOTION (only when the description names a moving part — a swinging lamp, a turning wheel): keyframe
+ that part's OWN rotation/location on `ctx.frame(0.0)` and `ctx.frame(1.5)` (LINEAR), or a simple
+ driver of `frame` (`frame * 0.2`); put the part's origin at its pivot. Amplitude must read at scene
+ distance (≥ 0.15 rad or ≥ 0.05 m).
+{% if library_rows %}
+- The sheet names shipped library calls. `src/lib/` ships with the scene: import them
+ (`from lib.vegetation import tree`) and compose what they build into `ctx.collection` instead of
+ rebuilding them; every factory takes the collection, a name and a seed.
+{{ library_rows }}
+{% endif %}
+{% if skeleton_files is defined and skeleton_files %}
+
+## Current files (skeleton already in src/ — keep its structure, fill in every stub)
+{% for path, body in skeleton_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+
+## DO / DON'T
+- DO use the exact size numbers above; the zone builders and the placement gate rely on them.
+- DO give it the 3–4 recognisable features a person would name (a stone lantern: base, post, light
+ box with 4 windows, curved roof, finial) — plus 2–3 pieces of wear or incident that make it look
+ used: a chipped corner, a leaning post, moss at the base, a rope, a hanging tool.
+- DO make `variant` (0..n) change the SILHOUETTE, not just the scale: at least 3 visibly different
+ versions (a different crown shape, a different roof pitch, a broken vs whole rail). Zones rely on
+ this for variety, so a `variant` that only scales is a wasted asset.
+- DO give any repeated natural asset per-instance hue room: vary the colour from `variant` /
+ `ctx.rng(seed)` so 20 copies are not one colour.
+- DON'T model a flat plane with a colour where the thing has real thickness (a fence is stakes and
+ rails, not a textured quad) — closeups are judged.
+- DON'T leave floating pieces: every sub-shape overlaps a neighbour by ≥ 2 mm, and the lowest point
+ is exactly z = 0 (the harness measures a part sunk below it or hovering above it).
+- DON'T write anything outside the listed file.
+{% if current_code %}
+
+## Current file (edit and return COMPLETE)
+```
+{{ current_code }}
+```
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2 b/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2
new file mode 100644
index 00000000..e9872456
--- /dev/null
+++ b/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2
@@ -0,0 +1,111 @@
+# Environment module for `{{ title }}` — write `{{ env_file }}`
+
+Scene: {{ spec_prompt }}
+Setting: {{ setting }}. Mood: {{ mood }}.
+Bounds (Z up, −Y front, metres — already converted from the plan): {{ bounds }}
+
+## Environment plan (realise these numbers; its prose is Y-up: "y up" there is z here, "+z" there is −y here)
+{{ environment }}
+{% if interior and glazed %}
+## This is a GLASS HOUSE — the enclosure is yours
+Build the glass walls and roof on the bounds' faces with `room_shell(ctx.collection, frame_mat,
+center=…, extents=…, thickness=0.2, openings=(…), glazed=True)` from `lib/architecture.py` — an iron
+frame grid with glass panes, named `RoomShell…` / `Ceiling…` so the overview rig can lift the lid
+— cut the plan's doors as openings, and let the SUN do the lighting: it comes through the glass and
+the frame throws its grid of shadows on the floor. Never put an opaque wall or roof around it.
+{% elif interior %}
+## This is an INTERIOR — the enclosure is yours
+Build the room on the bounds' faces with `room_shell(ctx.collection, wall_mat, center=…, extents=…,
+thickness=0.2, openings=(…))` from `lib/architecture.py` — floor, four walls and a ceiling named
+`RoomShell…` / `Ceiling…` (the overview rig lifts the lid by name). Cut the plan's windows and doors
+as openings (face, centre along the wall / up from the floor, size, metres), glaze or frame them, and
+LIGHT THE INSIDE: an Area light per window aimed into the room, practicals where the brief has lamps
+(the sun is outside: without openings and lights a closed room reads black). Measured 2026-09-07
+over six interior runs: with no owner for walls and roof, every one was judged "not enclosed, a
+diorama on a flat plane, tool racks floating at a missing wall" (0.0–0.3).
+{% endif %}
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+
+### The harness assembles `{{ entry_file }}` and runs YOUR module like this — nothing else runs
+```python
+ctx.collection = scene root # build_env links into it
+out = env.build_env(ctx) # ONE argument, and it is ctx
+ctx.env = out if isinstance(out, dict) else {} # what the zones read as ctx.env
+ctx.height_at = env.height_at # THE ground every zone seats on
+```
+So `{{ env_file }}` must define exactly:
+- `def height_at(x, y) -> z` — the terrain height (0.0 for flat ground), deterministic and cheap; every
+ zone places things with it, so the PATH, a pond basin and a terrace are carved INTO it (then what
+ stands on the path stands on the path). Keep it within about ±1.5 m of 0 inside the bounds: the
+ plan's camera heights are absolute.
+- `def build_env(ctx) -> dict` — builds the world (sky), the Sun lamp, the ground mesh (sampled from
+ `height_at`, named `Ground…`), the atmosphere (a bounded fog volume) and the backdrop (a sky-named
+ horizon ring) into `ctx.collection`, and RETURNS the dict zones share: `{"ground_material": …,
+ "sun_direction": (x, y, z), "water_level": …, "palette": …}`.
+- module constants `SUN_AZIMUTH_DEG` (compass: 0 = +X, 90 = +Y) and `SUN_ELEVATION_DEG` — zones and
+ the harness's overview rig read the sun side from them.
+The world (`bpy.data.worlds.new`, `ctx.scene.world =`) is YOURS and nobody else's: a zone that
+builds one fails the lint. No cameras (the plan's), no `scene.render.*`, no frame changes.
+
+## What this module is graded on
+The chapters behind these rules are printed in full at the end of this brief (**Recipes**) — copy
+their numbers and snippets; the shipped `lib/` does each in one call (the catalog follows).
+
+1. **Ground must not be one flat colour.** Three or four colours blended by height, slope and
+ noise (a `FLOAT_COLOR` attribute read by an Attribute node, or `lib.terrain.ground` with
+ `lib.materials.mineral_surface`), relief from `lib.terrain.make_height_at`, the path carved into
+ `height_at` in both height and colour — never a single-colour plane, a scored defect
+ (`flat_ground`).
+2. **No world edge.** The ground reaches ≥ 2.5 × the plan span; the fog box covers all of it in the
+ sky's HORIZON colour (`lib.sky.haze`); a sky-named silhouette ring (`SkyRidge`: hills, rooftops,
+ mesas, a treeline — solid geometry, never flat cut-outs) at ~0.6 × the visible range in its own
+ colour DARKENED 0.6–0.8 × — the fog hazes it, never tint it yourself.
+3. **The floor stays near z = 0** (rule above): a knoll or a pond basin is fine, a 7 m plateau puts
+ every plan camera underground (`camera_underground`, cap 0.50). Ponds, terraces and gravel beds
+ are CARVED INTO `height_at`, never a hard-edged disc laid on the ground.
+4. **Coloured atmosphere, not monochrome.** The brief's time of day as the recipes' numbers: a
+ physical sky world (`lib.sky.sun_world`, MULTIPLE_SCATTERING) or a deep flat colour for night,
+ a Sun lamp of 1–5 W/m² (`lib.lighting.sun`; a moon at 0.05–0.3), the world strength 0.1–0.6, the
+ fog 0.003–0.008. A warm sun under a cool sky is the whole trick; shade must carry sky colour,
+ never black — with the sun under 25° keep the world strength ≥ 0.2 or the frame trips
+ `dark_frame` (cap 0.55). Exposure is fixed at 0 and the harness owns it.
+5. **Shadows must read.** The Sun's `angle` 1–3° (soft but defined); never a second Sun to fill — the
+ sky world is the fill.
+6. No {% if not (textures is defined and textures) %}image textures, no {% endif %}file IO, no `bpy.ops` in loops, no unseeded randomness (`ctx.rng(seed)`).
+
+## DON'T
+- No assets or zones here (they come from other modules). No cameras. No `scene.*` render / view settings.
+- Do not re-declare the path polyline in a zone: export it (or a `dist_to_path`) from here.
+
+## Effects planned (only the ones targeting the environment)
+{{ effects }}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+After editing run `build`, then `scene_views` and LOOK: is the horizon hazy, is the ground
+multi-coloured, is the shade coloured rather than black? Read the frame table it prints:
+every authored camera must pass the exposure checks. `scene_probe` says whether the world
+and the atmosphere were found.
+{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+{% if recipes is defined and recipes %}
+
+# Recipes (from the scene cookbook — copy these numbers and snippets)
+{{ recipes }}
+{% endif %}
+{% if textures is defined and textures %}
+
+{{ textures }}
+(These are PNG files under `public/textures/`: load one with `bpy.data.images.load("public/textures/<file>",
+check_existing=True)` into an Image Texture node; the build runs with the workspace root as its working directory.)
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/scene_refine.j2 b/harness/codeverse3d/prompts/tracks/scene_refine.j2
index 4ab4c1dd..c8a7f26b 100644
--- a/harness/codeverse3d/prompts/tracks/scene_refine.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_refine.j2
@@ -63,6 +63,7 @@ timid: double the amplitude / the count / the contrast this time.
| sparse, token, "a diorama on a plane", empty midground | `"Set dressing"` + `"Scene layering"` — hit the per-zone prop counts, add a foreground element 2-4 m from each camera |
| flat / dark / monochrome light, black shade, jagged shadows | `"Atmosphere: time-of-day triads with numbers"` — warm key vs cool fill ≥ 60° apart, shadow texel ≤ 0.05 m |
| frames at t=0 and t=1.5 identical, "nothing moves" | `"Motion you can SEE between t = 0 and t = 1.5 s"` — the hook is `userData.update` (never `tick`), amplitudes from the table |
+| `hard_edged_particles`, "sharp-edged quads / spheres / discs for steam, dust, sparks", the brief's "soft particle effect" must-item unverified | `"Soft particles"` — `makeSmoke` / `makeSteam` / `makeMotes` / `makeFire`, or a `softDot` sprite on every point; never a bare `PointsMaterial` or a chain of spheres |
| camera inside geometry / shows only sky or a wall | move the camera in `src/scene.js` and mask scatter within ~4 m of it (`cameraMask`) |
{% if current_files %}
diff --git a/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2 b/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2
new file mode 100644
index 00000000..31516bce
--- /dev/null
+++ b/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2
@@ -0,0 +1,108 @@
+# Refine `{{ title }}` — round {{ round_index }}
+
+The scene builds and was rendered from the authored cameras at t=0 and t=1.5 s, then judged. Make
+exactly the changes below, keep everything else, keep the build clean (no zone dropped, no Python
+driver, nothing floating or sunken).
+
+## Changes to make (priority order; `[gate/...]` items are hard failures — fix them first)
+{% for t in tasks %}
+{{ loop.index }}. {{ t }}
+{% endfor %}
+
+Targets: {{ targets | join(', ') }}
+{% if edit_only_these %}
+EDIT ONLY THESE FILES (other tasks edit other files in parallel):
+{% for f in files %}- `{{ f }}`
+{% endfor %}
+{% else %}
+Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+{% endif %}
+
+## What the judge saw
+{{ judge_summary }}
+
+## Plan (unchanged truth; numbers below are in YOUR frame — Z up, −Y front, metres)
+Bounds: {{ bounds }} · Setting: {{ setting }} · Mood: {{ mood }}
+Environment (its prose is Y-up: "y" there is z here): {{ environment }}
+Zones:
+{{ zones_table }}
+Cameras:
+{{ cameras }}
+Assets:
+{{ asset_api }}
+Effects:
+{{ effects }}
+Animation: {{ animation }}
+
+## Acceptance checklist
+{{ acceptance }}
+
+## Reminders
+{{ frame_doc }}
+- A lighting/mood/ground/horizon change lives in `{{ env_file }}` (the world, `SUN_AZIMUTH_DEG` /
+ `SUN_ELEVATION_DEG` and the Sun's energy, the fog box's density and colour, the ground's blend,
+ the sky-named backdrop ring).
+- A composition/camera change is the plan's: `{{ entry_file }}` is harness data — move the SUBJECT
+ (a zone's placement) rather than the camera.
+- A zone change lives in its `src/zones/<zone>.py` (`def build(ctx)`, motion as keyframes on
+ `ctx.frame(0.0)` / `ctx.frame(1.5)`); an asset change in `src/assets/<asset>.py`
+ (`build_<asset>(ctx, variant=0)`).
+- A dropped zone / asset (`zone_error`, `asset_error`): fix the named line; never wrap the whole
+ builder in try/except to hide it.
+- Everything rests on `ctx.height_at(x, y)` or on its support (`lib.place.seat`); nothing floats,
+ sinks or runs through a neighbour (`lib.place.clear_of`); repeats are collection instances.
+- No world or cameras outside `{{ env_file }}`, no file IO, no `random.*`, no Python drivers.
+
+## The recurring defects on this track and the cookbook chapter that fixes each
+Do not re-explain the problem back — apply the recipe (the named chapters are printed in full
+under **Recipes** at the end of this brief) and change the numbers. If the judge repeated an issue
+from the previous round, the earlier fix was too timid: double the amplitude / the count / the
+contrast this time.
+
+| what the judge wrote | fix it with |
+|---|---|
+| flat / one-colour ground, no paths, hard raised-bed edges | `"Ground that reads real"` — the colour-attribute blend, carve the path into `height_at`, dress the seams |
+| a hard world edge against the sky, missing horizon | `"Horizon: the world must not end"` — ground ≥ 2.5 × the span, fog = the sky's horizon colour, a `SkyRidge` at 0.6 × the visible range |
+| the backdrop looks like flat / beige / untextured cut-outs | same chapter, rules 4–5 — solid geometry, darken the base colour, never tint it toward the fog |
+| a pond / terrace is a hard-edged plane sitting on the ground | carve it into `height_at` in `{{ env_file }}` and dress the seam (`"Ground that reads real"`); water is `"Water"` |
+| `floating` / `sunken` / `interpenetration` / `unsupported` (the placement gate's metres) | `"Placement self-check"` — `lib.place.seat` / `rest_on`, `clear_of`; a rock may sit a third in, a crate may not |
+| "camera is N m below ground level" / `camera_in_geometry` | the terrain lifted the floor: flatten `height_at` toward z = 0 inside the bounds, or move the thing in front of the lens |
+| identical cones / stacked blocks / primitive repetition | `"Vegetation that reads real"`, `"Rocks, cliffs and boulders that read organic"` — 3+ silhouettes, clustered, scale / hue jitter, no axis-aligned stacks |
+| sparse, token, "a diorama on a plane", empty midground | `"Set dressing"` + `"Scene layering"` — hit the per-zone prop counts, add a foreground element 2–4 m from each camera |
+| flat / dark / monochrome light, black shade, `dark_frame` | `"Atmosphere: time-of-day triads with numbers"`, `"Dusk / night lighting recipe"`, `"Lighting for Cycles + AgX"` — the table's sun / world / fog numbers, practicals with a radius |
+| frames at t=0 and t=1.5 identical, "nothing moves", `nothing_moves` | `"Motion you can SEE between t = 0 and t = 1.5 s"` — LINEAR keyframes on `ctx.frame(0.0)` / `ctx.frame(1.5)`, amplitudes from the table; `python_driver` = a driver that needs Python, rewrite it as `frame * k` |
+| `hard_edged_particles`, "sharp-edged quads / spheres / discs for steam, dust, sparks", the brief's "soft particle effect" must-item unverified | `"Soft particles"` — `lib.materials.volume` on a `Batch` of subdivision-3 spheres, tagged free, drifting ≥ 0.6 m; never a translucent Principled puff, metaball, torus or disc |
+| "plastic", "one grey material", `placeholder_material` | `"Materials: Principled recipes and the lib palette"` — a colour and a roughness on every surface, a noise bump, wood grain, the lib palette |
+| `zone_error` / `asset_error` (a dropped module) | the named `file:line` — fix the raise; Blender 5.2 facts in `"Traps"` (no `use_nodes`, `Factor` not `Fac`, `ShaderNodeMix`, `Action.fcurves` is gone, GN inputs via `mod.properties.inputs`) |
+{% if current_files %}
+
+## Current file contents (edit and return each COMPLETE)
+{% for path, body in current_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+Run `build` → `check_placement` → fix → `build` after editing (and `scene_probe` for the census);
+finish only when both are clean. `check_placement` measures floating / sunken / unsupported /
+interpenetrating assets deterministically — its numbers, not your impression. `scene_views` prints the
+frame table and the MEASURED MOTION per camera — use those numbers, not your impression.
+{% endif %}
+{% if recipes is defined and recipes %}
+
+# Recipes (from the scene cookbook — the chapters for the files you own; copy their numbers)
+{{ recipes }}
+{% endif %}
+
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/scene_zone_bpy.j2 b/harness/codeverse3d/prompts/tracks/scene_zone_bpy.j2
new file mode 100644
index 00000000..23620a34
--- /dev/null
+++ b/harness/codeverse3d/prompts/tracks/scene_zone_bpy.j2
@@ -0,0 +1,124 @@
+# Zone `{{ zone_name }}` of `{{ title }}` — write `{{ zone_file }}`
+
+Scene: {{ spec_prompt }} · Setting: {{ setting }} · Mood: {{ mood }}
+
+## This zone
+- Description (density counts and depth role are binding): {{ zone_description }}
+- Bbox (Z up, −Y front, metres — already converted from the plan): {{ zone_bbox }} — place EVERYTHING
+ inside it (x/y), on the ground via `ctx.height_at(x, y)` or on the surface it stands on.
+{% if interior %}- INTERIOR: the enclosure (walls, ceiling, roof) is `env.py`'s `room_shell` on the scene bounds' faces —
+ never build walls or a roof here. Fixtures on a wall sit flush against the inner face of the bounds;
+ a window or door is an OPENING env cut, so glazing and door leaves go in the opening, not through the wall.
+{% endif %}- Contents (asset names to place): {{ zone_contents | join(', ') if zone_contents else '(none — build local detail from bmesh)' }}
+- Every asset in `ctx.assets` is a Collection AT THE SIZE the asset API states; place it at scale 1
+ (per-instance jitter within ±30 %, never a re-size to "fit"). The placement gate measures every
+ placed thing against the plan's size, and a mismatch is a finding the judge repeats (measured
+ 2026-09-08, round 0: a 1.15 m stove placed at 3.60 m, 0.48 m oil lamps at 0.03 m — both cost the
+ round). The same gate measures a placed asset as ONE object: never stretch a part of an instance; a
+ chimney, pipe or cable that must reach further is a SEPARATE object you add beside it.
+
+{% if layout is defined and layout %}## Zone director's layout (realise EXACTLY these placements; positions are world metres (x, y) in THIS frame)
+{{ layout }}
+
+{% endif %}Neighbouring zones (do not build into them):
+{% for n in neighbours %}- {{ n }}
+{% endfor %}
+
+Authored cameras that will photograph this scene (Z up, metres; keep their first metres clear, and
+give the ones that look at this zone a foreground element):
+{{ cameras }}
+
+## Assets available (sizes are measured, metres)
+{{ asset_api }}
+
+Place one with `instance(ctx.collection, ctx.assets['<snake>'], unique_name('Name', i), x, y,
+height_at=ctx.height_at, rot_z=…)` from `lib/scatter.py` + `lib/place.py` (a collection-instance
+Empty seated on the ground = ONE placement row), or scatter many with `scatter(...)`. Shared materials
+and the terrain come from the environment: `ctx.env['ground_material']`, `ctx.env['sun_direction']`,
+`ctx.height_at`; zones may also `from env import SUN_AZIMUTH_DEG`. A hero GLB is already imported for
+you as `ctx.assets['<snake>']` — instance it, never import a file. There is no `ctx.rand` and no
+`ctx.materials`; randomness is `rng = ctx.rng(<seed>)`.
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+
+### The harness assembles `{{ entry_file }}` and runs YOUR module like this — nothing else runs
+```python
+ctx.collection = <this zone's own Collection, active> # bpy.ops primitives land in it
+out = zones.<snake>.build(ctx) # the function MUST be named `build`, one argument
+# a raise = this zone DROPPED (file:line reported), everything it made removed; the rest builds
+```
+So `{{ zone_file }}` defines `def build(ctx) -> bpy.types.Collection` that links everything into
+`ctx.collection` and returns it. `build_{{ zone_name }}`, `main` and `register` are never called.
+Animation is DATA: keyframes on `ctx.frame(0.0)` / `ctx.frame(1.5)` and simple drivers of `frame`
+(`lib/motion.py`); there is no per-frame hook.
+
+## What this zone is graded on
+The recipes for the points below are printed in full at the end of this brief (**Recipes**) — copy
+their numbers and snippets; the `lib/` catalog does each in one call.
+
+1. **Hit the density counts in the description.** A zone with 5 objects in it reads as a token
+ gesture; the counts are the difference between 0.5 and 0.8. Props go **against** things (path
+ edges, wall bases, under benches, in corners), never in a grid or a perfect ring, with ≥ 20 %
+ positional jitter and full yaw jitter (`lib.scatter.scatter`, `along_path`, `poisson`).
+2. **Variation, not clones.** Any repeated natural element needs ≥ 3 distinct silhouettes
+ (`lib.vegetation.tree` kinds, `shrub`, `fern`; `lib.terrain.boulder` seeds), per-instance scale
+ jitter ±30 %, hue jitter (`lib.materials.tint` or `ob.color` through an Object Info node), full yaw
+ jitter and a few degrees of lean. Clustered placement, never uniform scatter, never a ring of
+ identical cones.
+3. **Seated, and clear of each other — measured.** Every placed root object: its feet on
+ `ctx.height_at` or on what it stands on (`lib.place.seat`, `rest_on`; gap ≤ 0.02 m), sunk 3–5 cm
+ where it meets soil, with 6–15 dressing pieces along the seam. Run `lib.place.clear_of(objs)` before
+ you finish: two boxes sharing > 10% of the smaller one are `interpenetration` (ERROR at 35%), a
+ foot 0.05 m up is `floating` (ERROR at 0.08 m), a foot 0.10 m under is `sunken` (ERROR at 0.20 m).
+ `obj["placement"] = "free"` only for things that hang in the air; the share of tagged things is
+ reported. NEVER lay a hard-edged disc (a pond, a gravel bed, a terrace) flat on the ground: use the
+ depression `height_at` already carves for it and ring the seam with a kerb + dressing.
+4. **Serve the cameras.** Skip any SCATTER point inside a ~4 m disc around an authored camera (the
+ `camera_mask` recipe) — a tree 1 m in front of the establishing camera ruins the shot. Then, by
+ hand, place ONE element 2.5–4 m from a camera that looks across this zone, off to one side, as its
+ foreground frame.
+5. **Motion that shows.** Amplitudes from the Recipes table (foliage ±0.10–0.20 rad, a mover ≥ 0.6 m
+ per 1.5 s), as keyframes on `ctx.frame(0.0)` / `ctx.frame(1.5)` (LINEAR) or a simple driver of
+ `frame`. The harness DIFFERENCES the t=0 and t=1.5 frames pixel by pixel and reports the number:
+ too small a change counts as `nothing_moves`. Give this zone at least one motion big enough to see
+ across the frame.
+6. **One object = one thing; names unique.** A multi-part prop is one mesh or one parent Empty with
+ children; repeats are collection instances; the hundreds (blades, pebbles, litter) are a
+ geometry-nodes cloud (`lib.vegetation.grass_patch`, `lib.scatter.gn_scatter`). Every placed copy
+ `unique_name(base, i)`; never `bpy.ops` in a loop.
+
+## DON'T
+- No world, no sun, no cameras, no ground here (the env's); lights only as practicals and the odd window.
+- No file IO, {% if not (textures is defined and textures) %}no image textures, {% endif %}no `random.*` (`ctx.rng(seed)`), no Python drivers, no `scene.*` settings.
+- Do not place assets marked NOT AVAILABLE; do not edit other files.
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+After editing run `build` → `check_placement` (it names every asset that floats, is sunken, touches
+nothing or interpenetrates another, with the exact "lower X by 0.23 m onto Ground" fix; a
+deliberately airborne thing gets `obj["placement"] = "free"`) → fix → `build` again, then
+`scene_views` and LOOK at the frames: count the silhouettes, look for a flat colour under your
+props, and read the MEASURED MOTION line it prints — if it reports your zone's cameras as STATIC,
+double the amplitude and render again.
+{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+{% if recipes is defined and recipes %}
+
+# Recipes (from the scene cookbook — copy these numbers and snippets)
+{{ recipes }}
+{% endif %}
+{% if textures is defined and textures %}
+
+{{ textures }}
+(These are PNG files under `public/textures/`: load one with `bpy.data.images.load("public/textures/<file>",
+check_existing=True)` into an Image Texture node; the build runs with the workspace root as its working directory.)
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse3d/prompts/variants.py b/harness/codeverse3d/prompts/variants.py
new file mode 100644
index 00000000..ecd2163a
--- /dev/null
+++ b/harness/codeverse3d/prompts/variants.py
@@ -0,0 +1,285 @@
+"""Per-model prompt / skill variants: one overlay directory per name, chosen explicitly (D105).
+
+WHY. The owner's 2026-10-14 decision: gemini-4-argon on the scene track gets its own prompt
+wording and skill routing, tuned by a loop (``eval/bench/loop.py``) that must be able to accept
+or roll back a change without touching the base files every other model reads. A variant is
+therefore an OVERLAY, never a fork: ``codeverse3d/prompts/variants/<name>/<rel>`` shadows
+``codeverse3d/prompts/<rel>`` for the callers of :func:`codeverse3d.prompts.load_text` /
+``render`` (they do not change), and ``codeverse3d/skills/variants/<name>/`` shadows bundles by
+name and adds ``routes.toml`` boosts (``codeverse3d.skills``). Everything a variant does is a
+file the loop can diff, snapshot and hash — :func:`variant_hash` goes into the run record beside
+the prompt hashes, so two runs can be told apart by what their models were shown.
+
+HOW it is chosen (Law 4: never a regex over the model id). ``Settings.variant``
+(``C3D_VARIANT``, or ``3dcode make --variant``, frozen on ``RunOptions.variant``) names one for
+the whole process; otherwise ``Settings.variants`` maps an EXACT generator id to a name — by the
+id as typed, then by ``<kind>:<served model>`` (``agy:gemini-4-argon-high`` runs the model
+``gemini-4-argon``, so one mapping keyed on the served model covers every effort suffix). An
+unknown name is a ``ValueError`` at resolution time, before a run directory exists.
+
+WHERE it is active. A ``ContextVar`` set by :func:`activate` around the whole run
+(``tracks/lifecycle.BaseTrack.run``) and inherited by every fan-out thread, because
+``proc.fan_out`` copies the caller's context into its workers; outside any run,
+``get_settings().variant`` — the process switch, like every other ``C3D_*`` knob.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import tomllib
+from collections.abc import Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse3d.config import Settings, get_settings
+
+log = logging.getLogger(__name__)
+
+#: the overlay directories: ``VARIANTS_DIR/<name>/`` mirrors ``codeverse3d/prompts/`` file for file
+VARIANTS_DIR: Path = Path(__file__).resolve().parent / "variants"
+#: the one file every variant must ship (its name, version, generators and knobs)
+VARIANT_FILE = "variant.toml"
+#: ``[knobs]`` may set ONLY these ``Settings`` fields — the skills dials a variant tunes. Applied
+#: like a profile (``Settings.apply_profile``): a field the user stated themselves wins.
+KNOB_FIELDS: frozenset[str] = frozenset({"skills_max", "skills_only"})
+_KNOB_TYPES: dict[str, type] = {"skills_max": int, "skills_only": str}
+#: files under an overlay that are documentation, never material a model sees: left out of the hash
+HASH_EXCLUDED: frozenset[str] = frozenset({"README.md"})
+
+_ACTIVE: ContextVar[str | None] = ContextVar("c3d_variant", default=None)
+_WARNED: set[str] = set()
+
+
+class VariantInfo(BaseModel):
+ """``variant.toml``, parsed and type-checked."""
+
+ model_config = {"frozen": True}
+
+ name: str = Field(description="equals the overlay directory name")
+ version: int = Field(ge=1, description="the loop bumps it on accept (eval/bench/loop.py)")
+ generators: tuple[str, ...] = Field(default=(), description="informative: the generator ids it was tuned "
+ "for; selection is Settings.variants / --variant")
+ description: str = ""
+ knobs: dict[str, Any] = Field(default_factory=dict, description="Settings fields to apply (KNOB_FIELDS only)")
+
+
+# --------------------------------------------------------------------------- the catalogue
+def _plain_name(name: str) -> bool:
+ """A variant name is a plain directory name: no separators, no dot-prefix."""
+ return bool(name) and Path(name).name == name and not name.startswith(".")
+
+
+def variant_root(name: str) -> Path:
+ """``VARIANTS_DIR / name`` — the prompts half of the overlay (it need not exist yet)."""
+ if not _plain_name(name):
+ raise ValueError(f"variant name {name!r} must be a plain directory name")
+ return VARIANTS_DIR / name
+
+
+def list_variants() -> dict[str, VariantInfo]:
+ """Every variant the tree ships, by name (a directory under ``VARIANTS_DIR`` with a ``variant.toml``).
+ A file that does not parse raises: a shipped variant is never half-known."""
+ if not VARIANTS_DIR.is_dir():
+ return {}
+ return {d.name: _parse(d / VARIANT_FILE, d.name)
+ for d in sorted(VARIANTS_DIR.iterdir()) if d.is_dir() and (d / VARIANT_FILE).is_file()}
+
+
+def variant_info(name: str) -> VariantInfo:
+ """``variant.toml`` of ``name``; ``ValueError`` for an unknown name (naming the known ones)."""
+ path = variant_root(name) / VARIANT_FILE if _plain_name(name) else None
+ if path is None or not path.is_file():
+ known = ", ".join(list_variants()) or "none"
+ raise ValueError(f"unknown variant {name!r} (known: {known})")
+ return _parse(path, name)
+
+
+def _parse(path: Path, dir_name: str) -> VariantInfo:
+ try:
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
+ except tomllib.TOMLDecodeError as e:
+ raise ValueError(f"{path}: not valid TOML: {e}") from e
+ head = data.get("variant")
+ if not isinstance(head, dict):
+ raise ValueError(f"{path}: missing the [variant] table")
+ unknown_tables = sorted(set(data) - {"variant", "knobs"})
+ if unknown_tables:
+ raise ValueError(f"{path}: unknown table(s) {unknown_tables}; variant.toml holds [variant] and [knobs]")
+ unknown = sorted(set(head) - {"name", "version", "generators", "description"})
+ if unknown:
+ raise ValueError(f"{path}: unknown [variant] key(s) {unknown}")
+ name = head.get("name")
+ if name != dir_name:
+ raise ValueError(f"{path}: [variant] name {name!r} must equal the directory name {dir_name!r}")
+ version = head.get("version", 1)
+ if isinstance(version, bool) or not isinstance(version, int) or version < 1:
+ raise ValueError(f"{path}: version must be an integer >= 1, got {version!r}")
+ generators = head.get("generators", [])
+ if not isinstance(generators, list) or not all(isinstance(g, str) for g in generators):
+ raise ValueError(f"{path}: generators must be a list of generator ids")
+ description = head.get("description", "")
+ if not isinstance(description, str):
+ raise ValueError(f"{path}: description must be a string")
+ knobs = data.get("knobs", {})
+ if not isinstance(knobs, dict):
+ raise ValueError(f"{path}: [knobs] must be a table")
+ for key, value in knobs.items():
+ if key not in KNOB_FIELDS:
+ raise ValueError(f"{path}: [knobs] {key!r} is not a variant knob (allowed: {sorted(KNOB_FIELDS)})")
+ want = _KNOB_TYPES[key]
+ if isinstance(value, bool) or not isinstance(value, want) or (want is int and value < 0):
+ raise ValueError(f"{path}: [knobs] {key} must be a {want.__name__}"
+ f"{' >= 0' if want is int else ''}, got {value!r}")
+ return VariantInfo(name=name, version=version, generators=tuple(generators), description=description,
+ knobs=dict(knobs))
+
+
+# --------------------------------------------------------------------------- selection
+def served_id(generator_id: str) -> str:
+ """``agy:gemini-4-argon-high`` → ``agy:gemini-4-argon``: the id by the model the vendor serves, without
+ the effort suffix; ``""`` for an id that is not ``<kind>:<model>`` (a single-shot id, a bare name)."""
+ from codeverse3d.agents.backends import api_model_effort
+ from codeverse3d.agents.registry import parse_agent_id
+
+ try:
+ kind, model = parse_agent_id(generator_id)
+ except ValueError:
+ return ""
+ return f"{kind}:{api_model_effort(model)[0]}"
+
+
+def resolve_variant(settings: Settings, generator_id: str) -> str:
+ """The variant name for a run of ``generator_id`` under ``settings``: ``settings.variant`` (non-empty)
+ > ``settings.variants[generator_id]`` > ``settings.variants["<kind>:<served model>"]`` > ``""`` (base).
+ Plain dict lookups, never a pattern over the id. An unknown name raises ``ValueError``."""
+ name = settings.variant.strip()
+ if not name and settings.variants:
+ name = settings.variants.get(generator_id, "")
+ if not name:
+ served = served_id(generator_id)
+ if served and served != generator_id:
+ name = settings.variants.get(served, "")
+ name = (name or "").strip()
+ if name:
+ variant_info(name)
+ return name
+
+
+# --------------------------------------------------------------------------- the active variant
+def active_variant() -> str:
+ """The variant everything resolves through right now: the ``ContextVar`` :func:`activate` set, else
+ the process switch ``get_settings().variant``. ``""`` is the base."""
+ current = _ACTIVE.get()
+ if current is not None:
+ return current
+ name = get_settings().variant.strip()
+ if name and not _plain_name(name):
+ if name not in _WARNED:
+ _WARNED.add(name)
+ log.warning("C3D_VARIANT=%r is not a plain variant name; using the base prompts", name)
+ return ""
+ return name
+
+
+@contextmanager
+def activate(name: str) -> Iterator[str]:
+ """Set the active variant for the block (``""`` = base). An unknown name raises before anything in
+ the block renders from a directory that does not exist. Nests: the outer value returns on exit."""
+ name = (name or "").strip()
+ if name:
+ variant_info(name)
+ token = _ACTIVE.set(name)
+ try:
+ yield name
+ finally:
+ _ACTIVE.reset(token)
+
+
+# --------------------------------------------------------------------------- provenance
+def _skills_root(name: str) -> Path:
+ from codeverse3d.skills import variant_dir
+
+ return variant_dir(name)
+
+
+def variant_hash(name: str) -> str:
+ """``sha256[:12]`` over the sorted ``(relpath, bytes)`` of the prompt AND skills overlay files of
+ ``name`` (``README.md`` left out: documentation, not prompt material); ``""`` for the base. The two
+ trees are keyed ``prompts/<rel>`` and ``skills/<rel>`` so a same-named file in both still counts twice.
+ For an empty overlay this is the hash of ``variant.toml`` + ``routes.toml``, so a version bump moves it."""
+ if not name:
+ return ""
+ variant_info(name)
+ h = hashlib.sha256()
+ for prefix, root in (("prompts", variant_root(name)), ("skills", _skills_root(name))):
+ if not root.is_dir():
+ continue
+ for p in sorted(x for x in root.rglob("*") if x.is_file()):
+ if p.name in HASH_EXCLUDED or p.name.startswith(".") or "__pycache__" in p.parts:
+ continue
+ h.update(f"{prefix}/{p.relative_to(root).as_posix()}\0".encode())
+ h.update(p.read_bytes())
+ h.update(b"\0")
+ return h.hexdigest()[:12]
+
+
+def variant_block(name: str) -> dict[str, Any]:
+ """``{"name", "version", "hash"}`` for a record (``RunRecord.extra["variant"]``, the ``variant.active``
+ event). Tolerant: a variant that vanished mid-run keeps its name with version 0 / hash ``""``."""
+ if not name:
+ return {"name": "", "version": 0, "hash": ""}
+ try:
+ return {"name": name, "version": variant_info(name).version, "hash": variant_hash(name)}
+ except (ValueError, OSError) as e:
+ log.warning("variant %r cannot be read for the record: %s", name, e)
+ return {"name": name, "version": 0, "hash": ""}
+
+
+# --------------------------------------------------------------------------- knobs
+def apply_variant_knobs(settings: Settings, info: VariantInfo) -> dict[str, Any]:
+ """Set ``info.knobs`` on ``settings`` as DEFAULTS, the way a profile is applied: a field the user
+ stated (config file / ``C3D_*`` / an explicit constructor kwarg — ``model_fields_set``) is never
+ touched, and the field-set is restored afterwards so a knob is not later mistaken for a statement
+ (``Settings.apply_profile.put_section`` keeps the same invariant). Returns what was set."""
+ stated = set(settings.model_fields_set)
+ applied: dict[str, Any] = {}
+ for field_name, value in info.knobs.items():
+ if field_name not in KNOB_FIELDS or field_name in stated:
+ continue
+ setattr(settings, field_name, value)
+ applied[field_name] = value
+ settings.__pydantic_fields_set__ = stated
+ return applied
+
+
+@contextmanager
+def knobs_applied(settings: Settings, info: VariantInfo | None) -> Iterator[dict[str, Any]]:
+ """:func:`apply_variant_knobs` for the block ONLY (``info`` ``None``: nothing applied).
+
+ WHY a block. The prompt and skill overlays are scoped by :func:`activate`'s ``ContextVar``, but
+ the knobs are written onto a ``Settings`` object that outlives the run — the process singleton
+ ``attach_skills`` reads, a rig's injected Settings — so a variant's ``skills_max`` stayed on it for
+ every later run of the process (a manifest rig, a bench cell after a variant cell, any script
+ calling ``track.run`` twice), and since ``apply_variant_knobs`` keeps the field-set, the leaked
+ value was indistinguishable from the default. On exit — whatever the block raised — every knob
+ field goes back to its prior value and its prior field-set membership; a statement the block made
+ to any OTHER field is kept. Yields what was set, for the ``variant.active`` event."""
+ prior = {field_name: getattr(settings, field_name) for field_name in KNOB_FIELDS}
+ stated = set(settings.model_fields_set) & KNOB_FIELDS
+ applied = apply_variant_knobs(settings, info) if info is not None else {}
+ try:
+ yield applied
+ finally:
+ for field_name, value in prior.items():
+ setattr(settings, field_name, value) # pydantic marks each as set: undone next line
+ settings.__pydantic_fields_set__ = (set(settings.model_fields_set) - KNOB_FIELDS) | stated
+
+
+__all__ = ["HASH_EXCLUDED", "KNOB_FIELDS", "VARIANTS_DIR", "VARIANT_FILE", "VariantInfo", "activate",
+ "active_variant", "apply_variant_knobs", "knobs_applied", "list_variants", "resolve_variant", "served_id",
+ "variant_block", "variant_hash", "variant_info", "variant_root"]
diff --git a/harness/codeverse3d/prompts/variants/argon/README.md b/harness/codeverse3d/prompts/variants/argon/README.md
new file mode 100644
index 00000000..88b5565a
--- /dev/null
+++ b/harness/codeverse3d/prompts/variants/argon/README.md
@@ -0,0 +1,26 @@
+# argon — the prompt overlay for gemini-4-argon on the scene track
+
+This directory is a **variant** (D105, 2026-10-14): an overlay on `codeverse3d/prompts/`.
+A file placed here shadows the base file of the same relative path for every run that
+activates the variant — `scene_threejs/cookbook.md` here replaces the base cookbook,
+`tracks/scene_zone.j2` the zone template — and a file that is not here is read from the base.
+A template here may `include` or `extends` a base file (the variant's loader falls through to
+the base directory).
+
+The overlay ships **empty**: iteration 0 of the tuning loop (`eval/bench/loop.py`) measures the
+base prompts under the variant plumbing, so the first accepted iteration is a measured delta,
+not a guess. The loop writes files here, bumps `version` in `variant.toml` on accept and
+restores the previous snapshot on rollback.
+
+* `variant.toml` — name (must equal this directory's name), version, the generator ids the
+ variant was tuned for (informative), an optional `[knobs]` table (`skills_max`,
+ `skills_only`, applied like a profile: a field the user stated wins).
+* The skills half lives in `codeverse3d/skills/variants/argon/` (bundles that shadow base
+ bundles by name, `routes.toml` with boosts / disabled rules / extra rows).
+* `variant_hash("argon")` (`codeverse3d/prompts/variants.py`) covers both halves, this README
+ excluded; the run record names the variant, its version and that hash.
+
+How a run picks it: `3dcode make --variant argon`, `C3D_VARIANT=argon`, or
+`C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}'` (an exact generator id, looked up as typed
+and then by `<kind>:<served model>` so the effort suffix does not matter). Never a pattern
+over the model id (Law 4).
diff --git a/harness/codeverse3d/prompts/variants/argon/tracks/scene_zone.j2 b/harness/codeverse3d/prompts/variants/argon/tracks/scene_zone.j2
new file mode 100644
index 00000000..ef1ccf0d
--- /dev/null
+++ b/harness/codeverse3d/prompts/variants/argon/tracks/scene_zone.j2
@@ -0,0 +1,145 @@
+# Zone `{{ zone_name }}` of `{{ title }}` — write `{{ zone_file }}`
+
+Scene: {{ spec_prompt }} · Setting: {{ setting }} · Mood: {{ mood }}
+
+## This zone
+- Description (density counts and depth role are binding): {{ zone_description }}
+- Bbox: {{ zone_bbox }} — place EVERYTHING inside it (x/z), on the ground via `heightAt`.
+{% if interior %}- INTERIOR: the enclosure (walls, ceiling, roof) is `env.js`'s `roomShell` on the scene bounds' faces —
+ never build walls or a roof here. Fixtures on a wall sit flush against the inner face of the bounds;
+ a window or door is an OPENING env cut, so glazing and door leaves go in the opening, not through the wall.
+{% endif %}- Contents (asset names to place): {{ zone_contents | join(', ') if zone_contents else '(none — build local detail from primitives)' }}
+- Every builder returns its asset AT THE SIZE the asset API states; place it at scale 1 (per-instance jitter
+ within +/-30 %, never a re-size to "fit"). The placement gate measures every placed thing against the
+ plan's size, and a mismatch is a finding the judge repeats (measured 2026-09-08, round 0: a 1.15 m stove
+ placed at 3.60 m, 0.48 m oil lamps at 0.03 m — both cost the round). The same gate measures a placed
+ asset as ONE object, parts included: never stretch or re-scale a part of a placed clone (a stove whose
+ flue you pulled up to the roof reads as a 4.8 m stove — three runs lost their round to it); a chimney,
+ pipe or cable that must reach further is a SEPARATE object you add beside it.
+
+{% if layout is defined and layout %}## Zone director's layout (realise EXACTLY these placements; positions are world meters)
+{{ layout }}
+
+{% endif %}Neighbouring zones (do not build into them):
+{% for n in neighbours %}- {{ n }}
+{% endfor %}
+
+Authored cameras that will photograph this scene (keep their first metres clear, and give the
+ones that look at this zone a foreground element):
+{{ cameras }}
+
+## Assets available (sizes are measured, meters w×h×d)
+{{ asset_api }}
+
+Those paths are written relative to `src/`; **from `src/zones/` prefix them with `../`**
+(`import { buildStoneLantern } from '../assets/stone_lantern.js';`). Shared materials and the
+terrain come from the environment: `import { MATS, heightAt } from '../env.js';` (or use
+`ctx.heightAt`). A GLB asset is already loaded for you at `ctx.assets['<snake_name>']` — add
+`.clone()` of it, never `loaders.gltf` again. A clone that carries clips (a keyframed Blender part) plays
+them by itself; set `clone.userData.clipOffset = <seconds>` to de-phase copies. There is no `ctx.rand` and no `ctx.MATS`.
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+
+### The harness assembles `src/scene.js` and calls YOUR module like this — nothing else runs
+```js
+const ctx = { THREE, scene, renderer, loaders, heightAt, env, assets };
+const g = await build(ctx); // the export MUST be named `build`, one argument
+scene.add(g); // g must be a THREE.Group / Object3D
+if (g.userData.update) g.userData.update(t, dt); // the ONLY animation hook that runs
+```
+So `{{ zone_file }}` exports `export function build(ctx) → THREE.Group` named `"{{ zone_name }}"`.
+`build{{ zone_name }}` and `userData.tick` are never called: if an asset carries its own
+`userData.update`, cache it at build time and call it from the zone's `userData.update`.
+`ctx` also gives you `ctx.env` (whatever `buildEnv` returned) and `ctx.heightAt`.
+
+## What this zone is graded on
+The recipes for all five points below are printed in full at the end of this brief
+(**Recipes**) — copy their numbers and snippets; do not invent your own.
+
+1. **Hit the density counts in the description.** A zone with 5 objects in it reads as a token
+ gesture; the counts are the difference between 0.5 and 0.8. Props go **against** things
+ (path edges, wall bases, under benches, in corners), never in a grid or a perfect ring, with
+ >= 20 % positional jitter and full yaw jitter.
+2. **Variation, not clones.** Any repeated natural element needs >= 3 distinct silhouettes
+ (different geometry, not just scale), per-instance scale jitter +/-30 %, hue jitter +/-0.03
+ via `setColorAt`, full yaw jitter and a few degrees of lean. Clustered placement (cluster
+ seeds + members around them), never uniform scatter and never a ring of identical cones.
+3. **Blend into the ground.** Anything that meets the terrain sinks 3-5 cm into it and gets
+ 6-15 dressing pieces along the seam (tufts, pebbles, leaves). A raised bed gets a chamfered
+ kerb, not a naked box on grass. NEVER lay a hard-edged disc or square (a pond, a gravel
+ bed, a terrace, a lawn patch) flat on top of the ground: use the depression `heightAt`
+ already carves for it and ring the seam with a kerb + dressing, or its outline shows from
+ every overview camera (`flat_ground` / `floating_or_sunken_asset`). Add the zone's share of
+ ground cover (300-800 instanced tufts for a planted zone) unless the description says bare.
+4. **Serve the cameras.** Skip any SCATTER instance inside a ~4 m disc around an authored camera
+ (write a zero-scale matrix, keep the index; `cameraMask` in the cookbook) — a tree 1 m in front
+ of the establishing camera ruins the shot. Then, by hand (not scatter, so the mask does not
+ remove it), place ONE element 2.5-4 m from a camera that looks across this zone, off to one
+ side, as its foreground frame.
+5. **Motion that shows.** Amplitudes from the Recipes table (foliage +/-0.10-0.20 rad, particles
+ >= 0.6 m per 1.5 s). The harness DIFFERENCES the t=0 and t=1.5 frames pixel by pixel and
+ reports the number: too small a change counts as `nothing_moves` (-0.05 and the animation
+ criterion). Sub-centimetre sway is invisible at 1024x576. Give this
+ zone at least one motion big enough to see across the frame, and everything a pure function of `t`.
+6. Use `InstancedMesh` for anything repeated > 5x.
+
+## Before you return — what the argon scenes of iteration 0 lost their points to
+Thirty argon three.js scenes were measured on 2026-10-15 (mean 0.76). Every point below is one
+tool call away and cost whole rounds:
+1. **Your LAST `check_placement` of this session shows 0 ERROR rows for this zone.** Every
+ session ran the check; the rounds that still shipped 29 interpenetration + 9 sunken ERRORs
+ edited again afterwards and never re-checked. Edit → `build` → `check_placement` → fix EVERY
+ row it names (move the smaller thing 0.3 m clear; lower / raise by the stated metres) → `build`
+ → `check_placement` again until clean → only then `scene_views`.
+2. **One placed thing = one direct child of the zone group.** A `…MidProps` / `…Dressing` /
+ `SeamDressing` Group holding several props is measured as ONE asset whose box is their union,
+ so every prop inside it reads as interpenetration (11 of 29 rows). Add each prop to the zone
+ group itself; a prop built from parts is one Group; hundreds of one thing are one InstancedMesh.
+3. **Scatter clear of what you placed** (`keepClear` / `isClear` in the Zones chapter of the
+ cookbook): a scattered rock, fern or crate inside a placed table, rockery or tower is an
+ interpenetration at 100 % of the smaller box. A wide flat thing on a slope (a talus field, a
+ stockpile conveyor) is `sunken` at its uphill end unless each piece follows `heightAt`.
+4. **Particles are soft or absent**: `makeSmoke` / `makeSteam` / `makeMotes` / `makeFire`, or
+ `softDot` sprites (the "Soft particles" chapter below). A bare `PointsMaterial`, a chain of
+ spheres for a steam jet or polygon sparks is `hard_edged_particles` AND fails the brief's "soft
+ particle effect" must-item — both fired together in 5 of 30 scenes.
+5. **A zone that throws at build time is DROPPED and scores nothing** — three runs lost 2-3
+ zones each: `walk(fig, t)` runs ONLY inside `userData.update(t)` (a build-time `walk(fig)`
+ throws `time must be finite`); import only names the effects catalog prints for a module
+ (`concrete` is not in `lib/materials.js` — that SyntaxError dropped two zones); `mergeGeometries`
+ returns null on mismatched attributes (check before `computeVertexNormals`); run `build` after
+ your last edit and read its zone list.
+
+## DON'T
+- No lights except small point lights for lanterns; no cameras; no sky/ground here.
+- No DOM, {% if not (textures is defined and textures) %}no textures, {% endif %}no fetch, no Math.random (`mulberry32(seed)` from `lib/noise.js`).
+- Do not import assets marked NOT AVAILABLE; do not edit other files.
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+After editing run `build` → `check_placement` (it names every asset that floats, is sunken,
+touches nothing or interpenetrates another, with the exact "lower X by 0.23 m onto Terrain"
+fix; a deliberately airborne thing gets `obj.userData.placement = 'free'`) → fix → `build`
+again, then `scene_views` and LOOK at the frames: count the silhouettes, look
+for a flat colour under your props, and read the MEASURED MOTION line it prints — if it reports your
+zone's cameras as STATIC, double the amplitude and render again.
+{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+{% if recipes is defined and recipes %}
+
+# Recipes (from the scene cookbook — copy these numbers and snippets)
+{{ recipes }}
+{% endif %}
+{% if textures is defined and textures %}
+
+{{ textures }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse3d/prompts/variants/argon/tracks/scene_zone_bpy.j2 b/harness/codeverse3d/prompts/variants/argon/tracks/scene_zone_bpy.j2
new file mode 100644
index 00000000..efdae8de
--- /dev/null
+++ b/harness/codeverse3d/prompts/variants/argon/tracks/scene_zone_bpy.j2
@@ -0,0 +1,148 @@
+# Zone `{{ zone_name }}` of `{{ title }}` — write `{{ zone_file }}`
+
+Scene: {{ spec_prompt }} · Setting: {{ setting }} · Mood: {{ mood }}
+
+## This zone
+- Description (density counts and depth role are binding): {{ zone_description }}
+- Bbox (Z up, −Y front, metres — already converted from the plan): {{ zone_bbox }} — place EVERYTHING
+ inside it (x/y), on the ground via `ctx.height_at(x, y)` or on the surface it stands on.
+{% if interior %}- INTERIOR: the enclosure (walls, ceiling, roof) is `env.py`'s `room_shell` on the scene bounds' faces —
+ never build walls or a roof here. Fixtures on a wall sit flush against the inner face of the bounds;
+ a window or door is an OPENING env cut, so glazing and door leaves go in the opening, not through the wall.
+{% endif %}- Contents (asset names to place): {{ zone_contents | join(', ') if zone_contents else '(none — build local detail from bmesh)' }}
+- Every asset in `ctx.assets` is a Collection AT THE SIZE the asset API states; place it at scale 1
+ (per-instance jitter within ±30 %, never a re-size to "fit"). The placement gate measures every
+ placed thing against the plan's size, and a mismatch is a finding the judge repeats (measured
+ 2026-09-08, round 0: a 1.15 m stove placed at 3.60 m, 0.48 m oil lamps at 0.03 m — both cost the
+ round). The same gate measures a placed asset as ONE object: never stretch a part of an instance; a
+ chimney, pipe or cable that must reach further is a SEPARATE object you add beside it.
+
+{% if layout is defined and layout %}## Zone director's layout (realise EXACTLY these placements; positions are world metres (x, y) in THIS frame)
+{{ layout }}
+
+{% endif %}Neighbouring zones (do not build into them):
+{% for n in neighbours %}- {{ n }}
+{% endfor %}
+
+Authored cameras that will photograph this scene (Z up, metres; keep their first metres clear, and
+give the ones that look at this zone a foreground element):
+{{ cameras }}
+
+## Assets available (sizes are measured, metres)
+{{ asset_api }}
+
+Place one with `instance(ctx.collection, ctx.assets['<snake>'], unique_name('Name', i), x, y,
+height_at=ctx.height_at, rot_z=…)` from `lib/scatter.py` + `lib/place.py` (a collection-instance
+Empty seated on the ground = ONE placement row), or scatter many with `scatter(...)`. Shared materials
+and the terrain come from the environment: `ctx.env['ground_material']`, `ctx.env['sun_direction']`,
+`ctx.height_at`; zones may also `from env import SUN_AZIMUTH_DEG`. A hero GLB is already imported for
+you as `ctx.assets['<snake>']` — instance it, never import a file. There is no `ctx.rand` and no
+`ctx.materials`; randomness is `rng = ctx.rng(<seed>)`.
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+
+### The harness assembles `{{ entry_file }}` and runs YOUR module like this — nothing else runs
+```python
+ctx.collection = <this zone's own Collection, active> # bpy.ops primitives land in it
+out = zones.<snake>.build(ctx) # the function MUST be named `build`, one argument
+# a raise = this zone DROPPED (file:line reported), everything it made removed; the rest builds
+```
+So `{{ zone_file }}` defines `def build(ctx) -> bpy.types.Collection` that links everything into
+`ctx.collection` and returns it. `build_{{ zone_name }}`, `main` and `register` are never called.
+Animation is DATA: keyframes on `ctx.frame(0.0)` / `ctx.frame(1.5)` and simple drivers of `frame`
+(`lib/motion.py`); there is no per-frame hook.
+
+## What this zone is graded on
+The recipes for the points below are printed in full at the end of this brief (**Recipes**) — copy
+their numbers and snippets; the `lib/` catalog does each in one call.
+
+1. **Hit the density counts in the description.** A zone with 5 objects in it reads as a token
+ gesture; the counts are the difference between 0.5 and 0.8. Props go **against** things (path
+ edges, wall bases, under benches, in corners), never in a grid or a perfect ring, with ≥ 20 %
+ positional jitter and full yaw jitter (`lib.scatter.scatter`, `along_path`, `poisson`).
+2. **Variation, not clones.** Any repeated natural element needs ≥ 3 distinct silhouettes
+ (`lib.vegetation.tree` kinds, `shrub`, `fern`; `lib.terrain.boulder` seeds), per-instance scale
+ jitter ±30 %, hue jitter (`lib.materials.tint` or `ob.color` through an Object Info node), full yaw
+ jitter and a few degrees of lean. Clustered placement, never uniform scatter, never a ring of
+ identical cones.
+3. **Seated, and clear of each other — measured.** Every placed root object: its feet on
+ `ctx.height_at` or on what it stands on (`lib.place.seat`, `rest_on`; gap ≤ 0.02 m), sunk 3–5 cm
+ where it meets soil, with 6–15 dressing pieces along the seam. Run `lib.place.clear_of(objs)` before
+ you finish: two boxes sharing > 10% of the smaller one are `interpenetration` (ERROR at 35%), a
+ foot 0.05 m up is `floating` (ERROR at 0.08 m), a foot 0.10 m under is `sunken` (ERROR at 0.20 m).
+ `obj["placement"] = "free"` only for things that hang in the air; the share of tagged things is
+ reported. NEVER lay a hard-edged disc (a pond, a gravel bed, a terrace) flat on the ground: use the
+ depression `height_at` already carves for it and ring the seam with a kerb + dressing.
+4. **Serve the cameras.** Skip any SCATTER point inside a ~4 m disc around an authored camera (the
+ `camera_mask` recipe) — a tree 1 m in front of the establishing camera ruins the shot. Then, by
+ hand, place ONE element 2.5–4 m from a camera that looks across this zone, off to one side, as its
+ foreground frame.
+5. **Motion that shows.** Amplitudes from the Recipes table (foliage ±0.10–0.20 rad, a mover ≥ 0.6 m
+ per 1.5 s), as keyframes on `ctx.frame(0.0)` / `ctx.frame(1.5)` (LINEAR) or a simple driver of
+ `frame`. The harness DIFFERENCES the t=0 and t=1.5 frames pixel by pixel and reports the number:
+ too small a change counts as `nothing_moves`. Give this zone at least one motion big enough to see
+ across the frame.
+6. **One object = one thing; names unique.** A multi-part prop is one mesh or one parent Empty with
+ children; repeats are collection instances; the hundreds (blades, pebbles, litter) are a
+ geometry-nodes cloud (`lib.vegetation.grass_patch`, `lib.scatter.gn_scatter`). Every placed copy
+ `unique_name(base, i)`; never `bpy.ops` in a loop.
+
+## Before you return — what the argon scenes of iteration 0 lost their points to
+Thirty argon Blender scenes were measured on 2026-10-15 (mean 0.75). Every point below is one
+tool call away and cost whole rounds:
+1. **Your LAST `check_placement` of this session shows 0 ERROR rows for this zone.** Every
+ session ran the check; 13 of 30 picked rounds still shipped interpenetration ERRORs because the
+ zone was edited again afterwards and never re-checked. Edit → `build` → `check_placement` →
+ fix EVERY row it names (move the smaller thing 0.3 m clear; lower / raise by the stated metres)
+ → `build` → `check_placement` again until clean → only then `scene_views`.
+2. **Scatter clear of what you placed**: `mask = clear_mask(placed_roots, margin=0.3)` from
+ `lib.place`, then `poisson(rng, area=…, min_dist=…, max_count=…, mask=mask)` (or keep only the
+ `along_path` / `grid` points with `mask(x, y) > 0`) BEFORE `scatter(...)` — 9 of the 13 were
+ small props scattered INTO a cart, a rack, a shrub or a salt mound (100 % of the smaller box).
+ Then `for a, b, frac in clear_of([*roots, *scattered]):` and delete the smaller offender
+ (`bpy.data.objects.remove`), as the placement self-check chapter shows.
+3. **A pit, a bank or a floor you carve in this zone is the ground for what stands in it**: seat
+ those things on YOUR surface (`rest_on(obj, pit_floor)`), not on `ctx.height_at`, or the gate
+ reads the sheaves 0.4 m sunk and the anchor plates 0.28 m floating (as in one iteration-0 run).
+4. **Particles are volumes**: `lib.materials.volume` on a `Batch` of subdivision-3 spheres, tagged
+ `placement = "free"`, drifting >= 0.6 m (the "Soft particles" chapter below). Translucent
+ Principled puffs, metaballs, tori and discs were `hard_edged_particles` in 8 of 30 scenes AND
+ failed the brief's "soft particle effect" must-item every time.
+5. **Stay inside your bbox**: two runs shipped cross-zone overlaps (a wind pump into a salt
+ mound, a lane prop into a canopy frame); `keep_inside(obj, bbox)` before you return.
+
+## DON'T
+- No world, no sun, no cameras, no ground here (the env's); lights only as practicals and the odd window.
+- No file IO, {% if not (textures is defined and textures) %}no image textures, {% endif %}no `random.*` (`ctx.rng(seed)`), no Python drivers, no `scene.*` settings.
+- Do not place assets marked NOT AVAILABLE; do not edit other files.
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+After editing run `build` → `check_placement` (it names every asset that floats, is sunken, touches
+nothing or interpenetrates another, with the exact "lower X by 0.23 m onto Ground" fix; a
+deliberately airborne thing gets `obj["placement"] = "free"`) → fix → `build` again, then
+`scene_views` and LOOK at the frames: count the silhouettes, look for a flat colour under your
+props, and read the MEASURED MOTION line it prints — if it reports your zone's cameras as STATIC,
+double the amplitude and render again.
+{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+{% if recipes is defined and recipes %}
+
+# Recipes (from the scene cookbook — copy these numbers and snippets)
+{{ recipes }}
+{% endif %}
+{% if textures is defined and textures %}
+
+{{ textures }}
+(These are PNG files under `public/textures/`: load one with `bpy.data.images.load("public/textures/<file>",
+check_existing=True)` into an Image Texture node; the build runs with the workspace root as its working directory.)
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse3d/prompts/variants/argon/variant.toml b/harness/codeverse3d/prompts/variants/argon/variant.toml
new file mode 100644
index 00000000..1a7873d4
--- /dev/null
+++ b/harness/codeverse3d/prompts/variants/argon/variant.toml
@@ -0,0 +1,26 @@
+# The `argon` variant: gemini-4-argon on the scene track (threejs + blender). D105, 2026-10-14.
+#
+# This directory mirrors codeverse3d/prompts/: a file placed here (scene_threejs/cookbook.md,
+# tracks/scene_zone.j2, ...) shadows the base file of the same relative path for every run that
+# activates the variant; a file not placed here is read from the base. The overlay ships EMPTY
+# so iteration 0 of eval/bench/loop.py measures the base prompts under the variant plumbing;
+# the loop writes files beside this one and bumps `version` on accept.
+#
+# Iteration 1 (2026-10-15): tracks/scene_zone.j2 and tracks/scene_zone_bpy.j2 shadow the base zone
+# briefs with a "Before you return" block — the last check_placement must be clean, one placed thing
+# per zone child, scatter clear of placed roots (lib.place.clear_mask), volumes for particles, and
+# the three build-time crashes that dropped zones; skills/variants/argon/routes.toml boosts the two
+# placement skills to the top of the standing list.
+#
+# Selection is explicit, never a regex over the model id: `3dcode make --variant argon`,
+# C3D_VARIANT=argon, or C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}' (by the served model, so
+# agy:gemini-4-argon-high maps too). `generators` below is informative.
+
+[variant]
+name = "argon"
+version = 1
+generators = ["agy:gemini-4-argon"]
+description = "gemini-4-argon on the scene track (threejs + blender): zone briefs with the iteration-0 placement / particle / crash lessons, placement skills first"
+
+# [knobs] # optional; only Settings.skills_max / skills_only, applied like a profile
+# skills_max = 4 # (a field the user stated in config.yaml / C3D_* wins)
diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.py
index f1ec2105..5e07718d 100644
--- a/harness/codeverse3d/record/telemetry.py
+++ b/harness/codeverse3d/record/telemetry.py
@@ -109,6 +109,7 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:
except Exception as e: # pragma: no cover - settings should always load
log.debug("settings unavailable: %s", e)
env = dict(record.environment)
+ variant, variant_version, variant_hash = _variant_fields(record)
return SettingsSnapshot(
roles=_role_settings(record),
budget=spec.budget.model_dump(mode="json"),
@@ -125,9 +126,26 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:
price_table_version=price_table_version(),
render=render,
limits=limits,
+ variant=variant,
+ variant_version=variant_version,
+ variant_hash=variant_hash,
)
+def _variant_fields(record: RunRecord) -> tuple[str, int, str]:
+ """``(name, version, hash)`` of the variant the run used (D105): what the track stamped as it ran
+ (``record.extra["variant"]``), else the environment / the spec's frozen name with no version or hash
+ (a record written by another tool); the base is ``("", 0, "")``."""
+ block = record.extra.get("variant")
+ block = block if isinstance(block, dict) else {}
+ name = str(block.get("name") or record.environment.get("variant") or record.spec.options.variant or "")
+ if not name:
+ return "", 0, ""
+ version = block.get("version")
+ hashed = block.get("hash") or record.prompt_hashes.get("variant", "")
+ return name, int(version) if isinstance(version, int) and not isinstance(version, bool) else 0, str(hashed or "")
+
+
_TOOL_KEYS = frozenset({"python", "platform", "host", "blender", "blender_path", "node", "three",
"chrome", "puppeteer", "codeverse3d", "harness_git_sha"})
diff --git a/harness/codeverse3d/skills/__init__.py b/harness/codeverse3d/skills/__init__.py
index 9c03df3b..a9e914e2 100644
--- a/harness/codeverse3d/skills/__init__.py
+++ b/harness/codeverse3d/skills/__init__.py
@@ -14,6 +14,16 @@ workspace copy, but the source of truth ships in the wheel, so it must be packag
(``pyproject.toml`` ``[tool.setuptools.package-data]``) — a sibling wave already shipped
a wheel whose starter tree was silently empty for want of that glob.
+Per-model variants (D105, 2026-10-14): ``<skills_dir>/variants/<name>/`` is an OVERLAY on
+the library while that variant is active (``codeverse3d.prompts.variants.active_variant``):
+its bundles shadow base bundles by name or add new ones (:func:`all_skills` merges the two
+roots, :func:`library_roots`), its ``_claims/`` is consulted first
+(``addons/skill_targets.claims_path``), and its ``routes.toml`` — boosts, disabled rule ids,
+extra typed rows — reshapes the routing table (:func:`variants_table`, parsed with ``tomllib``
+into typed records; ``registry.select`` applies it). ``bundle_dirs`` never descends into it:
+``variants/`` has no ``SKILL.md``, so the base listing is what it always was — ``3dcode skills
+validate`` / ``list`` and ``doctor --skills`` walk every shipped root through :func:`shipped_roots`.
+
Public surface for the rest of the harness::
from codeverse3d.skills import select, attach_skills, probe_reads
@@ -27,10 +37,14 @@ is behind ``C3D_SKILLS``: ON by default since 2026-09-22, ``C3D_SKILLS=0`` turns
from __future__ import annotations
import logging
-from collections.abc import Iterator
+import tomllib
+from collections.abc import Iterable, Iterator
+from dataclasses import dataclass
from pathlib import Path
+from typing import TYPE_CHECKING, Any
from codeverse3d.config import get_settings
+from codeverse3d.prompts.variants import active_variant
from codeverse3d.skills.model import (
SKILL_FILE,
Skill,
@@ -39,8 +53,17 @@ from codeverse3d.skills.model import (
validate_bundle,
)
+if TYPE_CHECKING:
+ from codeverse3d.skills.registry import Route
+
log = logging.getLogger(__name__)
+#: the per-model overlays live under the library: ``<skills_dir>/variants/<name>/``
+VARIANTS_SUBDIR = "variants"
+#: a variant's routing-table overlay, beside its bundles
+ROUTES_FILE = "routes.toml"
+
+
def skills_dir() -> Path:
"""The bundle root: this package's directory, as for prompts and rubrics
(``C3D_SKILLS_DIR`` points it elsewhere, read at call time)."""
@@ -50,12 +73,30 @@ def skills_dir() -> Path:
return Path(__file__).resolve().parent
+def variant_dir(name: str) -> Path:
+ """``<skills_dir>/variants/<name>`` — the skills half of a variant overlay (it need not exist)."""
+ return skills_dir() / VARIANTS_SUBDIR / name
+
+
+def library_roots(variant: str | None = None) -> list[Path]:
+ """The bundle roots in shadowing order: the base library, then the active variant's overlay
+ when the variant ships one. ``variant`` names one explicitly instead of :func:`active_variant`."""
+ name = active_variant() if variant is None else variant
+ roots = [skills_dir()]
+ if name:
+ overlay = variant_dir(name)
+ if overlay.is_dir():
+ roots.append(overlay)
+ return roots
+
+
def bundle_dirs(root: Path | None = None) -> list[Path]:
"""Every directory under the library that looks like a bundle, sorted by name.
``_claims/`` and ``__pycache__/`` are deliberately invisible: the library shares a
directory with this package's modules, and a pure tree is what ``skills-ref
- validate`` and the CLIs expect to walk.
+ validate`` and the CLIs expect to walk. ``variants/`` has no ``SKILL.md`` and is skipped
+ the same way — an overlay root is listed by passing it as ``root``.
"""
base = Path(root) if root is not None else skills_dir()
if not base.is_dir():
@@ -81,23 +122,195 @@ def iter_skills(root: Path | None = None, *, strict: bool = False) -> Iterator[S
def all_skills(root: Path | None = None, *, strict: bool = False) -> dict[str, Skill]:
- """name → Skill for the whole library (empty dict when no bundles ship yet)."""
- return {s.name: s for s in iter_skills(root, strict=strict)}
+ """name → Skill. With no ``root``: the base library updated by the active variant's overlay
+ (a same-name bundle shadows the base one, a new name is added); with ``root``: that directory
+ alone. Empty when no bundles ship yet."""
+ if root is not None:
+ return {s.name: s for s in iter_skills(root, strict=strict)}
+ out: dict[str, Skill] = {}
+ for r in library_roots():
+ out.update({s.name: s for s in iter_skills(r, strict=strict)})
+ return out
def load_skill(name: str, root: Path | None = None) -> Skill:
- """One bundle by name; raises :class:`SkillError` when it is missing or invalid."""
- base = Path(root) if root is not None else skills_dir()
- d = base / name
- if not (d / SKILL_FILE).is_file():
- raise SkillError(f"no skill {name!r} in {base}")
- return parse_skill(d)
+ """One bundle by name — the active variant's copy first; raises :class:`SkillError` when it is
+ missing or invalid."""
+ roots = [Path(root)] if root is not None else list(reversed(library_roots()))
+ for base in roots:
+ d = base / name
+ if (d / SKILL_FILE).is_file():
+ return parse_skill(d)
+ raise SkillError(f"no skill {name!r} in {' or '.join(str(r) for r in roots)}")
+
+
+@dataclass(frozen=True)
+class ShippedRoot:
+ """One root the library ships: the base (``variant == ""``) or one variant's skills overlay."""
+
+ variant: str
+ path: Path
+
+ def label(self, bundle: str) -> str:
+ """How the CLIs and the doctor name a bundle of this root: ``<variant>/<bundle>`` for an overlay."""
+ return f"{self.variant}/{bundle}" if self.variant else bundle
+
+
+def shipped_roots(variants: Iterable[str] | None = None) -> list[ShippedRoot]:
+ """The base root, then the skills overlay of every shipped variant that has one — every directory
+ a run can route a bundle from, whichever variant it activates. ``3dcode skills validate`` /
+ ``list`` and ``doctor --skills`` walk THIS rather than :func:`bundle_dirs` alone: an overlay bundle
+ a loop iteration wrote is routed the moment its variant is active (:func:`all_skills`), so a
+ malformed one must fail validation here, not vanish from a session with a logged warning while
+ the row that named it routes nothing. ``variants`` names the ones to walk; the default is every
+ variant ``prompts.variants.list_variants`` knows, and a ``variant.toml`` that does not parse raises
+ its ``ValueError`` (a shipped variant is never half-known)."""
+ from codeverse3d.prompts.variants import list_variants
+
+ names = list(list_variants()) if variants is None else list(variants)
+ roots = [ShippedRoot("", skills_dir())]
+ roots += [ShippedRoot(name, variant_dir(name)) for name in names if variant_dir(name).is_dir()]
+ return roots
+
+
+# ===================================================================== the variant routing table
+@dataclass(frozen=True)
+class RouteBoost:
+ """``[[boost]]``: ``delta`` is added to the priority of every route naming ``skill``
+ (``registry.effective_priority`` clamps: a standing row stays below 90, a gate-fired row never
+ falls under it)."""
+
+ skill: str
+ delta: int
+
+
+@dataclass(frozen=True)
+class VariantRoutes:
+ """A variant's ``routes.toml``: boosts, disabled base rule ids and extra typed rows, parsed with
+ ``tomllib`` (no regex). The extra rows are appended AFTER the base table (ties keep base order)."""
+
+ variant: str = ""
+ routes: tuple[Route, ...] = ()
+ boosts: tuple[RouteBoost, ...] = ()
+ disabled: frozenset[str] = frozenset()
+
+ @property
+ def boost_map(self) -> dict[str, int]:
+ """skill → summed delta (what ``registry.select`` takes)."""
+ out: dict[str, int] = {}
+ for b in self.boosts:
+ out[b.skill] = out.get(b.skill, 0) + b.delta
+ return out
+
+ @property
+ def empty(self) -> bool:
+ return not (self.routes or self.boosts or self.disabled)
+
+
+def variants_table(name: str) -> VariantRoutes:
+ """The variant's table: ``<skills_dir>/variants/<name>/routes.toml`` parsed, or an empty table when
+ the variant ships none (or ``name`` is the base). A table that does not type-check raises
+ ``ValueError`` naming the row and the problem — ``attach_skills`` logs it and routes with the
+ base table, so a typo costs the overlay, never the round."""
+ if not name:
+ return VariantRoutes()
+ path = variant_dir(name) / ROUTES_FILE
+ if not path.is_file():
+ return VariantRoutes(variant=name)
+ return parse_routes(path, variant=name)
+
+
+_ROUTE_KEYS = frozenset({"rule", "skill", "priority", "tracks", "languages", "kinds",
+ "requires_all", "requires_any", "findings", "why"})
+_ROUTE_TUPLES = ("tracks", "languages", "kinds", "requires_all", "requires_any", "findings")
+
+
+def parse_routes(path: Path, *, variant: str = "") -> VariantRoutes:
+ """Parse one ``routes.toml`` into typed records; every typing error is a ``ValueError`` that names
+ the row (``<path>: [[route]] #2: priority must be an integer``)."""
+ from codeverse3d.skills.registry import GATE_FIRED_PRIORITY, ROUTES, Route
+
+ try:
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
+ except tomllib.TOMLDecodeError as e:
+ raise ValueError(f"{path}: not valid TOML: {e}") from e
+ unknown = sorted(set(data) - {"boost", "disable", "route"})
+ if unknown:
+ raise ValueError(f"{path}: unknown table(s) {unknown}; routes.toml holds [[boost]], [[disable]] "
+ f"and [[route]] rows")
+ boosts = tuple(RouteBoost(skill=_str(row, "skill", where), delta=_int(row, "delta", where))
+ for where, row in _rows(data, "boost", path, {"skill", "delta"}))
+ disabled = frozenset(_str(row, "rule", where) for where, row in _rows(data, "disable", path, {"rule"}))
+ routes: list[Route] = []
+ taken = {r.rule for r in ROUTES}
+ for where, row in _rows(data, "route", path, _ROUTE_KEYS):
+ findings = _tuple(row, "findings", where)
+ priority = _int(row, "priority", where)
+ # the table's law (design §5.2 law 2): a priority >= 90 MEANS "a gate routed this" to telemetry
+ # and to Selection.gate_fired, so an extra row may only sit there when it answers a finding
+ if findings and priority < GATE_FIRED_PRIORITY:
+ raise ValueError(f"{where}: a gate-fired row (it names findings) needs priority >= "
+ f"{GATE_FIRED_PRIORITY}, got {priority}")
+ if not findings and priority >= GATE_FIRED_PRIORITY:
+ raise ValueError(f"{where}: a standing row (no findings) must stay below "
+ f"{GATE_FIRED_PRIORITY}, got {priority}")
+ route = Route(rule=_str(row, "rule", where), skill=_str(row, "skill", where), priority=priority,
+ tracks=_tuple(row, "tracks", where), languages=_tuple(row, "languages", where),
+ kinds=_tuple(row, "kinds", where), requires_all=_tuple(row, "requires_all", where),
+ requires_any=_tuple(row, "requires_any", where), findings=findings,
+ why=_str(row, "why", where, required=False))
+ if route.rule in taken:
+ raise ValueError(f"{where}: rule id {route.rule!r} is already taken — a rule id names ONE "
+ f"routing decision in every record and ledger row")
+ taken.add(route.rule)
+ routes.append(route)
+ return VariantRoutes(variant=variant, routes=tuple(routes), boosts=boosts, disabled=disabled)
+
+
+def _rows(data: dict[str, Any], key: str, path: Path, allowed: frozenset[str] | set[str]) -> list[tuple[str, dict[str, Any]]]:
+ rows = data.get(key, [])
+ if not isinstance(rows, list):
+ raise ValueError(f"{path}: [[{key}]] must be an array of tables")
+ out: list[tuple[str, dict[str, Any]]] = []
+ for i, row in enumerate(rows):
+ where = f"{path}: [[{key}]] #{i}"
+ if not isinstance(row, dict):
+ raise ValueError(f"{where}: must be a table")
+ extra = sorted(set(row) - set(allowed))
+ if extra:
+ raise ValueError(f"{where}: unknown key(s) {extra} (allowed: {sorted(allowed)})")
+ out.append((where, row))
+ return out
+
+
+def _str(row: dict[str, Any], key: str, where: str, *, required: bool = True) -> str:
+ value = row.get(key, "")
+ if not isinstance(value, str):
+ raise ValueError(f"{where}: {key} must be a string, got {value!r}")
+ if required and not value.strip():
+ raise ValueError(f"{where}: {key} is required")
+ return value.strip()
+
+
+def _int(row: dict[str, Any], key: str, where: str) -> int:
+ value = row.get(key)
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise ValueError(f"{where}: {key} must be an integer, got {value!r}")
+ return value
+
+
+def _tuple(row: dict[str, Any], key: str, where: str) -> tuple[str, ...]:
+ value = row.get(key, [])
+ if not isinstance(value, list) or not all(isinstance(v, str) and v.strip() for v in value):
+ raise ValueError(f"{where}: {key} must be a list of non-empty strings, got {value!r}")
+ return tuple(v.strip() for v in value)
from codeverse3d.skills.materialize import attach_skills, materialize_skills # noqa: E402
from codeverse3d.skills.registry import plan_signals, select # noqa: E402
from codeverse3d.skills.telemetry import probe_reads # noqa: E402
-__all__ = ["Skill", "SkillError", "all_skills", "attach_skills", "bundle_dirs",
- "iter_skills", "load_skill", "materialize_skills", "plan_signals", "probe_reads", "select",
- "skills_dir", "validate_bundle"]
+__all__ = ["ROUTES_FILE", "VARIANTS_SUBDIR", "RouteBoost", "ShippedRoot", "Skill", "SkillError",
+ "VariantRoutes", "all_skills", "attach_skills", "bundle_dirs", "iter_skills", "library_roots",
+ "load_skill", "materialize_skills", "parse_routes", "plan_signals", "probe_reads", "select",
+ "shipped_roots", "skills_dir", "validate_bundle", "variant_dir", "variants_table"]
diff --git a/harness/codeverse3d/skills/_claims/c3d-bpy-scene-lighting.toml b/harness/codeverse3d/skills/_claims/c3d-bpy-scene-lighting.toml
new file mode 100644
index 00000000..5410e4d6
--- /dev/null
+++ b/harness/codeverse3d/skills/_claims/c3d-bpy-scene-lighting.toml
@@ -0,0 +1,103 @@
+# The frame-gate thresholds this bundle quotes, pinned to spatial/frame_metrics.py. The measured
+# exposure bands (references/exposure-bands.md section 2) are measurements with their provenance,
+# not code constants, so they carry no rows.
+
+[[claim]]
+key = "dark_mean_lum"
+text = "0.12"
+python = "codeverse3d.spatial.frame_metrics:DARK_MEAN_LUM"
+format = "{:.2f}"
+context = "mean luminance below"
+
+[[claim]]
+key = "lowkey_min_std"
+text = "0.12"
+python = "codeverse3d.spatial.frame_metrics:LOWKEY_MIN_STD"
+format = "{:.2f}"
+context = "contrast"
+
+[[claim]]
+key = "dark_frac"
+text = "35 %"
+python = "codeverse3d.spatial.frame_metrics:DARK_FRAC"
+scale = 100
+format = "{:.0f} %"
+context = "near black"
+
+[[claim]]
+key = "blown_frac"
+text = "20 %"
+python = "codeverse3d.spatial.frame_metrics:BLOWN_FRAC"
+scale = 100
+format = "{:.0f} %"
+context = "pure white"
+
+[[claim]]
+key = "flat_modal_frac"
+text = "85 %"
+python = "codeverse3d.spatial.frame_metrics:FLAT_MODAL_FRAC"
+scale = 100
+format = "{:.0f} %"
+context = "one luminance band"
+
+[[claim]]
+key = "flat_modal_error"
+text = "92 %"
+python = "codeverse3d.spatial.frame_metrics:FLAT_MODAL_ERROR"
+scale = 100
+format = "{:.0f} %"
+context = "ERROR above"
+
+# references/exposure-bands.md restates the five in its own table
+
+[[claim]]
+key = "dark_mean_lum"
+file = "references/exposure-bands.md"
+text = "0.12"
+python = "codeverse3d.spatial.frame_metrics:DARK_MEAN_LUM"
+format = "{:.2f}"
+context = "below"
+
+[[claim]]
+key = "lowkey_min_std"
+file = "references/exposure-bands.md"
+text = "0.12"
+python = "codeverse3d.spatial.frame_metrics:LOWKEY_MIN_STD"
+format = "{:.2f}"
+context = "at least"
+
+[[claim]]
+key = "dark_frac"
+file = "references/exposure-bands.md"
+text = "35 %"
+python = "codeverse3d.spatial.frame_metrics:DARK_FRAC"
+scale = 100
+format = "{:.0f} %"
+context = "dark_frac"
+
+[[claim]]
+key = "blown_frac"
+file = "references/exposure-bands.md"
+text = "20 %"
+python = "codeverse3d.spatial.frame_metrics:BLOWN_FRAC"
+scale = 100
+format = "{:.0f} %"
+context = "blown_frac"
+
+[[claim]]
+key = "flat_modal_frac"
+file = "references/exposure-bands.md"
+text = "85 %"
+python = "codeverse3d.spatial.frame_metrics:FLAT_MODAL_FRAC"
+scale = 100
+format = "{:.0f} %"
+context = "modal_frac"
+
+[[claim]]
+key = "flat_modal_error"
+file = "references/exposure-bands.md"
+text = "92 %"
+python = "codeverse3d.spatial.frame_metrics:FLAT_MODAL_ERROR"
+scale = 100
+format = "{:.0f} %"
+context = "modal_frac"
diff --git a/harness/codeverse3d/skills/_claims/c3d-bpy-scene-materials.toml b/harness/codeverse3d/skills/_claims/c3d-bpy-scene-materials.toml
new file mode 100644
index 00000000..d98e6712
--- /dev/null
+++ b/harness/codeverse3d/skills/_claims/c3d-bpy-scene-materials.toml
@@ -0,0 +1,5 @@
+# This bundle quotes no number from live code: the socket names and node ids are Blender 5.2.2
+# facts (the languages/blender lint tables hold the rename list as strings, not numeric
+# constants), the recipe arguments are the agent's (`<placeholders>`), and the lib defaults it
+# relies on (glass IOR, foliage variants) are keyword defaults in src/lib/materials.py, which the
+# grammar cannot pin. Nothing to pin; the file exists so the claims check finds an empty table.
diff --git a/harness/codeverse3d/skills/_claims/c3d-bpy-scene-placement.toml b/harness/codeverse3d/skills/_claims/c3d-bpy-scene-placement.toml
new file mode 100644
index 00000000..5da9f49d
--- /dev/null
+++ b/harness/codeverse3d/skills/_claims/c3d-bpy-scene-placement.toml
@@ -0,0 +1,42 @@
+# Numbers this bundle quotes, pinned to the constants that produce them.
+#
+# The gate's THRESHOLDS (contact, floating, sunk, overlap, free-exempt) are pydantic defaults on
+# codeverse3d.config:Placement, which this grammar cannot reach (`python = "module:NAME"` resolves
+# a module attribute, and `Placement.model_fields[...].default` is not one). The body therefore
+# names the Settings FIELDS and sends the reader to the summary line of `check_placement`, which
+# prints the values a run used, instead of quoting numbers. A `field = "floating_error_m"` key
+# reading `Placement.model_fields[field].default` would let the numbers back in (REPORT.md).
+
+[[claim]]
+key = "foot_columns"
+text = "5"
+js = "runtime_js/lib/host_placement.mjs:MAX_COLUMNS"
+format = "{:.0f}"
+context = "foot columns"
+
+# references/finding-to-fix.md
+
+[[claim]]
+key = "max_findings_per_kind"
+file = "references/finding-to-fix.md"
+text = "8"
+python = "codeverse3d.spatial.scene_placement:MAX_FINDINGS_PER_KIND"
+format = "{:.0f}"
+context = "per kind"
+
+[[claim]]
+key = "max_assets"
+file = "references/finding-to-fix.md"
+text = "400"
+js = "runtime_js/lib/host_placement.mjs:MAX_ASSETS"
+format = "{:.0f}"
+context = "stops at"
+
+[[claim]]
+key = "time_budget_s"
+file = "references/finding-to-fix.md"
+text = "4 s"
+js = "runtime_js/lib/host_placement.mjs:TIME_BUDGET_MS"
+scale = 0.001
+format = "{:.0f} s"
+context = "stops at"
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-lighting/SKILL.md b/harness/codeverse3d/skills/c3d-bpy-scene-lighting/SKILL.md
new file mode 100644
index 00000000..afe8a548
--- /dev/null
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-lighting/SKILL.md
@@ -0,0 +1,127 @@
+---
+name: c3d-bpy-scene-lighting
+description: "Use when lighting a scene_blender env, zone, refine or rebuild session, or when scene_frames called a Blender frame too dark, blown out or flat. The harness renders with Cycles under AgX at exposure 0 and owns every render setting, so lamp energies, the world strength and the albedos are the only dials. Gives what the frame gate measures with its thresholds, the measured exposure bands of sky, sun, night and interior setups under this renderer, the sun-and-sky, night, interior and practical recipes through lib.sky and lib.lighting, the one-sun rule, why an emissive mesh is not a lamp at 32 samples, and how to prove the band on every camera including the harness rig."
+license: Apache-2.0
+compatibility: Blender 5.2.2 LTS headless, scene_blender runtime; Cycles 32 samples + OIDN, AgX view transform, look None, exposure 0 — all harness-owned (render_bpy_scene.setup_render).
+metadata:
+ evidence: mixed
+ evidence_note: 'The gate thresholds are read from live code (spatial/frame_metrics.py, runtime_js/lib/host_metrics.mjs) and the render setup from languages/wrappers/render_bpy_scene.py on 2026-10-14; the exposure bands were measured that day on Blender 5.2.2 LTS with that exact setup on a synthetic test scene (references/exposure-bands.md says how), not on run output. The corpus half is empty: zero gated scene_blender runs exist on 2026-10-14; the first loop iteration attaches numbers.'
+ verified: "2026-10-14"
+ target_metric: "bpy_exposure_findings"
+ target_direction: "down"
+ target_unit: "findings per run"
+ target_measurable: "true"
+ target_baseline: "n=0 — no gated scene_blender runs yet (2026-10-14); measured on the first loop iteration"
+---
+
+# Lighting a Cycles scene the frame gate will accept
+
+## What is fixed, and what is measured
+
+The harness renders the authored cameras and the first overview rig views with Cycles at 32
+samples plus denoising, AgX view transform, look None, exposure 0 — and it owns every one of
+those settings: an assignment to `scene.render`, `scene.cycles` or `scene.view_settings` is a lint
+ERROR (harness-owned). There is no exposure knob. Lamp energies, the world strength and the
+albedos are the whole of your control.
+
+The gate (`scene_frames`) reads the Blender PNGs with the statistics it reads three.js frames
+with — per camera `mean_lum`, `lum_std`, `dark_frac`, `blown_frac` and `modal_frac` in the
+`camera_checks` of `metrics.json`:
+
+| finding | fires when | authored camera | harness rig view |
+|---|---|---|---|
+| `dark_frame` | mean luminance below 0.12, or more than 35 % of the pixels near black | ERROR | WARN |
+| `dark_frame`, "dim but lit" | dark by the mean, but with contrast (`lum_std`) of at least 0.12 and not mostly black | WARN | WARN |
+| `blown_frame` | more than 20 % of the pixels pure white | ERROR | WARN |
+| `flat_frame` | one luminance band holds more than 85 % of the frame | WARN; ERROR above 92 % | WARN |
+
+An ERROR of each kind is a score ceiling in the scene rubric, and every finding's hint carries the
+scene_blender wording (lamps, world nodes, `ctx.height_at`), not the three.js one. The rig views
+(`overview_*`) are WARN-only; fix them anyway — the judge reads those pictures.
+
+## The bands, measured on this renderer
+
+Measured 2026-10-14 on Blender 5.2.2 LTS with the harness's exact render setup, on a synthetic
+scene (a flat ground plane of linear albedo a and six boxes; an eye-level camera with sky in the
+top third, and a camera at the overview rig's angle). Numbers are `mean_lum`; the full tables
+and the other four statistics are in `references/exposure-bands.md`.
+
+| setup | `mean_lum` | what it says |
+|---|---|---|
+| the multiple-scattering sky alone, sun disc ON (a hand-built world), strength 0.05 / 0.2 / 1.0 (eye camera) | 0.63 / 0.82 / 0.96 | with its disc the physical sky IS daylight at strength 0.05-0.1; at 1.0 the sky starts to clip |
+| sky 0.2 with the disc off + ONE sun lamp at 1 / 3 / 10 W per square metre, a = 0.3 (overview) | 0.57 / 0.63 / 0.73 | the lamp is a weak dial under AgX |
+| the same sun at 3, ground albedo 0.03 / 0.15 / 0.6 (overview) | 0.32 / 0.52 / 0.72 | albedo is the strong dial |
+| sun lamp 3 with the sky's disc ALSO on (two suns) | 0.83 | the doubled sun: washed, shadows fight |
+| dark-blue night world alone / with a moon sun of 0.2 / 0.5 | 0.02 / 0.06 / 0.10 | too dark, and evenly so: no low-key escape, because `lum_std` stays under 0.05 |
+| that night + two practical area lamps 2.5 m up at 45 / 150 / 500 W | 0.05 / 0.08 / 0.14 | 45 W is a look, not a light; 500 W per lamp passes, with contrast |
+| that night + two fixture-sized emissive spheres at strength 5 / 80 / 320, no lamps | 0.03 / 0.05 / 0.09 | emission does not carry a frame; it needs a lamp beside it |
+| a closed 6 m room, one 1 m ceiling area lamp at 50 / 200 / 800 W | 0.34 / 0.61 / 0.82 | interiors are easy: tens to hundreds of watts |
+
+Two things fall out of the table. Under any daylight world nothing is dark and the risk is the
+other two kinds: a uniformly coloured ground seen from the overview rig sat in the flat band
+(`modal_frac` 0.84-0.95) in every daylight row, so value variance on the ground and
+shadow-casting content are what break it, not more light. And at night the lamps that make the
+picture pass are an order of magnitude stronger than the ones that make the fixtures glow.
+
+## The recipe
+
+* **Sky and sun from `src/env.py` only.** `lib.sky.sun_world(scene, elevation_deg=..., azimuth_deg=..., strength=..., dust=...)`
+ and `lib.lighting.sun(collection, azimuth_deg=..., elevation_deg=..., color=..., energy=..., angle_deg=...)`
+ are a pair: ONE world, ONE sun lamp, the same compass angles. `sun_world` switches the sky's
+ own sun disc OFF because the lamp is the sun — a world built by hand with the disc on, plus a
+ lamp, is two suns (the fourth row of the table). The world is `build_env`'s — a world created
+ or assigned anywhere else is a harness-owned lint ERROR — and a second sun lamp in a zone
+ doubles the shadows. Fix a dark day with the albedos and the sun's `energy`, not by raising
+ the world strength.
+* **Dusk and overcast** are `lib.sky.gradient_world(scene, stops, clouds=..., strength=...)` with
+ a low warm sun; **night** is `lib.sky.night_world(scene, color=..., strength=...)` with a weak,
+ cool `sun` as the moon and the practicals doing the work.
+* **Atmosphere is a bounded box**, `lib.sky.haze(collection, loc, size, density=..., color=...)`:
+ volume-only, which the census counts as fog (the `no_fog` plan check wants one) and the
+ placement gate ignores. A world volume over a large scene swallows the sun and flattens the frame.
+* **Lamps in zones are yours** — `lib.lighting.area_light`, `point_light`, `spot`, and
+ `practical(collection, name, loc, color=..., energy=..., size=..., target=...)`, a small soft
+ area lamp for every lantern, window, fire or sign, aimed with `aim`. Its default energy is the
+ fixture's own glow on the surfaces beside it, not illumination that carries a frame: two of
+ them at that default measured `mean_lum` 0.05 (an ERROR); hundreds of watts each is where a
+ night frame passes. The lib creates lamps through `bpy.data.lights.new`; never through
+ `bpy.ops` — operators in a loop are a hang-risk lint finding, and `bpy.ops.object.light_add`
+ wants a view-layer context the build does not give.
+* **An emissive mesh is the look, not the light.** Cycles does scatter light from an emissive
+ surface, but a fixture-sized emitter throws almost nothing a frame can measure: two 0.15 m
+ emissive spheres at the strengths that make a lantern read as lit left the night frame at
+ `mean_lum` 0.03, and at forty times that strength — white blobs — it was still an ERROR; the
+ same scene passed once each sphere had a 500 W `practical` beside it (reference, section 4).
+ Keep the emission on the fixture (`lib.materials.emissive`), put the illumination in a lamp,
+ and keep the emission modest: AgX pulls a saturated emitter toward white, so a strong neon
+ tube renders as a white bar.
+* **Interiors**: `lib.architecture.room_shell` gives walls, floor and a ceiling the rig lifts; one
+ or two ceiling `area_light`s sized to the room, plus the practicals the brief names; a window is
+ an emissive pane with an `area_light` just inside it. The indoor placement tolerance is tighter,
+ so a lamp on a table is a `rest_on` case too.
+* **Albedo before light.** A ground whose Base Color is near black stays dark under any sun, and a
+ plaster wall clips under the sun that lights a lawn correctly. Set the large surfaces' albedo
+ first, then the sun, then the practicals.
+
+## Night: the band, not the floor
+
+A lantern-lit night is dim on average with real contrast — the "dim but lit" WARN, and that is
+the target. Both ends fail: a sky-lit average on a lantern scene is a grey wash (a flat frame, and
+the judge's unlit-or-blown defect), and glowing fixtures with no lamps behind them are a black
+frame with stickers. So: `night_world` low, every fixture paired with a `practical` strong enough
+that the pools overlap into a readable picture, dark materials with a low but non-zero Base
+Color, shadows left dark, and no fill lamp "to lift the average".
+
+## The hero must be visible
+
+The frames gate also reports `hero_unseen` and `hero_small_in_its_camera`; a hero in shadow at
+night is a hero the judge cannot find. Give it its own key — a `practical` or a `spot` aimed at
+it with `aim(obj, target)` — and look at its camera's frame.
+
+## Prove it
+
+`scene_views(cameras="all", times=[0.0])`, then read `camera_checks` per camera against the
+first table: the same five numbers the gate uses. A Blender view costs seconds, so render once
+per change, all cameras, and fix whatever the finding names on EVERY camera, rig views included.
+
+Full measured tables, the night and interior recipes as code: `references/exposure-bands.md`.
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-lighting/references/exposure-bands.md b/harness/codeverse3d/skills/c3d-bpy-scene-lighting/references/exposure-bands.md
new file mode 100644
index 00000000..c301136c
--- /dev/null
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-lighting/references/exposure-bands.md
@@ -0,0 +1,135 @@
+# Exposure bands under Cycles + AgX at exposure 0
+
+Companion to `c3d-bpy-scene-lighting`. The thresholds are `codeverse3d/spatial/frame_metrics.py`'s
+(read 2026-10-14); the pixel statistics are `runtime_js/lib/host_metrics.mjs`'s and are applied to
+the Blender PNGs unchanged: luminance is the Rec. 709 weighting of the 8-bit sRGB pixels, "near
+black" is the bottom few of the 256 levels, "pure white" is all three channels at the top, and the
+modal band is the fullest of eight equal luminance bands.
+
+## 1. The gate's numbers
+
+| statistic | threshold | finding |
+|---|---|---|
+| `mean_lum` | below 0.12 | `dark_frame` (ERROR on an authored camera) |
+| `dark_frac` | above 35 % | `dark_frame` |
+| `lum_std` | at least 0.12 while dark by the mean and not mostly black | the same finding downgraded to "dim but lit", a WARN |
+| `blown_frac` | above 20 % | `blown_frame` |
+| `modal_frac` | above 85 % | `flat_frame` WARN; ERROR above 92 % on an authored camera |
+
+A frame that is dark is not also reported flat; a frame can be dark by the mean with not one
+near-black pixel, or bright on average and still fail on the black fraction — fix whichever one
+the message names.
+
+## 2. How the bands were measured
+
+Blender 5.2.2 LTS, the harness's `setup_render` verbatim (Cycles, CUDA, 32 samples, adaptive,
+OIDN, AgX, look None, exposure 0, sRGB 8-bit PNG), 192 x 108 pixels, 2026-10-14. Scene: a 200 m
+ground plane of linear albedo a (roughness 0.85), six boxes 0.9-3 m of albedo 0.4. Cameras: eye
+level 1.6 m looking slightly down with the sky in the top third (`eye`), and a camera 25 m out at
+the overview rig's azimuth and elevation (`overview`). Sun elevation 35 degrees. These are bands
+for a bare scene, not rules: real content adds shadow, colour and contrast.
+
+## 3. Daylight
+
+The multiple-scattering sky alone, sun disc on, a = 0.3:
+
+| sky strength | eye `mean_lum` | overview `mean_lum` | note |
+|---|---|---|---|
+| 0.02 | 0.45 | 0.44 | an overcast-looking day |
+| 0.05 | 0.63 | 0.62 | daylight |
+| 0.1 | 0.74 | 0.73 | bright daylight |
+| 0.2 | 0.82 | 0.82 | hazy, washed |
+| 0.5 | 0.91 | 0.91 | the ground is pale |
+| 1.0 | 0.96 | 0.96 | `blown_frac` 0.11 on the eye camera: the sky clips |
+
+Sky at 0.2 with the disc off plus ONE sun lamp (overview camera):
+
+| sun lamp (W per square metre) | a = 0.03 | a = 0.08 | a = 0.15 | a = 0.3 | a = 0.6 |
+|---|---|---|---|---|---|
+| 1 | 0.28 | 0.37 | 0.45 | 0.57 | 0.68 |
+| 3 | 0.32 | 0.42 | 0.52 | 0.63 | 0.72 |
+| 5 | 0.36 | 0.47 | 0.56 | 0.67 | 0.76 |
+| 10 | 0.43 | 0.55 | 0.64 | 0.73 | 0.81 |
+
+Read the rows and the columns against each other: a tenfold sun moves the frame by about 0.15,
+a twentyfold albedo by about 0.4. The eye camera, with the sky in it, sat at 0.59-0.81 across
+the same grid — the sky carries an eye-level frame's mean on its own. With the sky's disc left on
+beside the lamp (sun 3, a = 0.3) the overview rose from 0.63 to 0.83: two suns.
+
+`modal_frac` on the overview camera was 0.80-0.95 in every daylight row: a single-colour ground
+lit evenly IS a flat frame by the gate's definition. Value variance on the ground, shadows from
+content and a horizon in the frame are what move it, not the sun.
+
+## 4. Night
+
+Flat dark-blue world (a night sky colour at strength 0.3), a = 0.3, no sun:
+
+| setup | eye `mean_lum` / `lum_std` / `dark_frac` | overview | verdict |
+|---|---|---|---|
+| world alone | 0.02 / 0.02 / 0.57 | 0.01 / 0.00 / 1.00 | `dark_frame` ERROR |
+| + moon sun 0.05 | 0.03 / 0.01 / 0.57 | 0.03 / 0.01 / 1.00 | ERROR |
+| + moon sun 0.2 | 0.06 / 0.02 / 0.02 | 0.07 / 0.02 / 0.08 | ERROR: dark by the mean, no contrast to rescue it |
+| + moon sun 0.5 | 0.10 / 0.05 / 0.01 | 0.13 / 0.03 / 0.07 | eye ERROR, overview passes |
+| + two point lamps 3 m up, 100 W | 0.06 / 0.04 / 0.11 | 0.05 / 0.06 / 0.59 | ERROR |
+| + two point lamps, 500 W | 0.13 / 0.12 / 0.07 | 0.14 / 0.13 / 0.21 | passes |
+| + two point lamps, 2000 W | 0.25 / 0.22 / 0.04 | 0.28 / 0.20 / 0.09 | passes with room to spare |
+| + two practical area lamps 2.5 m up, 45 W | 0.05 / 0.05 / 0.35 | 0.04 / 0.07 / 0.79 | ERROR: the lib's practical default is a glow, not illumination |
+| + two practicals, 150 W | 0.08 / 0.09 / 0.14 | 0.08 / 0.12 / 0.55 | ERROR on the eye camera; the overview is dim-but-lit |
+| + two practicals, 500 W | 0.14 / 0.16 / 0.07 | 0.14 / 0.18 / 0.28 | passes |
+| + two 0.15 m emissive spheres 2.5 m up, strength 5 (no lamps) | 0.03 / 0.04 / 0.57 | 0.01 / 0.03 / 0.99 | ERROR: the fixtures glow, the ground does not |
+| + the same spheres at strength 20 / 80 | 0.03 / 0.04 / 0.51 and 0.05 / 0.05 / 0.30 | 0.02 / 0.04 / 0.93 and 0.04 / 0.06 / 0.78 | ERROR |
+| + the same spheres at strength 320 (white blobs) | 0.09 / 0.10 / 0.08 | 0.09 / 0.11 / 0.38 | ERROR on the eye camera still |
+| + spheres at strength 8 AND two 45 W practicals | 0.05 / 0.06 / 0.35 | 0.04 / 0.07 / 0.81 | ERROR |
+| + spheres at strength 8 AND two 500 W practicals | 0.14 / 0.16 / 0.08 | 0.12 / 0.17 / 0.38 | the eye camera passes; the overview rig is a dim-but-lit WARN |
+
+The low-key escape needs contrast: an evenly moonlit plane has `lum_std` far below 0.12 at every
+moon strength and fails as unlit however blue it is. Practicals create the contrast; what they
+need is energy — hundreds of watts a lamp a few metres up, over a ground that is not black. An
+emissive fixture is not that lamp: its strength decides how the fixture looks, and the frame's
+mean barely moves until the fixture is a white blob, which the judge grades as blown.
+
+```python
+from lib import lighting, materials, sky
+
+def build_env(ctx): # a lantern-lit night
+ sky.night_world(ctx.scene, color=<deep blue hex>, strength=<low>)
+ lighting.sun(ctx.collection, azimuth_deg=<behind the hero>, elevation_deg=<low>, color=<cool hex>,
+ energy=<a fraction of one>, name="Moon")
+ sky.haze(ctx.collection, <centre>, <size>, density=<thin>, color=<the sky colour>)
+ ...
+
+# in a zone: each fixture is a look (emissive) AND a light (practical)
+mat = materials.emissive("LanternGlow", <warm hex>, <modest strength>)
+lighting.practical(ctx.collection, "LanternLight_0", (x, y, z), color=<warm hex>,
+ energy=<hundreds of watts>, size=<the fixture's size>, target=<the ground below it>)
+```
+
+## 5. Interiors
+
+A closed 6 m x 6 m x 3 m room (walls a = 0.6, floor a = 0.3, a table and a crate), one 1 m square
+area lamp at the ceiling, an eye-level camera inside:
+
+| lamp | `mean_lum` | `modal_frac` |
+|---|---|---|
+| 50 W | 0.34 | 0.45 |
+| 200 W | 0.61 | 0.60 |
+| 800 W | 0.82 | 0.85 |
+| 3000 W | 0.94 | 0.89 |
+
+Interiors need tens to hundreds of watts per lamp, and the failure mode above a few hundred is the
+flat band (one pale tone), not clipping — AgX refused to blow out even the 3000 W room.
+
+```python
+from lib import architecture, lighting
+
+def build_env(ctx): # a lit room
+ walls = architecture.room_shell(ctx.collection, <wall material>, center=<c>, extents=<e>, openings=<...>)
+ lighting.area_light(ctx.collection, "Ceiling_0", (<cx>, <cy>, <just under the ceiling>), <warm white hex>,
+ <tens to hundreds of watts>, size=<about a metre>, target=(<cx>, <cy>, 0.0), shape="SQUARE")
+ ...
+```
+
+## 6. The check
+
+`scene_views(cameras="all", times=[0.0])` writes `camera_checks` with the five statistics per
+camera, authored and rig. Read them; then change one dial at a time.
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-materials/SKILL.md b/harness/codeverse3d/skills/c3d-bpy-scene-materials/SKILL.md
new file mode 100644
index 00000000..e8c6fcce
--- /dev/null
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-materials/SKILL.md
@@ -0,0 +1,114 @@
+---
+name: c3d-bpy-scene-materials
+description: "Use in every scene_blender env, zone, asset or refine session that authors a surface — ground, walls, props, foliage, water, glass, a glowing sign. Cycles renders every node you wire, but the harness's census reads only three Principled sockets, so no gate rewards material work and the judge penalises the lack of it. Gives the Blender 5.2 node facts (no use_nodes, the 4.x socket names, ShaderNodeMix), the lib.materials recipes, variation across copies without identical twins, ground layering and the seam under props, water, glass and emissive done as dielectrics and fixtures, and what to zoom on before you finish."
+license: Apache-2.0
+compatibility: Blender 5.2.2 LTS headless, scene_blender runtime; Cycles 32 samples + OIDN under AgX (the harness's render settings), Principled BSDF 4.x socket names.
+metadata:
+ evidence: mixed
+ evidence_note: 'The census facts are read from live code on 2026-10-14 (wrappers/_census_glb.py, wrappers/_census.py, the languages/blender lint tables verified against Blender 5.2.2 LTS) and the defect wording from the scene judge rubric; the recipes restate the scene_blender starter library. The corpus half is empty: zero graded scene_blender runs exist on 2026-10-14; the first loop iteration attaches numbers.'
+ verified: "2026-10-14"
+ target_metric: "flat_principled_materials"
+ target_direction: "down"
+ target_unit: "materials whose Base Color, Roughness and Metallic are all unlinked constants (prospective census)"
+ target_measurable: "false"
+ target_baseline: "n=0 — no graded scene_blender runs yet (2026-10-14); the first loop iteration attaches numbers once the census records the count"
+---
+
+# Surfaces that read as a place — Principled recipes the census cannot see
+
+## Who sees what
+
+The judge sees Cycles pixels: every noise texture, bump and vertex colour you wire is in the
+picture, and the rubric names the failures directly — `placeholder_material` (default-grey or
+untextured flat surfaces, with a score ceiling of its own), `flat_ground` (one flat colour with
+a hard undressed seam where objects meet it) and `monotonous_vegetation` (one shape stamped many
+times with no variation in hue or size) — under its `materials_shaders_effects` criterion. The
+deterministic side sees almost nothing: the census GLB the gates read carries each material's Principled `Base Color`,
+`Metallic` and `Roughness` default values only, and a LINKED socket exports as its default. So
+no gate measures material work; this sheet is about the judge's picture, plus the one census
+fact that does bite — a mesh with no material at all is warned as exporting grey.
+
+## Blender 5.2 facts the lint checks
+
+* `bpy.data.materials.new(name)` already carries a node tree with a Principled BSDF: reach into
+ `mat.node_tree.nodes["Principled BSDF"]`. A `use_nodes` line is not needed, and the lint
+ reports it as deprecated.
+* Socket names are the 4.x ones — `Base Color`, `Roughness`, `Metallic`, `IOR`, `Alpha`,
+ `Normal`, `Emission Color` plus `Emission Strength`, `Transmission Weight`, `Coat Weight`,
+ `Sheen Weight`, `Subsurface Weight`, `Specular IOR Level`. Never write the old `Specular`,
+ `Transmission`, `Emission`, `Subsurface` or `Clearcoat` keys: they raise, and the lint names the
+ renamed ones for you. `Specular Tint` is a colour, so assign a 4-tuple.
+* Mixing colours is `ShaderNodeMix` with its data type set to RGBA (`Factor`, `A`, `B` in,
+ `Result` out), not `ShaderNodeMixRGB`, which is gone.
+* Per-face materials: set `material_index` on the bmesh faces BEFORE `bm.to_mesh`. Every new
+ polygon starts on slot 0, and the census warns about slots no polygon uses — the part was
+ authored in four colours and exports in one.
+
+## The recipes — `lib.materials` first
+
+Every call takes a name and returns a material; colours are sRGB hex strings (`rgba` decodes
+them to linear). Procedural detail reads OBJECT coordinates, so `noise_scale` is features per
+metre whatever the object's size, and the lib's own band for a non-emissive albedo is 0.02-0.8
+linear: pure black reads as a hole, pure white as a blown surface.
+
+| want | call |
+|---|---|
+| any surface with value variance | `material(name, color, roughness=..., metal=..., noise_scale=..., bump=..., emission=...)` — a `noise_scale` above zero is the low-contrast map every large surface needs |
+| stone, brick, plaster | `masonry(name, color, mortar=..., scale=...)`, `limestone(name, color, scale=...)`, `ashlar(name, color)`, `mineral_surface(name, color, stone=...)` |
+| wood | `woodgrain(mat, dark=..., light=..., direction=...)` on an existing material |
+| worn paint, used metal | `chipped_paint(mat, paint, substrate, scale=...)`, `worn_alloy(name, color, seed=..., metal=...)` |
+| foliage, snow, ice | `foliage(name, color, variants=3)` returns a LIST of variant materials; `snow(name)`, `ice(name)` |
+| water | `water(name, color=..., roughness=..., scale=..., flow=..., ctx=ctx)` for a tinted, moving surface; `clear_water(name)` for shallow, almost colourless water (a basin, a bowl, a stream) |
+| glass | `glass(name, color=..., roughness=..., ior=...)` |
+| a glowing fixture | `emissive(name, color, strength)` — the look only; the light is a `practical` lamp (c3d-bpy-scene-lighting) |
+| a copy that is not a twin | `tint(mat, variant)` — a copy with its Base Color shifted, one per VARIANT and shared by that variant's copies; it leaves a LINKED Base Color alone, so a noise-mapped material gets its variant from `material` called with another colour |
+
+## Variation without twins
+
+Collection instances share the source collection's materials, so per-instance tinting is not
+"edit the material". Variation across copies comes from (a) several SOURCE variants —
+`build_<snake>(ctx, variant=k)` picking a different `foliage` entry or `tint` — placed in
+rotation, (b) per-instance scale and yaw from `lib.scatter.scatter`, and (c) for one material
+over many copies, an Object Info node's `Random` output driving a hue shift, which Cycles
+evaluates per instance. The `stamped_ring` plan check measures rings of identical copies at one
+radius, and the judge calls the result monotonous vegetation.
+
+## Ground: layers, not a colour
+
+`lib.terrain.ground` takes ONE material; make it earn its area. `mineral_surface` or
+`material(..., noise_scale=...)` as the base, a second colour mixed in by slope (the Geometry
+node's `Normal`, its Z through a ColorRamp into the mix factor) and by height (object Z from
+Texture Coordinate) — grass to earth to rock — plus a worn band as a noise-masked third colour
+where the plan's paths run. The seam under a building is `flat_ground`'s own wording: a darker,
+rougher band of ground tint under big structures, and ground cover (`gn_scatter`, `grass_patch`)
+along their feet. A colour attribute on the ground mesh read by a Color Attribute node does the
+same job when the bands are easier to paint per vertex than to compute per pixel.
+
+## Water, glass, fog — dielectrics and volumes
+
+* Water is a dielectric: `water` and `clear_water` set transmission, a low roughness and
+ `Metallic` at zero — never a metallic mirror plane. Moving water scrolls its mapping node on
+ `ctx.frame(t)` through `lib.motion.scroll`, which is why `water(..., ctx=ctx)` wants the context.
+* Glass is `glass`: full `Transmission Weight`, low roughness, the lib's default IOR. The bounce
+ budget is the harness's, so a stack of transmissive layers along one sight line goes dark —
+ keep it to one or two.
+* Fog is a VOLUME-ONLY material on a box (`lib.sky.haze`): only the Material Output's Volume
+ socket linked. A box with a surface shader as well is matter to the census — a huge placed
+ asset enclosing everything — and the `no_fog` check does not count it as atmosphere.
+
+## Emissive and metal under AgX
+
+AgX desaturates bright emitters toward white: a saturated sign needs a modest
+`Emission Strength` and a coloured `practical` lamp beside it for the glow on the ground. Metals
+need something to reflect — the sky world and the haze are what `worn_alloy` mirrors; a metal
+under a black world is a black shape.
+
+## Verify before you finish
+
+`scene_views(cameras="authored", times=[0.0])` and zoom one frame: a wall or a ground that is one
+flat value needs `noise_scale`; two copies you cannot tell apart need variants; a grey default is
+a mesh that never got a material (the build output warns about it by name). Then `scene_probe`
+for triangle counts — materials are free, geometry is not.
+
+Node snippets — noise to bump, the slope mix, the Object Info tint, per-face slots, the
+volume-only box, the socket rename table — in `references/principled-recipes.md`.
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-materials/references/principled-recipes.md b/harness/codeverse3d/skills/c3d-bpy-scene-materials/references/principled-recipes.md
new file mode 100644
index 00000000..71758138
--- /dev/null
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-materials/references/principled-recipes.md
@@ -0,0 +1,114 @@
+# Principled recipes — the node snippets
+
+Companion to `c3d-bpy-scene-materials`. Socket names and node ids verified against Blender
+5.2.2 LTS on 2026-10-14 (`codeverse3d/languages/blender/__init__.py` keeps the rename table the
+lint reports from). Every snippet assumes `mat = bpy.data.materials.new(name)` and
+`nodes, links = mat.node_tree.nodes, mat.node_tree.links`, `bsdf = nodes["Principled BSDF"]`.
+Prefer the `lib.materials` call that does the same thing; write nodes only for what no call covers.
+
+## 1. Socket renames the lint reports
+
+| old key (raises) | 4.x / 5.x key |
+|---|---|
+| `Specular` | `Specular IOR Level` |
+| `Subsurface` | `Subsurface Weight` |
+| `Subsurface Color` | folded into `Base Color` |
+| `Transmission` | `Transmission Weight` |
+| `Transmission Roughness` | removed — use `Roughness` |
+| `Emission` | `Emission Color`, with `Emission Strength` |
+| `Clearcoat` | `Coat Weight` |
+| `Sheen` | `Sheen Weight` |
+
+`Specular Tint` and `Anisotropic` still exist; `Specular Tint` is an RGBA colour.
+
+## 2. Value variance: noise into colour and bump
+
+```python
+noise = nodes.new("ShaderNodeTexNoise")
+noise.inputs["Scale"].default_value = <texels per metre: 2-5 cm at walking distance>
+noise.inputs["Detail"].default_value = 6.0
+mix = nodes.new("ShaderNodeMix")
+mix.data_type = "RGBA"
+mix.inputs["A"].default_value = (<r>, <g>, <b>, 1.0) # the base colour
+mix.inputs["B"].default_value = (<r2>, <g2>, <b2>, 1.0) # a few percent darker or warmer
+links.new(noise.outputs["Fac"], mix.inputs["Factor"])
+links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])
+bump = nodes.new("ShaderNodeBump")
+bump.inputs["Strength"].default_value = <0.05-0.15 for stone and plaster>
+links.new(noise.outputs["Fac"], bump.inputs["Height"])
+links.new(bump.outputs["Normal"], bsdf.inputs["Normal"])
+```
+
+`lib.materials.material(name, color, noise_scale=..., bump=...)` wires exactly this; roughness
+variation is the same noise into `Roughness` through a Map Range node.
+
+## 3. Ground bands by slope and height
+
+```python
+geo = nodes.new("ShaderNodeNewGeometry")
+sep = nodes.new("ShaderNodeSeparateXYZ")
+links.new(geo.outputs["Normal"], sep.inputs["Vector"])
+ramp = nodes.new("ShaderNodeValToRGB") # a ColorRamp: slope -> 0..1
+ramp.color_ramp.elements[0].position = <cos of the rock angle, e.g. 0.65>
+ramp.color_ramp.elements[1].position = <a few hundredths higher: a soft edge>
+links.new(sep.outputs["Z"], ramp.inputs["Fac"])
+mix = nodes.new("ShaderNodeMix")
+mix.data_type = "RGBA"
+links.new(ramp.outputs["Color"], mix.inputs["Factor"])
+links.new(<rock colour node>.outputs["Result"], mix.inputs["A"])
+links.new(<grass colour node>.outputs["Result"], mix.inputs["B"])
+links.new(mix.outputs["Result"], bsdf.inputs["Base Color"])
+```
+
+Height bands use the Object output of a Texture Coordinate node, Z through a second ramp.
+A worn path is a third colour masked by a low-frequency noise sampled along the path's polyline.
+
+## 4. One material, many copies: the Object Info tint
+
+```python
+info = nodes.new("ShaderNodeObjectInfo")
+hsv = nodes.new("ShaderNodeHueSaturation")
+links.new(info.outputs["Random"], hsv.inputs["Hue"]) # 0..1 per object / instance
+hsv.inputs["Saturation"].default_value = 1.0
+links.new(<colour node>.outputs["Result"], hsv.inputs["Color"])
+links.new(hsv.outputs["Color"], bsdf.inputs["Base Color"])
+```
+
+`Random` differs per instance in Cycles, so the shrubs placed from one source collection no
+longer match; keep the hue swing small (a Map Range from `Random` into a narrow band around
+0.5) or the copies look like different species.
+
+## 5. Per-face slots, before `bm.to_mesh`
+
+```python
+me.materials.append(stone) # slot 0
+me.materials.append(moss) # slot 1
+for f in bm.faces:
+ f.material_index = 1 if f.normal.z > 0.7 else 0
+bm.to_mesh(me)
+```
+
+The census reports a slot no polygon uses; assigning after `bm.to_mesh` goes through
+`me.polygons` instead.
+
+## 6. The volume-only box (fog the census recognises)
+
+```python
+mat = bpy.data.materials.new("Haze")
+nodes, links = mat.node_tree.nodes, mat.node_tree.links
+nodes.remove(nodes["Principled BSDF"]) # no surface shader at all
+vol = nodes.new("ShaderNodeVolumePrincipled")
+vol.inputs["Density"].default_value = <0.002-0.02>
+links.new(vol.outputs["Volume"], nodes["Material Output"].inputs["Volume"])
+```
+
+`lib.sky.haze(collection, loc, size, density=..., color=...)` builds this on a box sized to the
+play area. Leave the Surface socket unlinked: a box with both is a placed asset to the gate.
+
+## 7. Water and glass, as the lib sets them
+
+| material | the sockets that matter |
+|---|---|
+| `water` / `clear_water` | `Transmission Weight` at one, `Roughness` low, `Metallic` zero, a bump from scrolled noise; the plane is named with a water word so feet on it count as on water |
+| `glass` | `Transmission Weight` at one, `Roughness` near zero, `IOR` the lib's default; thin panes as single faces with a Solidify-free thickness read best at 32 samples |
+| `emissive` | `Emission Color` and a modest `Emission Strength`; the illumination is a `practical` lamp |
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md b/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md
new file mode 100644
index 00000000..f2229017
--- /dev/null
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md
@@ -0,0 +1,138 @@
+---
+name: c3d-bpy-scene-placement
+description: "Use in every scene_blender env, zone, refine or rebuild session that places anything, and whenever check_placement or the scene_placement gate reported a floating, sunken, unsupported, interpenetrating or cantilevered asset, or too many free-tagged ones. Everything placed is ONE row in a measured table and its feet are sampled against what is under them. Gives what the gate measures and on which geometry, how a collection instance differs from a geometry-nodes cloud, the lib.place calls that seat a thing the way the gate samples it, the self-check to run before the build, and the finding-to-fix table."
+license: Apache-2.0
+compatibility: Blender 5.2.2 LTS headless, scene_blender runtime; the gate measures the harness-written census GLB (the evaluated depsgraph), never the .blend.
+metadata:
+ evidence: mixed
+ evidence_note: 'The instrument half is read from live code on 2026-10-14 (spatial/scene_placement.py, runtime_js/lib/host_placement.mjs, config.Placement, wrappers/_census_glb.py) and the lib calls from the scene_blender starter library. The corpus half is empty: zero gated scene_blender runs exist on 2026-10-14; the first loop iteration attaches numbers.'
+ verified: "2026-10-14"
+ target_metric: "bpy_placement_errors"
+ target_direction: "down"
+ target_unit: "ERROR findings per run"
+ target_measurable: "true"
+ target_baseline: "n=0 — no gated scene_blender runs yet (2026-10-14); measured on the first loop iteration"
+---
+
+# Everything sits on something — placement the gate can measure
+
+**Read this if** you are writing a zone, the env, or fixing a `check_placement` finding. The
+placement gate is deterministic and strict (the 2026-10-14 standards: a hand's breadth of hover
+is an ERROR), every ERROR is a score ceiling in the scene rubric, and the judge is handed a
+close-up crop of each measured finding — a hover that is invisible in an overview is graded at
+full size.
+
+## What is measured, and on what
+
+The build writes a census GLB from the evaluated depsgraph (modifiers, geometry nodes and
+instances included) and the gate reads that, never the `.blend`. A **placed thing** is every
+direct child of a zone collection that has mesh descendants, and each one is ONE row:
+
+| what you build | rows | measured |
+|---|---|---|
+| a mesh object, with or without children | 1 — the whole subtree | yes |
+| a collection-instance Empty (`lib.scatter.instance`) | 1 per placed copy | yes — its clones are sampled like a mesh |
+| a multi-part prop finished under one root Empty (`Batch.finish`, `parent_under`) | 1 | yes |
+| twelve loose meshes that together are a hut | 12 | yes, each at its own feet: the roof floats |
+| a geometry-nodes or particle cloud (`gn_scatter`, `grass_patch`) | 1, exempt as instanced | no — and never a support either |
+| a volume-only mesh (`lib.sky.haze`) | exempt as volumetric | no, and never a support or an overlap partner |
+| ground, water and sky by name and shape; a shell that swallows the content box | exempt as backdrop or enclosure | no |
+| anything tagged `obj["placement"] = "free"`, or its whole zone collection | exempt as free | no — but counted, see below |
+
+Per row, from up to 5 **foot columns** taken from its lowest vertices — a table is measured at
+its leg tips, not under its top:
+
+* `ground_gap_m` — the vertical distance from the foot to the nearest surface of any OTHER mesh
+ below it (terrain, floor, table top), else to the census ground level.
+* `sunk_m` — how far a foot sits below a surface that passes through the asset's own extent.
+* `on_water` — a water-named surface at or above the foot: supported, never sunk.
+* `attached` — another asset's box within contact distance: mounted, so a small gap is left alone.
+* `gap_max_m`, `columns_resting`, `tilt_m` — how many columns rest and how far the worst one hangs.
+
+The kinds the report names, worst first: `floating` (a gap above the indoor or outdoor
+tolerance; ERROR when it passes `floating_error_m` or when more than `floating_error_count`
+assets float), `unsupported` (a smaller gap, touching nothing: WARN), `sunken` (burial past
+`sunk_m`; ERROR past `sunk_error_m` when it also swallows `sunk_error_frac` of the height),
+`interpenetration` (two boxes overlapping more than `overlap_warn` of the smaller one, confirmed by
+`inside_frac` of its vertices inside the other; ERROR past `overlap_error`), `cantilevered` (at
+most one of four or more columns rests while the worst one hangs: WARN) and `free_exempt` (the
+share of free-tagged assets past `free_exempt_warn`, then `free_exempt_error`). Every threshold
+is a `Settings.placement` field and the summary line of `check_placement` prints the values it
+used; this sheet does not restate them. Interiors get the tighter tolerance, and the plan's
+setting words decide that (`is_interior`), not your zone.
+
+Three exemptions are by NAME (`placement_words.json`, one file read by the gate and by the
+boot-time settle): `buried_ok` words (pit, pool, well, trench) are never sunken; `slope_ok` words
+(path, platform, stairs, terrace) follow the terrain; `partial_ok` words (rock, tree, post, fence,
+pebble) may sink up to `partial_ok_frac` of their height. Name things what they are and the gate
+already knows how they sit. Renaming a bench "Rock" to dodge the check is pointless: the judge
+grades the crop.
+
+## Build so the rows come out right
+
+1. **One height authority.** `height_at(x, y)` in `src/env.py` is the ground: build it with
+ `lib.terrain.make_height_at`, let `lib.terrain.ground` mesh it, and let every zone read
+ `ctx.height_at`. A zone that flattens its own patch to zero is how a bench ends up buried on
+ one side and floating on the other.
+2. **Seat with the lib, not by eye.** `lib.place.seat(obj, ctx.height_at, sink=...)` samples the
+ same foot columns the gate does and returns the move it made. A placed copy of an asset is
+ `lib.scatter.instance(ctx.collection, ctx.assets["<snake>"], name, x, y, height_at=ctx.height_at, rot_z=..., scale=..., sink=...)`
+ — one Empty, already seated (an instance Empty you built yourself: `lib.place.seat_instance`).
+ A thing ON a thing — a cup on a table, a lantern on a post — is `lib.place.rest_on(obj, support)`:
+ the gate measures the gap to the SUPPORT, and `ctx.height_at` would drop it through the table.
+ Every `lib.place` call reads the point set the gate measures — the object, its children and,
+ for an instance Empty, the source collection under the Empty's transform — so pass the root.
+3. **Sink only what sinks.** `sink` is for things whose name says they sink — a rock, a post, a
+ tree with modelled roots; the words file tolerates those. A crate sunk "so it cannot float" is
+ a `sunken` finding and a crop of a crate in the ground.
+4. **Slopes.** `seat` rests the foot that stands over the lowest ground and buries the rest, so
+ a wide thing on a slope comes back `sunken` on its uphill side; placing a thing at the ground
+ height of its CENTRE instead (`height_at` of one point, the old skeleton's way) leaves the
+ downhill feet hanging, which is the `cantilevered` finding. For wide things on a slope, flatten
+ a pad in `height_at` under them (the ground mesh follows), split a long wall into segments each
+ seated with `seat`, or turn it along the contour with `lib.place.face_toward`.
+5. **A prop is one row.** Build its parts in one `lib.mesh.Batch` and `Batch.finish(ctx.collection, parent=True)`:
+ ONE root Empty, one row, one seat. Twelve loose meshes are twelve rows with twelve chances to
+ float, and twelve overlap partners for each other.
+6. **Copies vs clouds.** Things the brief counts — props, trees near a camera, figures — are
+ collection instances (`lib.scatter.instance`, `lib.scatter.scatter`): each is a row, each
+ seated. Ground cover — grass, pebbles, leaves — is `gn_scatter` or `grass_patch`: exempt,
+ cheap, never a support. Do not scatter benches with `gn_scatter` to escape the gate: the
+ plan-contents check counts instances either way and the judge still sees a floating bench.
+7. **`free` is for hanging and airborne things only** — a bird, a kite, a lantern on a chain, a
+ drone. The gate reports the share of free-tagged assets (`free_exempt`), and the judge's
+ floating defect still sees a free-tagged crate in the air.
+8. **Stay inside.** `lib.place.keep_inside(obj, bbox)` with the zone's plan box as (centre,
+ extents) slides it back horizontally. A thing entirely outside the plan bounds is the
+ `out_of_bounds` kind, and one far from its planned `approx_size_m` is the `scale` kind — both
+ target the zone, and the fix for the second is the SOURCE asset's build, not the Empties.
+9. **Names are global in Blender.** `lib.place.unique_name(base, i)`; a second `Lantern_0` in
+ another zone becomes `Lantern_0.001` and the plan-contents check loses it.
+
+## The self-check, then the gate
+
+Before the build, `lib.place.clear_of(objs)` lists the pairs whose boxes overlap past the gate's
+own interpenetration band, as (name, name, fraction) — run it over the zone's root objects and
+fix every pair it names (move, shrink, or make the two ONE prop). Then `build`, then
+`check_placement`, which prints the findings with their fix hints and the table behind them:
+
+```
+asset | gap to support (m) | support | sunk (m) | into | water | attached
+Market/Bench_0 | +0.236 | Terrain | 0.000 | - | - | -
+interpenetration Market/Cart_1 × Market/Stall_0: 41% box, 23% inside
+```
+
+Apply the hint's number literally — `lower Bench_0 by 0.24 m onto Terrain` means `seat` it,
+not "move it down a bit" — then `build` again. Do not finish a round whose last
+`check_placement` still lists an ERROR: the rubric caps the run on each one, and a PASSED gate is
+what vetoes the judge's own floating claim.
+
+## Motion does not excuse the feet
+
+The census is taken at the build's current frame, so a moving thing must be seated at every time
+the harness samples. Keep a swaying tree's origin at its base (it rotates about its feet), drift
+a boat ON water (`on_water` makes it supported), and let a bird be free. Keyframes go through
+`lib.motion` on `ctx.frame(t)`; never move an object by shifting its mesh data after seating it.
+
+Worked zone, where the rows come from in the census GLB, and the finding-to-fix table:
+`references/finding-to-fix.md`.
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-placement/references/finding-to-fix.md b/harness/codeverse3d/skills/c3d-bpy-scene-placement/references/finding-to-fix.md
new file mode 100644
index 00000000..ac75c865
--- /dev/null
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-placement/references/finding-to-fix.md
@@ -0,0 +1,82 @@
+# Finding to fix, where rows come from, and a worked zone
+
+Companion to `c3d-bpy-scene-placement`. Read against `codeverse3d/spatial/scene_placement.py`,
+`runtime_js/lib/host_placement.mjs`, `codeverse3d/languages/wrappers/_census_glb.py` and the
+`Placement` section of `codeverse3d/config.py` on 2026-10-14. The lib calls are the scene_blender
+starter's (`src/lib/`, harness-owned: call it, never edit it).
+
+## 1. Finding to fix
+
+| kind, and what the line says | severity | it means | do this |
+|---|---|---|---|
+| `floating` — `X is floating 0.24 m above Terrain (touches nothing)` | WARN; ERROR past `floating_error_m`, or when more than `floating_error_count` assets float | the lowest foot column hangs in the air | `lib.place.seat(obj, ctx.height_at)`, or `lib.place.rest_on(obj, support)` for a thing on a thing; the printed number IS the gap |
+| `unsupported` — `X is unsupported: hovers 0.03 m above Terrain and touches nothing` | WARN | off the contact tolerance but inside the floating band | `seat` it; if it really hangs, tag it `obj["placement"] = "free"` |
+| `sunken` — `X is sunken 0.31 m into Terrain` | WARN; ERROR past `sunk_error_m` when the burial also passes `sunk_error_frac` of the height | a foot column sits below the surface | raise it by the number, drop its `sink`, or — only if it is driven or grown in — give it a `partial_ok` name |
+| `interpenetration` — `A and B overlap (41% of the smaller box; 23% of its vertices inside the other)` | WARN past `overlap_warn`, ERROR past `overlap_error` | two rows share volume | move the smaller one out, shrink one, or make them ONE prop (`lib.mesh.parent_under`, or one `Batch`) so there is one row |
+| `cantilevered` — one column rests, the worst one hangs | WARN | a thing placed at its centre's ground height on a slope or a bump: the downhill feet hang | `seat` it (the lowest ground wins, the rest sink), then flatten a pad in `height_at`, split it into seated segments, or turn it along the contour |
+| `free_exempt` — too many assets tagged free | WARN past `free_exempt_warn`, ERROR past `free_exempt_error` | the tag is hiding things from the gate | untag everything that stands; `free` is for hanging and airborne things only |
+| `scale` — `each of the 6 lantern instances in Square/Lanterns measures 2.80 m but the plan sized lantern at ~0.60 m (4.7x)` | WARN, ERROR by factor | the asset is built at the wrong size | scale the SOURCE collection's build, not the Empties |
+| `out_of_bounds` — `X sits entirely outside the plan bounds` | ERROR | wrong coordinates | `lib.place.keep_inside(obj, bbox)` with the zone bbox |
+| `truncated` — `… and 4 more floating finding(s) not listed` | INFO | the report keeps the worst 8 per kind | fix the listed ones, rebuild, read the next batch |
+
+The table under the findings stops at 400 assets or after 4 s of sampling and says so; a scene
+that hits either limit has more placed rows than a judge can read anyway — merge props and move
+ground cover to `gn_scatter`.
+
+## 2. Where a row comes from
+
+The census GLB writer walks the evaluated depsgraph; the placement table reads the GLB:
+
+* a collection-instance Empty becomes one node whose children are the instanced meshes — one
+ clone per placed copy, so each copy is a row sampled at its own feet;
+* a mesh with children is its own group: the subtree is one row;
+* any other instance cloud (geometry nodes, particles, dupli-verts) becomes one gpu-instancing
+ node per source mesh — an `InstancedMesh` to the gate, counted as instances and exempt from
+ per-asset placement, and never a support;
+* custom properties of plain value travel as node extras, which is how `obj["placement"] = "free"`
+ reaches the gate; a property on the zone's collection exempts the whole zone;
+* an object whose every material is volume-only is fog: not indexed, not a support, not an
+ overlap partner, and the `no_fog` check counts it as atmosphere.
+
+Supports are the OTHER rows' meshes plus the terrain and floors: a lantern resting on a post is
+measured to the post, a crate on a jetty to the jetty, a boat on a water-named plane is on water.
+
+`seat`, `seat_instance`, `rest_on`, `clear_of`, `keep_inside` and `bbox_world` all read the same
+point set the gate measures — an object's own geometry, its children's and, for a collection
+instance, the source collection's under the Empty's transform — so an instance Empty is a valid
+argument to every one of them, and the root of a finished prop is the thing to seat.
+
+## 3. A worked zone
+
+```python
+from lib import place, scatter
+
+def build(ctx):
+ rng, h = ctx.rng(11), ctx.height_at
+ bench = scatter.instance(ctx.collection, ctx.assets["bench"], place.unique_name("Bench", 0),
+ 3.0, -2.0, height_at=h, rot_z=0.4) # one Empty, seated: ONE row
+ pts = scatter.poisson(rng, area=(<x0>, <y0>, <x1>, <y1>), min_dist=2.5, max_count=12) # the zone's plan box
+ for i, (x, y) in enumerate(pts):
+ scatter.instance(ctx.collection, ctx.assets["shrub"], place.unique_name("Shrub", i), x, y,
+ height_at=h, rot_z=rng.uniform(0.0, 6.28), scale=rng.uniform(0.8, 1.2), sink=0.03)
+ lantern = <a lib.mesh prop built in this zone, finished under one root> # a mesh root: one row
+ place.rest_on(lantern, bench) # measured to the BENCH
+ kite = <a lib.mesh prop>
+ kite.location.z += 4.0
+ kite["placement"] = "free" # airborne by design
+ for a, b, frac in place.clear_of([o for o in ctx.collection.objects if o.parent is None]):
+ print("overlap before build:", a, b, frac) # fix every pair it names
+ return ctx.collection
+```
+
+`Shrub` carries a `partial_ok` word, so its small `sink` is accepted; the bench, the lantern and
+the kite carry no such word and are measured as they stand.
+
+## 4. The loop
+
+```
+build -> check_placement -> fix every ERROR, then the deepest WARN -> build
+```
+
+`check_placement` reads the census of the last build; pass `rebuild=true` only when you doubt
+that census. Never finish a round on an ERROR.
diff --git a/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md b/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md
index 3daba175..ff4cfbe2 100644
--- a/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md
@@ -5,7 +5,7 @@ license: Apache-2.0
compatibility: track scene, language scene_threejs (three r182, headless Chrome, the harness builds the cameras from your plain camera objects).
metadata:
evidence: mixed
- evidence_note: "Camera checks, score caps and the backdrop classifier are read from live code (spatial/frame_metrics.py, judges/rubrics/scene_v1.yaml, runtime_js/lib/backdrop.mjs, runtime_js/lib/scene_host.mjs). The corpus behind them is thin: only 3 graded scene runs exist, so every count below names its n."
+ evidence_note: "Camera checks, score caps and the backdrop classifier are read from live code (spatial/frame_metrics.py, judges/rubrics/scene_v2.yaml, runtime_js/lib/backdrop.mjs, runtime_js/lib/scene_host.mjs). The corpus behind them is thin: only 3 graded scene runs exist, so every count below names its n."
verified: "2026-08-25"
corpus: "3 graded scene_threejs runs with gate artefacts, mined 2026-08-25"
target_metric: "camera_placement_findings"
@@ -62,7 +62,7 @@ Three consequences you must design around:
## Cameras are measured, and the numbers are hard
`codeverse3d/spatial/frame_metrics.py` runs on the authored cameras, where every finding is an
-**ERROR** (the harness's own orbit rig only gets WARNs). `judges/rubrics/scene_v1.yaml`
+**ERROR** (the harness's own orbit rig only gets WARNs). `judges/rubrics/scene_v2.yaml`
turns those ERRORs into score ceilings:
| condition | constant | finding | cap on the run |
diff --git a/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md b/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md
index 746a5195..69ca4ff5 100644
--- a/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md
+++ b/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md
@@ -1,7 +1,7 @@
# From bounds to cameras, by arithmetic
Companion to `c3d-scene-composition`. Constants read from
-`codeverse3d/spatial/frame_metrics.py`, `codeverse3d/judges/rubrics/scene_v1.yaml`,
+`codeverse3d/spatial/frame_metrics.py`, `codeverse3d/judges/rubrics/scene_v2.yaml`,
`runtime_js/lib/backdrop.mjs`, `runtime_js/lib/host_census.mjs` and
`runtime_js/lib/scene_host.mjs` on 2026-08-25.
diff --git a/harness/codeverse3d/skills/materialize.py b/harness/codeverse3d/skills/materialize.py
index af23b3c5..15a80ada 100644
--- a/harness/codeverse3d/skills/materialize.py
+++ b/harness/codeverse3d/skills/materialize.py
@@ -41,6 +41,7 @@ from pathlib import Path
from typing import Any
from codeverse3d.config import get_settings
+from codeverse3d.prompts.variants import active_variant
from codeverse3d.skills.model import Selection, Skill, SkillsMaterialized
from codeverse3d.skills.prompting import (
AGENTS_SKILL_ROOT,
@@ -49,7 +50,7 @@ from codeverse3d.skills.prompting import (
index_tokens,
inline_body,
)
-from codeverse3d.skills.registry import plan_signals, select
+from codeverse3d.skills.registry import ROUTES, plan_signals, select
log = logging.getLogger(__name__)
@@ -198,14 +199,19 @@ def attach_skills(
if not library:
log.warning("C3D_SKILLS_ONLY=%s matches no bundle in the library; this session attaches nothing",
",".join(sorted(picked)))
+ # the active variant (D105): its overlay bundles are already in all_skills() (select's default
+ # library) and its routes.toml reshapes the table — extra rows after the base ones, boosts, disabled ids
+ variant = active_variant()
+ table = _routes_table(variant)
sel: list[Selection] = select(
track, language, kind,
signals=plan_signals(plan), findings=findings, library=library,
max_skills=cfg.skills_max if max_skills is None else max_skills,
allow_unverified=cfg.skills_unverified if allow_unverified is None else allow_unverified,
+ routes=(*ROUTES, *table.routes), boosts=table.boost_map, disabled=table.disabled,
)
out = SkillsMaterialized(listed=[s.name for s in sel], selections=list(sel),
- reasons={s.name: s.reason for s in sel}, attached_at=time.time())
+ reasons={s.name: s.reason for s in sel}, attached_at=time.time(), variant=variant)
if not sel or single_shot:
# an empty selection is a legal desired set: the sweep must still run, or last
# round's bundles stay live where the native CLIs discover skills by directory
@@ -235,5 +241,17 @@ def attach_skills(
return out
+def _routes_table(variant: str) -> Any:
+ """The variant's ``routes.toml`` as typed rows, or the empty table when it does not type-check: a
+ typo in the overlay costs the overlay (logged, base routing), never the round's skills."""
+ from codeverse3d.skills import VariantRoutes, variants_table
+
+ try:
+ return variants_table(variant)
+ except (ValueError, OSError) as e:
+ log.warning("variant %r: routes.toml rejected (%s); this session routes with the base table", variant, e)
+ return VariantRoutes(variant=variant)
+
+
__all__ = ["BODY_FILES", "CONTROL_NAME", "MARK_BEGIN", "MARK_END", "SKILL_ROOTS",
"attach_skills", "materialize_skills", "write_control", "write_index"]
diff --git a/harness/codeverse3d/skills/model.py b/harness/codeverse3d/skills/model.py
index bc560641..4879dcd9 100644
--- a/harness/codeverse3d/skills/model.py
+++ b/harness/codeverse3d/skills/model.py
@@ -98,6 +98,8 @@ class SkillsMaterialized(BaseModel):
inlined: str = Field(default="", description="single-shot: the one body inlined, '' otherwise")
attached_at: float = Field(default=0.0, description="epoch seconds of the attach: the read probe credits "
"only tool calls a CLI session logged after it (telemetry.probe_reads)")
+ variant: str = Field(default="", description="the prompt/skill variant active at the attach ('' = base; "
+ "D105) — its overlay bundles and routes.toml shaped `selections`")
# ===================================================================== loader
diff --git a/harness/codeverse3d/skills/registry.py b/harness/codeverse3d/skills/registry.py
index 090990b7..e5d8c60e 100644
--- a/harness/codeverse3d/skills/registry.py
+++ b/harness/codeverse3d/skills/registry.py
@@ -20,6 +20,7 @@ claim that a skill helps, and that claim needs evidence; most kinds have no row.
from __future__ import annotations
import logging
+from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any
@@ -50,6 +51,21 @@ SHADER_PREFLIGHT = "shader_preflight/*"
MOTION_WRONG_DIRECTION = "motion_direction/wrong_direction"
LINT = "lint/*"
LINT_PART_NOT_IMPORTED = f"lint/{LintKind.PART_NOT_IMPORTED.value}"
+#: the scene_placement gate's seating kinds (spatial/scene_placement.py; ``free_exempt`` and
+#: ``cantilevered`` are 2026-10-14's, D105). Its PLAN kinds (no_fog, no_backdrop, scale, zone_empty, …)
+#: are deliberately not here: they are env / composition findings, not seating.
+SCENE_PLACEMENT_FLOATING = "scene_placement/floating"
+SCENE_PLACEMENT_SUNKEN = "scene_placement/sunken"
+SCENE_PLACEMENT_UNSUPPORTED = "scene_placement/unsupported"
+SCENE_PLACEMENT_INTERPENETRATION = "scene_placement/interpenetration"
+SCENE_PLACEMENT_FREE_EXEMPT = "scene_placement/free_exempt"
+SCENE_PLACEMENT_CANTILEVERED = "scene_placement/cantilevered"
+#: the six seating kinds a placement row answers (a family pattern ``"scene_placement/*"`` would
+#: also attach the placement sheet to a no_fog or stamped_ring finding, which it cannot fix)
+SCENE_PLACEMENT_SEATING: tuple[str, ...] = (
+ SCENE_PLACEMENT_FLOATING, SCENE_PLACEMENT_SUNKEN, SCENE_PLACEMENT_UNSUPPORTED,
+ SCENE_PLACEMENT_INTERPENETRATION, SCENE_PLACEMENT_FREE_EXEMPT, SCENE_PLACEMENT_CANTILEVERED,
+)
def finding_kind(finding: Any) -> str | None:
@@ -94,6 +110,9 @@ def _iter_findings(obj: object):
OBJECT_TRACKS = ("static_object", "articulated_object")
BLENDER_LANGS = ("blender", "urdf_blender")
THREEJS_LANGS = ("scene_threejs", "threejs")
+BPY_SCENE_LANGS = ("scene_blender",)
+#: the scene track's session kinds (tracks/scene.py: env, zone, refine, rebuild; asset is quiet)
+BPY_SCENE_KINDS = ("env", "zone", "refine", "rebuild")
BUILD_KINDS = ("baseline", "part", "refine", "rebuild", "repair")
#: kinds that attach nothing on their own (design §5.2 law 4): short, narrow sessions the
#: corpus attaches no defect class to. A gate-fired row still reaches them.
@@ -214,6 +233,31 @@ ROUTES: tuple[Route, ...] = (
Route("R28", "c3d-scene-materials", 65, tracks=("scene",), languages=("scene_threejs",),
kinds=("baseline", "zone", "refine"),
why="flat albedo and identical twins are the reference audit's most-cited surface defects"),
+ # R29-R34 (2026-10-14, D105): the scene_blender bundles. Placement rides every build session
+ # because every placed thing is a measured row and the 2026-10-14 thresholds make a hand's
+ # breadth of hover an ERROR; lighting and materials ride the sessions that author light and
+ # surfaces. R34 is the three.js half of "a gate-fired route on scene_placement for both
+ # languages": composition's first rule is the one height function everything samples.
+ Route("R29", "c3d-bpy-scene-placement", 80, tracks=("scene",), languages=BPY_SCENE_LANGS, kinds=BPY_SCENE_KINDS,
+ why="every placed thing is a measured placement row, and the strict 2026-10-14 thresholds make a "
+ "hand's breadth of hover an ERROR with a score ceiling"),
+ Route("R30", "c3d-bpy-scene-placement", 95, tracks=("scene",), languages=BPY_SCENE_LANGS,
+ findings=SCENE_PLACEMENT_SEATING,
+ why="the previous round's placement gate found a floating, sunken, unsupported, interpenetrating or "
+ "cantilevered asset, or too many free-tagged ones"),
+ Route("R31", "c3d-bpy-scene-lighting", 65, tracks=("scene",), languages=BPY_SCENE_LANGS, kinds=BPY_SCENE_KINDS,
+ why="Cycles under AgX at exposure 0 with no exposure knob: lamp energy, world strength and albedo are "
+ "the only dials, and the frame gate measures both ends"),
+ Route("R32", "c3d-bpy-scene-lighting", 95, tracks=("scene",), languages=BPY_SCENE_LANGS,
+ findings=(SCENE_DARK, SCENE_FLAT, SCENE_BLOWN),
+ why="the frame gate called a Blender render dark, flat or blown out"),
+ Route("R33", "c3d-bpy-scene-materials", 65, tracks=("scene",), languages=BPY_SCENE_LANGS, kinds=BPY_SCENE_KINDS,
+ why="the census reads three Principled sockets and no gate rewards material work, so placeholder and "
+ "flat-ground defects are the judge's alone to penalise"),
+ Route("R34", "c3d-scene-composition", 95, tracks=("scene",), languages=("scene_threejs",),
+ findings=SCENE_PLACEMENT_SEATING,
+ why="the previous round's placement gate fired on a three.js scene: one height function everything "
+ "samples is the bundle's first rule"),
)
#: every skill the table can attach — the Author phase's contract for which bundles must exist
@@ -277,6 +321,30 @@ def _row_applies(row: Route, track: str, language: str, kind: str, signals: dict
return not (row.requires_any and not any(signals.get(k) for k in row.requires_any))
+#: the floor of a gate-fired row (design §5.2 law 2). ``model.Selection.gate_fired`` reads a priority
+#: >= 90 as "a gate routed this", so a variant boost may neither lift a standing row up to it nor
+#: drop a fired row under it — the table's meaning must survive the overlay
+GATE_FIRED_PRIORITY = 90
+
+
+def effective_priority(row: Route, boosts: Mapping[str, int]) -> int:
+ """``row.priority`` plus the variant's boost for its skill, clamped to the table's law: a standing
+ row stays below :data:`GATE_FIRED_PRIORITY` (a warning says it was clamped — the boost is too
+ big, not wrong), a gate-fired row never drops below it, nothing goes under 0."""
+ delta = int(boosts.get(row.skill, 0))
+ if not delta:
+ return row.priority
+ boosted = row.priority + delta
+ if row.gate_fired:
+ return max(GATE_FIRED_PRIORITY, boosted)
+ if boosted >= GATE_FIRED_PRIORITY:
+ log.warning("variant boost %+d lifts standing route %s (%s, priority %d) to %d: clamped to %d — a "
+ "standing row never outranks a gate-fired one", delta, row.rule, row.skill, row.priority,
+ boosted, GATE_FIRED_PRIORITY - 1)
+ return GATE_FIRED_PRIORITY - 1
+ return max(0, boosted)
+
+
def select(
track: str,
language: str,
@@ -287,23 +355,34 @@ def select(
library: dict[str, Skill] | None = None,
max_skills: int = 5,
allow_unverified: bool = False,
+ routes: Sequence[Route] = ROUTES,
+ boosts: Mapping[str, int] | None = None,
+ disabled: frozenset[str] = frozenset(),
) -> list[Selection]:
"""The routed bundles for one session, ranked, capped, each with its reason.
``findings`` may be ``GateFinding``s, ``GateReport``s, or already-classified kind
strings — the caller usually has the previous ``RoundRecord.gates`` on hand.
+
+ ``routes`` / ``boosts`` / ``disabled`` are a variant's reshaping of the table
+ (``skills.variants_table``): the rows to evaluate, in order (a variant's extra rows come after
+ the base ones, so ties keep the base order), a priority delta per skill
+ (:func:`effective_priority` clamps it) and the rule ids to skip.
"""
from codeverse3d.skills import all_skills
lib = library if library is not None else all_skills()
sig = dict(signals or {})
+ boost: Mapping[str, int] = boosts or {}
kinds = [f for f in findings if isinstance(f, str)] if findings else []
if findings and not kinds:
kinds = finding_kinds(findings)
best: dict[str, Selection] = {}
first_seen: dict[str, int] = {}
- for order, row in enumerate(ROUTES):
+ for order, row in enumerate(routes):
+ if row.rule in disabled:
+ continue
hit = row.matches_finding(kinds) if row.gate_fired else None
if row.gate_fired and hit is None:
continue
@@ -321,14 +400,16 @@ def select(
if skill.evidence == EVIDENCE_INHERITED and not allow_unverified:
log.debug("skill %s is %s and C3D_SKILLS_UNVERIFIED is off; not routed", skill.name, EVIDENCE_INHERITED)
continue
- reason = f"{row.rule}: {row.why}" + (f" [{hit}]" if hit else "")
+ priority = effective_priority(row, boost)
+ reason = (f"{row.rule}: {row.why}" + (f" [{hit}]" if hit else "")
+ + (f" (variant boost {priority - row.priority:+d})" if priority != row.priority else ""))
first_seen.setdefault(row.skill, order)
prev = best.get(row.skill)
if prev is None:
- best[row.skill] = Selection(skill=skill, priority=row.priority, rules=(row.rule,), reason=reason)
- elif row.priority > prev.priority:
+ best[row.skill] = Selection(skill=skill, priority=priority, rules=(row.rule,), reason=reason)
+ elif priority > prev.priority:
# a gate-fired row overrides the standing one, and says so in the reason
- best[row.skill] = Selection(skill=skill, priority=row.priority, rules=(*prev.rules, row.rule), reason=reason)
+ best[row.skill] = Selection(skill=skill, priority=priority, rules=(*prev.rules, row.rule), reason=reason)
else:
best[row.skill] = prev.model_copy(update={"rules": (*prev.rules, row.rule)})
diff --git a/harness/codeverse3d/skills/variants/argon/README.md b/harness/codeverse3d/skills/variants/argon/README.md
new file mode 100644
index 00000000..dac552df
--- /dev/null
+++ b/harness/codeverse3d/skills/variants/argon/README.md
@@ -0,0 +1,19 @@
+# argon — the skills overlay for gemini-4-argon on the scene track
+
+The skills half of the `argon` variant (D105, 2026-10-14; the prompts half is
+`codeverse3d/prompts/variants/argon/`). Three things may live here:
+
+* **Bundles** — `c3d-<name>/SKILL.md` (+ `references/`), shadowing a base bundle of the same
+ name or adding a new one. `codeverse3d.skills.all_skills()` is the base library updated by
+ this directory while the variant is active; a bundle here is validated like a base one.
+* **`_claims/<name>.toml`** — a shadowed bundle's pinned numbers; looked up here first, then in
+ the base `_claims/`.
+* **`routes.toml`** — `[[boost]]` rows (a priority delta per skill, clamped so a standing row
+ never reaches the gate-fired floor of 90 and a fired row never drops under it), `[[disable]]`
+ rows (base rule ids to skip) and `[[route]]` rows (extra typed routes, appended after the base
+ table). Parsed with `tomllib` into typed records; a row that does not type-check is logged
+ and the base table routes.
+
+It ships empty: iteration 0 of `eval/bench/loop.py` measures the base library and table.
+The run record's `extra.variant.hash` covers this directory (README excluded) together with
+the prompts overlay.
diff --git a/harness/codeverse3d/skills/variants/argon/routes.toml b/harness/codeverse3d/skills/variants/argon/routes.toml
new file mode 100644
index 00000000..9d18bf0d
--- /dev/null
+++ b/harness/codeverse3d/skills/variants/argon/routes.toml
@@ -0,0 +1,32 @@
+# The `argon` variant's routing table (D105). Parsed by codeverse3d/skills/__init__.py::parse_routes
+# with tomllib into typed rows (no regex); a row that does not type-check is rejected at attach time
+# (logged, the base table routes) and refused by the tests. Three row kinds:
+#
+# [[boost]] # add `delta` to the priority of every route naming `skill`: a standing
+# skill = "c3d-scene-materials" # row is clamped below 90, a gate-fired row never drops under 90
+# delta = 20
+#
+# [[disable]] # skip a base rule by id
+# rule = "R27"
+#
+# [[route]] # an extra typed row, appended AFTER the base table (ties keep base order);
+# rule = "V1" # a fresh id (never one the base table uses); priority >= 90 only with `findings`
+# skill = "c3d-scene-materials"
+# priority = 85
+# tracks = ["scene"]
+# languages = ["scene_blender"]
+# kinds = ["env", "zone", "refine"]
+# why = "flat albedo is the audit's most-cited surface defect on argon zones"
+
+# Iteration 1 (2026-10-15): placement is the measured defect that capped the most iteration-0
+# rounds (threejs 7/30 interpenetration + 5/30 sunken; blender 13/30 + 5/30), and the skills that
+# teach it sat behind lighting / materials in the attached list. The boosts put them FIRST in
+# every standing zone / env / refine session (R14 75 -> 89, R29 80 -> 89; the gate-fired rows
+# R30 / R34 already route at 95).
+[[boost]]
+skill = "c3d-scene-composition"
+delta = 14
+
+[[boost]]
+skill = "c3d-bpy-scene-placement"
+delta = 9
diff --git a/harness/codeverse3d/spatial/frame_metrics.py b/harness/codeverse3d/spatial/frame_metrics.py
index e88a15d4..2fa9f2b4 100644
--- a/harness/codeverse3d/spatial/frame_metrics.py
+++ b/harness/codeverse3d/spatial/frame_metrics.py
@@ -443,8 +443,12 @@ def _hero_findings(checks: list[dict[str, Any]], census: dict[str, Any]) -> list
base = url.rsplit("/", 1)[-1]
best = max(seen.values())
listing = ", ".join(f"{n} {v:.1%}" for n, v in list(seen.items())[:6])
+ # one instance's extent (scene_host glbUsage; until 2026-10-14 the union of every clone was the
+ # size, and a 2.2 m sofa placed three times read "6.5 m across"); the copy count says why the
+ # frame fraction and the size can disagree
size = _num(r, "size_m")
- placed = f" ({size:.1f} m across as placed)" if size else ""
+ copies = int(r.get("instances") or 0)
+ placed = f" ({size:.1f} m across as placed{f', {copies} copies' if copies > 1 else ''})" if size else ""
if best < HERO_MIN_FRAC:
out.append(_f(Severity.ERROR, base,
f"{base}{placed} is in the scene but fills at most {best:.1%} of any authored frame ({listing}) — "
diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.py
index 436ca972..ae43d529 100644
--- a/harness/codeverse3d/spatial/probes.py
+++ b/harness/codeverse3d/spatial/probes.py
@@ -94,7 +94,7 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =
args += ["--compile", "--shaders-out", str(ws.artifacts / "shader_preflight.json")]
if glb is not None:
# D3: nothing moves the JS copy of a scene Blender renders — no settle, no camera repair
- args += ["--glb", str(glb), "--no-settle"]
+ args += ["--glb", str(Path(glb).resolve()), "--no-settle"] # node runs in runtime_js/: a relative path would miss
else:
# every probe runs under the SAME settle / camera-repair / auto-exposure policy every
# render uses — ONE parser, render_scene (review-3 S4: the build used to carry none of
diff --git a/harness/codeverse3d/spatial/render_blender.py b/harness/codeverse3d/spatial/render_blender.py
index 8054a729..5e8b35ee 100644
--- a/harness/codeverse3d/spatial/render_blender.py
+++ b/harness/codeverse3d/spatial/render_blender.py
@@ -9,10 +9,15 @@
2. **pixels** — ``languages/wrappers/render_bpy_scene.py`` inside Blender on the built
``artifacts/scene.blend``: the authored cameras × every time + the first
``MAX_JUDGE_OVERVIEWS`` overview views at the first time (what someone reads — the judge and
- the motion metric; the eye-level rig views get geometry checks but no pixels). Engine /
- samples / device come from ``Settings.render.blender_*`` (Cycles CUDA 32 spp + OIDN by
- default); a GPU render holds one of ``blender_gpu_slots`` machine-wide flock'd slots and
- falls back to the CPU when none frees within ``blender_gpu_wait_s`` or the GPU run dies;
+ the motion metric; the eye-level rig views get geometry checks but no pixels). The high
+ overviews (``noFog``) render without the world volume and with a room shell's lid lifted —
+ the three.js host's ``skyLayersBelow`` rule, so both languages are judged on the same
+ interior (the driver names what it hid in each frame's ``hidden``). Engine /
+ samples / device / per-frame time cap come from ``Settings.render.blender_*`` (Cycles CUDA
+ 32 spp + GPU OIDN + persistent data by default — the fast path measured on Blender 5.2.2 LTS,
+ see ``render_bpy_scene.setup_render``); a GPU render holds one of ``blender_gpu_slots``
+ machine-wide flock'd slots and falls back to the CPU when none frees within
+ ``blender_gpu_wait_s`` or the GPU run dies;
3. **geometry** — ``runtime_js/render_scene.mjs --external-frames`` on the census GLB the build
wrote (``--glb``: booted through ``runtime_js/lib/glb_scene.mjs``): camera checks (near
geometry, inside a mesh, ground below/above, line of sight, coverage masks) from the scene,
@@ -108,7 +113,7 @@ def _run_driver(blend: Path, job: dict[str, Any], out_dir: Path, *, device: str,
write_json_atomic(job_path, job)
blender = settings.resolve_blender()
if not blender:
- raise SceneRenderError("no Blender binary (set C3D_BINARIES__BLENDER or put blender-5.0 on PATH)")
+ raise SceneRenderError("no Blender binary (set C3D_BINARIES__BLENDER or put blender-5.2 on PATH)")
cmd = [blender, "-b", "--factory-startup", str(blend), "--python", str(DRIVER), "--", str(job_path)]
proc = run_subprocess(cmd, cwd=out_dir, env=_blender_env(str(job["engine"]), device), timeout_s=timeout_s)
result = read_json_or_none(result_path)
@@ -181,7 +186,10 @@ def fit_orbit(census_path: Path, views: Sequence[ViewPreset], *, width: int, hei
def _pixel_orbit(specs: list[dict[str, Any]]) -> set[str]:
- """The rig views that get Blender pixels: the first ``MAX_JUDGE_OVERVIEWS`` overviews."""
+ """The rig views that get Blender pixels: the first ``MAX_JUDGE_OVERVIEWS`` overviews — the
+ same four tiles ``render_scene.select_judge_views`` hands the judge (the three high views
+ and the ground-level ``overview_low_front`` since scene_v2); the eye-level rig is measured
+ by the geometry pass and never rendered."""
return set([str(o["name"]) for o in specs if str(o["name"]).startswith("overview")][:MAX_JUDGE_OVERVIEWS])
@@ -244,8 +252,8 @@ def render_blender_scene(
"look_at": _to_blender(o["lookAt"]), "fov": o.get("fov") or 50.0, "no_fog": bool(o.get("noFog")),
"times": times[:1]} for o in orbit_specs if o["name"] in pixel]
job = {"out": str(out_dir), "result": str(out_dir / RESULT_NAME), "engine": engine or s.render.blender_engine,
- "samples": int(samples or s.render.blender_samples), "width": width, "height": height, "times": times,
- "authored": cameras is None, "cameras": job_cams}
+ "samples": int(samples or s.render.blender_samples), "frame_time_limit_s": s.render.blender_frame_time_limit_s,
+ "width": width, "height": height, "times": times, "authored": cameras is None, "cameras": job_cams}
t0 = time.monotonic()
frames = render_frames(blend, out_dir, job, timeout_s=tmo, settings=s)
blender_ms = int((time.monotonic() - t0) * 1000)
@@ -282,6 +290,7 @@ def render_blender_scene(
metrics["blender"] = {
"engine": frames.get("engine"), "device": frames.get("device"), "device_names": frames.get("device_names") or [],
"samples": frames.get("samples"), "fallback": frames.get("fallback") or "", "version": frames.get("blender"),
+ "persistent_data": bool(frames.get("persistent_data", False)), "frame_time_limit_s": frames.get("frame_time_limit_s"),
"gl_renderer": frames.get("gl_renderer") or "", "n_frames": len(views),
"frame_ms": [v["render_ms"] for v in views],
"timings_ms": {"fit": fit_ms, "slot_wait": frames.get("slot_wait_ms", 0), "blender": blender_ms,
diff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.py
index 6b18e3a8..121d8f32 100644
--- a/harness/codeverse3d/spatial/render_scene.py
+++ b/harness/codeverse3d/spatial/render_scene.py
@@ -42,8 +42,10 @@ log = logging.getLogger(__name__)
#: views the judge sees (contact sheet + individual images are built from these)
JUDGE_MAX_VIEWS = 10
#: how many overview-rig tiles the judge gets (layout / grounding X-ray; the eye-level
-#: rig views are diagnostics only and never reach the judge)
-MAX_JUDGE_OVERVIEWS = 3
+#: rig views are diagnostics only and never reach the judge). 4 since scene_v2
+#: (2026-10-14): the three high views plus ``overview_low_front``, the ground-level contact
+#: camera the judge's contact crops are cut from (``conventions.SCENE_VIEWS``).
+MAX_JUDGE_OVERVIEWS = 4
class SceneRenderError(RuntimeError):
diff --git a/harness/codeverse3d/spatial/scene_placement.py b/harness/codeverse3d/spatial/scene_placement.py
index 44745957..339482e2 100644
--- a/harness/codeverse3d/spatial/scene_placement.py
+++ b/harness/codeverse3d/spatial/scene_placement.py
@@ -19,6 +19,16 @@ height and its name words because the harness's own starter scene buries rocks
20–50 % of their height, digs a pond basin 1.4 m under the terrain and drives jetty
posts 0.97 m into the pond bed — a naive "> 0.10 m" rule flagged all of them
(measured 2026-08-26). Word matching is a set lookup on ``to_snake`` words.
+
+Thresholds are ``Settings.placement`` (``config.Placement``), read when the gate RUNS: the owner
+asked for stricter contact standards on 2026-10-14 (D105) and the defaults are those — floating
+ERROR at 0.08 m or more than 2 floaters, sunk ERROR 0.20 m + 20 % of the height, interpenetration
+WARN at 10 % / ERROR at 35 % of the smaller box — while a variant or an A/B arm sets its own
+through ``C3D_PLACEMENT__*`` and the summary INFO finding records what a round was judged by.
+Two findings the strict pass added: ``free_exempt`` (the share of assets tagged
+``placement='free'`` — w1_tearoom, 2026-10-13, tagged 17 of 36 and passed) and ``cantilevered``
+(seated on one foot column of four or more while the others hang). Every per-asset finding
+carries ``data.bbox`` (GLB-frame centre + size) so the judge's contact crops can be aimed at it.
"""
from __future__ import annotations
@@ -30,6 +40,7 @@ from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, ConfigDict, Field
+from codeverse3d.config import Placement, get_settings
from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
from codeverse3d.conventions import to_snake
from codeverse3d.proc import read_json_or_none
@@ -42,13 +53,20 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
GATE = "scene_placement"
-CONTACT_M = 0.02 # a foot this close to what is under it rests on it
-FLOATING_OUTDOOR_M, FLOATING_INDOOR_M = 0.05, 0.02
-FLOATING_ERROR_M, FLOATING_ERROR_COUNT = 0.15, 3 # this high, or more than this many, → ERROR
-SUNK_M, SUNK_ERROR_M = 0.10, 0.30
-SUNK_ERROR_FRAC = 0.25 # an ERROR burial must also swallow this fraction of the height
-OVERLAP_WARN, OVERLAP_ERROR = 0.20, 0.60
+#: The metres / fractions that grade a row are ``Settings.placement`` (``config.Placement``), taken
+#: at call time — ``placement_findings(thresholds=…)``, default ``get_settings().placement`` — never
+#: at import, so an A/B child's ``C3D_PLACEMENT__FLOATING_ERROR_M`` is what its rounds are judged by.
+#: The JS probe keeps its own measurement constants (host_placement.mjs CONTACT_TOL_M / FLOATING_M /
+#: SUNK_M / OVERLAP_MIN_FRAC): those decide what is MEASURED, these decide severities.
MAX_FINDINGS_PER_KIND = 8
+#: ``free_exempt`` needs this many ``placement='free'`` rows before their share is a finding: one
+#: hanging lantern among two placed things is 50 % and would cap a correct scene (scene_v2 caps a
+#: free_exempt ERROR at 0.75). The case it exists for — w1_tearoom, argon, 2026-10-13 — tagged 17.
+FREE_EXEMPT_MIN_ROWS = 2
+#: ``cantilevered`` needs this many foot columns resting on at most this many: a crate seated by its
+#: lowest corner on a slope rests on 1 of 4 (what seating by the lowest vertex produces); a level box
+#: on a planar slope rests on an edge, 2 columns, and is not flagged.
+CANTILEVER_MIN_COLUMNS, CANTILEVER_MAX_RESTING = 4, 1
#: setting / environment words that make a scene "indoors" (tighter floating tolerance)
INDOOR_WORDS = frozenset({
@@ -104,6 +122,12 @@ class AssetRow(BaseModel):
sunk_into: str = ""
on_water: bool = False
attached: list[str] = Field(default_factory=list)
+ columns: int = Field(default=0, description="foot columns probed (≤ 5: the lowest vertex and the ±x / ±z extremes of the foot band)")
+ gap_max_m: float | None = Field(default=None, description="the LARGEST column gap (ground_gap_m is the smallest); a row "
+ "measured before 2026-10-14 carries none")
+ columns_resting: int | None = Field(default=None, description="columns within contact of their support, or buried; "
+ "None before 2026-10-14")
+ tilt_m: float | None = Field(default=None, description="gap_max_m - ground_gap_m: how unevenly the feet meet the ground")
inner: list[str] = Field(
default_factory=list,
description="named descendants of this row (host_placement.MAX_INNER_NAMES) — a zone "
@@ -136,6 +160,15 @@ class AssetRow(BaseModel):
size = _nums((self.bbox or {}).get("size"))
return size[1] if size else 0.0
+ def bbox_data(self) -> dict[str, list[float]] | None:
+ """``{"center", "size"}`` of the row's box in the GLB frame, on every per-asset finding: the
+ judge's contact crops (judges/prompt_builder.plan_detail_crops) are aimed at it."""
+ b = self.bbox or {}
+ lo, hi = _nums(b.get("min")), _nums(b.get("max"))
+ if lo is None or hi is None:
+ return None
+ return {"center": [round((lo[i] + hi[i]) / 2, 3) for i in range(3)], "size": [round(hi[i] - lo[i], 3) for i in range(3)]}
+
class Interpenetration(BaseModel):
model_config = ConfigDict(extra="ignore")
@@ -159,6 +192,7 @@ class PlacementTable(BaseModel):
exempt: dict[str, int] = Field(default_factory=dict)
ground_y: float | None = None
notes: list[str] = Field(default_factory=list)
+ thresholds: dict[str, float] = Field(default_factory=dict, description="the probe's own measurement constants")
error: str = ""
@@ -197,6 +231,9 @@ LANGUAGE_WORDS: dict[str, dict[str, str]] = {
"ring": ("vary them — at least 3 silhouettes, scale 0.6-1.6x, radius +-25 %, random yaw, clusters rather than a "
"ring — or drop the ring and let the starter's worldShell ridge and makeOutskirts hills close the horizon"),
"place": "import its builder / clone its GLB",
+ "free_exempt": ("userData.placement = 'free' is for hanging / airborne things only (a bird, a hung lantern, a drone): "
+ "delete the tag on everything that stands on something and seat it with heightAt(x, z) or on its support"),
+ "cantilever": "seat every foot: follow the ground with heightAt(x, z) at each corner, sink it a few cm, or shorten the overhang",
},
"scene_blender": {
"seat": "seat it with ctx.height_at(x, y) or on the surface it stands on",
@@ -213,6 +250,10 @@ LANGUAGE_WORDS: dict[str, dict[str, str]] = {
"ring": ("vary them — at least 3 silhouettes, scale 0.6-1.6x, radius +-25 %, random yaw, clusters rather than a "
"ring — or drop the ring and close the horizon with terrain ridges and hills"),
"place": "place a collection-instance Empty of ctx.assets['<snake>']",
+ "free_exempt": ('obj["placement"] = "free" is for hanging / airborne things only (a bird, a hung lantern, a drone): '
+ "delete the tag on everything that stands on something and seat it with ctx.height_at(x, y) / lib.place.seat"),
+ "cantilever": ("seat every foot: follow the ground with ctx.height_at(x, y) at each corner (lib.place.seat), "
+ "sink it a few cm, or shorten the overhang"),
},
}
@@ -231,7 +272,7 @@ def _support_label(row: AssetRow, ground_y: float | None) -> str:
return f"the ground (census ground_y = {ground_y:.2f} m)" if ground_y is not None else "the ground"
-def _sunk_severity(row: AssetRow) -> Severity | None:
+def _sunk_severity(row: AssetRow, p: Placement) -> Severity | None:
"""WARN / ERROR / None for a buried foot, honouring height fraction and name words."""
if row.sunk_m <= 0 or row.on_water:
return None
@@ -242,70 +283,121 @@ def _sunk_severity(row: AssetRow) -> Severity | None:
if words & seated.partial_ok:
if frac <= seated.partial_ok_frac:
return None
- return Severity.ERROR if row.sunk_m > SUNK_ERROR_M else Severity.WARN
- if row.sunk_m > SUNK_ERROR_M and frac > SUNK_ERROR_FRAC:
+ return Severity.ERROR if row.sunk_m > p.sunk_error_m else Severity.WARN
+ if row.sunk_m > p.sunk_error_m and frac > p.sunk_error_frac:
return Severity.ERROR
- return Severity.WARN if row.sunk_m > SUNK_M else None
+ return Severity.WARN if row.sunk_m > p.sunk_m else None
+
+def _cantilever(row: AssetRow, p: Placement) -> bool:
+ """Seated on at most ``CANTILEVER_MAX_RESTING`` of ≥ ``CANTILEVER_MIN_COLUMNS`` foot columns while
+ another hangs past the outdoor floating tolerance: a crate seated by its lowest corner on a slope,
+ a bench with one leg on a rock. ``gap_max_m`` / ``columns_resting`` are the column measures
+ host_placement.mjs added on 2026-10-14; a row measured before says nothing. Slope-following names
+ (stairs, ramps, paths — placement_words.json) meet the ground unevenly by construction."""
+ if row.columns < CANTILEVER_MIN_COLUMNS or row.columns_resting is None or row.gap_max_m is None:
+ return False
+ if row.columns_resting > CANTILEVER_MAX_RESTING or row.gap_max_m <= p.floating_outdoor_m:
+ return False
+ return not (_words(row.name) & _seated_words().slope_ok)
-def _asset_findings(rows: list[AssetRow], *, floating_m: float, ground_y: float | None,
+
+def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, ground_y: float | None,
words: dict[str, str]) -> list[GateFinding]:
out: list[GateFinding] = []
floating: list[tuple[AssetRow, float]] = []
for row in rows:
q = row.qualified
- sev = _sunk_severity(row)
+ at = {"zone": row.zone, "bbox": row.bbox_data()}
+ sev = _sunk_severity(row, p)
if sev is not None:
out.append(_f(sev, f"{q} is sunken {row.sunk_m:.2f} m into {row.sunk_into or 'the ground'}", target=q,
hint=f"raise {q} by {row.sunk_m:.2f} m so its lowest point sits on {row.sunk_into or 'the ground'}",
- kind="sunken", sunk_m=row.sunk_m, into=row.sunk_into, zone=row.zone))
+ kind="sunken", sunk_m=row.sunk_m, into=row.sunk_into, **at))
continue
gap = row.ground_gap_m
- if gap is None or row.on_water or row.sunk_m > 0 or gap <= CONTACT_M:
+ if gap is None or row.on_water:
continue
if row.attached: # mounted on what it touches: the settle leaves it, so does the gate
continue
support = _support_label(row, ground_y)
+ if row.sunk_m > 0 or gap <= p.contact_m:
+ # seated at its lowest column — on how many of the others?
+ if _cantilever(row, p):
+ out.append(_f(Severity.WARN, f"{q} rests on {row.columns_resting} of its {row.columns} foot columns: the others "
+ f"hang up to {row.gap_max_m:.2f} m above {support} (tilt {row.tilt_m or 0:.2f} m)",
+ target=q, hint=f"{words['cantilever']}; a deliberately airborne thing gets "
+ f"{words['free'].format(name=row.name)}",
+ kind="cantilevered", gap_max_m=row.gap_max_m, tilt_m=row.tilt_m, columns=row.columns,
+ columns_resting=row.columns_resting, **at))
+ continue
if gap > floating_m:
floating.append((row, gap))
else:
out.append(_f(Severity.WARN, f"{q} is unsupported: hovers {gap:.2f} m above {support} and touches nothing", target=q,
hint=f"lower {q} by {gap:.2f} m onto {support}, or attach it to a neighbour; "
f"if it is meant to hang free set {words['free'].format(name=row.name)}",
- kind="unsupported", gap_m=gap, zone=row.zone))
- many = len(floating) > FLOATING_ERROR_COUNT
+ kind="unsupported", gap_m=gap, **at))
+ many = len(floating) > p.floating_error_count
for row, gap in floating:
q = row.qualified
support = _support_label(row, ground_y)
- sev = Severity.ERROR if (many or gap > FLOATING_ERROR_M) else Severity.WARN
+ sev = Severity.ERROR if (many or gap > p.floating_error_m) else Severity.WARN
out.append(_f(sev, f"{q} is floating {gap:.2f} m above {support} (touches nothing)", target=q,
hint=f"lower {q} by {gap:.2f} m onto {support} — {words['seat']}; "
f"a deliberately airborne thing gets {words['free'].format(name=row.name)}",
- kind="floating", gap_m=gap, zone=row.zone))
+ kind="floating", gap_m=gap, zone=row.zone, bbox=row.bbox_data()))
return out
-def _pair_findings(pairs: list[Interpenetration]) -> list[GateFinding]:
+def _pair_findings(pairs: list[Interpenetration], p: Placement, rows: dict[str, AssetRow]) -> list[GateFinding]:
out: list[GateFinding] = []
# one finding per PAIR OF NAMES, keeping the worst overlap: a zone that stamps four
# TerracottaPlanters against one arbour used to yield four identical ERRORs
# (measured on t36_santorini) and flood the refine prompt with one fact
best: dict[tuple[str, str], Interpenetration] = {}
- for p in pairs:
- key = tuple(sorted((f"{p.zone_a}/{p.a}", f"{p.zone_b}/{p.b}")))
- if key not in best or p.aabb_overlap > best[key].aabb_overlap:
- best[key] = p
- for p in best.values():
- qa = f"{p.zone_a}/{p.a}" if p.zone_a else p.a
- qb = f"{p.zone_b}/{p.b}" if p.zone_b else p.b
- sev = Severity.ERROR if p.aabb_overlap > OVERLAP_ERROR else Severity.WARN
- out.append(_f(sev, f"interpenetration: {qa} and {qb} overlap ({p.aabb_overlap:.0%} of the smaller box; "
- f"{p.inside_frac:.0%} of its vertices inside the other)", target=qa,
- hint=f"move {qa} out of {qb} or shrink one of them so their boxes share ≤ {OVERLAP_WARN:.0%}",
- kind="interpenetration", overlap=p.aabb_overlap, inside_frac=p.inside_frac, other=qb, zone=p.zone_a))
+ for pr in pairs:
+ # the probe reports every pair past its own floor (host_placement OVERLAP_MIN_FRAC = the
+ # default overlap_warn); an arm that raises overlap_warn filters here
+ if pr.aabb_overlap <= p.overlap_warn:
+ continue
+ key = tuple(sorted((f"{pr.zone_a}/{pr.a}", f"{pr.zone_b}/{pr.b}")))
+ if key not in best or pr.aabb_overlap > best[key].aabb_overlap:
+ best[key] = pr
+ for pr in best.values():
+ qa = f"{pr.zone_a}/{pr.a}" if pr.zone_a else pr.a
+ qb = f"{pr.zone_b}/{pr.b}" if pr.zone_b else pr.b
+ sev = Severity.ERROR if pr.aabb_overlap > p.overlap_error else Severity.WARN
+ row = rows.get(qa)
+ out.append(_f(sev, f"interpenetration: {qa} and {qb} overlap ({pr.aabb_overlap:.0%} of the smaller box; "
+ f"{pr.inside_frac:.0%} of its vertices inside the other)", target=qa,
+ hint=f"move {qa} out of {qb} or shrink one of them so their boxes share ≤ {p.overlap_warn:.0%}",
+ kind="interpenetration", overlap=pr.aabb_overlap, inside_frac=pr.inside_frac, other=qb, zone=pr.zone_a,
+ bbox=row.bbox_data() if row is not None else None))
return out
+def _free_exempt_finding(t: PlacementTable, p: Placement, words: dict[str, str]) -> GateFinding | None:
+ """One finding per report: the share of placed assets tagged ``placement='free'`` — exempt from
+ every check — among the assets that would otherwise have been checked. The tag is for hanging
+ and airborne things; it is also the one line that silences the gate, and the hint on every
+ floating finding names it. Measured on w1_tearoom (argon, 2026-10-13): 17 of 36 placed things
+ tagged free, the gate's only finding a sunken shoji screen."""
+ free = [r for r in t.assets if r.exempt == "free"]
+ n = t.checked + len(free)
+ if len(free) < FREE_EXEMPT_MIN_ROWS or n == 0:
+ return None
+ share = len(free) / n
+ if share <= p.free_exempt_warn:
+ return None
+ sev = Severity.ERROR if share > p.free_exempt_error else Severity.WARN
+ names = [r.qualified for r in free[:8]]
+ listed = ", ".join(names) + (f" (+{len(free) - 8} more)" if len(free) > 8 else "")
+ return _f(sev, f"{len(free)} of {n} placed assets are tagged placement='free' ({share:.0%}) and skip every placement "
+ f"check: {listed}", target="scene", hint=words["free_exempt"],
+ kind="free_exempt", free=len(free), of=n, share=round(share, 3), names=names)
+
+
def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
"""Keep the worst ``MAX_FINDINGS_PER_KIND`` per kind (ERROR first, then magnitude); the
rest becomes one INFO line, so 30 floating pebbles cannot flood the refine prompt."""
@@ -315,7 +407,8 @@ def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
by_kind.setdefault(str(f.data.get("kind")), []).append(f)
out: list[GateFinding] = []
for kind, fs in by_kind.items():
- fs.sort(key=lambda f: (rank[f.severity], -float(f.data.get("gap_m") or f.data.get("sunk_m") or f.data.get("overlap") or 0)))
+ fs.sort(key=lambda f: (rank[f.severity], -float(f.data.get("gap_m") or f.data.get("sunk_m") or f.data.get("overlap")
+ or f.data.get("gap_max_m") or 0)))
out.extend(fs[:MAX_FINDINGS_PER_KIND])
if len(fs) > MAX_FINDINGS_PER_KIND:
out.append(_f(Severity.INFO, f"… and {len(fs) - MAX_FINDINGS_PER_KIND} more {kind} finding(s) not listed", target="scene",
@@ -323,27 +416,49 @@ def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
return out
-def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool = False,
- language: str | None = None) -> GateReport:
- """The ``scene_placement`` GateReport for one census placement table (pure)."""
+#: the per-asset kinds the summary counts (``free_exempt`` is one finding per report, counted apart)
+ASSET_KINDS = ("floating", "sunken", "unsupported", "interpenetration", "cantilevered")
+
+
+def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool = False, language: str | None = None,
+ thresholds: Placement | None = None) -> GateReport:
+ """The ``scene_placement`` GateReport for one census placement table: pure given ``thresholds``,
+ which default to the process's ``Settings.placement`` (read now, not at import)."""
t = table if isinstance(table, PlacementTable) else PlacementTable.model_validate(table or {})
if t.error:
return GateReport.of(GATE, [
_f(Severity.WARN, f"placement probe failed: {t.error[:300]}", target="scene", kind="probe_failed",
hint="harness instrumentation, not your code; the placement check was skipped this round")])
- floating_m = FLOATING_INDOOR_M if indoor else FLOATING_OUTDOOR_M
+ p = thresholds or get_settings().placement
+ floating_m = p.floating_indoor_m if indoor else p.floating_outdoor_m
+ words = placement_words(language)
rows = [r for r in t.assets if not r.exempt]
- findings = _cap_per_kind(_asset_findings(rows, floating_m=floating_m, ground_y=t.ground_y, words=placement_words(language))
- + _pair_findings(t.interpenetrations))
- counts = {k: sum(1 for f in findings if f.data.get("kind") == k and f.severity != Severity.INFO)
- for k in ("floating", "sunken", "unsupported", "interpenetration")}
+ raw = (_asset_findings(rows, p=p, floating_m=floating_m, ground_y=t.ground_y, words=words)
+ + _pair_findings(t.interpenetrations, p, {r.qualified: r for r in t.assets}))
+ free = _free_exempt_finding(t, p, words)
+ findings = _cap_per_kind(raw) + ([free] if free is not None else [])
+ # `counts` are what was MEASURED, `listed` what survived the per-kind cap: the judge's measured
+ # block and the loop's diagnosis read the first, the refine prompt shows the second
+ counts = {k: sum(1 for f in raw if f.data.get("kind") == k) for k in ASSET_KINDS}
+ listed = {k: sum(1 for f in findings if f.data.get("kind") == k) for k in ASSET_KINDS}
+ n_free = sum(1 for r in t.assets if r.exempt == "free")
+ free_share = n_free / (t.checked + n_free) if t.checked + n_free else 0.0
n_exempt = sum(t.exempt.values())
- summary = (f"{t.checked} assets checked ({t.total} placed, {n_exempt} exempt): {counts['floating']} floating, "
- f"{counts['sunken']} sunken, {counts['unsupported']} unsupported, {counts['interpenetration']} interpenetrating"
- + (f"; {'indoor' if indoor else 'outdoor'} tolerance {floating_m * 100:.0f} cm")
+
+ def shown(kind: str) -> str:
+ return f"{counts[kind]}" + (f" ({listed[kind]} listed)" if listed[kind] < counts[kind] else "")
+
+ summary = (f"{t.checked} assets checked ({t.total} placed, {n_exempt} exempt): {shown('floating')} floating, "
+ f"{shown('sunken')} sunken, {shown('unsupported')} unsupported, {shown('interpenetration')} interpenetrating"
+ + (f", {shown('cantilevered')} cantilevered" if counts["cantilevered"] else "")
+ + (f", {n_free} tagged free ({free_share:.0%})" if n_free else "")
+ + f"; {'indoor' if indoor else 'outdoor'} tolerance {floating_m * 100:.0f} cm, ERROR past "
+ f"{p.floating_error_m * 100:.0f} cm or more than {p.floating_error_count} floating"
+ ("; table truncated (first 400 assets / time budget)" if t.truncated else ""))
- findings.insert(0, _f(Severity.INFO, summary, target="scene", kind="summary", counts=counts, checked=t.checked, total=t.total,
- exempt=t.exempt, truncated=t.truncated))
+ findings.insert(0, _f(Severity.INFO, summary, target="scene", kind="summary", counts=counts, listed=listed, checked=t.checked,
+ total=t.total, exempt=t.exempt, free=n_free, free_share=round(free_share, 3), truncated=t.truncated,
+ thresholds={**p.model_dump(), "floating_m": floating_m, "indoor": indoor},
+ probe_thresholds=dict(t.thresholds)))
return GateReport.of(GATE, findings)
@@ -608,7 +723,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
else:
continue
out.append(_f(sev, f"{what} measures {measured:.2f} m but the plan sized {key} at ~{sizes[key]:.2f} m ({f:.1f}x)",
- target=r.qualified, kind="scale", factor=round(f, 2), zone=r.zone, instances=n,
+ target=r.qualified, kind="scale", factor=round(f, 2), zone=r.zone, instances=n, bbox=r.bbox_data(),
hint=f"scale {'each ' + key if n else r.name} so its largest dimension is ~{sizes[key]:.2f} m as planned"))
# -- content inside the world bounds
bounds = _plan_bounds(plan)
@@ -624,7 +739,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
if fully_out:
out.append(_f(Severity.ERROR, f"{r.qualified} sits entirely outside the plan bounds "
f"(x {bmin[0]:.0f}..{bmax[0]:.0f}, z {bmin[2]:.0f}..{bmax[2]:.0f})",
- target=r.qualified, kind="out_of_bounds", zone=r.zone,
+ target=r.qualified, kind="out_of_bounds", zone=r.zone, bbox=r.bbox_data(),
hint="move it inside the plan bounds or into its zone bbox"))
return out
diff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.py
index 70958e26..ba24208b 100644
--- a/harness/codeverse3d/spatial/tools.py
+++ b/harness/codeverse3d/spatial/tools.py
@@ -500,9 +500,11 @@ class CheckPlacementArgs(BaseModel):
@tool("check_placement", CheckPlacementArgs,
"The round's scene_placement gate on the last build (scene only): per placed asset the gap from its feet to what "
"is under them, burial depth, water, contacts, plus 3-D interpenetrations between assets — findings read "
- "'floating / sunken / unsupported / interpenetration' with 'lower X by 0.23 m onto Terrain' hints — and the "
- "plan checks (fog, backdrop, zone contents, scale, bounds). Reads the census of the last build/scene_probe; "
- "rebuild=true probes again. Tag a deliberately airborne thing with obj.userData.placement = 'free'.",
+ "'floating / sunken / unsupported / cantilevered / interpenetration' with 'lower X by 0.23 m onto Terrain' hints, the "
+ "share of assets tagged placement='free' (a 'free_exempt' finding when the tag hides more than a quarter of them) — "
+ "and the plan checks (fog, backdrop, zone contents, scale, bounds). Reads the census of the last build/scene_probe; "
+ "rebuild=true probes again. Tag ONLY a deliberately airborne thing (a hanging lantern, a bird) with "
+ "obj.userData.placement = 'free' (bpy: obj['placement'] = 'free').",
languages=SCENE_LANGUAGES, cost_hint="fast")
def check_placement(ctx: ToolContext, args: CheckPlacementArgs) -> Observation:
ws = ctx.workspace
diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.py
index 16b0f25a..10aca224 100644
--- a/harness/codeverse3d/tracks/common.py
+++ b/harness/codeverse3d/tracks/common.py
@@ -159,6 +159,9 @@ class RunContext:
tool_cards: str = ""
prompt_hashes: dict[str, str] = field(default_factory=dict)
extra: dict[str, Any] = field(default_factory=dict)
+ #: the prompt/skill variant this run activated (``prompts/variants.py``, D105): ``""`` = base.
+ #: Informative here — the overlay itself is the ContextVar ``BaseTrack.run`` sets around the run
+ variant: str = ""
@property
def language(self) -> Language:
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index 77fbafcf..af6b7f52 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -14,7 +14,8 @@ from __future__ import annotations
import logging
import platform
import traceback
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Iterator, Sequence
+from contextlib import ExitStack, contextmanager
from dataclasses import dataclass, replace
from datetime import UTC, datetime
from pathlib import Path
@@ -46,6 +47,14 @@ from codeverse3d.orchestrator import (
from codeverse3d.proc import EventLog, fan_out, read_json_or_none
from codeverse3d.prompts import load_text, render
from codeverse3d.prompts.catalog import language_text
+from codeverse3d.prompts.variants import (
+ activate,
+ active_variant,
+ knobs_applied,
+ resolve_variant,
+ variant_block,
+ variant_info,
+)
from codeverse3d.record.record import previous_verdict
from codeverse3d.tracks.candidates import run_best_of_n
from codeverse3d.tracks.common import RunContext, Services
@@ -90,8 +99,16 @@ def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
def plan_stage_key(spec: Spec, track: Track) -> dict[str, Any]:
"""The plan stage's cache key: a run's, and the one a pinned A/B plan is seeded under
- (``eval/bench/pin_plan``) — a seed under any other key is a cache MISS and re-plans."""
- return {"spec": plan_stage_inputs(spec), "track": track.value}
+ (``eval/bench/pin_plan``) — a seed under any other key is a cache MISS and re-plans.
+
+ A variant (the spec's frozen one, else the active one) is part of the key ONLY when set: it may
+ overlay the planner template, so its plan is cached — and a pinned plan seeded — under its name,
+ while the default run's key never moves (``tests/prompts/manifest.py`` STAGE_HINT)."""
+ key: dict[str, Any] = {"spec": plan_stage_inputs(spec), "track": track.value}
+ variant = spec.options.variant or active_variant()
+ if variant:
+ key["variant"] = variant
+ return key
def spec_fingerprint(spec: Spec) -> str:
@@ -303,11 +320,16 @@ class BaseTrack:
# ------------------------------------------------------------------ public API
def run(self, spec: Spec, ws: Workspace, *, resume: bool = False, force: bool = False) -> RunRecord:
ws.create()
+ variant = self.variant_for(spec)
# the run's own ledger even when nobody opened one (a test, a script): the CLI /
# bench open the same file first and run_ledger nests, restoring theirs on exit.
# Keep THEIR name when they bound one — a compare_backends cell is "<prompt>:<arm>",
# and rebinding it to the directory ("run") collapsed every cell into one bucket.
- with run_ledger(ws.root, run=run_binding().run or ws.root.name):
+ # The variant overlay (D105) wraps the WHOLE run: every prompt file, template and skill
+ # bundle below resolves through it, in the fan-out threads too (proc.fan_out copies the
+ # context); a resume re-activates what the spec froze. Its knobs hold for exactly as long.
+ with activate(variant), run_ledger(ws.root, run=run_binding().run or ws.root.name), \
+ self._apply_variant(variant) as knobs:
if not ws.spec_path.is_file() or not resume:
ws.write_json(ws.spec_path, spec)
events = EventLog(ws.events_path)
@@ -320,7 +342,10 @@ class BaseTrack:
ctx = self.build_context(spec, ws, events, state)
runner = StageRunner(ws, events, state, frozen=bool(rounds))
events.emit("run.start", track=self.track.value, language=spec.language.value, resume=resume,
- agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge)
+ agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge,
+ variant=variant)
+ if variant:
+ events.emit("variant.active", **variant_block(variant), knobs=knobs)
stop = RunStatus.FAILED
error = ""
try:
@@ -345,6 +370,33 @@ class BaseTrack:
raise
return self.finalise(ctx, rounds, stop, error=error)
+ # ------------------------------------------------------------------ the variant (D105)
+ @staticmethod
+ def variant_for(spec: Spec) -> str:
+ """The variant this run activates: the spec's frozen choice (``3dcode make --variant``,
+ ``run_bench --variant``), else the process switch — ``C3D_VARIANT``, or ``C3D_VARIANTS`` by the
+ generator id — read from ``get_settings()`` like every other switch, so a direct ``track.run``
+ under an A/B arm's environment honours it. An unknown name raises before anything is paid."""
+ return spec.options.variant or resolve_variant(get_settings(), spec.backends.generator)
+
+ @contextmanager
+ def _apply_variant(self, variant: str) -> Iterator[dict[str, Any]]:
+ """The variant's ``[knobs]`` as defaults on the process settings (where ``attach_skills`` reads
+ ``skills_max`` / ``skills_only``) and on an injected ``Settings`` too, for the RUN ONLY: both
+ objects outlive it (the singleton, a rig's shared Settings), so the prior values and field-sets
+ come back on exit and the next run of this process starts from its own base, never from a knob
+ the last variant left behind (``knobs_applied``). A user-stated field wins
+ (``apply_variant_knobs``). Yields what was set, for the ``variant.active`` event."""
+ if not variant:
+ yield {}
+ return
+ info = variant_info(variant)
+ with ExitStack() as stack:
+ applied = stack.enter_context(knobs_applied(get_settings(), info))
+ if self._settings is not None and self._settings is not get_settings():
+ stack.enter_context(knobs_applied(self._settings, info))
+ yield applied
+
# ------------------------------------------------------------------ resume reconciliation
def reconcile_resume(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState,
*, resume: bool, force: bool) -> list[RoundRecord]:
@@ -453,7 +505,8 @@ class BaseTrack:
agent_id=spec.backends.generator,
# metered like the ones services hand out: an injected agent or model spends
# money too, and the ledger is the only record of it
- agent=metered_agent(self._agent), model=metered_chat_model(self._model))
+ agent=metered_agent(self._agent), model=metered_chat_model(self._model),
+ variant=active_variant())
ctx.contract_text = language_text(spec.language, "contract.md")
ctx.cookbook_text = language_text(spec.language, "cookbook.md")
ctx.tool_cards = self.services.tool_cards(self.track.value, spec.language.value)
@@ -728,6 +781,10 @@ class BaseTrack:
# the record post-hoc (flywheel captions, texturing/run.record_texturing, prior
# sessions' aborted_rounds, prompt hashes of stages not re-executed): seed from
# the prior record — unknown keys preserved, this session's values win.
+ # the variant this session ran under (D105): name/version/hash beside the prompt hashes, so two
+ # runs can be told apart by what their models were shown; the base writes "" / 0 / "" and no hash
+ variant = variant_block(ctx.variant)
+ extra["variant"] = variant
prior_extra, prior_hashes = self._prior_record_fields(ctx.ws)
if ctx.extra.get("finalise_rebuild_failed", None) == "": # rebuilt successfully this session
prior_extra.pop("finalise_rebuild_failed", None)
@@ -738,12 +795,17 @@ class BaseTrack:
if isinstance(prior_aborted, list) and ctx.extra.get("aborted_rounds"):
extra["aborted_rounds"] = prior_aborted + [a for a in ctx.extra["aborted_rounds"]
if a not in prior_aborted]
+ hashes = {**prior_hashes, **dict(ctx.prompt_hashes)}
+ if ctx.variant and variant["hash"]:
+ hashes["variant"] = variant["hash"]
+ elif not ctx.variant:
+ hashes.pop("variant", None) # a prior session's overlay is not this session's
return RunRecord(
spec=ctx.spec, plan=ctx.plan, workspace=str(ctx.ws.root), status=status, rounds=rounds,
total_usage=ledger_usage(load_ledger(ctx.ws.root)), steps=list(ctx.state.steps),
environment={"python": platform.python_version(), "host": platform.node(), "track": self.track.value,
- "language": ctx.language.value, "generator": ctx.agent_id},
- prompt_hashes={**prior_hashes, **dict(ctx.prompt_hashes)}, started_at=ctx.state.started_at,
+ "language": ctx.language.value, "generator": ctx.agent_id, "variant": ctx.variant},
+ prompt_hashes=hashes, started_at=ctx.state.started_at,
finished_at=datetime.now(UTC), error=error,
extra=extra,
)
diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.py
index acdaa23b..d2b0a51c 100644
--- a/harness/codeverse3d/tracks/plan_features.py
+++ b/harness/codeverse3d/tracks/plan_features.py
@@ -15,7 +15,10 @@ from codeverse3d.config import Settings
#: switches that act AFTER planning — ``--pin-plan`` may share one plan across arms that
#: differ only by these. Anything else is treated as plan-side: refusing to pin costs one
#: noisy A/B, pinning wrongly costs a confident wrong answer (eval/docs/EVAL.md §8.1
-#: measured it — the A/A's worst pair differed 1 part vs 10).
+#: measured it — the A/A's worst pair differed 1 part vs 10). ``C3D_VARIANT`` / ``C3D_VARIANTS``
+#: (``prompts/variants.py``, D105) are deliberately NOT here: a variant overlays prompt files, the
+#: planner templates included, and its name is part of the plan stage key
+#: (``lifecycle.plan_stage_key``) — two arms that differ by variant must each plan.
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED",
"C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF", "C3D_SEED_RECIPES"})
#: the two the node side reads itself (runtime_js: gpu_launch.cjs, browser_daemon.cjs)
diff --git a/harness/codeverse3d/tracks/planner.py b/harness/codeverse3d/tracks/planner.py
index e367a3f0..a34c1250 100644
--- a/harness/codeverse3d/tracks/planner.py
+++ b/harness/codeverse3d/tracks/planner.py
@@ -35,7 +35,12 @@ from pydantic import BaseModel, ValidationError
from codeverse3d.config import get_settings
from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart
from codeverse3d.contracts.common import Language, Track, Usage
-from codeverse3d.contracts.plan import AcceptanceItem, EngineeringBrief
+from codeverse3d.contracts.plan import (
+ AcceptanceItem,
+ EngineeringBrief,
+ ScenePlan,
+ scene_plan_schema,
+)
from codeverse3d.contracts.spec import Spec
from codeverse3d.conventions import LANGUAGE_FRAME, frame_doc, to_pascal, to_snake
from codeverse3d.models import get_chat_model
@@ -460,8 +465,18 @@ def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None) -> Any:
# ===================================================================== worked examples
-def plan_example(track: Track) -> dict[str, Any]:
- """Compact, valid worked example per track (concrete beats abstract)."""
+def plan_example(track: Track, language: Language | None = None) -> dict[str, Any]:
+ """Compact, valid worked example per track (concrete beats abstract) — and, where a language
+ plans differently, per language: a scene_blender plan names ``bpy`` modules where a three.js
+ plan names ``threejs`` ones (``SCENE_ASSET_KINDS``). Its NUMBERS are the same Y-up GLB-frame
+ numbers (D12: the plan never changes frame; the skeleton and the prompts convert for the
+ author), so the two examples differ in the asset kinds and nothing else."""
+ if track is Track.SCENE and language is Language.SCENE_BLENDER:
+ example = plan_example(Track.SCENE)
+ for asset in example["assets"]:
+ if asset["kind"] == "threejs":
+ asset["kind"] = "bpy"
+ return example
if track is Track.GRAPHICS:
return {
"title": "Neon rain on a window", "summary": "Looking through a rain-streaked window at a neon-lit street at night; "
@@ -739,16 +754,34 @@ def _truncated(exc: Exception) -> bool:
"""Did this model error mean 'the answer did not fit'?"""
return "MAX_TOKENS" in str(exc)
-PLAN_TEMPLATES: dict[Track, str] = {
- Track.STATIC_OBJECT: "tracks/plan_static.j2",
- Track.ARTICULATED_OBJECT: "tracks/plan_articulated.j2",
- Track.SCENE: "tracks/plan_scene.j2",
- Track.GRAPHICS: "tracks/plan_graphics.j2", # no 3D frame: passes, uniforms, motion
+#: the planner's system-prompt template per (track, language); ``(track, None)`` is the track's
+#: default and the fallback for every language without a row of its own. A scene_blender
+#: director reads the bpy twin: the same plan shape and frame (D12), the bpy library and the
+#: ``bpy`` asset kind instead of the three.js effects and ``threejs``.
+PLAN_TEMPLATES: dict[tuple[Track, Language | None], str] = {
+ (Track.STATIC_OBJECT, None): "tracks/plan_static.j2",
+ (Track.ARTICULATED_OBJECT, None): "tracks/plan_articulated.j2",
+ (Track.SCENE, None): "tracks/plan_scene.j2",
+ (Track.SCENE, Language.SCENE_BLENDER): "tracks/plan_scene_bpy.j2",
+ (Track.GRAPHICS, None): "tracks/plan_graphics.j2", # no 3D frame: passes, uniforms, motion
}
#: the output-token floor ``plan_tokens`` grows from; a graphics plan starts at the model's ceiling
PLAN_OUTPUT_FLOOR = 24_000
+def plan_template(track: Track, language: Language | None = None) -> str:
+ """The planner template for ``(track, language)``: the language's own row, else the track's."""
+ return PLAN_TEMPLATES.get((track, language)) or PLAN_TEMPLATES[(track, None)]
+
+
+def plan_schema(spec: Spec, plan_model: type[BaseModel]) -> dict[str, Any]:
+ """The response schema the planner call carries: a scene's names the asset kinds of ITS
+ language (``scene_plan_schema``); every other plan is its model's schema as is."""
+ if issubclass(plan_model, ScenePlan):
+ return scene_plan_schema(spec.language)
+ return plan_model.model_json_schema()
+
+
def plan_temperature(track: Track) -> float:
"""What the planner samples at: 0.5 for a shader brief, 0.4 for everything else. THE value —
``record/telemetry`` reports this function, not a default it guesses."""
@@ -820,7 +853,7 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works
images = [ImagePart(path=r.path, label=f"{r.role}: {r.note}".strip(": ")) for r in spec.references]
messages = [ChatMessage.user(user, images=images or None)]
base_messages = list(messages)
- schema = plan_model.model_json_schema()
+ schema = plan_schema(spec, plan_model)
last_error = ""
invalid = requeried = grown = restarts = 0
tokens = plan_tokens(budget, PLAN_TOKENS_MAX if spec.track is Track.GRAPHICS else PLAN_OUTPUT_FLOOR)
@@ -929,12 +962,12 @@ def build_system_prompt(spec: Spec, plan_model: type[BaseModel], *, budget: Plan
lang: Language = spec.language
budget = budget or plan_budget(spec)
return render(
- PLAN_TEMPLATES[spec.track],
+ plan_template(spec.track, lang),
track=spec.track.value,
language=lang.value,
frame_doc=frame_doc(LANGUAGE_FRAME[lang.value]),
contract=language_text(lang, "contract.md"),
- example_json=json.dumps(plan_example(spec.track), indent=1),
+ example_json=json.dumps(plan_example(spec.track, lang), indent=1),
schema_fields=", ".join(plan_model.model_json_schema().get("properties", {}).keys()),
target_parts=budget.target_parts,
min_parts=budget.min_parts,
@@ -1055,8 +1088,8 @@ def normalise_names[P: BaseModel](plan_obj: P) -> P:
__all__ = ["MAX_PLAN_RESTARTS", "MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS",
- "PLAN_TOKENS_MAX", "PlanningError", "add_acceptance_item",
+ "PLAN_TEMPLATES", "PLAN_TOKENS_MAX", "PlanningError", "add_acceptance_item",
"articulation_acceptance", "build_system_prompt", "build_user_prompt", "plan_event_stats",
"ensure_acceptance", "missing_link_names", "normalise_names", "plan",
- "degenerate_plan", "plan_example", "plan_temperature", "plan_tokens", "restart_enabled",
- "restart_note"]
+ "degenerate_plan", "plan_example", "plan_schema", "plan_template", "plan_temperature", "plan_tokens",
+ "restart_enabled", "restart_note"]
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
index 8477ba68..fec27c34 100644
--- a/harness/codeverse3d/tracks/scene.py
+++ b/harness/codeverse3d/tracks/scene.py
@@ -24,6 +24,7 @@ from __future__ import annotations
import logging
import time
from collections.abc import Callable, Sequence
+from dataclasses import dataclass
from typing import Any
from codeverse3d.contracts.artifacts import (
@@ -34,10 +35,10 @@ from codeverse3d.contracts.artifacts import (
RenderSet,
Severity,
)
-from codeverse3d.contracts.common import TRACK_INFO, Track
-from codeverse3d.contracts.plan import Plan, ScenePlan, ZonePlan
+from codeverse3d.contracts.common import ENTRY_FILE, TRACK_INFO, Language, Track
+from codeverse3d.contracts.plan import BBox, CameraPlan, Plan, ScenePlan, ZonePlan
from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.conventions import to_snake
+from codeverse3d.conventions import fmt3, to_authoring_frame, to_snake
from codeverse3d.judges.base import judged_subset
from codeverse3d.models import get_chat_model
from codeverse3d.orchestrator import BudgetExceeded, TaskGroup, compact_instructions
@@ -51,7 +52,6 @@ from codeverse3d.tracks.generation import GenerationResult, GenerationTask
from codeverse3d.tracks.lifecycle import CLOCK, MATERIALIZE, SKELETON, BaseTrack, StageNode
from codeverse3d.tracks.prompting import (
base_prompt_context,
- bbox_line,
cookbook_sections,
judge_digest,
reference_images,
@@ -82,8 +82,11 @@ ENV_RECIPES: tuple[str, ...] = (
ZONE_RECIPES: tuple[str, ...] = (
"Vegetation that reads real", "Rocks, cliffs and boulders that read organic",
"Set dressing: how many props a place needs", "Scene layering: foreground, midground, background",
- "Motion you can SEE between t = 0 and t = 1.5 s",
+ "Motion you can SEE between t = 0 and t = 1.5 s", "Soft particles",
)
+#: the zone chapters above run to ~25 k chars on scene_blender: the inlining budget must hold them all
+#: (the default 24 k clipped the LAST chapter, which is the one iteration 0 needed — 2026-10-15)
+ZONE_RECIPES_MAX_CHARS = 30_000
ENV_TIMEOUT_S = 420
ZONE_TIMEOUT_S = 600
#: a refine session that runs for half an hour (the desert-canyon round 1 did) spends the
@@ -91,6 +94,62 @@ ZONE_TIMEOUT_S = 600
REFINE_TIMEOUT_S = 900
+@dataclass(frozen=True)
+class SceneTemplates:
+ """The four prompt templates a scene language's sessions read (``prompts/tracks/``)."""
+
+ env: str
+ zone: str
+ refine: str
+ asset: str
+
+
+#: per language — the three.js templates stay the files they were (byte-identical), the bpy
+#: twins carry the same context keys with Blender wording and the bpy library's calls
+SCENE_TEMPLATES: dict[Language, SceneTemplates] = {
+ Language.SCENE_THREEJS: SceneTemplates("tracks/scene_env.j2", "tracks/scene_zone.j2", "tracks/scene_refine.j2",
+ "tracks/scene_asset.j2"),
+ Language.SCENE_BLENDER: SceneTemplates("tracks/scene_env_bpy.j2", "tracks/scene_zone_bpy.j2", "tracks/scene_refine_bpy.j2",
+ "tracks/scene_asset_bpy.j2"),
+}
+#: ``SceneRuntime.env_file`` per language, for a runtime that does not state it (a fake, an
+#: older runtime): the typed fallback of :func:`env_file`, never a ``.js`` / ``.py`` test
+ENV_FILES: dict[Language, str] = {Language.SCENE_THREEJS: "src/env.js", Language.SCENE_BLENDER: "src/env.py"}
+
+
+def scene_templates(language: Language) -> SceneTemplates:
+ """The templates of a scene language (``KeyError`` for a language the scene track does not run)."""
+ return SCENE_TEMPLATES[language]
+
+
+def env_file(ctx: RunContext) -> str:
+ """The environment module of this run's scene language: the runtime's word (``env_file``),
+ else the typed per-language table."""
+ return getattr(ctx.runtime, "env_file", None) or ENV_FILES[ctx.language]
+
+
+def plan_vec(v: Sequence[float], language: Language, *, extents: bool = False) -> tuple[float, float, float]:
+ """A plan (GLB-frame, Y-up) vector in ``language``'s authoring frame — the identity for a
+ Y-up language, so the three.js prompts keep their numbers byte for byte; a Z-up author (bpy)
+ reads ``(x, -z, y)`` points and ``(w, d, h)`` sizes (D12: the plan itself never changes frame).
+ ``+ 0.0`` folds the ``-0.0`` a negated zero leaves into ``0.0`` (``fmt3`` would print ``-0.000``)
+ and is the identity on every other finite value."""
+ x, y, z = to_authoring_frame(v, language.value, extents=extents)
+ return (x + 0.0, y + 0.0, z + 0.0)
+
+
+def plan_bbox_line(bbox: BBox, language: Language) -> str:
+ """``prompting.bbox_line`` in the authoring frame of ``language``."""
+ return f"centre ({fmt3(plan_vec(bbox.center, language))}) m, extents ({fmt3(plan_vec(bbox.extents, language, extents=True))}) m"
+
+
+def plan_camera_line(c: CameraPlan, language: Language) -> str:
+ """One authored camera as a prompt line, its points in the authoring frame of ``language``."""
+ p, la = plan_vec(c.position, language), plan_vec(c.look_at, language)
+ return (f"- {c.name}: position ({p[0]:.1f}, {p[1]:.1f}, {p[2]:.1f}) look_at ({la[0]:.1f}, {la[1]:.1f}, {la[2]:.1f}) "
+ f"fov {c.fov:.0f} — {c.purpose}")
+
+
class ScenePipeline:
"""No GLB measurement; the placement gate from the build's census (the build's own probe and
preflight reports join the round through ``BuildResult.gates``); render_scene; console caps."""
@@ -115,7 +174,7 @@ class ScenePipeline:
def post_render_gates(self, ctx: RunContext, round_index: int, renders: RenderSet) -> list[GateReport]:
errs = [e for e in renders.console_errors if e.strip()]
- findings = [GateFinding(gate="render_console", severity=Severity.ERROR, target=_guess_target(e, ctx.plan), message=e[:300],
+ findings = [GateFinding(gate="render_console", severity=Severity.ERROR, target=_guess_target(e, ctx), message=e[:300],
data={"kind": "console_error"}, fix_hint="open the named module, fix the thrown error; run the build/probe tool until no console errors")
for e in errs[:MAX_CONSOLE_ERRORS]]
out = [GateReport.of("render_console", findings)]
@@ -216,7 +275,7 @@ class SceneTrack(BaseTrack):
if alias is None:
_, alias = select_assets(list(plan.assets), MAX_ASSETS)
ctx.extra["assets"], ctx.extra["asset_alias"] = assets, alias
- return asset_api_summary(plan, assets, alias)
+ return asset_api_summary(plan, assets, alias, language=ctx.language)
# ---- degradation ------------------------------------------------------
def _strategy(self, ctx: RunContext, stage: str) -> RunContext:
@@ -257,7 +316,19 @@ class SceneTrack(BaseTrack):
task = task_for(gen)
skills_hook.attach_for_round(gen, index=0, kind=kind)
try:
- return generate_for(gen, skills_hook.with_inlined_skill(gen, [task])[0])
+ task = skills_hook.with_inlined_skill(gen, [task])[0]
+ res = generate_for(gen, task)
+ if res.transient and not res.ok and ctx.budget.ok():
+ # ONE transport retry, the round loop's rule (lifecycle: a 503 storm / dropped
+ # socket is not a verdict on the work — the session never really happened):
+ # the same task again under the ``.a2`` label the CLI's own second session
+ # wears, so the ledger and the trajectory dir tell the two apart. Typed:
+ # ``GenerationResult.transient`` only — a quota wall or a session that merely
+ # timed out is not retried. Only while the budget still allows; the clock
+ # check inside ``generate`` stops a retry that would overrun it.
+ ctx.events.emit("stage.transport_retry", stage=stage, label=task.label, detail=res.notes[:500])
+ res = generate_for(gen, task.model_copy(update={"label": f"{task.label}.a2"}))
+ return res
finally:
skills_hook.record_usage(gen, index=0, kind=kind)
ctx.ws.commit(stage)
@@ -288,9 +359,9 @@ class SceneTrack(BaseTrack):
return {"ok": res.ok, "files": [c.path for c in res.files_changed], "notes": res.notes}
def _env_task(self, ctx: RunContext) -> GenerationTask:
- prompt = render("tracks/scene_env.j2", **self._ctx(ctx, recipes=cookbook_sections(ctx, ENV_RECIPES)))
+ prompt = render(scene_templates(ctx.language).env, **self._ctx(ctx, recipes=cookbook_sections(ctx, ENV_RECIPES)))
ctx.record_prompt("scene_env", prompt)
- return GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=["src/env.js"], round=0, kind="env",
+ return GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=[env_file(ctx)], round=0, kind="env",
temperature=0.5, timeout_s=ctx.budget.timeout_s(ENV_TIMEOUT_S, floor_s=120),
images=reference_images(ctx))
@@ -335,15 +406,16 @@ class SceneTrack(BaseTrack):
plan: ScenePlan = ctx.plan # type: ignore[assignment]
names = [z.name for z in batch]
files = [ctx.runtime.zone_file(z.name) for z in batch]
- recipes = cookbook_sections(ctx, ZONE_RECIPES)
+ recipes = cookbook_sections(ctx, ZONE_RECIPES, max_chars=ZONE_RECIPES_MAX_CHARS)
+ template = scene_templates(ctx.language).zone
briefs = []
for i, zone in enumerate(batch):
- neighbours = [f"{z.name}: {bbox_line(z.bbox)}" for z in plan.zones if z.name != zone.name]
+ neighbours = [f"{z.name}: {plan_bbox_line(z.bbox, ctx.language)}" for z in plan.zones if z.name != zone.name]
# a batched session reads ONE copy of the recipes (they are identical per zone)
- briefs.append(render("tracks/scene_zone.j2", **self._ctx(ctx, recipes=recipes if i == 0 else "", zone_name=zone.name, zone_description=zone.description,
- zone_bbox=bbox_line(zone.bbox), zone_contents=zone.contents,
- zone_file=ctx.runtime.zone_file(zone.name), neighbours=neighbours,
- layout=layout_block(ctx.extra.get("layouts", {}).get(zone.name)))))
+ briefs.append(render(template, **self._ctx(ctx, recipes=recipes if i == 0 else "", zone_name=zone.name, zone_description=zone.description,
+ zone_bbox=plan_bbox_line(zone.bbox, ctx.language), zone_contents=zone.contents,
+ zone_file=ctx.runtime.zone_file(zone.name), neighbours=neighbours,
+ layout=layout_block(ctx.extra.get("layouts", {}).get(zone.name), language=ctx.language))))
if len(batch) == 1:
prompt, label = briefs[0], f"zone_{to_snake(names[0])}"
else:
@@ -402,10 +474,10 @@ class SceneTrack(BaseTrack):
def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
files = group.files or ctx.runtime.expected_files(ctx.plan)
lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)
- prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, recipes=refine_recipes(ctx, files), round_index=index, tasks=lines,
- targets=group.targets, files=files, edit_only_these=parallel,
- judge_summary=judge_digest(last),
- current_files=refine_inline_files(ctx, files)))
+ prompt = render(scene_templates(ctx.language).refine, **self._ctx(ctx, recipes=refine_recipes(ctx, files), round_index=index, tasks=lines,
+ targets=group.targets, files=files, edit_only_these=parallel,
+ judge_summary=judge_digest(last),
+ current_files=refine_inline_files(ctx, files)))
ctx.record_prompt("scene_refine", prompt)
# parallel groups are file-disjoint by plan_refine_groups: enforce the split they promised
return GenerationTask(label=f"refine_{group.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),
@@ -424,10 +496,10 @@ class SceneTrack(BaseTrack):
if (ctx.ws.root / rel).is_file():
files = [rel]
files = files or ctx.runtime.expected_files(ctx.plan)
- prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, recipes="", round_index=index, tasks=[report], targets=["build"],
- files=files, edit_only_these=False,
- judge_summary="(no judgment: the scene did not build — fix the errors above first)",
- current_files=refine_inline_files(ctx, files)))
+ prompt = render(scene_templates(ctx.language).refine, **self._ctx(ctx, recipes="", round_index=index, tasks=[report], targets=["build"],
+ files=files, edit_only_these=False,
+ judge_summary="(no judgment: the scene did not build — fix the errors above first)",
+ current_files=refine_inline_files(ctx, files)))
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",
@@ -435,26 +507,34 @@ class SceneTrack(BaseTrack):
# ------------------------------------------------------------------ helpers
def _ctx(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:
+ """The variables every scene template may use. Plan numbers are printed in the AUTHORING
+ frame of the run's language (``plan_vec``: the identity for three.js, so those prompts are
+ byte-identical; a bpy author reads Z-up points and (w, d, h) sizes, D12), plus the
+ runtime's file names (``env_file`` / ``entry_file``) so a template never spells a path."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
- zones_table = "\n".join(f"- {z.name}: {z.description} — {bbox_line(z.bbox)}; contents: {', '.join(z.contents) or '-'}" for z in plan.zones)
- cameras = "\n".join(f"- {c.name}: position ({c.position[0]:.1f}, {c.position[1]:.1f}, {c.position[2]:.1f}) look_at "
- f"({c.look_at[0]:.1f}, {c.look_at[1]:.1f}, {c.look_at[2]:.1f}) fov {c.fov:.0f} — {c.purpose}" for c in plan.cameras)
+ lang = ctx.language
+ zones_table = "\n".join(f"- {z.name}: {z.description} — {plan_bbox_line(z.bbox, lang)}; contents: {', '.join(z.contents) or '-'}"
+ for z in plan.zones)
+ cameras = "\n".join(plan_camera_line(c, lang) for c in plan.cameras)
effects = "\n".join(f"- {e.name} ({e.kind}, on {e.target or 'scene'}): {e.description}" for e in plan.effects) or "(none)"
return base_prompt_context(
- ctx, title=plan.title, setting=plan.setting, mood=plan.mood, bounds=bbox_line(plan.bounds), environment=plan.environment,
+ ctx, title=plan.title, setting=plan.setting, mood=plan.mood, bounds=plan_bbox_line(plan.bounds, lang), environment=plan.environment,
interior=plan.interior, glazed=plan.glazed,
zones_table=zones_table, cameras=cameras, effects=effects, animation="; ".join(plan.animation) or "(none)",
asset_api=ctx.extra.get("asset_api", "(no assets)"),
- textures=texture_pack_prompt(ctx.extra.get("textures") or {}), **extra)
+ textures=texture_pack_prompt(ctx.extra.get("textures") or {}),
+ env_file=env_file(ctx), entry_file=ENTRY_FILE[lang], **extra)
# ----------------------------------------------------------------------------- helpers
def refine_recipes(ctx: RunContext, files: Sequence[str]) -> str:
- """The cookbook chapters that match the files this refine task owns (env / zones)."""
+ """The cookbook chapters that match the files this refine task owns (env / zones), told apart
+ by the RUNTIME's file names (``env_file``, ``zone_file``), never by a suffix test."""
+ zone_files = {ctx.runtime.zone_file(z.name) for z in (getattr(ctx.plan, "zones", None) or [])}
names: list[str] = []
- if any(f.endswith("env.js") for f in files):
+ if env_file(ctx) in files:
names += list(ENV_RECIPES)
- if any("/zones/" in f for f in files) or not names:
+ if any(f in zone_files for f in files) or not names:
names += list(ZONE_RECIPES)
return cookbook_sections(ctx, names)
@@ -468,14 +548,18 @@ def _touched(path: Any, since: float) -> bool:
return False
-def _guess_target(error: str, plan: Any) -> str:
+def _guess_target(error: str, ctx: RunContext) -> str:
+ """The refine target a console error names: a zone or asset by its snake name, the env
+ module or the entry by the RUNTIME's file names (``env_file``, ``ENTRY_FILE``), else overall."""
low = error.lower()
for attr in ("zones", "assets"):
- for item in getattr(plan, attr, None) or []:
+ for item in getattr(ctx.plan, attr, None) or []:
if to_snake(item.name) in low:
return item.name
- if "env.js" in low:
+ # a browser stack frame names the bare file (`at env.js:12:3`), the wrapper the src/ path
+ env, entry = env_file(ctx).lower(), ENTRY_FILE[ctx.language].lower()
+ if env in low or env.rsplit("/", 1)[-1] in low:
return "env"
- if "scene.js" in low:
+ if entry in low or entry.rsplit("/", 1)[-1] in low:
return "composition"
return "overall"
diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.py
index 83895a4c..bb39c2c7 100644
--- a/harness/codeverse3d/tracks/scene_assets.py
+++ b/harness/codeverse3d/tracks/scene_assets.py
@@ -4,6 +4,10 @@
generated **single-shot** (one chat call) + a deterministic node check + ONE
error-feedback repair; a full agent session is the escalation, not the default
(agent sessions cost 10× and 10 minutes per file).
+* ``bpy`` assets (a scene_blender plan's modules) → ``src/assets/<snake>.py`` defining
+ ``build_<snake>(ctx, variant=0)`` — the SAME ladder; the deterministic check builds the
+ one module in a throw-away Blender workspace (``check_bpy_asset``) and measures it off
+ the census GLB like a hero.
* ``blender_glb`` assets are **heroes**: a sub-workspace under ``<ws>/_assets/<snake>``
runs the Blender runtime and climbs the SAME single-shot ladder (``_ladder``) before
an agent session; the GLB is copied to ``public/assets/<snake>.glb``.
@@ -31,7 +35,7 @@ from typing import Any
from pydantic import BaseModel, Field
from codeverse3d.contracts.artifacts import Judgment
-from codeverse3d.contracts.common import ENTRY_FILE, Language, Track
+from codeverse3d.contracts.common import ENTRY_FILE, TRACK_LANGUAGES, Language, Track
from codeverse3d.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, StaticPlan
from codeverse3d.contracts.spec import Constraints, Spec
from codeverse3d.conventions import MAX_TRIS_OBJECT, OBJECT_VIEWS_QUICK, to_pascal, to_snake
@@ -75,6 +79,12 @@ ASSET_AGENT_TIMEOUT_S = 420
#: round 0 did not start until 18.9 min.
ASSET_SESSION_SHARE = 0.15
ASSET_RUBRIC = "asset_v1"
+#: the asset kinds that are a MODULE in the scene workspace (one factory per file, placed by the
+#: zones); ``blender_glb`` is the hero, built as an object and shipped as a GLB
+MODULE_KINDS: frozenset[str] = frozenset({"threejs", "bpy"})
+#: the languages whose asset sessions share the SCENE workspace (a stray write would hit zones /
+#: env, so their tasks are ``edit_only``); a blender hero owns its whole sub-workspace
+SCENE_LANGUAGES: frozenset[Language] = frozenset(TRACK_LANGUAGES[Track.SCENE])
def asset_timeout_s(ctx: Any, floor_s: int) -> int:
@@ -101,11 +111,17 @@ class AssetResult(BaseModel):
-def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], alias: dict[str, str] | None = None) -> str:
- """What zone/composer tasks need to know about each asset (names + sizes + how to get it).
+def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], alias: dict[str, str] | None = None, *,
+ language: Language = Language.SCENE_THREEJS) -> str:
+ """What zone/composer tasks need to know about each asset (names + sizes + how to get it),
+ in the words of the scene language that places them.
- Merged assets (``alias``) point at the surviving factory and the ``opts.variant``
- the zone must pass."""
+ three.js: a module is imported and its factory called; a hero is preloaded into
+ ``ctx.assets`` and cloned. Merged assets (``alias``) point at the surviving factory and
+ the ``opts.variant`` the zone must pass. bpy: the harness builds EVERY module (a merged
+ twin's shim included) and imports every hero before any zone runs, so each is a Collection
+ at ``ctx.assets['<snake>']`` to place as a collection instance — the zone never imports or
+ calls a factory, and a merged twin needs no variant number."""
alias = alias or {}
lines = []
for a in plan.assets:
@@ -114,7 +130,9 @@ def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], alias: d
size = (r.size_m if r and r.size_m and not kept else a.approx_size_m)
s = f"{size[0]:.2f}×{size[1]:.2f}×{size[2]:.2f} m (w×h×d)"
status = "" if (r and r.ok) else " [NOT AVAILABLE — do not reference]"
- if kept:
+ if language is Language.SCENE_BLENDER:
+ lines.append(_bpy_api_line(a, r, kept, s, status))
+ elif kept:
lines.append(f"- {a.name}: use `build{to_pascal(kept)}(THREE, {{ variant: {variant_index(alias, a.name)} }})` "
f"from './assets/{to_snake(kept)}.js' (merged variant), base at y=0, {s}{status}")
elif a.kind == "threejs":
@@ -123,9 +141,27 @@ def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], alias: d
motion = f", carries {r.clips} motion clip(s) (played automatically; `clone.userData.clipOffset` de-phases copies)" if r and r.clips else ""
lines.append(f"- {a.name}: preloaded at `ctx.assets['{to_snake(a.name)}']` (clone it; GLB public/assets/{to_snake(a.name)}.glb), "
f"base at y=0, {s}{motion}{status}")
+ if lines and language is Language.SCENE_BLENDER:
+ lines.insert(0, "Sizes are width × height × depth in metres, the plan's Y-up order: in your Blender frame x = width, "
+ "y = depth, z = height. Every entry is a Collection built at the origin with its base on z = 0 and its "
+ "front facing -Y; place it with `lib.scatter.instance(ctx.collection, ctx.assets['<snake>'], name, x, y, "
+ "height_at=ctx.height_at)` (a collection-instance Empty seated on the ground = ONE placement row).")
return "\n".join(lines) or "(no assets)"
+def _bpy_api_line(a: AssetPlan, r: AssetResult | None, kept: str | None, size: str, status: str) -> str:
+ """One asset's line of the bpy asset API (see ``asset_api_summary``)."""
+ snake = to_snake(a.name)
+ if kept:
+ return (f"- {a.name}: `ctx.assets['{snake}']` — variant {to_snake(kept)} builds (its module `src/assets/{snake}.py` is a "
+ f"harness shim onto `build_{to_snake(kept)}`), {size}{status}")
+ if a.kind == "blender_glb":
+ motion = f", carries {r.clips} keyframed motion clip(s) (its action plays in every instance)" if r and r.clips else ""
+ return (f"- {a.name}: `ctx.assets['{snake}']` — the hero GLB `public/assets/{snake}.glb` imported by the harness "
+ f"into the Blender frame, {size}{motion}{status}")
+ return f"- {a.name}: `ctx.assets['{snake}']` — built by the harness from `src/assets/{snake}.py` (`build_{snake}(ctx, variant=0)`), {size}{status}"
+
+
def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str, AssetResult]:
"""Generate every asset (parallel) and return results keyed by asset name."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
@@ -146,10 +182,12 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,
def _one(asset: AssetPlan) -> AssetResult:
if asset.kind == "blender_glb":
return build_blender_asset(ctx, asset, judge=judge_assets)
+ if asset.kind == "bpy":
+ return build_bpy_asset(ctx, asset, judge=judge_assets)
return build_threejs_asset(ctx, asset, judge=judge_assets)
workers = ctx.settings.limits.max_parallel_agents
- if any(a.kind == "blender_glb" for a in assets):
+ if any(a.kind in ("blender_glb", "bpy") for a in assets): # both kinds check in a Blender process
workers = min(workers, ctx.settings.limits.max_parallel_builds)
results = fan_out(assets, _one, max_workers=workers, label="assets", item_name=lambda a: a.name)
out: dict[str, AssetResult] = {}
@@ -162,7 +200,7 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,
ctx.events.emit("asset.failed", asset=asset.name, error=f"{type(r).__name__}: {r}")
else:
out[asset.name] = r
- shims = write_variant_shims(ctx.ws, alias, {n for n, r in out.items() if r.ok})
+ shims = write_variant_shims(ctx.ws, alias, {n for n, r in out.items() if r.ok}, language=ctx.language)
_record_spec_hashes(ctx, out, assets) # the reuse guard's identity registry (rounds/ bookkeeping)
ctx.ws.commit("assets")
ctx.events.emit("assets.done", ok=[n for n, r in out.items() if r.ok], failed=[n for n, r in out.items() if not r.ok],
@@ -216,10 +254,40 @@ def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
strategy, chk, notes = _ladder(ctx, asset, rel, language=Language.SCENE_THREEJS, files=[rel], check=check,
timeout_s=asset_timeout_s(ctx, 120))
+ return _module_result(ctx, asset, rel, strategy, chk, notes, check=check, language=Language.SCENE_THREEJS, judge=judge)
+
+
+def build_bpy_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
+ """A scene_blender plan's procedural module (``src/assets/<snake>.py``, ``build_<snake>(ctx,
+ variant=0)``): the three.js module's ladder exactly — committed-child reuse, single-shot →
+ ``check_bpy_asset`` (one Blender build of this module alone) → ONE repair → the agent session.
+ ``judge``: the quick-sheet judge runs only when the runtime renders a module on its own
+ (``render_asset``); the scene_blender runtime has none, so the scene judge sees the asset
+ placed, like a three.js module before 2026-09-07."""
+ rel, snake = ctx.runtime.asset_file(asset), to_snake(asset.name)
+ if (ctx.ws.root / rel).is_file() and _spec_hash_matches(ctx, asset):
+ chk0 = check_bpy_asset(ctx, rel, snake, expected_size_m=asset.approx_size_m)
+ if chk0.ran and chk0.ok:
+ ctx.events.emit("asset.generated", asset=asset.name, strategy="reused", ok=True, tris=chk0.tris, errors=[])
+ return AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=chk0.size_m,
+ strategy="reused", notes="committed module reused (Blender build check passed)")
+
+ def check(c: RunContext) -> AssetCheck:
+ return check_bpy_asset(c, rel, snake, expected_size_m=asset.approx_size_m)
+
+ strategy, chk, notes = _ladder(ctx, asset, rel, language=Language.SCENE_BLENDER, files=[rel], check=check,
+ timeout_s=asset_timeout_s(ctx, 120))
+ return _module_result(ctx, asset, rel, strategy, chk, notes, check=check, language=Language.SCENE_BLENDER, judge=judge)
+
+
+def _module_result(ctx: RunContext, asset: AssetPlan, rel: str, strategy: str, chk: AssetCheck | None, notes: str, *,
+ check: Callable[[RunContext], AssetCheck], language: Language, judge: bool) -> AssetResult:
+ """What a MODULE asset's ladder outcome means (both module kinds): a module that will not
+ import / build is NOT AVAILABLE to zones; a merely imperfect one (size off, still a bit
+ plain) stays usable — the ladder already spent a repair on it. Then the quick-sheet judge
+ + ONE fix pass, when the runtime can render the module alone (``render_asset``)."""
if strategy == "outage":
return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=notes)
- # a module that will not import is NOT AVAILABLE to zones; a merely imperfect one
- # (size off, still a bit plain) stays usable — we already spent a repair on it
ok = (ctx.ws.root / rel).is_file() and not (chk is not None and chk.ran and chk.fatal)
result = AssetResult(name=asset.name, kind=asset.kind, ok=ok, path=rel if ok else "", notes=notes, strategy=strategy,
size_m=chk.size_m if chk and chk.size_m else None)
@@ -245,7 +313,7 @@ def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
return _restore
result = _judge_and_fix(ctx, asset, result, lambda out_dir: render_asset(ctx.ws, asset.name, out_dir), files=[rel],
- language=Language.SCENE_THREEJS, after_fix=_after_fix, snapshot=_snapshot)
+ language=language, after_fix=_after_fix, snapshot=_snapshot)
return result
@@ -317,9 +385,9 @@ def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: La
system=_asset_system(ctx, language),
files_hint=files, round=0, kind="asset", temperature=0.5, timeout_s=timeout_s,
images=reference_images(ctx),
- # threejs assets share the scene workspace (a stray write would hit
- # zones/env); blender heroes own their whole sub-workspace
- edit_only=language is Language.SCENE_THREEJS)
+ # scene-language modules share the scene workspace (a stray write would
+ # hit zones/env); blender heroes own their whole sub-workspace
+ edit_only=language in SCENE_LANGUAGES)
return generate_for(ctx, task)
@@ -555,8 +623,8 @@ def _judge_wanted(ctx: RunContext, asset: AssetPlan, chk: AssetCheck | None, *,
def _largest_module(ctx: RunContext) -> str:
- """The name of the plan's biggest ``threejs`` asset by planned volume ('' when none)."""
- mods = [a for a in (getattr(ctx.plan, "assets", None) or []) if a.kind == "threejs"]
+ """The name of the plan's biggest module asset (``MODULE_KINDS``) by planned volume ('' when none)."""
+ mods = [a for a in (getattr(ctx.plan, "assets", None) or []) if a.kind in MODULE_KINDS]
if not mods:
return ""
return max(mods, key=lambda a: a.approx_size_m[0] * a.approx_size_m[1] * a.approx_size_m[2]).name
@@ -629,13 +697,13 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
instructions = [f"- {i.target}: {i.instruction}" for i in verdict.improvement_plan[:4]]
gen = single_shot_ctx(ctx) or ctx
current = _inline(gen, files) if gen.single_shot else ""
- prompt = render("tracks/scene_asset.j2", **base_prompt_context(
+ prompt = render(asset_template(language), **base_prompt_context(
gen, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description,
asset_size=asset.approx_size_m, asset_file=files[0], asset_files=files, asset_language=language.value,
- fix_instructions=instructions, current_code=current, skeleton_files={}, **_scene_context(ctx)))
+ fix_instructions=instructions, current_code=current, skeleton_files={}, library_rows="", **_scene_context(ctx)))
task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, system=_asset_system(gen, language),
files_hint=files, round=0, kind="asset_fix", temperature=0.4,
- edit_only=language is Language.SCENE_THREEJS, timeout_s=asset_timeout_s(ctx, 120))
+ edit_only=language in SCENE_LANGUAGES, timeout_s=asset_timeout_s(ctx, 120))
restore = snapshot() if snapshot is not None else None # BEFORE the fix rewrites the files
res = generate_for(gen, task)
if not res.ok:
@@ -660,6 +728,17 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
# ----------------------------------------------------------------------------- helpers
+def asset_template(language: Language) -> str:
+ """The asset-session template of a scene language (``tracks/scene.SCENE_TEMPLATES``); a blender
+ hero — not a scene language — reads the three.js table's ``scene_asset.j2``, whose bpy branch
+ it has always used."""
+ from codeverse3d.tracks.scene import (
+ SCENE_TEMPLATES, # scene imports this module: resolved at call time
+ )
+
+ return SCENE_TEMPLATES.get(language, SCENE_TEMPLATES[Language.SCENE_THREEJS]).asset
+
+
def _asset_system(ctx: RunContext, language: Language) -> str:
"""The system prompt for one asset generation — same language, DIFFERENT task.
@@ -667,10 +746,14 @@ def _asset_system(ctx: RunContext, language: Language) -> str:
sub-workspace, so it gets the blender language base COMPOSED with the prop-for-a-scene
role overlay. A three.js asset module is not a scene build at all — the scene_threejs
base (lighting, cameras, multi-file) would mislead it — so it gets the dedicated
- asset-module prompt instead of that base.
+ asset-module prompt instead of that base. A bpy module likewise gets its own
+ ``scene_blender/asset.md``, with the prop role overlay that tells it what a scene prop is.
"""
if language is Language.SCENE_THREEJS:
return language_text(Language.SCENE_THREEJS, "asset.md").strip()
+ if language is Language.SCENE_BLENDER:
+ return (language_text(Language.SCENE_BLENDER, "asset.md").strip() + "\n\n"
+ + render("system/role_asset.j2", language=language.value).strip())
return language_system_prompt(Language.BLENDER, role="asset", tools=not is_single_shot(ctx.agent_id))
@@ -685,28 +768,36 @@ def _scene_context(ctx: RunContext) -> dict[str, Any]:
return {"spec_prompt": brief, "constraints": ctx.extra.get("scene_style") or "(none)"} if brief else {}
-#: what names a library row: a camelCase factory right after a backtick (``makeTree(``,
-#: ``patchMoss``) — a bare lowercase one (``seat``, ``block``) is an ordinary word in a sheet —
-#: and the module it lives in (``lib/tree.js``)
-_CATALOG_CALL_RE = re.compile(r"`([a-z]+[A-Z]\w*)[(`]")
-_CATALOG_MODULE_RE = re.compile(r"`lib/(\w+\.js)`")
+#: what names a library row, per scene language: the factory right after a backtick and the module
+#: it lives in. three.js: a camelCase call (``makeTree(``, ``patchMoss``) — a bare lowercase one
+#: (``seat``, ``block``) is an ordinary word in a sheet — and ``lib/tree.js``. bpy: the library is
+#: snake_case (``tree(``, ``water_surface(``) and ``lib/vegetation.py``; a sheet that says "a stone
+#: water trough" draws the water row too, which costs a line and never misleads.
+_CATALOG_RES: dict[Language, tuple[re.Pattern[str], re.Pattern[str]]] = {
+ Language.SCENE_THREEJS: (re.compile(r"`([a-z]+[A-Z]\w*)[(`]"), re.compile(r"`lib/(\w+\.js)`")),
+ Language.SCENE_BLENDER: (re.compile(r"`([a-z_][a-z0-9_]*)\("), re.compile(r"`lib/(\w+\.py)`")),
+}
-def library_rows(description: str) -> str:
+def library_rows(description: str, language: Language = Language.SCENE_THREEJS) -> str:
"""The effects-catalog rows of the library factories an asset sheet names, by call or by module
- (D100): a three.js asset may compose ``src/lib/``, and a single-shot writer cannot open the
- module to learn the call — the rows carry it. The whole catalog is a zone-sized prompt."""
+ (D100): a module asset may compose ``src/lib/``, and a single-shot writer cannot open the
+ module to learn the call — the rows carry it. The whole catalog is a zone-sized prompt.
+ ``""`` for a language without a catalog (a blender hero)."""
+ if language not in _CATALOG_RES:
+ return ""
+ call_re, module_re = _CATALOG_RES[language]
words = set(re.findall(r"\w+(?:\.\w+)*", description))
- return "\n".join(line for line in language_text(Language.SCENE_THREEJS, "effects_catalog.md").splitlines()
+ return "\n".join(line for line in language_text(language, "effects_catalog.md").splitlines()
if line.startswith("| ")
- and words & (set(_CATALOG_CALL_RE.findall(line)) | set(_CATALOG_MODULE_RE.findall(line))))
+ and words & (set(call_re.findall(line)) | set(module_re.findall(line))))
def _asset_prompt(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str] | None = None) -> str:
files = list(files or [rel])
- prompt = render("tracks/scene_asset.j2", **base_prompt_context(
+ prompt = render(asset_template(language), **base_prompt_context(
ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description, asset_size=asset.approx_size_m,
- library_rows=library_rows(asset.description) if language is Language.SCENE_THREEJS else "",
+ library_rows=library_rows(asset.description, language),
asset_file=rel, asset_files=files, asset_language=language.value, fix_instructions=[], current_code="",
# a single-shot hero has to see the multi-file skeleton it is filling in, like a static object
skeleton_files=skeleton_files(ctx) if (ctx.single_shot and len(files) > 1) else {},
@@ -815,6 +906,102 @@ def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: fl
return chk
+#: the probe zone of a bpy asset check: ONE collection instance of the module at the origin, so
+#: the census GLB (which excludes the asset sources themselves) carries exactly the asset's
+#: evaluated geometry — measured like a hero's GLB, in the same Y-up frame
+BPY_CHECK_ZONE = "check"
+
+
+def _bpy_check_workspace(ws: Workspace, rel: str, snake: str) -> Workspace:
+ """A throw-away workspace under ``_assets/`` (git-ignored, beside the hero sub-workspaces)
+ holding only what one module's build needs: an entry that lists this asset alone, the
+ module, the harness library it may import, and the probe zone. Rebuilt from scratch on
+ every check so a module's last attempt never shadows its next."""
+ from codeverse3d.languages.scene_blender import render_scene_py
+
+ scratch = Workspace(ws.root / "_assets" / f"{snake}_check")
+ if scratch.root.exists():
+ shutil.rmtree(scratch.root)
+ for sub in ("assets", "zones", "lib"):
+ (scratch.src / sub).mkdir(parents=True, exist_ok=True)
+ scratch.artifacts.mkdir(parents=True, exist_ok=True)
+ (scratch.root / ENTRY_FILE[Language.SCENE_BLENDER]).write_text(render_scene_py([], [snake], [], []))
+ shutil.copyfile(ws.root / rel, scratch.src / "assets" / f"{snake}.py")
+ lib = ws.src / "lib"
+ for src in sorted(lib.glob("*.py")) if lib.is_dir() else []:
+ shutil.copyfile(src, scratch.src / "lib" / src.name)
+ (scratch.src / "zones" / f"{BPY_CHECK_ZONE}.py").write_text(
+ f'"""The harness\'s probe zone: one instance of {snake}, so the census GLB measures it."""\n'
+ "import bpy\n\n\n"
+ "def build(ctx):\n"
+ f" ob = bpy.data.objects.new({to_pascal(snake)!r}, None)\n"
+ ' ob.instance_type = "COLLECTION"\n'
+ f" ob.instance_collection = ctx.assets[{snake!r}]\n"
+ " ctx.collection.objects.link(ob)\n"
+ " return ctx.collection\n")
+ return scratch
+
+
+def check_bpy_asset(ctx: RunContext, rel: str, snake: str, *, expected_size_m: tuple[float, float, float] | None = None,
+ timeout_s: float | None = None) -> AssetCheck:
+ """Build ``src/assets/<snake>.py`` alone in Blender and inspect what it made.
+
+ The scene_blender wrapper (``runtime.run_wrapper``) runs on a throw-away workspace whose
+ entry lists only this asset and whose one zone instances it: a module that raises is FATAL
+ with its ``file:line`` (the wrapper's isolated-stage report), the module's own triangles
+ come from the bpy facts, and the instance's size, ground contact, mesh and material counts
+ come off the census GLB through ``services.measure`` — the hero's measurement, so the
+ soft findings (size vs the plan beyond 2.5×, sunk below z = 0, the triangle budget, a
+ one-box placeholder) are the three.js module's exactly.
+
+ Never raises: a runtime without a Blender build (a fake, no binary) and a harness fault inside
+ the wrapper (``BuildResult.harness_failure``: the census-GLB writer) yield ``ran=False, ok=True``
+ — the scene build will catch it."""
+ path = ctx.ws.root / rel
+ if not path.is_file():
+ return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
+ run_wrapper = getattr(ctx.runtime, "run_wrapper", None)
+ if not callable(run_wrapper):
+ return AssetCheck(ok=True, ran=False, warnings=["checker unavailable: the runtime builds no module on its own"])
+ try:
+ scratch = _bpy_check_workspace(ctx.ws, rel, snake)
+ run = run_wrapper(scratch, scratch.artifacts, zones={BPY_CHECK_ZONE: to_pascal(BPY_CHECK_ZONE)}, blend=False,
+ timeout_s=float(timeout_s or ctx.settings.limits.build_timeout_s))
+ except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker
+ log.warning("bpy asset check could not run for %s: %s", rel, e)
+ return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])
+ report = run.report or {}
+ for e in report.get("errors") or []:
+ if e.get("stage") == "asset" and e.get("name") == snake:
+ where = f"{e.get('error_file') or rel}:{e.get('error_line')}" if e.get("error_line") else str(e.get("error_file") or rel)
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"{where}: {e.get('error_type')}: {str(e.get('error_message'))[:300]}"])
+ if run.result.harness_failure:
+ # the wrapper's OWN instrumentation failed after the stages ran (``CensusGlbError``: the
+ # census-GLB writer), not the module — the rule of a runtime without Blender: never a blocker
+ log.warning("bpy asset check could not finish for %s: %s", rel, run.result.error_type)
+ return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {run.result.error_type}"])
+ if not run.result.ok:
+ # the wrapper itself did not finish — a build that never ends or dies (an unbounded loop,
+ # an allocation past the rlimit) is this module's doing: the entry lists nothing else
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"the module's build did not finish: {run.result.error_type}: {run.result.error_message}"[:300]])
+ if any(e.get("stage") == "zone" for e in report.get("errors") or []):
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"build_{snake}(ctx) returned no Collection the scene could instance (ctx.assets[{snake!r}] is missing)"])
+ chk = AssetCheck(ok=True, ran=True, tris=int((run.facts or {}).get("unique_tris") or 0))
+ try:
+ m = ctx.services.measure(scratch.artifacts / "census.glb")
+ except Exception as e: # noqa: BLE001 — a module that built but cannot be measured is still usable
+ chk.warnings.append(f"measure unavailable: {type(e).__name__}")
+ return chk
+ chk.size_m = (round(m.extents[0], 3), round(m.extents[1], 3), round(m.extents[2], 3))
+ chk.min_y, chk.meshes, chk.materials = round(m.bbox_min[1], 3), m.n_meshes, m.materials
+ chk.tris = chk.tris or m.tri_count
+ _soft_findings(chk, expected_size_m)
+ return chk
+
+
def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None, *, max_tris: int = ASSET_MAX_TRIS) -> None:
"""Findings that make the asset WRONG but not broken → errors worth one repair."""
if not chk.ok:
@@ -943,23 +1130,34 @@ def read_dedupe_note(ws: Workspace) -> dict[str, str] | None:
return None if data is None else dict(data.get("alias") or {})
-def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str]) -> list[str]:
+def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str], *,
+ language: Language = Language.SCENE_THREEJS) -> list[str]:
"""Replace a merged asset's skeleton stub with a shim onto the surviving factory.
- Zone code is TOLD to call ``build<Kept>(THREE, {variant: n})``, but a zone that
- imports the old name anyway must get the real prop, not the placeholder blockout
- box the skeleton left behind."""
+ three.js: zone code is TOLD to call ``build<Kept>(THREE, {variant: n})``, but a zone that
+ imports the old name anyway must get the real prop, not the placeholder blockout box the
+ skeleton left behind. bpy: the wrapper builds every ``src/assets/*.py`` into
+ ``ctx.assets``, so the shim IS how the merged twin exists — ``build_<dropped>`` builds the
+ survivor's variant into its own Collection and the zones place it by its own name."""
written: list[str] = []
for dropped, kept in sorted(alias.items()):
if kept not in available:
continue
- rel = f"src/assets/{to_snake(dropped)}.js"
+ variant = variant_index(alias, dropped)
+ if language is Language.SCENE_BLENDER:
+ rel = f"src/assets/{to_snake(dropped)}.py"
+ text = (f'"""{dropped} is a variant of {kept} (assets were merged into one factory): the harness\'s shim."""\n'
+ f"from assets.{to_snake(kept)} import build_{to_snake(kept)}\n\n\n"
+ f"def build_{to_snake(dropped)}(ctx, variant={variant}):\n"
+ f" return build_{to_snake(kept)}(ctx, variant=variant)\n")
+ else:
+ rel = f"src/assets/{to_snake(dropped)}.js"
+ text = (f"// {dropped} is a variant of {kept} (assets were merged into one factory).\n"
+ f"import {{ build{to_pascal(kept)} }} from './{to_snake(kept)}.js';\n\n"
+ f"export function build{to_pascal(dropped)}(THREE, opts = {{}}) {{\n"
+ f" return build{to_pascal(kept)}(THREE, {{ variant: {variant}, ...opts }});\n}}\n")
path = ws.root / rel
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(
- f"// {dropped} is a variant of {kept} (assets were merged into one factory).\n"
- f"import {{ build{to_pascal(kept)} }} from './{to_snake(kept)}.js';\n\n"
- f"export function build{to_pascal(dropped)}(THREE, opts = {{}}) {{\n"
- f" return build{to_pascal(kept)}(THREE, {{ variant: {variant_index(alias, dropped)}, ...opts }});\n}}\n")
+ path.write_text(text)
written.append(rel)
return written
diff --git a/harness/codeverse3d/tracks/skills_hook.py b/harness/codeverse3d/tracks/skills_hook.py
index 8fe6effb..4d0d2f8e 100644
--- a/harness/codeverse3d/tracks/skills_hook.py
+++ b/harness/codeverse3d/tracks/skills_hook.py
@@ -58,7 +58,8 @@ def attach_for_round(ctx: RunContext, *, index: int, kind: str, findings: Sequen
for sel in got.selections:
ctx.record_prompt(f"skill:{sel.name}", sel.skill.body)
ctx.events.emit("skills.attached", round=index, kind=kind, skills=got.listed,
- index_tokens=got.index_tokens, inlined=got.inlined or None, reasons=got.reasons)
+ index_tokens=got.index_tokens, inlined=got.inlined or None, reasons=got.reasons,
+ variant=got.variant)
return got
@@ -114,7 +115,7 @@ def record_usage(ctx: RunContext, *, index: int, kind: str) -> SkillsUsage | Non
usage = probe_reads(ctx.ws.root, got)
append_usage(ctx.ws.root, usage, round=index, kind=kind, agent=ctx.agent_id,
track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),
- language=ctx.language.value)
+ language=ctx.language.value, variant=got.variant)
except Exception as e: # noqa: BLE001 — telemetry never costs a round
log.warning("skills telemetry failed for round %d: %s", index, e)
return None
diff --git a/harness/codeverse3d/tracks/zone_layout.py b/harness/codeverse3d/tracks/zone_layout.py
index d56b4d0f..3473afb1 100644
--- a/harness/codeverse3d/tracks/zone_layout.py
+++ b/harness/codeverse3d/tracks/zone_layout.py
@@ -20,8 +20,9 @@ import math
from typing import Any
from codeverse3d.contracts.chat import ChatMessage, ChatRequest
+from codeverse3d.contracts.common import Language
from codeverse3d.contracts.plan import ScenePlan, ZoneLayout, ZonePlan
-from codeverse3d.conventions import to_snake
+from codeverse3d.conventions import Frame, authoring_frame, to_authoring_frame, to_snake
from codeverse3d.models.schema_utils import parse_json_lenient
from codeverse3d.orchestrator import BudgetExceeded
from codeverse3d.proc import NULL_EVENTS, fan_out
@@ -116,8 +117,21 @@ def validate_layout(layout: ZoneLayout, zone: ZonePlan, plan: ScenePlan) -> str:
return "; ".join(problems)
-def layout_block(layout: ZoneLayout | dict[str, Any] | None) -> str:
- """The prompt table a zone builder realises (`""` when there is no layout)."""
+def ground_point(xz: tuple[float, float], language: Language | str) -> tuple[float, float]:
+ """A layout's ground point — ``(x, z)`` in the plan's Y-up frame — as the two horizontal
+ coordinates an author of ``language`` places with: the same pair for a Y-up language, ``(x, y)``
+ with ``y = -z`` for a Z-up one (``conventions.to_authoring_frame``; D12: the plan stays Y-up,
+ only what the author reads is converted)."""
+ v = to_authoring_frame((xz[0], 0.0, xz[1]), str(language))
+ x, y = (v[0], v[1]) if authoring_frame(str(language)) is Frame.Z_UP_NEG_Y_FRONT else (v[0], v[2])
+ # ``+ 0.0`` folds the ``-0.0`` a negated zero leaves (z = 0 is the director's default cluster line;
+ # the brief would print ``(3.0, -0.0)``) — the fold ``tracks.scene.plan_vec`` uses
+ return (x + 0.0, y + 0.0)
+
+
+def layout_block(layout: ZoneLayout | dict[str, Any] | None, *, language: Language | str = Language.SCENE_THREEJS) -> str:
+ """The prompt table a zone builder realises (`""` when there is no layout), its points in the
+ authoring frame of ``language`` (scene_threejs's reads the layout's own numbers)."""
if layout is None:
return ""
lay = layout if isinstance(layout, ZoneLayout) else ZoneLayout.model_validate(layout)
@@ -125,10 +139,11 @@ def layout_block(layout: ZoneLayout | dict[str, Any] | None) -> str:
for p in lay.placements:
faces = f", facing {p.faces}" if p.faces else ""
support = f", on {p.support}" if p.support and p.support != "ground" else ""
- lines.append(f"- {p.count}x {p.asset} around ({p.cluster[0]:.1f}, {p.cluster[1]:.1f}) "
+ cx, cz = ground_point(p.cluster, language)
+ lines.append(f"- {p.count}x {p.asset} around ({cx:.1f}, {cz:.1f}) "
f"spread {p.spread_m:.1f} m{faces}{support}")
if lay.path_points:
- pts = " -> ".join(f"({x:.1f}, {z:.1f})" for x, z in lay.path_points)
+ pts = " -> ".join("({:.1f}, {:.1f})".format(*ground_point(pt, language)) for pt in lay.path_points)
lines.append(f"- path polyline: {pts}")
dress = [f"{n} {label}" for n, label in ((lay.mid_props, "mid props"), (lay.small_props, "small props"),
(lay.ground_cover, "ground-cover instances")) if n]
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index f4c516cd..ec63b1ae 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -1,7 +1,7 @@
# 3dcodeverse harness — architecture
Package `codeverse3d`, CLI `3dcodeverse` (short alias `3dcode`), repo location
-`/home/yipeng/3dcodeverse/harness`. Backend only. Python 3.13 (one fixed version), a small Node
+`harness/` in the 3dcodeverse checkout. Backend only. Python 3.13 (one fixed version), a small Node
runtime (`runtime_js/`) for everything Three.js / headless Chrome, and moderngl
for the graphics track. Checked against the code on 2026-09-22; design history and deviations are in
`docs/DECISIONS.md`, how-to in `docs/RUNBOOK.md`, evaluation protocol in
@@ -131,6 +131,10 @@ codeverse3d/
scene_blender render driver (render_bpy_scene) and what they
share (_wrapper_common: script run + error mapping + report; _census: the Blender census;
_census_glb: scene_blender's census GLB writer, D102)
+ scene_blender/starter/src/ is its plan-less example (scene.py, env.py, zones/{hamlet,
+ lakeside, orchard}.py, assets/{crate, lantern_post}.py) and lib/ the harness-owned bpy library
+ (D51 for this language: noise, mesh, materials, terrain, sky, lighting, water, vegetation,
+ architecture, scatter, place, figure, motion), indexed by prompts/scene_blender/effects_catalog.md
spatial/ node.py, render.py, observe.py, tool_common.py (shared tool plumbing),
render_scene.py (judge view subset, content-fitted orbit),
render_blender.py (scene_blender: Blender pixels under a GPU slot + CPU fallback,
@@ -138,8 +142,9 @@ codeverse3d/
frame_metrics.py (scene_frames gate), frame_motion.py (measured inter-frame motion),
scene_placement.py (scene_placement gate = the check_placement tool's verdict,
placement_gate(ws, census, plan) for both: floating / sunken /
- unsupported / interpenetration per placed asset from the probe census's placement
- table, runtime_js/lib/host_placement.mjs; added 2026-08-26),
+ unsupported / interpenetration / cantilevered per placed asset + free_exempt per
+ report from the probe census's placement table, runtime_js/lib/host_placement.mjs;
+ thresholds = Settings.placement, D105; added 2026-08-26),
gl_render.py (GlHost), frame_stats.py (gl_frames),
sheet.py (montage_2x2, crop_region), measure.py, connectivity.py,
contract.py (authoring-frame hints), sections.py (the cross_section tool and the
@@ -153,13 +158,16 @@ codeverse3d/
Render modes are contracts.artifacts.RENDER_MODES (shaded wire normals silhouette
clay — no 'depth'); build error_type spellings are languages/_common.MISSING_ENTRY
("MissingEntryFile") and BUILD_TIMEOUT ("BuildTimeout") for every runtime
- skills/ registry.py (typed ROUTES + the router that evaluates them),
- model.py (Skill/Selection + the SKILL.md loader), prompting.py
- (per-backend delivery policy + the index/mandate text),
- materialize.py,
- telemetry.py (the read probe: the CLIs' own tool calls first, atime as
- fallback); its switches are Settings fields (C3D_SKILLS*, ON by default since
- 2026-09-22)
+ skills/ registry.py (typed ROUTES + the router that evaluates them; select takes a
+ variant's extra rows / boosts / disabled ids, effective_priority clamps a
+ boost at the gate-fired floor), model.py (Skill/Selection + the SKILL.md
+ loader), prompting.py (per-backend delivery policy + the index/mandate text),
+ materialize.py, telemetry.py (the read probe: the CLIs' own tool calls first,
+ atime as fallback); its switches are Settings fields (C3D_SKILLS*, ON by
+ default since 2026-09-22). variants/<name>/ (D105) is the skills half of a
+ variant overlay: bundles that shadow base bundles by name (library_roots /
+ all_skills merge it while the variant is active), their _claims/, and
+ routes.toml parsed by __init__.variants_table into typed rows (tomllib)
cost/ types.py (CallCost/Stage/Role) ledger.py (append-only telemetry/cost.jsonl + price provenance)
context.py (per-call > ambient attribution) instrument.py (MeteredChatModel /
MeteredAgent — one row per ChatModel.generate; one session row only for a backend
@@ -247,6 +255,12 @@ codeverse3d/
until 2026-09-22 the contract came through the runtime, the cookbook through
tracks/common, the system prompt and the catalog through tracks/prompting). sections.py splits that
markdown into chapters so a STAGE can name the recipes it needs.
+ variants.py (D105): per-model OVERLAYS — variants/<name>/<rel> shadows <rel> for
+ load_text / render / language_text while that variant is active (a ContextVar
+ BaseTrack.run sets around the whole run from RunOptions.variant, else the
+ C3D_VARIANT / C3D_VARIANTS switch, resolved by exact generator id — never a
+ regex); variant.toml = name/version/generators/knobs, variant_hash covers the
+ prompt + skills overlays and lands in the record. variants/argon/ ships empty.
The other half of the split: codeverse3d/skills/ is what an AGENT chooses
to read (SKILL.md + references/ + a _claims file pinning its numbers to
live constants). A file that tries to be both is the bug this prevents.
@@ -426,8 +440,9 @@ must-acceptance and
`PairwiseJudge` (position-swapped, tie on disagreement; only `3dcode pick --by pairwise` asks it); `ReferenceJudge` for
image-conditioned specs.
Rubrics (pass threshold 0.70 unless named): `static_object_v1` (0.72), `articulated_v1`
-(requires pose views: the `missing_pose_sheet` cap), `scene_v1` (frame-gate caps
-dark/blown/flat/content_small), `asset_v1`, `reference_v1`, `shader_v2` (graphics, `gl_frames`
+(requires pose views: the `missing_pose_sheet` cap), `scene_v2` (D105: placement caps floating 0.60 / sunken 0.65 /
+interpenetration 0.70 / scale 0.75 / free_exempt 0.75 measured by `scene_placement`, frame-gate caps
+dark/blown/flat/content_small, graded must-acceptance; `scene_v1` is kept frozen for replays), `asset_v1`, `reference_v1`, `shader_v2` (graphics, `gl_frames`
caps; also the `LikenessJudge` default); `shader_v1` stays for calibration replays only.
**Calibration** (`addons/calibration.py`: re-judges recorded rounds, n samples each) is why the
@@ -569,7 +584,7 @@ the since-deleted in-process `api-agent` and the since-removed pass / plateau st
`n_samples ≥ 3` for decisions. Detail crops are position-heuristic (no 2D part
boxes yet).
* Scene judging is deliberately narrow: the judge sees the scene's OWN cameras (first,
- and the detail crop is taken from one of them) plus at most three overview-rig tiles;
+ and the detail crop is taken from one of them) plus at most four overview-rig tiles (the fourth is the low contact camera `overview_low_front`, D105);
the harness's eye-level rig is a diagnostic only. A `must` acceptance item the harness
cannot verify caps a round at 0.60 AND fails its verdict, so on the scene track only the spec's
`must_have` list keeps that priority (the plan's own checklist is `should`).
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index b48f1be6..1d9415bc 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -15,10 +15,13 @@ Reproduce:
3dcode cost prices [--unverified] # the price table + provenance
```
-The audit is `codeverse3d/addons/costreport/audit.py`; it reconstructs a per-call ledger from
-old runs (`codeverse3d/cost/reconstruct.py`), so it works on every run recorded so
-far — no re-instrumentation needed. `eval/bench/out/compare_v1_full` (a partial,
-superseded compare battery) is excluded.
+The audit is `codeverse3d/addons/costreport/audit.py`. Part I was measured with a
+reconstruction of per-call rows from those runs' trajectories, verdicts and events
+(`cost/reconstruct.py`); every run since 2026-08-23 writes its own ledger, the reconstruction
+went on 2026-09-22 (434 of 467 archived runs carry a ledger; the 33 without are five v1
+batteries outside the repo), and `3dcode cost` now reads the ledger alone — so Part I's
+figures are the audit's record, not something this tree re-derives.
+`eval/bench/out/compare_v1_full` (a partial, superseded compare battery) is excluded.
> **Re-run 2026-08-23 (wave 3).** Every figure in Part I below was recomputed
> after a de-duplication bug in the reconstruction was fixed (§6): a retried agent
@@ -198,9 +201,9 @@ model — **88% of the clock is waiting for a model**, 12% is the harness
> the in-run best with the judgement stops: a run is now the baseline + `--rounds` refine
> rounds, each built on the round before it, every round is kept, and which one to hand
> over is picked after the run (`addons/select`). A round that scored lower is a candidate
-> for that pick, not waste, so `3dcode cost` no longer reports those kinds (nor the
-> `cost.round` `regression` / `zero_delta` flags). "Repair loop that never converged" is
-> now repair money spent in a round that still did not build; post-budget stays.
+> for that pick, not waste, so `3dcode cost` no longer reports those kinds (and the
+> `cost.round` event that carried their flags went too, §32). "Repair loop that never
+> converged" is now repair money spent in a round that still did not build; post-budget stays.
Concrete examples:
@@ -271,12 +274,12 @@ above are what `audit_runs()` prints today, and the script that prints them is i
the scratchpad; anyone who can reproduce 25/$4.37 should say which run set it used.
**Both holes are now closed at the source, so this section is about history:**
-the live ledger (§12) writes one row per call at the time of the call, the
-`BudgetGuard` charges the planner, aborted rounds, retried sessions and the
-texture pass through the same door, and a post-hoc pass joins the run's ledger
-(`3dcode texture pass` opens it with `create=False`). A run recorded from now on
-cannot have an off-record dollar; the reconstruction path exists for the 61 runs
-recorded before it.
+the live ledger (§12) writes one row per call at the time of the call — the planner,
+aborted rounds, retried sessions and the texture pass included — and a post-hoc pass joins
+the run's ledger (`3dcode texture pass` opens it with `create=False`); since 2026-09-22 the
+record's total IS that ledger's sum (§32). A run recorded from now on
+cannot have an off-record dollar; the reconstruction that audited the 61 runs recorded
+before it went on 2026-09-22, and with it `tests/cost/test_reconstruct.py`.
## 7. Price hygiene (checked 2026-08-23)
@@ -336,9 +339,10 @@ residency (1.1x) and fast-mode multipliers, per-search server-tool fees.
| role | model | $/call | measured quality | when |
|---|---|---|---|---|
| planner | `gemini:gemini-3.7-flash` ★ | $0.013 | no failure attributable to the planner | always — the plan is 0.8% of a run |
-| generator | `gemini-cli:gemini-3.7-flash` ★ | $0.73 | 0.827 on compare_v1 | default for every track with tools since 2026-08-28 |
+| generator | `agy:gemini-4-argon` ★ | not yet measured | — | default for every track with tools since 2026-10-13 (D103: gemini-cli removed; agy in Gemini-API mode, pool key + MCP, priced at list) |
+| generator | `gemini-cli:gemini-3.7-flash` (removed in D103) | $0.73 | 0.827 on compare_v1 | the default 2026-08-28 – 2026-10-13; the expectation the agy arm is held to until a battery re-measures it |
| generator | `single-shot:gemini:gemini-3.7-flash` | $0.05 | graphics: 5/6 passed, median 0.810 | glsl / opengl — one file, compiler feedback |
-| generator | `gemini-cli:gemini-3.6-flash` | $0.52 | compare_v1 mean 0.835 (best arm measured) | the cheaper arm, and the one every recorded battery was run on |
+| generator | `gemini-cli:gemini-3.6-flash` (removed in D103; `agy:gemini-3.6-flash` is its successor) | $0.52 | compare_v1 mean 0.835 (best arm measured) | the cheaper arm, and the one every recorded battery was run on |
| generator | `codex:gpt-5.6-sol` | $1.93 in-loop / $0.20 one-shot | one-shot 0.786 | strong one-shot baseline, expensive loop |
| generator | `oneshot:claude-code` | $1.04 | 0.673, 0/2 passed | not for bulk generation |
| judge | `gemini:gemini-3.1-pro-preview` ★ | $0.060 | σ 0.030, pearson(gate errors, score) **+0.63** | every decision that persists |
@@ -383,13 +387,14 @@ the model, is what makes the artifact), and cheaper judges (§8).
## 10. The cost ledger (`codeverse3d/cost/`)
```python
-from codeverse3d.cost import record_call, load_ledger, summarise
+from codeverse3d.cost import record_call, load_ledger
+from codeverse3d.cost.ledger import summarise
-with run_ledger(ws.root): # <run>/telemetry/cost.jsonl (cost_ledger.jsonl = symlink alias)
+with run_ledger(ws.root): # <run>/telemetry/cost.jsonl
record_call(res.usage, run=ws.slug, round=idx, stage="refine", role="generator",
label=job.label, outcome=res.exit_reason) # one append-only JSONL row
-rows = load_ledger(ws.root) # telemetry/cost.jsonl, else the pre-2026-08-23 root file
+rows = load_ledger(ws.root) # telemetry/cost.jsonl
summarise(rows).dimension("stage")["judge"].cost_usd
```
@@ -400,11 +405,6 @@ prices actually used, price_source + price_approximate + price_checked
source`. Writing never raises and never blocks a run; unknown models are
recorded at $0 **and flagged**, never silently dropped.
-Until the call sites are wired, `codeverse3d.cost.reconstruct` rebuilds the same
-rows from `record.json` + `events.jsonl` + `trajectories/**` — that is what this
-audit runs on, and it reconciles to `record.total_usage` on every run (or says
-why it does not, §6).
-
One helper exists for the callers:
* `estimate_call(model_id, prompt=…, n_images=…, output_tokens=…)` →
@@ -447,8 +447,8 @@ out not to pay.
captioner, texturing and single-shot generation.
* **`MeteredAgent`** wraps everything `agents.get_coding_agent` hands out: it sets
the ambient round/stage for the session (so the rows above land in the right
- bucket) and, for a backend whose calls we cannot see (gemini-cli / claude-code / codex /
- agy), records one session row from `AgentResult.usage`.
+ bucket) and, for a backend whose calls we cannot see (claude-code / codex / agy; gemini-cli
+ until D103), records one session row from `AgentResult.usage`.
**Which backends those are is a property of the backend, not a guess.** The
first version asked "did anybody write a ledger row while this session ran?"
@@ -474,10 +474,9 @@ assemble, rebuild → repair, asset / asset_fix → assets); before 2026-08-29 t
landed in `other`. Candidate generation sessions carry `stage=candidate` with labels
`baseline_c<k>`; candidate judge money is booked `stage=judge`, and the pairwise tie-break
`stage=pairwise` (its ledger row carries `role=judge`, label `pairwise:…`). Role, label and
-round live on the `CallCost` row, never on the guard — `BudgetGuard.charge/add` take
-`(usage, *, stage, enforce)` only since 2026-08-30 (D45). `audit.lost_candidate` counts
-generator sessions only and reads both label forms — `baseline_c<k>` (live) and
-`c<k>:baseline` (reconstructed).
+round live on the `CallCost` row — and since 2026-09-22 the guard keeps no money at all (§32).
+`audit.lost_candidate` counts
+generator sessions only, by their `baseline_c<k>` label.
**Who opens a ledger.** `3dcode make` / `3dcode resume` (`cli.main._run_track`),
`3dcode texture pass` (with `create=False`), **and the bench drivers** —
@@ -497,25 +496,22 @@ token counts, the three **unit prices actually used** plus their provenance
`cache_hit`, outcome and `n_calls`. Writing never raises and never blocks: a
pricing failure logs and keeps the recorded dollar.
-**Where it lands.** `<run>/telemetry/cost.jsonl` (the run-layout telemetry
-bucket), with `<run>/cost_ledger.jsonl` left as a relative symlink so
-`record.telemetry.live_ledger_path` and the `telemetry/usage.jsonl` alias keep
-working — one physical copy. A call made with no run context (a `3dcode judge`
+**Where it lands.** `<run>/telemetry/cost.jsonl` (the run-layout telemetry bucket) — its
+one name since 2026-09-22: the root `cost_ledger.jsonl` and `telemetry/usage.jsonl` aliases
+are no longer written or read. A call made with no run context (a `3dcode judge`
outside a run, a bench script, a notebook) goes to a per-process log under
-`<cache_dir>/cost/`; `C3D_COST_LEDGER=off` disables writing entirely.
+`<cache_dir>/cost/`. There is no off switch: the ledger is the only record of money (§32).
-**No double counting.** `BudgetGuard` only buckets and enforces; `MeteredAgent` /
-`MeteredChatModel` are the one writer of `telemetry/cost.jsonl`, and `BaseTrack.run`
-opens the run ledger itself. The guard's own aggregate writer and its
-`per_call_metering()` sentinel were deleted 2026-08-29: every production entry point
-(`3dcode make`, the bench drivers) opened `run_ledger` first, so it never wrote there —
-and with `C3D_COST_LEDGER=off` it wrote anyway, which is now really off.
+**No double counting.** `MeteredAgent` / `MeteredChatModel` (and the image model's own row)
+are the one writer of `telemetry/cost.jsonl`, and `BaseTrack.run` opens the run ledger itself.
+The guard's own aggregate writer and its `per_call_metering()` sentinel were deleted
+2026-08-29, and its money on 2026-09-22 (§32).
-**Reading it.** `cost.reconstruct.reconstruct_run` prefers a live ledger and
-falls back to rebuilding from trajectories / verdicts / events, so
-`3dcode cost` and the run layout's `telemetry/cost.json`
-both pick the live rows up automatically and the 61 recorded runs keep auditing
-(`RunLedger.source` says `live` or `reconstructed`).
+**Reading it.** `3dcode cost` (`addons/costreport/audit.read_run` / `read_cell`) and the run
+layout's `telemetry/cost.json` read `telemetry/cost.jsonl` and nothing else; a run without one
+has no rows. A run in a battery is named by its place under the audited path (`RunId`), so an
+A/B battery's control and variant cells of one prompt stay two runs (they shared one label
+while the name was the cell's last two path segments).
### Verified on two fresh live runs
@@ -675,7 +671,7 @@ given**, so `3dcode resume` reproduces it.
| | economy | balanced | quality |
|---|---|---|---|
-| generator | `single-shot:gemini:gemini-3.7-flash` | `gemini-cli:gemini-3.7-flash` | `gemini-cli:gemini-3.7-flash` |
+| generator | `single-shot:gemini:gemini-3.7-flash` | `agy:gemini-4-argon` | `agy:gemini-4-argon` |
| judge | flash, n=2 | **pro, n=1** | **pro, n=3** |
| refine rounds | 2 | 4 | 4 |
| best-of-N | 1 | 1 | 2 |
@@ -685,6 +681,9 @@ given**, so `3dcode resume` reproduces it.
| ceilings | $1.50 / 30 min | $5 / 60 min | $8 / 90 min |
| expected from the audit | ~$0.30/run | ~$1.47/run | ~$3.20/run |
+(balanced / quality expectations were measured on gemini-cli; the generator moved to agy on
+2026-10-13, D103, and they have not been re-measured on it.)
+
Why these numbers: r01 buys a score point for $4.93 and r02 for $6.80 while r03
costs $33.49 (§5), so economy stops at 2; the pro judge is *cheaper* than matching
its precision with flash (§8), so balanced and quality both use it and only
@@ -837,7 +836,7 @@ rule and the r03+ marginal stop, which cut 2 runs / **$1.14** with **0 best roun
over the 107 recorded rounds (`waste-and-accounting/replay_stops.py`) — were **removed on
2026-09-22** with every other judgement stop: the owner fixed the round count (baseline +
`--rounds`, cut short only by the clock or a hard failure) and moved the choice of round to
-after the run. Every round still emits its `cost.round` event.
+after the run.
---
@@ -999,7 +998,7 @@ storm independently spends a full failed round-trip to learn what its siblings a
know, then sleeps on its own private backoff schedule. That is the 2 833 waits / 17.7 h
in §18.
-`codeverse3d/models/retry.py` adds a process-wide `StormGate` per model (`retry.py:449`):
+`codeverse3d/models/retry.py` added a process-wide `StormGate` per model (deleted 2026-09-22, below):
* the first worker to see a 503 calls `hit()`, which closes the gate for a short,
escalating window (never longer than `MAX_WAIT_S` — patience comes from the *number*
@@ -1087,8 +1086,10 @@ progress* is never cut — the deadline bounds retrying, not the call. Past it
is `infra_failed`, which is excluded from every rate and re-runnable with
`--redo-status infra_failed` (`eval/docs/EVAL.md` §7).
-**The wall-clock ceiling is only checked when money is spent.** `BudgetGuard.check()`
-is called from `spend()`/`charge()`, so a run whose calls never *complete* is never
+**The wall-clock ceiling is only checked when money is spent** (so it was then; since
+2026-09-22 the guard has no money path — `check()` runs at the loop head, after each agent
+session that did work, at each generation phase's end and before a session or a single-shot
+call is bought). `BudgetGuard.check()` was called from `spend()`/`charge()`, so a run whose calls never *complete* is never
tested against `max_minutes`: nothing is billed, so nothing is checked. That is how a
`--max-minutes 90` run reached **200 minutes**. The retry deadline is the root fix —
every call now terminates within ~15 min and charges or raises, so the ceiling is
@@ -1244,7 +1245,7 @@ only what is billed. `cost/billing.py` names the flat-rate backends
counter, `billed_usd`, alongside `spent.cost_usd`. `summary()` reports both:
`spent_usd` (billed, real dollars) and `notional_usd` (list price, what the reports want).
-`gemini-cli` is deliberately **not** exempt: it authenticates with an API key, so its
+`gemini-cli` (removed in D103; agy in Gemini-API mode is the same case today) is deliberately **not** exempt: it authenticates with an API key, so its
tokens draw on a real per-token quota even when that quota is free. Unknown backends
bill by default — a new provider nobody classified must be enforced, not exempted.
Getting it wrong the other way reports a run as free when someone was billed for it.
@@ -1252,6 +1253,11 @@ Getting it wrong the other way reports a run as free when someone was billed for
The corollary for benchmarking: an arm on a subscription backend and an arm on an API
backend do not bill comparably, so compare them on `notional_usd`, never on `spent_usd`.
+> **2026-09-22 — the split is gone with its reader.** Nothing enforces dollars any more (the
+> USD ceiling went in fbf89a5), so `billed_usd` and `cost/billing.py` fed nothing; the guard is a
+> clock and the record's money is the ledger at list price (the owner: 账本合计,按标价), a
+> subscription backend's rows included — which is what an arm comparison wants anyway (§32).
+
## 27. A 503 is per key at any instant — rotate before you wait (2026-08-26)
@@ -1270,7 +1276,7 @@ once **every** key in the pool has 503'd inside one logical call (a 22-key pool
times first). What this buys per call is the whole storm wait it used to pay first (median
5 s × the storm streak, up to 900 s); what it costs is one more round-trip on a fresh key.
Follow-ups worth measuring: rank keys by recent latency (the 30 s keys are consistent), and
-record the key index in `telemetry/usage.jsonl` so the distribution of calls per key can be
+record the key index in `telemetry/cost.jsonl` so the distribution of calls per key can be
read instead of probed.
**Amended 2026-08-27 (owner's rule):** the first cut of this gated the rotation behind a
@@ -1322,8 +1328,8 @@ nothing, so the hedge is free while it storms; only a success-then-success waste
*The ledger records the key and the attempt count.* `keys.py` scanned 1 542 files of the corpus
for the `"key": "…xxxx"` that `gemini.py:_once` puts in `ChatResponse.raw` and found none, so
"is one key hammered" was unanswerable. `rotate_with_retries(stats=)` hands back `attempts`
-(round-trips issued, hedged siblings included; 1 = clean) and `hedged`; `GeminiModel` puts both
-in `raw` and `attempts` on the raised `ModelError`; `cost/instrument.py` copies the key suffix
+(round-trips issued, hedged siblings included; 1 = clean) and `hedged`; `GeminiModel` puts
+`attempts` in `raw` and on the raised `ModelError` (`hedged` stays in the stats); `cost/instrument.py` copies the key suffix
(last 4 chars, never more) and `attempts` onto every `CallCost` row (`key`, `attempts`, both
defaulted so old rows load); `3dcode cost` adds a per-key table and a
`tries/call` column (`CostBucket.attempts_per_call`) whenever the ledger carries them.
@@ -1553,3 +1559,83 @@ Secondary observation, not a controlled comparison: the paired sd of the battery
this code is 0.131 against the A/A's 0.225 on the old code (n_for_power for ±0.02: ~172
pairs against ~506). Different runs and different arms, so it is an observation — but the
direction is the one the fix predicts, since a retry storm is variance.
+
+## 31. Minutes: the steps of a run, minus provider errors (2026-09-22)
+
+The owner's definition: time every step of a run from start to end, do not count the time lost
+to 503 / token-limit / overloaded errors, and report the sum (按步骤记录并扣除错误时间). It
+replaced six definitions that disagreed by up to 8x (on 52 resumed runs the record span said
+209 h where the active clock said 24.6 h): the record span (gallery), the bench process's wall
+clock (bench report), the compare cell's wall clock, the cost audit's active time, the budget
+guard's `elapsed_min` (ab_view) and telemetry-else-Σ-rounds (complexity_report).
+
+**What is timed.** `contracts.run.StepTime{step, round, wall_s, lost_s}`, one per step:
+`plan`, `skeleton`, the scene's `textures`, `assets+env+layouts` (the three run side by side, so
+they are ONE step; `assets+env` with `C3D_ZONE_LAYOUTS=off`), `zones`, `assemble`, best-of-N `candidates` — run-level, on
+`RunRecord.steps` (persisted in `run_state.json` as they happen, the part of an aborted round
+that ran included) — and per round `generate` (one per phase: a phase's sessions run side by
+side), `build` (+ repair), `gates`, `render`, `judge` (+ a re-judge), on `RoundRecord.steps`.
+**`RunRecord.minutes`** = Σ (wall − lost) / 60 over all of them: THE number, the one every reader
+reports (`addons/select` per round, the gallery, `3dcode cost`, `3dcode show`, the dataset index,
+eval/bench). Work after the run — a pick's texture pass or pairwise verdict, captions — is not a step
+of it (its money joins the ledger; its time is the pick's). Harness glue between steps (git
+commits, skill bundles, writing records) is not a step either.
+
+**What is lost.** `cost/tally.py`: a step opens a `Tally`; the meters book into every open one.
+An agent session books its `AgentResult.provider_wait_s` (the CLI's own 503 / 429 retries, read
+from its log by the agents). An API call books everything outside its answered round-trips once
+one of them failed without an answer — the failed tries, their back-off and the key waits
+(`cost.instrument._RoundTrips`, fed by the per-attempt sink `models.retry.rotate_with_retries`
+already reports through; a backend that reports no round-trips — the SDK adapters — is charged
+everything outside the answer it returned). A reply that came back unusable (bad JSON, empty)
+is the model's own time and is not lost. Calls in one thread add up; threads side by side (fan-out
+sessions, judge samples, candidates) lose `max(wall) − max(wall − lost)` — what the slowest thread
+would have been spared.
+
+**One fallback.** A record or a round written before step timing (`steps is None`) counts its own
+clock: the run's `extra["budget"]["elapsed_min"]` (all 470 archived records carry it), a round's
+`duration_s`.
+
+**Minutes are a statistic, `max_minutes` is a limit.** `orchestrator.BudgetGuard` keeps counting
+every active second, errors included — it has to stop a run inside a 503 storm, which is exactly
+when the minutes stand still. A run can therefore stop on `budget` with its minutes well under
+`max_minutes` (the stool run of 2026-09-22b: 51 minutes on the clock, a 2 100 s baseline session
+killed after its 503 / 429 retries).
+
+## 32. The ledger is the only record of money (2026-09-22)
+
+The owner's rule: the money of a run is its ledger's sum at list price (账本合计,按标价). Before
+it the harness kept two books — the ledger, one row per call, and `BudgetGuard`'s running total,
+fed by twelve `charge` / `add` call sites — and `record.total_usage` took the guard's. The guard
+never saw a round-trip the provider billed and the call discarded (a hedge loser that landed
+after the winner, a charged-but-invalid reply: the ledger's `source="extra"` rows), so the two
+drifted. Selector: every `record.json` under `~/3dcodeverse_bench_out` and
+`~/3dcodeverse_runs` that has a `telemetry/cost.jsonl` (437 of 470): the ledgers sum to
+**$882.77**, the records to **$845.63**, and 119 runs differ by more than 5 %. The live stool run
+of 2026-09-22b recorded **$0.3054** over a ledger of **$0.379**: its judge's hedged retry landed a
+second, discarded verdict for $0.0736 that only the ledger saw.
+
+What a run's money is now:
+
+* **`record.total_usage`** = the sum of `telemetry/cost.jsonl` (``cost.ledger.ledger_usage``),
+ read when the record is written (`BaseTrack._record`, `record.package_run`) — every billed row
+ exactly once: `live` (one per call), `session` (one per CLI session), `extra` (a billed round-trip
+ the call discarded). `attempt` rows are forensics, their tokens already on their call's row.
+ Post-run work (a pick's texture pass, captions) joins it when the run is re-packaged.
+* **a round's `usage`** = the rows booked while it ran (`cost.tally`: `record_call` books every
+ priced row into the open tallies), so a judge's discarded-but-billed verdict and a killed
+ session's recovered usage land on their round; best-of-N adds its candidates' own tallies.
+* **an aborted round** reports its tally: `rounds/aborted_rNN.json` and
+ `record.extra["aborted_rounds"][i].cost_usd`.
+* **money by stage** is `cost.ledger.summarise` — `telemetry/cost.json`, `3dcode cost`, the gallery.
+
+Gone: the guard's `spent` / `billed_usd` / `calls` / `by_stage`, `charge` / `add` / `mark` /
+`stage_summary`, `usage_delta`, the snapshot's money fields (an old snapshot still loads),
+`_reconcile_billed_from_ledger`, `cost/billing.py`, `record.extra["cost_by_stage"]` and
+`["rounds_summary"]` (written, never read), the `cost.round` event (no reader; it restated the
+ledger by round and stage), `CostSummary.ledger_usd` / `unattributed_usd` / `post_run_usd` (one
+number now), and `C3D_COST_LEDGER` — whose `off` turned the one money record off, and whose other
+values made every command die (a `bool` Settings field fed `none` or a path).
+`BudgetGuard` is a clock: `check` / `ok` / `timeout_s` / soft cap / grace / the active seconds a
+resume carries — unchanged (§31 says why minutes and the clock differ).
+
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index 2ae12f6e..af358b49 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -1,9 +1,9 @@
# Installing the 3dcodeverse harness
Everything below was executed on this machine (WSL2 Ubuntu, RTX 5090, Python
-3.13.9, node v24.14.0, Blender 5.0.1) on 2026-08-23; the version numbers and the
+3.13.9, node v24.14.0, Blender 5.2.2 LTS — since 2026-10-14, was 5.0.1) on 2026-08-23; the version numbers and the
`3dcodeverse doctor` output in §9 are real, not illustrative. Paths are relative
-to the harness root `/home/yipeng/3dcodeverse/harness` unless absolute.
+to the harness root (`harness/` in the 3dcodeverse checkout) unless absolute.
Once installed, read `docs/RUNBOOK.md` (how to run), `docs/ARCHITECTURE.md`
(what a run does) and `CLAUDE.md` (working rules).
@@ -63,7 +63,7 @@ workflow, so the offline suite and `ruff` are run locally before every push (see
|---|---|---|---|
| **python** | **3.13** | `requires-python = ">=3.13"`; ruff `target-version = "py313"`; `PY_FLOOR` in `tests/core/test_portability.py`; `MIN_PY_MINOR` in `setup.sh` | the four places are pinned together by the portability test |
| **node** | **20.6.0+** (developed on 24 LTS) | `runtime_js/package.json` `engines.node`; `codeverse3d.spatial.node.NODE_MIN` fails every node workload with an actionable message | 20.6 is the `--import` module-hook floor |
-| **Blender** | 4.2+ (developed on 5.0.1) | runtime probe only (`Settings.resolve_blender()`) | `blender` / `urdf_blender` are the only users |
+| **Blender** | **5.2 LTS** only (developed and measured on 5.2.2; D104, 2026-10-14) | `BLENDER_MIN = (5, 2)` in `codeverse3d/config.py`; `3dcode doctor` fails anything older; `Settings.resolve_blender()` | `blender`, `urdf_blender` and `scene_blender` are the users |
| **OS** | Linux x86_64 (WSL2 Ubuntu here) | — | macOS should work (nothing is Linux-specific except `resource.setrlimit` guards) but is not tested |
The offline suite on this box, 2026-09-23: **1332 passed of the 1332 selected**
@@ -76,11 +76,11 @@ Moving to another Python later is the same four-line change (`requires-python`,
| what | required? | verified here | how it degrades without it |
|---|---|---|---|
-| **Python 3.13** | yes | 3.13.9 (`/home/yipeng/miniconda3/bin/python`) | nothing runs; `requires-python = ">=3.13"` (§2.1) |
+| **Python 3.13** | yes | 3.13.9 (`~/miniconda3/bin/python`) | nothing runs; `requires-python = ">=3.13"` (§2.1) |
| **pip + venv** | yes | pip 25.3, `python -m venv` | `setup.sh` cannot install the package. A stock Debian/Ubuntu `/usr/bin/python3` ships **without** pip and is PEP 668 `EXTERNALLY-MANAGED`, so `pip install -e harness` refuses even once pip is present: `sudo apt install python3-venv python3-pip`, then use a virtualenv |
| **git** | yes | 2.53.0 | run workspaces are git repos (one commit per round); `Workspace.create()` and the flywheel pair miners fail |
| **node ≥ 20.6** | yes, except for the `graphics` track | v24.14.0 (npm 11.9.0) | the `threejs` / `scene_threejs` languages disappear **and no object renders happen at all**: `spatial/render.py` renders *every* GLB (Blender-built and CadQuery-built included) with three.js in headless Chrome. Only `graphics` (moderngl) is node-free |
-| **Blender 4.2+ / 5.x** | optional | 5.0.1 (`~/.local/bin/blender-5.0`) | `blender` and `urdf_blender` languages unavailable → the `static_object` default language and the whole `articulated_object` track cannot build (`BlenderNotFoundError`); scenes lose planner-chosen bpy GLB assets |
+| **Blender 5.2 LTS** | optional | 5.2.2 LTS (`~/.local/bin/blender-5.2`) | `blender`, `urdf_blender` and `scene_blender` languages unavailable → the `static_object` default language and the whole `articulated_object` track cannot build (`BlenderNotFoundError`); scenes lose planner-chosen bpy GLB assets |
| **EGL-capable GPU stack** | optional | ANGLE / D3D12 / RTX 5090 Laptop | headless Chrome falls back to **SwiftShader** and moderngl to **llvmpipe** — everything still renders, just several times slower; no correctness change |
| C toolchain | usually no | — | only if pip has to build a wheel from source (`python-fcl`, `manifold3d` ship wheels for cp310–cp313 x86_64) |
@@ -222,7 +222,7 @@ cache was cleared or when `PUPPETEER_SKIP_DOWNLOAD` was set:
```bash
cd harness/runtime_js && npx puppeteer browsers install chrome
-# [email protected] /home/yipeng/.cache/puppeteer/chrome/linux-148.0.7778.97/chrome-linux64/chrome
+# [email protected] ~/.cache/puppeteer/chrome/linux-148.0.7778.97/chrome-linux64/chrome
```
Re-running it is a no-op that just prints the cached path. `PUPPETEER_CACHE_DIR`
@@ -253,41 +253,58 @@ something the agent may install into.
## 6. Blender
-Optional, but the `static_object` default language and the entire
-`articulated_object` track need it. Any headless-capable 4.2+ / 5.x build works.
+Optional, but the `static_object` default language, the entire `articulated_object`
+track and the `scene_blender` scene language need it. **Blender 5.2 LTS is the one
+supported version** (D104, 2026-10-14: developed and measured on 5.2.2; `doctor` fails
+anything older — 4.2 / 5.0 compatibility was dropped on purpose, the prompts and lints
+state 5.2 API facts).
-Option A — distro package (simplest, often older):
+Option A — distro package (only if it ships 5.2 LTS):
```bash
sudo apt-get install blender # or: brew install --cask blender
```
-Option B — official tarball (what this box uses, no sudo needed); check
-<https://www.blender.org/download/> for the current file name:
+Option B — official tarball (what this box uses, no sudo needed); verify the checksum
+against <https://download.blender.org/release/Blender5.2/blender-5.2.2.sha256>:
```bash
mkdir -p ~/tools && cd ~/tools
-curl -LO https://download.blender.org/release/Blender5.0/blender-5.0.1-linux-x64.tar.xz
-tar xf blender-5.0.1-linux-x64.tar.xz
-~/tools/blender-5.0.1-linux-x64/blender --version
+curl -LO https://download.blender.org/release/Blender5.2/blender-5.2.2-linux-x64.tar.xz
+tar xf blender-5.2.2-linux-x64.tar.xz
+~/tools/blender-5.2.2-linux-x64/blender --version # Blender 5.2.2 LTS
```
+### The judged-frame fast path (scene_blender, measured on 5.2.2)
+
+`render_bpy_scene.py` owns every render setting. On this box (RTX 5090, 1024×576, a
+460-object scene) one Cycles frame at 32 spp with GPU OIDN costs 0.64 s; with
+`render.use_persistent_data` the synced scene and BVH survive between the cameras of
+one job, so 8 frames take 2.2 s instead of 5.3 s (0.21 s per frame after the first).
+64 spp 0.69 s, 128 spp 0.86 s, CPU 2.3 s. EEVEE in background mode is *slower* here
+(5.2 s per frame plus a 12 s shader compile per process) and Workbench is 0.12 s.
+`Settings.render.blender_frame_time_limit_s` (default 20 s, `cycles.time_limit`) caps
+a heavy scene's sampling per frame. **OptiX is not available under WSL2** (no
+`libnvoptix`, init error 7804) and setting the compute device type to OPTIX and back
+crashes Blender 5.2.2 — the harness only ever enumerates CUDA; `3dcode doctor` times one
+256×144 frame on exactly this path.
+
### The `LD_LIBRARY_PATH` wrapper trick
The stock Linux build links `libSM.so.6` / `libICE.so.6` even in `--background`
mode, and those are not installed system-wide here (no sudo). They were
extracted from the Ubuntu debs into `~/.local/xlibs`, and a one-line wrapper on
`PATH` prepends that directory to the loader path so no caller has to remember —
-`~/.local/bin/blender-5.0`:
+`~/.local/bin/blender-5.2`:
```bash
#!/bin/bash
-BLENDER_HOME="${BLENDER_HOME:-/home/yipeng/3dcodeverse_data/tools/blender-5.0.1-linux-x64}"
-export LD_LIBRARY_PATH="/home/yipeng/.local/xlibs/usr/lib/x86_64-linux-gnu:${LD_LIBRARY_PATH}"
+BLENDER_HOME="${BLENDER_HOME:-$HOME/tools/blender-5.2.2-linux-x64}"
+export LD_LIBRARY_PATH="$HOME/.local/xlibs/usr/lib/x86_64-linux-gnu:${LD_LIBRARY_PATH}"
exec "$BLENDER_HOME/blender" "$@"
```
-Make it executable (`chmod +x ~/.local/bin/blender-5.0`) and keep the name — it
+Make it executable (`chmod +x ~/.local/bin/blender-5.2`) and keep the name — it
is the first candidate the harness looks for. If your distro does have the X11
libs, point the wrapper at the tarball and drop the `LD_LIBRARY_PATH` line, or
skip the wrapper entirely.
@@ -300,8 +317,7 @@ skip the wrapper entirely.
`C3D_BINARIES__BLENDER=/path/to/blender`. A configured binary is never replaced
by one from `PATH`: if it is missing or not executable, builds raise
`BlenderNotFoundError` and `doctor` reports `blender FAIL`;
-2. only when nothing is configured: `blender-5.0`, `blender`, `blender-5.1`,
- `blender-4.2` on `PATH`, in that order.
+2. only when nothing is configured: `blender-5.2`, then `blender` on `PATH`.
Nothing found → `3dcodeverse doctor` reports `blender FAIL` and builds raise
`BlenderNotFoundError`. Blender is always invoked `-b --factory-startup` with
@@ -393,7 +409,7 @@ this box runs on defaults plus env.
runs_dir: /data/runs
cache_dir: /data/cache/codeverse3d
binaries:
- blender: /home/yipeng/.local/bin/blender-5.0
+ blender: ~/.local/bin/blender-5.2
render:
gpu: auto # auto | on | off
width: 768
@@ -412,6 +428,7 @@ export C3D_BINARIES__BLENDER=/opt/blender/blender
export C3D_RENDER__GPU=off
export C3D_LIMITS__AGENT_TIMEOUT_S=900
export C3D_DEFAULT_CANDIDATES=2
+export C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}' # per-model prompt/skill variant by exact generator id (D105); C3D_VARIANT=argon names one for every run
```
Every knob the harness reads is a `Settings` field (`codeverse3d/config.py`, one
@@ -438,9 +455,9 @@ Real output on this box (exit code 0; any FAIL row makes it exit 1):
┏━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ check ┃ status ┃ detail ┃
┡━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
-│ python │ OK │ 3.13.9 (/home/yipeng/miniconda3/bin/python3.13) │
+│ python │ OK │ 3.13.9 (~/miniconda3/bin/python3.13) │
│ python deps │ OK │ 23/23 importable │
-│ blender │ OK │ Blender 5.0.1 @ /home/yipeng/.local/bin/blender-5.0 │
+│ blender │ OK │ Blender 5.2.2 LTS @ ~/.local/bin/blender-5.2 │
│ node │ OK │ v24.14.0 │
│ three │ OK │ 0.182.0 (…/harness/runtime_js/node_modules) │
│ puppeteer │ OK │ v24.43.1; chrome cache found (~/.cache/puppeteer) │
@@ -497,6 +514,8 @@ that the keys work end to end):
| `skills switch` | WARN | skills are disabled (`C3D_SKILLS=0`) | skills are on by default since 2026-09-22; unset `C3D_SKILLS` unless this is an A/B control arm |
| `skills library` | WARN / FAIL | no bundles were found, or one or more bundles are invalid | use a full checkout and validate the named bundle under `codeverse3d/skills/<name>/` |
| `skills routing` | WARN | a routed skill has no installed bundle | restore the missing bundle from the checkout or update the stale route |
+| `skills overlay` | FAIL | one row per shipped variant (`argon: …`): its skills overlay (`codeverse3d/skills/variants/<name>/`) has an invalid bundle or a `routes.toml` that does not type-check | fix the bundle `3dcode skills validate` names as `<variant>/<bundle>`, or the `routes.toml` row it names |
+| `skills variants` | FAIL | a shipped `variant.toml` under `codeverse3d/prompts/variants/` does not parse | fix that file (`[variant] name` = its directory name, an integer `version`); until then no overlay is checked |
| `skills discovery` | OK | always informational | shows the agent-native directories where bundles are materialised |
| `claude-code Skill tool` | FAIL | the Claude backend would deny native skill activation | update/reinstall the harness so `Skill` is present in Claude Code's allowed tools |
@@ -583,12 +602,12 @@ those by hand (`npm rm -g @anthropic-ai/claude-code @openai/codex`; agy: `rm ~/.
| component | version | where |
|---|---|---|
-| python | 3.13.9 (the one supported version — §2.1) | `/home/yipeng/miniconda3/bin/python` |
+| python | 3.13.9 (the one supported version — §2.1) | `~/miniconda3/bin/python` |
| pip packages | pydantic 2.13.2 · trimesh 4.12.2 · python-fcl 0.7.0.11 · moderngl 5.12.0 · shapely 2.1.2 · networkx 3.6.1 · manifold3d 3.5.2 · pyarrow 24.0.0 · mcp 2.0.0 · scipy 1.18.0 · yourdfpy 0.0.60 · cadquery 2.8.0 · google-genai 2.10.0 · pytest 9.1.1 · ruff 0.15.20 | editable install of `harness/` |
-| node / npm | v24.14.0 / 11.9.0 (floor 20.6.0 — §2.1, verified against node 20.19.5) | `/home/yipeng/miniconda3/bin/node` |
+| node / npm | v24.14.0 / 11.9.0 (floor 20.6.0 — §2.1, verified against node 20.19.5) | `~/miniconda3/bin/node` |
| runtime_js deps | three 0.182.0 · puppeteer 24.43.1 (99 packages, 97 MB) | `harness/runtime_js/node_modules` |
| Chrome (puppeteer) | 148.0.7778.97 (+ headless-shell) | `~/.cache/puppeteer` |
-| Blender | 5.0.1 (2025-12-16) | `~/.local/bin/blender-5.0` → `~/3dcodeverse_data/tools/blender-5.0.1-linux-x64` |
+| Blender | 5.2.2 LTS (build 2026-09-15; installed 2026-10-14, sha256-verified) | `~/.local/bin/blender-5.2` → `~/tools/blender-5.2.2-linux-x64` (any directory: the wrapper's `BLENDER_HOME`) |
| git | 2.53.0 | `/usr/bin/git` |
| agy / claude / codex | 1.3.4 / 2.1.241 / 0.149.0 | `~/.local/bin` / npm global |
| GPU (Chrome WebGL) | ANGLE · D3D12 · NVIDIA GeForce RTX 5090 Laptop GPU · OpenGL ES 3.1 | via `--use-angle=gl-egl` + Mesa d3d12 |
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 37744046..203c860a 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -161,6 +161,36 @@ get_settings().apply_profile(name, *, force=False) -> Profile
from codeverse3d.cli._common import resolve_dial, ResolvedDial # THE resolver, one per `3dcode make`
resolve_dial(settings, profile_flag=None, *, rounds=None, candidates=None,
max_minutes=None, texture=False) -> ResolvedDial
+from codeverse3d.cli._common import resolve_variant, ResolvedVariant, record_variant, replay_variant # D105
+resolve_variant(settings, generator, flag=None) -> ResolvedVariant{name, version, hash, source, label}
+ # `--variant` > settings.variant (C3D_VARIANT) > settings.variants[<generator>] (as typed, then by the served
+ # model) > "" (base); an unknown name is the typed 'bad configuration' refusal (exit 2) before a run dir exists;
+ # `3dcode make` freezes .name on RunOptions.variant. record_variant(record) -> the name a stored run used;
+ # replay_variant(record): a context that activates it for `3dcode judge` (a retired name warns → base)
+from codeverse3d.prompts.variants import VARIANTS_DIR, VariantInfo, list_variants, variant_info, resolve_variant, \
+ active_variant, activate, variant_root, variant_hash, variant_block, apply_variant_knobs, served_id
+ # the variant layer (D105): VariantInfo{name, version, generators, description, knobs} from
+ # prompts/variants/<name>/variant.toml; variant_info(name) / activate(name) raise ValueError for an unknown name;
+ # resolve_variant(settings, generator_id) -> "" | name (plain dict lookups, served_id("agy:x-high") == "agy:x");
+ # active_variant() = the ContextVar `activate` sets (BaseTrack.run wraps the whole run; proc.fan_out copies it
+ # into worker threads), else get_settings().variant; variant_hash(name) = sha256[:12] over the prompt AND skills
+ # overlay files (README.md excluded; "" = base); variant_block(name) -> {name, version, hash} for the record;
+ # apply_variant_knobs(settings, info) sets [knobs] (skills_max / skills_only) as DEFAULTS — a stated field wins
+from codeverse3d.prompts import load_text, render, prompt_root # every name resolves through the active variant
+prompt_root(rel) -> Path # the file a prompt name reads from: the overlay copy when it exists, else the base
+from codeverse3d.skills import library_roots, all_skills, load_skill, variants_table, parse_routes, VariantRoutes, RouteBoost, variant_dir
+library_roots(variant=None) -> [skills_dir(), <skills_dir>/variants/<v>] # the second only when it exists
+all_skills() -> base ∪ overlay (same name shadows, new names added); all_skills(root) -> that root alone
+variants_table(name) -> VariantRoutes{variant, routes: (Route…), boosts: (RouteBoost{skill, delta}…), disabled}
+ # <skills_dir>/variants/<name>/routes.toml parsed with tomllib into typed rows (parse_routes(path)): a typing
+ # error is a ValueError naming the row; attach_skills logs it and routes with the base table
+from codeverse3d.skills.registry import select, effective_priority, GATE_FIRED_PRIORITY
+select(track, language, kind, *, signals=None, findings=(), library=None, max_skills=5, allow_unverified=False,
+ routes=ROUTES, boosts=None, disabled=frozenset()) -> [Selection]
+ # routes: the rows to evaluate in order (a variant's extra rows after the base ones — ties keep base order);
+ # boosts: skill -> priority delta, clamped by effective_priority (a standing row stays below 90, a gate-fired
+ # row never drops under it); disabled: rule ids skipped. SkillsMaterialized.variant, the skills.attached
+ # event and the telemetry/skills.jsonl row name the variant the attach ran under
# profile/generator/planner/judge/captioner, judge_samples/judge_max_px/judge_montages/
# judge_detail_crops, agent_max_turns, rounds, candidates, texture, max_minutes.
# `--profile X` and `C3D_PROFILE=X` resolve to the SAME dial (they used to disagree on
@@ -264,6 +294,8 @@ rt.asset_file(asset: AssetPlan) -> str # factory module, or publ
rt.assemble(ws, plan: ScenePlan) -> BaseModel # writes the entry; plan cameras, else derived; artifacts/assemble.json
rt.probe(ws, *, timeout_s=60.0) -> SceneProbeResult # scene_probe gate + census.json (scene_probe / check_placement tools)
rt.render_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1024, height=576, sheet=True) -> RenderSet
+rt.env_file: str # Δ 2026-10-14 (D105) src/env.js / src/env.py — the env stage's one file,
+ # declared on languages/base.SceneRuntime; tracks.scene.env_file(ctx) reads it (tracks.scene.ENV_FILES is the typed fallback)
# Δ 2026-09-24 (D102) spatial.probes.run_probe(ws, *, compile=False, timeout_s=None, glb: Path | None = None, facts=None):
# glb = an OFFLINE scene's census GLB (probe_scene.mjs --glb → runtime_js/lib/glb_scene.mjs, served at /__census.glb;
# host_page.openHost(..., glb=)), facts merged into the census by probes.merge_facts before any finding;
@@ -283,7 +315,7 @@ BuildResult.error_type spellings (languages/_common.py): MISSING_ENTRY = "Missin
| `ThreeJsRuntime` | `src/object.js`, `src/parts/*.js` | **Δ export as authored** (census `placement_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; the build collides the REST pose only (RestPenetration > 5 mm, D17) — every pose is the round's `joint_sweep` gate — and writes no articulation.json / census.articulation (Δ 2026-09-22) |
| `SceneThreeJsRuntime` | `src/scene.js`, `src/zones/*.js`, `src/assets/*.js`, `src/env.js`, `src/shaders/*.{js,vert,frag,glsl}` | glb_path=None; local shader text loads inside async createScene; ok iff `spatial.probes.run_probe(ws, *, compile=True, timeout_s=None) -> (scene_probe, shader_preflight, census)` (one `probe_scene.mjs --compile` boot; `probe_scene` is the same call without `compile`) passes both; both reports ride `BuildResult.gates`, and the `shader_probe` tool reports the same call |
-| `SceneBlenderRuntime` | `src/scene.py`, `src/zones/*.py`, `src/assets/*.py`, `src/env.py` | **Δ 2026-09-24 (D102)** glb_path=None; `scene.py` is assembled DATA (`ZONES`/`ASSETS`/`HEROES` `{snake: Pascal}`, `CAMERAS` in the Blender frame, vertical fov); build = one Blender process (`wrappers/run_bpy_scene.py`: env, heroes, assets, zones each isolated — a raise is an ERROR on its `file:line` and the zone is dropped) → `artifacts/{census.glb, scene.blend, bpy_build.json, bpy_census.json}` → `run_probe(ws, glb=artifacts/census.glb, facts=bpy_census)` (no settle / camera repair; D2 unique-tri ERROR, no draw gate; D10 python drivers ERROR) → `BuildResult.gates=[scene_probe]`; `probe()` = the same measurement without touching build.json; `render_scene` raises NotImplementedError until DESIGN phase 2; frame clock `scene_blender.FPS`/`frame_of(t) = 1 + round(30 t)` |
+| `SceneBlenderRuntime` | `src/scene.py`, `src/zones/*.py`, `src/assets/*.py`, `src/env.py` | **Δ 2026-09-24 (D102)** glb_path=None; `scene.py` is assembled DATA (`ZONES`/`ASSETS`/`HEROES` `{snake: Pascal}`, `CAMERAS` in the Blender frame, vertical fov); build = one Blender process (`wrappers/run_bpy_scene.py`: env, heroes, assets, zones each isolated — a raise is an ERROR on its `file:line` and the zone is dropped) → `artifacts/{census.glb, scene.blend, bpy_build.json, bpy_census.json}` → `run_probe(ws, glb=artifacts/census.glb, facts=bpy_census)` (no settle / camera repair; D2 unique-tri ERROR, no draw gate; D10 python drivers ERROR) → `BuildResult.gates=[scene_probe]`; `probe()` = the same measurement without touching build.json; `render_scene` = `spatial.render_blender.render_blender_scene` (**Δ D102b**: Blender renders the authored cameras × times + the overviews from `artifacts/scene.blend`, the JS host keeps the camera checks and the metrics schema; **Δ 2026-10-14 (D105)** the track runs end to end — `env_file` = `src/env.py`, the bpy templates, planner schema and asset ladder under orchestrator/ + tracks/ below); frame clock `scene_blender.FPS`/`frame_of(t) = 1 + round(30 t)` |
| `GlslShaderRuntime` | `src/shader.frag`, `src/common.glsl`, `src/buffer_a.frag` (+ the harness-owned `src/recipes.glsl` when seeded) | harness owns `#version`/uniforms/`out` (wrap.HEADER: u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise + iTime/iChannel* aliases); `wrap.compose(shader, common, recipes_src=…)` pastes header < recipes < common < shader; build renders judge frames via GlHost; compile errors → GlslCompileError at mapped src file:line (recipes.glsl included); lint ERROR `redefines_recipe` when an agent file defines a recipes.glsl name; 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 |
@@ -345,7 +377,8 @@ render_blender_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5),
# render_scene.mjs --glb through lib/glb_scene.mjs); metrics.json = the three.js schema + {"language": "scene_blender", "blender": {engine, device, samples,
# fallback, frame_ms, timings_ms}}; Settings.render.blender_{engine,samples,device,gpu_slots,gpu_wait_s}
from codeverse3d.spatial.render_scene import select_judge_views, JUDGE_MAX_VIEWS, plan_bounds
-select_judge_views(rs, max_n=10) -> RenderSet # priority: authored@t0, 2 overview@t0, 2 authored@t_last, rest
+select_judge_views(rs, max_n=10) -> RenderSet # priority: authored@t0, MAX_JUDGE_OVERVIEWS=4 overview@t0 (Δ 2026-10-14,
+ # scene_v2: the fourth is conventions.SCENE_VIEWS' overview_low_front, az 20° el 7°, orbit.mjs fitContactCamera), 2 authored@t_last, rest
from codeverse3d.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
@@ -388,9 +421,14 @@ from codeverse3d.spatial.measure import measure_glb, world_transform, node_name_
# lands a finding in Measurement.extra["findings"] — trimesh re-parents renamed nodes and the numbers are approximate
from codeverse3d.spatial.scene_placement import placement_findings, placement_gate, placement_gate_safe, placement_census, placement_table_text
placement_census(ws, probe, *, force_probe=False, timeout_s=60.0) -> dict # Δ D101: probe = the language's SceneRuntime.probe
-placement_findings(table, *, indoor=False) -> GateReport # gate "scene_placement"; data.kind ∈ floating | sunken |
+placement_findings(table, *, indoor=False, language=None, thresholds=None) -> GateReport # gate "scene_placement"; data.kind ∈ floating | sunken |
# unsupported | interpenetration | summary | probe_failed; target "Zone/Asset" (routes to src/zones/<zone>.js);
- # messages carry the scene_v1 floating_part cap words; reads artifacts/census.json["placement"] (host_placement.mjs)
+ # messages carry the scene_v2 cap words (floating / sunken / interpenetration / scale / free_exempt); reads artifacts/census.json["placement"] (host_placement.mjs)
+ # Δ D105 (2026-10-14): thresholds = Settings.placement (config.Placement) read at CALL time, `thresholds=` overrides; the
+ # summary INFO's data carries `thresholds` (what graded) + `counts` (measured) / `listed` (after the per-kind cap);
+ # + kinds cantilevered (WARN: rests on ≤ 1 of ≥ 4 foot columns, host_placement rows gap_max_m / columns_resting / tilt_m)
+ # and free_exempt (one per report: share of assets tagged placement='free' past free_exempt_warn / _error);
+ # every per-asset / pair finding carries data.bbox = {center, size} (GLB frame) for the judge's contact crops
placement_gate(ws, census, plan) -> GateReport | None # THE verdict (Δ 2026-09-22): ScenePipeline.gates and the check_placement
# tool both return it — placement_gate_safe fed the zone layouts and the unbuilt assets from ws/stages/{layouts,assets}.json
placement_gate_safe(census, *, plan=None, layouts=None, unavailable=()) -> GateReport | None # the pure core: None without a table, WARN on failure, never raises; `unavailable` = assets the stage could not build (not "missing planned contents")
@@ -437,10 +475,12 @@ python -m codeverse3d.spatial.mcp_server --workspace <ws> [--track X] [--languag
from codeverse3d.judges.rubrics import load_rubric, Rubric # Rubric{…, defects: [DefectItem{id, text, penalty, cap}], caps[{…, when:, kinds}]}
from codeverse3d.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=None, detail_crops=None, max_px=None,
+ temperature=0.2, *, thinking=None, max_attempts=3, max_montages=None, detail_crops=None, max_px=None,
sample_budget_s=None, fixed_order=False, chat_model=None, cache_dir=None, label="judge")
- # Δ max_images is GONE → montage budget. The four None params resolve through Settings.judge
- # (montages=5 since D47, detail_crops=2, max_px=1024) and SAMPLE_BUDGET_S=900.0
+ # Δ max_images is GONE → montage budget. The None params resolve through Settings.judge
+ # (montages=5 since D47, detail_crops=2, max_px=1024, thinking="low" — Δ 2026-10-14 D105: thinking=None reads
+ # Settings.judge.thinking / C3D_JUDGE__THINKING, `3dcode judge --thinking` and calibrate(thinking=None) too) and
+ # SAMPLE_BUDGET_S=900.0; TRACK_MONTAGE_CAP = {"scene": 4, "graphics": 3} bounds the dial per track
VlmJudge.judge(inp) -> Judgment # clay/normals views travel ONLY as JudgeInput.geometry_views (no kwarg)
VlmJudge.slice_payload(inp) -> (list[(label, png_path)], provenance_elicitation: bool) # (D48) ([], False) unless
# Settings.judge.slices=="on-error" AND spec.track in judges.base.SLICE_TRACKS AND inp.glb_path exists AND the
@@ -459,6 +499,10 @@ plan_summary(plan, language) -> str # the digest for every track (object: "Ove
# also the texture gate's (texturing/generate.judge_gate)
from codeverse3d.judges.prompt_builder import plan_montages, render_montage, Montage # ≤5 2×2 montages (shaded/geometry/poses) + ≤2 detail
# crops @≤1024px replace the sheet + the 14-view rig (D47); clay/normals views (RenderView.mode) auto-route to the GEOMETRY montage
+ # Δ 2026-10-14 (scene_v2): plan_montages(…, gates=()) / plan_detail_crops(shaded, *, scene, gates=(), limit) — a scene sends the
+ # centre crop + ≤ limit CONTACT CROPs (plan_contact_crops: a scene_placement finding's data.bbox projected through the judged
+ # overview tile that shows it largest, project_box); gates_section(gates, *, scene=False) has a scene branch (placement →
+ # frames → lint, WARNs grouped by kind, one MEASURED PLACEMENT line: placement_block); the object text is unchanged
from codeverse3d.judges.prompt_builder import build_judge_messages, connectivity_error_pairs, PROVENANCE_ELICITATION
build_judge_messages(inp, rubric, *, …, extra_images=None (PREpended: references), extra_text="",
slice_images=None, provenance_elicitation=False) -> (system, [ChatMessage]) # (D48) slice_images
@@ -595,8 +639,25 @@ tracks.common.single_shot_agent_id(agent_id, chat_model_id='') -> str · single_
# asked for a final build + summary (WRAPUP_PROMPT) instead of being killed.
# EVERY session (attempt 1, <label>.a2 retry, <label>.wrapup) is charged as it ends.
from codeverse3d.tracks.repair import build_with_repair # RepairOutcome(.ok/.max_attempts, attempts, usage); build_with_repair(ctx, *, round_index, label, files_hint=None, max_attempts=None, timeout_s=None) — timeout_s clips every repair session (a scene asset's window)
-# scene assets (tracks/scene_assets.py): build_threejs_asset / build_blender_asset climb ONE ladder (_ladder: single-shot → check → one feedback repair → agent session); a hero's parts come from the static planner (hero_plan); SceneThreeJsRuntime.render_asset(ws, name, out_dir) renders a module on the hero's quick rig; the assembled scene.js plays every GLB clone's clips (clone.userData.clipOffset de-phases a copy)
+# scene assets (tracks/scene_assets.py): build_threejs_asset / build_blender_asset / build_bpy_asset (Δ D105) climb ONE ladder (_ladder: single-shot → check → one feedback repair → agent session); a hero's parts come from the static planner (hero_plan); SceneThreeJsRuntime.render_asset(ws, name, out_dir) renders a module on the hero's quick rig; the assembled scene.js plays every GLB clone's clips (clone.userData.clipOffset de-phases a copy)
# languages/blender.write_blender_skeleton(ws, plan, *, ground_tol_m=0.002) — the self-check's stands-on-z=0 tolerance (a scene hero passes 0.02)
+# Δ 2026-10-14 (D105) scene_blender first class: the scene track reaches a language through typed tables, never a suffix test
+tracks.scene.SCENE_TEMPLATES: dict[Language, SceneTemplates] # the env / zone / refine / asset templates per scene language
+ # (scene_templates(language) -> KeyError for a language the track does not run); the three.js files are byte-identical,
+ # the bpy twins carry the same context keys with Blender wording and the bpy library's calls
+tracks.scene.ENV_FILES: dict[Language, str] # src/env.js / src/env.py — the typed fallback of
+tracks.scene.env_file(ctx) -> str # the runtime's SceneRuntime.env_file (a fake, an older runtime)
+tracks.planner.PLAN_TEMPLATES: dict[tuple[Track, Language | None], str] # (track, None) = the track's default and the
+tracks.planner.plan_template(track, language=None) -> str # fallback; (SCENE, SCENE_BLENDER) = tracks/plan_scene_bpy.j2
+tracks.planner.plan_schema(spec, plan_model) -> dict # the planner call's response schema: a scene's names ITS language's
+contracts.plan.scene_plan_schema(language) -> dict # asset kinds (bpy / blender_glb; scene_threejs's = ScenePlan.model_json_schema())
+tracks.scene_assets.build_bpy_asset(ctx, asset, *, judge) -> AssetResult # src/assets/<snake>.py (build_<snake>(ctx, variant=0))
+ # on the one ladder; no render_asset, so the scene judge sees the module placed
+tracks.scene_assets.check_bpy_asset(ctx, rel, snake, *, expected_size_m=None, timeout_s=None) -> AssetCheck # ONE Blender
+ # build of the module alone (<ws>/_assets/<snake>_check): a raise is fatal on its file:line; a runtime without Blender or
+ # a harness fault inside the wrapper (BuildResult.harness_failure: the census-GLB writer) is ran=False, ok=True — never a blocker
+tracks.zone_layout.layout_block(layout, *, language=Language.SCENE_THREEJS) -> str # the director's placements in the
+ # AUTHORING frame of `language`: the plan's own numbers for three.js, (x, -z) for bpy (a -0.0 folded to 0.0)
from codeverse3d.tracks.steps import run_round, skip_judge_reason, record_aborted_round
skip_judge_reason(ctx, *, renders, ignore_budget=False) -> str # "" = judge it. ONLY states where the
# verdict is never bought at all: no judge / no renders / budget already exceeded
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index 9489a08e..7e2a5377 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -1,16 +1,16 @@
# Runbook — operating the harness
-Everything here was exercised on this machine (WSL2, RTX 5090, Blender 5.0.1,
+Everything here was exercised on this machine (WSL2, RTX 5090, Blender 5.2.2 LTS (since 2026-10-14; was 5.0.1),
node 24, gemini-cli 0.53 (removed in D103), claude 2.1, codex 0.147+, agy 1.1) on 2026-08-23;
the agy rows re-checked on agy 1.3.4, 2026-10-13. Paths
-are relative to `/home/yipeng/3dcodeverse/harness` unless absolute. The CLI is
+are relative to the harness root (`harness/` in the checkout) unless absolute. The CLI is
`3dcodeverse` with short alias `3dcode` (used below).
## 1. Install and check
```bash
-pip install -e /home/yipeng/3dcodeverse/harness # once; entry points 3dcodeverse and 3dcode
-cd /home/yipeng/3dcodeverse/harness/runtime_js && npm install # [email protected], puppeteer (chrome cached)
+pip install -e harness # once, from the checkout root; entry points 3dcodeverse and 3dcode
+cd harness/runtime_js && npm install # [email protected], puppeteer (chrome cached)
3dcode doctor # python deps (incl. python-fcl, moderngl), blender, node/three/puppeteer, chrome WebGL, keys, CLIs, git, mcp
3dcode doctor --live # + one tiny Gemini call ("pong", ~$0.00001)
python -m pytest tests -q # offline suite; live tests are opt-in (blender/node/GL run when the binaries exist)
@@ -54,7 +54,12 @@ after the run; see §6), `--no-pick` (package nothing: no `deliverable/`, no `se
`--must-not`, `--style`, `--tag`, `--seed` (a label: it re-keys the plan and the reference
images, nothing else is seeded by it), `--slug`, `--runs-dir`, `--force`,
`--no-run` (workspace + spec.json only — except that `--reference` still runs its
-paid grounding pass first, since the grounded spec is what it writes).
+paid grounding pass first, since the grounded spec is what it writes),
+`--variant NAME` (a per-model prompt/skill overlay — `codeverse3d/prompts/variants/<name>/` +
+`codeverse3d/skills/variants/<name>/`, D105 — frozen on `spec.options.variant` so `resume` and
+`judge` read the same files; default: `C3D_VARIANT`, else `C3D_VARIANTS` keyed by the exact
+generator id — as typed, then by its served model — else the base prompts; an unknown name is
+refused before the run directory exists; the run table prints `variant: argon v1 (<hash>)`).
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
@@ -169,7 +174,7 @@ unless you type `--host` yourself; it never serves a path outside the declared r
# paid verdict per pair, cached); --round N = that round; --texture = the
# texture pass on it first. `make`/`resume` run `pick --by score` for you
3dcode render <slug> [--round N] [--mode shaded|wire|normals|clay|silhouette] [--out dir]
-3dcode judge <slug> [--round N] [--rubric static_object_v1] [--model gemini:gemini-3.1-pro-preview] [--n 3]
+3dcode judge <slug> [--round N] [--rubric static_object_v1] [--model gemini:gemini-3.1-pro-preview] [--n 3] [--thinking off|low|medium|high]
# re-judges a round's recorded renders → artifacts/judge/rNN_cli.json
3dcode texture pass <slug> [--no-judge] [--model …] [--judge-model …] [--image-model …] [--size 1024]
3dcode texture scene-pack <slug> [--n 10] · 3dcode texture show <slug>
@@ -391,6 +396,20 @@ weather: they leave the provider's errors out (docs/COST.md §31); the ceiling d
trees). What it cannot drive is listed in `tests/prompts/manifest.py`. A new prompt file must
render through the loader (`tests/prompts/test_files.py`); a new language or track adds its
scenario to `SCENARIOS`.
+* **A per-model variant** (D105): `codeverse3d/prompts/variants/<name>/variant.toml` (`[variant]`
+ name = the directory name, version, generators, description; optional `[knobs]` — `skills_max`,
+ `skills_only` — applied like a profile, a user-stated field wins) beside the prompt files that
+ shadow the base ones by relative path (a template there may `include` a base file), and
+ `codeverse3d/skills/variants/<name>/` for bundles that shadow base bundles by name, their
+ `_claims/`, and `routes.toml` (`[[boost]]` skill + delta, `[[disable]]` rule, `[[route]]` extra
+ typed rows with fresh ids; parsed with `tomllib`, a typing error is logged and the base table
+ routes). Nothing else changes: `prompts.load_text` / `render` / `catalog.language_text` and
+ `skills.all_skills` resolve through the active variant, `BaseTrack.run` activates the spec's
+ frozen name (else the process switch), the record carries `extra.variant` {name, version, hash}
+ + `prompt_hashes.variant`, and `plan_stage_key` names the variant only when one is set. An
+ overlay starts EMPTY (the shipped `argon` is) so its first iteration measures the base; the
+ manifest gets one scenario per variant (`scene.scene_threejs.agent.variant_argon`). Selection is
+ explicit — `--variant`, `C3D_VARIANT`, `C3D_VARIANTS` — never a pattern over the model id.
* **New spatial tool**: pydantic args + `@tool("name", Args, "…", tracks=(…),
languages=(…), cost_hint=…)` in `spatial/tools.py`; available to tracks, MCP and prompt cards at once.
Update `tests/spatial_tools` EXPECTED_TOOLS.
diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.md
index 973e8281..ce80170e 100644
--- a/harness/docs/SKILLS.md
+++ b/harness/docs/SKILLS.md
@@ -136,7 +136,7 @@ This is the difference between a metric and a number that would have read 100% f
## 2. The library
-**Seventeen bundles.** `lines`/`tokens` are the body, against caps of 350 and 2,500.
+**Twenty bundles.** `lines`/`tokens` are the body, against caps of 350 and 2,500.
| skill | track | language | evidence | lines | tokens | routes |
|---|---|---|---|---|---|---|
@@ -145,7 +145,7 @@ This is the difference between a metric and a number that would have read 100% f
| `c3d-repeats-and-mirrors` | object tracks | any | measured | 112 | 1,527 | R6, R7 |
| `c3d-blender-forms` | any | blender, urdf_blender | measured | 97 | 1,811 | R8, R9 |
| `c3d-urdf-joints` | articulated_object | urdf_blender | measured | 139 | 1,989 | R12, R13 |
-| `c3d-scene-composition` | scene | scene_threejs | mixed | 118 | 1,691 | R14, R15 |
+| `c3d-scene-composition` | scene | scene_threejs | mixed | 118 | 1,691 | R14, R15, R34 |
| `c3d-scene-lighting` | scene | scene_threejs | mixed | 126 | 1,959 | R16, R17 |
| `c3d-scene-motion` | scene | scene_threejs | mixed | 178 | 2,223 | R18, R19 |
| `c3d-threejs-shader-traps` | scene + static | threejs both | mixed | 112 | 1,734 | R20, R21 |
@@ -157,8 +157,11 @@ This is the difference between a metric and a number that would have read 100% f
| `c3d-scene-water` | scene | scene_threejs | **inherited-unverified** | 71 | 806 | R26 |
| `c3d-scene-night` | scene | scene_threejs | **inherited-unverified** | 56 | 656 | R27 |
| `c3d-scene-materials` | scene | scene_threejs | **inherited-unverified** | 78 | 832 | R28 |
+| `c3d-bpy-scene-placement` | scene | scene_blender | mixed | 124 | 2,209 | R29, R30 |
+| `c3d-bpy-scene-lighting` | scene | scene_blender | mixed | 112 | 2,045 | R31, R32 |
+| `c3d-bpy-scene-materials` | scene | scene_blender | mixed | 99 | 1,741 | R33 |
-**All seventeen route by default since 2026-09-22** (`C3D_SKILLS` and
+**All twenty route by default since 2026-09-22** (the three `c3d-bpy-scene-*` bundles since 2026-10-14, D105) (`C3D_SKILLS` and
`C3D_SKILLS_UNVERIFIED` both default on; `C3D_SKILLS=0` turns the system off,
`C3D_SKILLS_UNVERIFIED=0` drops the six `inherited-unverified` bundles). The cap of 5 per
session still holds. Zero have a measured effect — they route because the owner made skills
diff --git a/harness/docs/SKILLS_LEDGER.md b/harness/docs/SKILLS_LEDGER.md
index 880f06c5..a4a88527 100644
--- a/harness/docs/SKILLS_LEDGER.md
+++ b/harness/docs/SKILLS_LEDGER.md
@@ -209,7 +209,7 @@ Baselines are recomputed 2026-08-25 from every run under `eval/bench/out` that a
**several bundles act on the first round and the repair loop hides them by the last.**
Graded runs per language (a run is a sample **iff** it has a round carrying a gate report):
-**blender 145, urdf_blender 25, glsl_shader 17, scene_threejs 9, opengl_python 6,
+**blender 145, urdf_blender 25, glsl_shader 17, scene_threejs 9, opengl_python 6, scene_blender 0 (2026-10-14: the loop's iteration 0 is the first sample),
cadquery 4, threejs 3.** The corpus is live — sibling batteries land runs during a wave —
so every number below carries the snapshot it was read from.
@@ -228,6 +228,9 @@ so every number below carries the snapshot it was read from.
| **c3d-threejs-shader-traps** | mixed | `shader_preflight_findings` | down | **0.00**, n=9 | 0.00, n=9 | 9 | **NOT INSTRUMENTED** — see §4 | **revised (delivery).** Every listing it has ever had was in a scene session that was never offered the read tool, so it is *unmeasured*, not unread |
| **c3d-cadquery-forms** | inherited-unverified | `build_failure_rate` | down | 0.00, n=4 (all 4 built) | same | **4** | no variance to move | **routed OFF.** Needs 20 graded cadquery runs; has **4**. Read 2/2 when forced on |
| **c3d-threejs-forms** | inherited-unverified | `missing_parts` | down | 0.00, n=3 | same | **3** | no variance to move | **routed OFF.** Needs 20 graded threejs runs; has 3. Read 2/2 when forced on |
+| **c3d-bpy-scene-placement** | mixed (gate code read 2026-10-14; no corpus) | `bpy_placement_errors` | down | **n=0** — no gated scene_blender runs (2026-10-14) | — | 0 | not yet measured | **new (D105).** Routed R29 (standing, 80) and R30 (gate-fired, the six seating kinds). The metric is the loop's own accept veto (floating + sunken + interpenetration ERRORs per run), so iteration 0 reads it for free. `unsupported` is WARN-only today and counts zero |
+| **c3d-bpy-scene-lighting** | mixed (gate code read 2026-10-14; bands measured that day on a synthetic scene, not on runs) | `bpy_exposure_findings` | down | **n=0** — no gated scene_blender runs (2026-10-14) | — | 0 | not yet measured | **new (D105).** Routed R31 / R32. Counts the same three `scene_frames` kinds as `c3d-scene-lighting` over `scene_blender` only — a run is one language, so each A/B keeps one owner; `test_no_two_bundles_claim_the_same_quantity` has to key on (kind, language) |
+| **c3d-bpy-scene-materials** | mixed (census code read 2026-10-14; no corpus) | `flat_principled_materials` | down | **UNMEASURABLE** (`measurable=false`) — see §6 | — | 0 | — | **new (D105).** Routed R33 (standing only: no gate sees material work). The census GLB reads three Principled default values and a linked socket exports as its default, so the honest instrument — a per-material linked-socket census — is a harness change, not a skill change (`wrappers/_census_glb.py`) |
**Cut this wave:** `c3d-form-manifest` (text in git history; `docs/skills-attic/` was removed 2026-09-21).
@@ -408,3 +411,14 @@ Raising it is not evidence the bundle worked.
Building the honest instrument — mask the plan's animated objects, diff only those pixels —
is a harness change, not a skill change.
+
+### 6.1 (2026-10-14) a second bundle with no honest proxy
+
+`c3d-bpy-scene-materials` joins `c3d-scene-motion` under `measurable=false`, for the same
+reason in a different instrument: the deterministic side cannot see the claim. The placement
+and frame gates read the census GLB and the PNGs; the GLB writer exports each material as its
+Principled `Base Color` / `Metallic` / `Roughness` default values (`_census_glb._Writer.material`),
+and a LINKED socket — every noise map, every bump — exports as its default. A variance census
+over the sampled texels, or simply "which sockets are linked" per material, is the candidate
+instrument; it is written beside the values the writer already reads, and until then the row is
+a finding about the bundle, not a number to move.
diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjs
index d996858d..3d6a4612 100644
--- a/harness/runtime_js/lib/host_placement.mjs
+++ b/harness/runtime_js/lib/host_placement.mjs
@@ -19,6 +19,11 @@
* asset's lowest vertices (lowest, ±x, ±z extremes of the band
* ≤ 5 % of its height above its minimum) — so a table is measured
* at its leg tips, not under its top.
+ * gap_max_m the LARGEST column gap (2026-10-14): a crate seated by its lowest
+ * corner on a slope has ground_gap_m 0 and gap_max_m the hang of the
+ * far corner; the python gate's `cantilevered` reads it
+ * columns_resting columns within CONTACT_TOL_M of what is under them, or buried
+ * tilt_m gap_max_m − ground_gap_m: how unevenly the feet meet the ground
* sunk_m max over columns of how far the foot sits below a surface that
* passes through the asset's own vertical extent at that column,
* or below a ground-like surface (terrain/floor) above it.
@@ -30,8 +35,8 @@
* floating gap > 0.05 m and not sunk (python re-derives with the indoor
* threshold; these booleans are for tools/humans)
* touches_nothing gap > 0.02 m, not sunk, attached to nothing
- * Interpenetration: pairs of checked assets whose AABBs overlap by > 20 % of the
- * smaller box, refined by sampling the smaller asset's vertices for containment
+ * Interpenetration: pairs of checked assets whose AABBs overlap by > 10 % of the
+ * smaller box (OVERLAP_MIN_FRAC), refined by sampling the smaller asset's vertices for containment
* in the larger one's meshes (parity of surfaces above the point per column) —
* a bench under a tree canopy is NOT an interpenetration, a crate half inside a
* wall is. `aabb_overlap` is the box fraction (the reported number), `inside_frac`
@@ -62,7 +67,12 @@ export const TIME_BUDGET_MS = 4000;
export const CONTACT_TOL_M = 0.02;
export const FLOATING_M = 0.05;
export const SUNK_M = 0.10;
-export const OVERLAP_MIN_FRAC = 0.20;
+// Pairs under this box fraction are neither confirmed nor reported; the python gate grades the
+// rest from Settings.placement (WARN past overlap_warn, ERROR past overlap_error) and this floor IS
+// the default overlap_warn — tests/scene_gates/test_placement.py pins the two together. 0.20 →
+// 0.10 on 2026-10-14 (D105, the owner's stricter contact standards): the 10–35 % band was never
+// measured, so the strict WARN level would have had nothing to read.
+export const OVERLAP_MIN_FRAC = 0.10;
//: named descendants recorded per row, so the plan-contents check can see through one
//: wrapper group without the table growing without bound
export const MAX_INNER_NAMES = 24;
@@ -276,6 +286,11 @@ function collectAssets(scene, indices, volumetrics, contentBox) {
}
const a = { obj: child, name: child.name || `${child.type}_${total}`, zone: zone === child ? '' : (zone.name || zone.type), meshes, instanced, inner, families, exempt: '' };
if (isFree(zone) || isFree(child)) a.exempt = 'free';
+ // the env's room shell (walls, lid, sills, lintels, trim under a `RoomShell…` root — the same
+ // name the overview rig lifts) is the enclosure, never a placed asset: its members abut and
+ // overlap each other by construction (2026-10-15: 24 of 41 Blender interpenetration ERRORs
+ // in the loop's iteration 0 were lintel x ceiling / trim x trim pairs of one shell)
+ else if (String(zone.name || '').startsWith('RoomShell')) a.exempt = 'enclosure';
// instanced first: an asset that is scatter PLUS a haze shell is exempt because its
// instances cannot be sampled at this budget, which is the more informative reason
else if (!meshes.length && instanced) a.exempt = 'instanced';
@@ -422,14 +437,17 @@ function survey(scene, opts) {
return { groundY, notes, indices, assets, total, owner: (mesh) => meshOwner.get(mesh) || nearestName(mesh) };
}
-/** Probe every foot column of `a`: smallest gap (`best`), deepest and shallowest burial (`sunk`,
- * `minSunk` — 0 once a column is not sunk), whether an unsunk column rests, any foot in water. */
+/** Probe every foot column of `a`: smallest gap (`best`) and largest (`gapMax`), how many columns
+ * rest (within contact, or buried), deepest and shallowest burial (`sunk`, `minSunk` — 0 once a
+ * column is not sunk), whether an unsunk column rests, any foot in water. */
function probeFeet(a, indices, owner, groundY) {
const cols = footColumns(a);
- const f = { columns: cols.length, best: null, sunk: null, water: false, minSunk: Infinity, anyRest: false };
+ const f = { columns: cols.length, best: null, gapMax: null, resting: 0, sunk: null, water: false, minSunk: Infinity, anyRest: false };
for (const col of cols) {
const r = probeColumn(a, col, indices, owner, groundY);
if (r.gap !== null && (!f.best || r.gap < f.best.gap)) f.best = r;
+ if (r.gap !== null && (f.gapMax === null || r.gap > f.gapMax)) f.gapMax = r.gap;
+ if (r.sunk > 0 || (r.gap !== null && r.gap <= CONTACT_TOL_M)) f.resting += 1;
if (r.sunk > 0) {
if (!f.sunk || r.sunk > f.sunk.sunk) f.sunk = r;
f.minSunk = Math.min(f.minSunk, r.sunk);
@@ -459,12 +477,15 @@ export function placementTable(scene, THREE, opts = {}) {
exempt: a.exempt, bbox: a.min ? boxJson(a.min, a.max) : null };
if (a.exempt) { rows.push(row); continue; }
if (Date.now() - t0 > TIME_BUDGET_MS) { row.exempt = 'time_budget'; timeCut = true; rows.push(row); continue; }
- const { columns, best, sunk, water } = probeFeet(a, indices, owner, groundY);
+ const { columns, best, gapMax, resting, sunk, water } = probeFeet(a, indices, owner, groundY);
a.attached = [];
a.row = row;
Object.assign(row, {
columns,
ground_gap_m: best ? r3(best.gap) : null,
+ gap_max_m: gapMax === null ? null : r3(gapMax),
+ columns_resting: resting,
+ tilt_m: best && gapMax !== null ? r3(gapMax - best.gap) : null,
support: best ? best.support : '',
sunk_m: sunk ? r3(sunk.sunk) : 0,
sunk_into: sunk ? sunk.into : '',
diff --git a/harness/runtime_js/lib/orbit.mjs b/harness/runtime_js/lib/orbit.mjs
index 45eb2438..599845ae 100644
--- a/harness/runtime_js/lib/orbit.mjs
+++ b/harness/runtime_js/lib/orbit.mjs
@@ -9,8 +9,11 @@
* 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).
+ * ~1.6 m above ground and look at the content centre, and a CONTACT view (elevation
+ * under 10°, `fitContactCamera`) stands at ~1.2× the content span, 0.4 m above the
+ * ground, aimed at the ground edge of the content box — the angle that shows daylight
+ * under a base. Azimuth 0 = front (+Z), CCW from above; elevation in degrees above
+ * the horizon (conventions.py).
*/
const DEG = Math.PI / 180;
@@ -130,6 +133,34 @@ export function fitZoneCamera(bbox, { azimuth = 45, floor = null, fov = 50 } = {
});
}
+const CONTACT_SPAN_FACTOR = 1.2; // eye distance from the content centre, in content spans
+const CONTACT_EYE_M = 0.4; // eye height above the ground: a base's daylight is a few cm tall
+
+/**
+ * Ground-level CONTACT camera on the given azimuth side (scene_v2's `overview_low_front`,
+ * 2026-10-14): the eye stands `CONTACT_SPAN_FACTOR` content spans from the centre, 0.4 m
+ * above the ground, and looks at the point where the view line leaves the content box's
+ * footprint AT ground height — so the near edge of the content sits mid-frame with the
+ * ground under it, where a hovering base or a part through a neighbour is visible. The
+ * overview fits look down at 32°+ and see a base's shadow, not its gap; the judge's
+ * contact crops are cut from this tile (judges/prompt_builder.plan_detail_crops).
+ * @returns {{position:number[], lookAt:number[], fov:number}}
+ */
+export function fitContactCamera(bbox, { azimuth = 20, floor = null, fov = 50 } = {}) {
+ const g = boxGeom(bbox, floor);
+ const [dx, , dz] = orbitDirection(azimuth, 0);
+ const hx = g.size[0] / 2, hz = g.size[2] / 2;
+ const tx = Math.abs(dx) > 1e-6 ? hx / Math.abs(dx) : Infinity;
+ const tz = Math.abs(dz) > 1e-6 ? hz / Math.abs(dz) : Infinity;
+ const edge = Math.min(tx, tz); // centre → footprint boundary along the view line
+ const dist = Math.max(edge + 2, CONTACT_SPAN_FACTOR * Math.max(span(bbox), 1));
+ return round3({
+ position: [g.center[0] + dx * dist, g.floor + CONTACT_EYE_M, g.center[2] + dz * dist],
+ lookAt: [g.center[0] + dx * edge, g.floor, g.center[2] + dz * edge],
+ fov,
+ });
+}
+
/**
* Overview camera on the given azimuth side, fitted so the bbox's eight
* corners fill the frame (exact per-corner frustum fit, ground-aware — never
@@ -151,7 +182,9 @@ export function fitOverviewCamera(bbox, { azimuth = 45, elevation = 30, fov = 50
/**
* Build camera specs for `views` around `bbox` ({min:[..], max:[..]}):
- * fitOverviewCamera above 20°, fitZoneCamera at eye level.
+ * fitOverviewCamera above 20°, fitZoneCamera at eye level (10°–20°), fitContactCamera
+ * under 10°. Only the overviews drop the fog and lift ceilings (`noFog`): the eye and
+ * contact views are pictures of the place as lit.
* @returns {Array<{name, position, lookAt, fov, kind:'orbit'}>}
*/
export function fitOrbitCameras(bbox, views, { fov = 50, aspect = 16 / 9, groundY = null, margin = 1.05 } = {}) {
@@ -159,9 +192,11 @@ export function fitOrbitCameras(bbox, views, { fov = 50, aspect = 16 / 9, ground
const out = [];
for (const v of views) {
const el = Math.max(3, Math.min(89, v.elevation));
- const fit = el <= 20
- ? fitZoneCamera(bbox, { azimuth: v.azimuth, floor: groundY, fov })
- : fitOverviewCamera(bbox, { azimuth: v.azimuth, elevation: el, fov, aspect, groundY, margin });
+ const fit = el < 10
+ ? fitContactCamera(bbox, { azimuth: v.azimuth, floor: groundY, fov })
+ : el <= 20
+ ? fitZoneCamera(bbox, { azimuth: v.azimuth, floor: groundY, fov })
+ : fitOverviewCamera(bbox, { azimuth: v.azimuth, elevation: el, fov, aspect, groundY, margin });
out.push({ name: v.name, ...fit, kind: 'orbit', noFog: el > 20 });
}
return out;
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index be402f53..c7fc6b11 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -197,18 +197,60 @@ function heroForCamera(name) {
return null;
}
+/** World boxes of the SINGLE instances of one loaded GLB: its meshes in `scene`, grouped by the
+ * highest ancestor whose subtree draws each of the file's geometries no more often than the file
+ * itself does — a clone root, or a wrapper holding one clone; two clones under one wrapper split at
+ * the wrapper. `.clone()` shares geometry, so a uuid seen twice under a node is two copies. */
+function glbInstanceBoxes(scene, g) {
+ const inFile = new Map();
+ for (const u of g.geometry_uuids) inFile.set(u, (inFile.get(u) || 0) + 1);
+ const meshes = [];
+ scene.traverse((o) => { if ((o.isMesh || o.isInstancedMesh) && o.geometry && inFile.has(o.geometry.uuid)) meshes.push(o); });
+ const below = new Map(); // ancestor -> Map(geometry uuid -> copies drawn under it)
+ for (const m of meshes) {
+ for (let a = m; a; a = a.parent) {
+ if (!below.has(a)) below.set(a, new Map());
+ const c = below.get(a);
+ c.set(m.geometry.uuid, (c.get(m.geometry.uuid) || 0) + 1);
+ }
+ }
+ const single = new Map(); // ancestor -> holds at most one copy of each geometry
+ const isSingle = (a) => {
+ if (!single.has(a)) single.set(a, [...below.get(a)].every(([u, n]) => n <= inFile.get(u)));
+ return single.get(a);
+ };
+ const boxes = new Map(); // instance root -> world box of its GLB meshes
+ for (const m of meshes) {
+ let root = m;
+ while (root.parent && isSingle(root.parent)) root = root.parent;
+ const box = drawableBox(m, THREE);
+ if (!box) continue;
+ if (!boxes.has(root)) boxes.set(root, new THREE.Box3());
+ boxes.get(root).union(box);
+ }
+ return [...boxes.values()].filter((b) => !b.isEmpty());
+}
+
function glbUsage(scene) {
let used;
try { used = geometryBoxes(scene); } catch { return []; }
return loadedGlbs.map((g) => {
- const all = new THREE.Box3();
let n = 0;
- for (const u of g.geometry_uuids) { const b = used.get(u); if (b) { n += 1; if (!b.isEmpty()) all.union(b); } }
- // the largest extent of the GLB as placed: "fills 0.3 % of the frame" reads as "microscopic"
- // without it (loop 23's lighthouse: a 4.4 m lantern room on a 30 m tower, far from every
- // camera, judged "scaled far too small" for three rounds)
- const size = all.isEmpty() ? null : +Math.max(...all.getSize(new THREE.Vector3()).toArray()).toFixed(2);
- return { url: g.url, meshes: g.geometry_uuids.length, meshes_in_scene: n, in_scene: n > 0, size_m: size };
+ for (const u of g.geometry_uuids) if (used.has(u)) n += 1;
+ // the largest extent of ONE placed instance: "fills 0.3 % of the frame" reads as "microscopic"
+ // without a size (loop 23's lighthouse: a 4.4 m lantern room on a 30 m tower, far from every
+ // camera, judged "scaled far too small" for three rounds) — and until 2026-10-14 the union of
+ // every clone was that size (a 2.2 m sofa placed three times across a lounge was "6.5 m across
+ // as placed" to the frames gate and the judge). `instances` says how many copies stand in the scene.
+ let size = null;
+ let instances = 0;
+ try {
+ const boxes = glbInstanceBoxes(scene, g);
+ instances = boxes.length;
+ for (const b of boxes) size = Math.max(size ?? 0, ...b.getSize(new THREE.Vector3()).toArray());
+ } catch { size = null; }
+ return { url: g.url, meshes: g.geometry_uuids.length, meshes_in_scene: n, in_scene: n > 0,
+ size_m: size === null ? null : +size.toFixed(2), instances };
});
}
diff --git a/harness/tests/blender_cadquery/test_blender_lint.py b/harness/tests/blender_cadquery/test_blender_lint.py
index c358d63a..fdcb2c99 100644
--- a/harness/tests/blender_cadquery/test_blender_lint.py
+++ b/harness/tests/blender_cadquery/test_blender_lint.py
@@ -128,3 +128,25 @@ def test_headless_pitfalls() -> None:
assert any("selected_objects" in m for m in w)
assert any("context-dict" in m for m in e)
assert any("use_auto_smooth" in m for m in e)
+
+
+def test_blender_52_gn_inputs_and_fast_solver_are_errors() -> None:
+ """Blender 5.2.2 (D104): `mod["Socket_2"] = v` raises TypeError (geometry-nodes inputs are RNA
+ properties now) and the boolean solver 'FAST' no longer exists (FLOAT / EXACT / MANIFOLD)."""
+ src = ("import bpy\no = bpy.context.object\nmod = o.modifiers.new('gn', 'NODES')\nmod['Socket_2'] = 5\n"
+ "mod['Input_3_attribute_name'] = 'x'\nb = o.modifiers.new('cut', 'BOOLEAN')\nb.solver = 'FAST'\n")
+ r = lint_blender_source(src)
+ gn = [f for f in r.findings if "geometry-nodes modifier inputs" in f.message]
+ assert [(f.severity, f.data["line"]) for f in gn] == [(Severity.ERROR, 4), (Severity.ERROR, 5)]
+ assert "mod.properties.inputs" in gn[0].fix_hint
+ fast = [f for f in r.findings if "solver 'FAST'" in f.message]
+ assert fast and fast[0].severity == Severity.ERROR and fast[0].data["line"] == 7
+
+
+def test_blender_52_idioms_are_clean() -> None:
+ """The 5.2 idioms, and a 'FAST' string that is not a solver, raise nothing."""
+ src = ("import bpy\no = bpy.context.object\nmod = o.modifiers.new('gn', 'NODES')\n"
+ "getattr(mod.properties.inputs, 'Socket_2').value = 5\nb = o.modifiers.new('cut', 'BOOLEAN')\n"
+ "b.solver = 'MANIFOLD'\nspeed = 'FAST'\n")
+ r = lint_blender_source(src)
+ assert not [f for f in r.findings if "geometry-nodes modifier inputs" in f.message or "solver 'FAST'" in f.message], _msgs(r)
diff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.py
index 916f1841..f839511b 100644
--- a/harness/tests/core/test_config_env_aliases.py
+++ b/harness/tests/core/test_config_env_aliases.py
@@ -54,6 +54,24 @@ def test_the_in_flight_cap_spellings_empty_zero_and_garbage(monkeypatch):
Settings()
+def test_the_variant_switches_parse_a_name_and_a_json_mapping(monkeypatch):
+ """D105: ``C3D_VARIANT`` names one variant for the process; ``C3D_VARIANTS`` is a JSON object of exact
+ generator id → name (consulted when the first is empty); unset / empty is the base, garbage JSON is a
+ configuration error (the CLI's exit 2), not a silently empty table."""
+ for name in ("C3D_VARIANT", "C3D_VARIANTS"):
+ monkeypatch.delenv(name, raising=False)
+ assert (Settings().variant, Settings().variants) == ("", {})
+ monkeypatch.setenv("C3D_VARIANT", "argon")
+ monkeypatch.setenv("C3D_VARIANTS", '{"agy:gemini-4-argon": "argon", "codex:gpt-6.1-sol": "sol"}')
+ s = Settings()
+ assert s.variant == "argon" and s.variants == {"agy:gemini-4-argon": "argon", "codex:gpt-6.1-sol": "sol"}
+ monkeypatch.setenv("C3D_VARIANT", "")
+ assert Settings().variant == "", "an empty value is unset, never the name ''"
+ monkeypatch.setenv("C3D_VARIANTS", "argon")
+ with pytest.raises(ValueError):
+ Settings()
+
+
# --------------------------------------------------------------------------- yaml layering
def test_the_environment_beats_the_config_files_per_setting(monkeypatch):
diff --git a/harness/tests/core/test_doctor.py b/harness/tests/core/test_doctor.py
index c348928d..cbcd854b 100644
--- a/harness/tests/core/test_doctor.py
+++ b/harness/tests/core/test_doctor.py
@@ -43,7 +43,7 @@ def _fake_probe(monkeypatch, tmp_path: Path, payload: dict) -> list:
def run(cmd, **kw):
seen["cmd"], seen["env"] = cmd, kw.get("env") or {}
- return ProcResult(0, "Blender 5.0.1\nC3D_DOCTOR " + json.dumps(payload) + "\nBlender quit\n", "", False, 5)
+ return ProcResult(0, "Blender 5.2.2 LTS\nC3D_DOCTOR " + json.dumps(payload) + "\nBlender quit\n", "", False, 5)
monkeypatch.setenv("C3D_CACHE_DIR", str(tmp_path))
monkeypatch.setattr(doctor, "run_subprocess", run)
@@ -53,9 +53,11 @@ def _fake_probe(monkeypatch, tmp_path: Path, payload: dict) -> list:
def test_doctor_reports_the_blender_render_capability(tmp_path: Path, monkeypatch):
- rows = {r[0]: r for r in _fake_probe(monkeypatch, tmp_path, {"cuda": ["RTX"], "gl": "D3D12 (NVIDIA RTX)"})}
+ rows = {r[0]: r for r in _fake_probe(monkeypatch, tmp_path, {"cuda": ["RTX"], "gl": "D3D12 (NVIDIA RTX)", "cycles_ms": 310})}
assert rows["blender cycles"][1] == "OK" and "CUDA: RTX" in rows["blender cycles"][2]
assert "cycles 32 spp" in rows["blender cycles"][2]
+ assert "310 ms" in rows["blender cycles"][2] and "persistent data" in rows["blender cycles"][2]
+ assert "frame cap 20s" in rows["blender cycles"][2]
assert rows["blender eevee"][1] == "OK" and rows["blender gpu slots"][1] == "OK"
soft = {r[0]: r for r in _fake_probe(monkeypatch, tmp_path, {"cuda": [], "gl": "llvmpipe (LLVM 19.1.1, 256 bits)"})}
assert soft["blender cycles"][1] == "WARN" and "CPU" in soft["blender cycles"][2]
@@ -71,3 +73,59 @@ def test_doctor_blender_render_probe_runs_for_real():
pytest.skip("no Blender binary")
rows = {r[0]: r for r in check_blender_render(eevee=False)}
assert rows["blender cycles"][1] in ("OK", "WARN") and "blender eevee" not in rows
+
+
+def test_doctor_skills_walks_every_shipped_overlay_and_labels_an_invalid_bundle_by_its_variant(tmp_path: Path, monkeypatch):
+ """An overlay bundle is routed the moment its variant is active (``all_skills``), so the doctor
+ checks each shipped variant's overlay as it checks the base library — one ``skills overlay`` row
+ per variant, the variant leading the detail (the row NAME is fixed: docs/INSTALL.md documents it)."""
+ from codeverse3d.config import get_settings
+ from codeverse3d.doctor import check_skills
+ from codeverse3d.prompts import variants as V
+ from codeverse3d.skills.registry import ROUTED_SKILLS
+ from tests.skills.conftest import write_bundle
+
+ lib = tmp_path / "lib"
+ for name in ROUTED_SKILLS:
+ write_bundle(lib, name)
+ overlay = lib / "variants" / "tv"
+ write_bundle(overlay, "c3d-bbox-contract", body="OVERLAY RULES.")
+ (overlay / "c3d-new-sheet").mkdir(parents=True)
+ (overlay / "c3d-new-sheet" / "SKILL.md").write_text("---\nname: c3d-new-sheet\n# the closing fence is missing\n")
+ prompts_root = tmp_path / "prompt_variants"
+ (prompts_root / "tv").mkdir(parents=True)
+ (prompts_root / "tv" / "variant.toml").write_text('[variant]\nname = "tv"\nversion = 1\n')
+ monkeypatch.setattr(V, "VARIANTS_DIR", prompts_root)
+ monkeypatch.setenv("C3D_SKILLS_DIR", str(lib))
+ monkeypatch.delenv("C3D_VARIANT", raising=False)
+ get_settings.cache_clear()
+ try:
+ rows = {name: (status, detail) for name, status, detail in check_skills()}
+ assert rows["skills library"] == ("OK", f"{len(ROUTED_SKILLS)} bundles, 0 invalid")
+ status, detail = rows["skills overlay"]
+ assert status == "FAIL" and detail.startswith("tv: 2 bundles, 1 invalid: tv/c3d-new-sheet"), detail
+ write_bundle(overlay, "c3d-new-sheet")
+ status, detail = {n: (st, d) for n, st, d in check_skills()}["skills overlay"]
+ assert status == "OK" and detail.startswith("tv: 2 bundles, 0 invalid") and "routes.toml: no rows" in detail
+ (overlay / "routes.toml").write_text('[[boost]]\nskill = "c3d-bbox-contract"\ndelta = "ten"\n')
+ status, detail = {n: (st, d) for n, st, d in check_skills()}["skills overlay"]
+ assert status == "FAIL" and detail.startswith("tv: ") and "routes.toml invalid" in detail
+ assert "delta must be an integer" in detail
+ finally:
+ get_settings.cache_clear()
+
+
+def test_doctor_skills_reports_the_shipped_argon_overlay(monkeypatch):
+ from codeverse3d.config import get_settings
+ from codeverse3d.doctor import check_skills
+
+ monkeypatch.delenv("C3D_SKILLS_DIR", raising=False)
+ monkeypatch.delenv("C3D_VARIANT", raising=False)
+ get_settings.cache_clear()
+ try:
+ rows = {name: (status, detail) for name, status, detail in check_skills()}
+ finally:
+ get_settings.cache_clear()
+ assert rows["skills library"][0] == "OK"
+ status, detail = rows["skills overlay"]
+ assert status == "OK" and detail.startswith("argon: 0 bundles, 0 invalid") and "2 boost(s)" in detail
diff --git a/harness/tests/core/test_portability.py b/harness/tests/core/test_portability.py
index c0609c18..fd86ffea 100644
--- a/harness/tests/core/test_portability.py
+++ b/harness/tests/core/test_portability.py
@@ -59,6 +59,20 @@ def test_write_example_refuses_to_write_nothing(tmp_path, monkeypatch) -> None:
with pytest.raises(FileNotFoundError, match="starter tree missing"):
skeleton.write_example(Workspace(tmp_path / "ws").create())
+
+def test_scene_blender_write_example_refuses_to_write_nothing(tmp_path, monkeypatch) -> None:
+ """The bpy starter tree (its example scene + the library) is package data too."""
+ import codeverse3d.languages.scene_blender as skeleton
+
+ monkeypatch.setattr(skeleton, "STARTER_DIR", tmp_path / "gone" / "src")
+ with pytest.raises(FileNotFoundError, match="starter tree missing"):
+ skeleton.write_example(Workspace(tmp_path / "ws").create())
+ empty = tmp_path / "empty" / "src"
+ empty.mkdir(parents=True)
+ monkeypatch.setattr(skeleton, "STARTER_DIR", empty)
+ with pytest.raises(FileNotFoundError, match="contains no .py files"):
+ skeleton.write_example(Workspace(tmp_path / "ws2").create())
+
# ------------------------------------------------------------------- the node floor gate
def test_node_version_parsing_and_gate() -> None:
for text, expected in (("v24.14.0\n", (24, 14, 0)), ("v22.0.0-nightly20240101", (22, 0, 0)), ("not found", None)):
diff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.py
index cfb3a1d9..f0e87c37 100644
--- a/harness/tests/flywheel_cli/conftest.py
+++ b/harness/tests/flywheel_cli/conftest.py
@@ -117,7 +117,7 @@ def make_fake_run(
rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.MAX_ROUNDS, rounds=rounds,
total_usage=Usage(cost_usd=0.06, input_tokens=2000, output_tokens=1000),
steps=[StepTime(step="plan", wall_s=30.0, lost_s=6.0)], finished_at=datetime.now(UTC),
- environment={"blender": "Blender 5.0.1"})
+ environment={"blender": "Blender 5.2.2 LTS"})
ws.write_json(ws.record_path, rec)
return ws, rec
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index 6b76b911..d8a2fdf1 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -530,6 +530,75 @@ def test_a_judge_unavailable_run_resumes_as_it_is(made_run, stub_track):
assert entered == [(True, False)]
+def test_make_freezes_the_variant_on_the_spec_and_refuses_an_unknown_one(tmp_path: Path, monkeypatch):
+ """D105: ``--variant`` is resolved once, validated before a run dir exists and frozen on
+ ``spec.options.variant``; with no flag ``C3D_VARIANTS`` maps the generator by its SERVED model
+ (the effort suffix does not matter) and the default run is the base. Unknown = exit 2, no orphan."""
+ from codeverse3d.config import get_settings
+
+ runs = tmp_path / "runs"
+ r = runner.invoke(app, ["make", "a clay pot", "--variant", "argon", "--no-run", "--runs-dir", str(runs), "--slug", "v"])
+ assert r.exit_code == 0, r.output
+ assert json.loads((runs / "v" / "spec.json").read_text())["options"]["variant"] == "argon"
+ out = " ".join(r.output.split())
+ assert "variant" in out and "argon v1" in out and "via --variant" in out
+
+ r = runner.invoke(app, ["make", "a clay pot", "--variant", "bogus", "--no-run", "--runs-dir", str(runs), "--slug", "b"])
+ assert r.exit_code == 2 and "unknown variant 'bogus'" in r.output and "argon" in r.output
+ assert "Traceback" not in r.output and not (runs / "b").exists(), "no workspace for a rejected flag"
+
+ r = runner.invoke(app, ["make", "a clay pot", "--no-run", "--runs-dir", str(runs), "--slug", "base"])
+ assert r.exit_code == 0 and json.loads((runs / "base" / "spec.json").read_text())["options"]["variant"] == ""
+ assert "base" in " ".join(r.output.split())
+
+ monkeypatch.setenv("C3D_VARIANTS", '{"agy:gemini-4-argon": "argon"}')
+ get_settings.cache_clear()
+ try:
+ r = runner.invoke(app, ["make", "a clay pot", "--generator", "agy:gemini-4-argon-high", "--no-run",
+ "--runs-dir", str(runs), "--slug", "served"])
+ assert r.exit_code == 0, r.output
+ assert json.loads((runs / "served" / "spec.json").read_text())["options"]["variant"] == "argon"
+ assert "via settings.variants" in " ".join(r.output.split())
+ r = runner.invoke(app, ["make", "a clay pot", "--generator", "codex:gpt-6.1-sol", "--no-run",
+ "--runs-dir", str(runs), "--slug", "other"])
+ assert r.exit_code == 0 and json.loads((runs / "other" / "spec.json").read_text())["options"]["variant"] == ""
+ finally:
+ get_settings.cache_clear()
+
+
+def test_a_judge_replay_runs_under_the_records_variant(tmp_path: Path, monkeypatch):
+ """`3dcode judge` reads the prompt files the run read: the record's variant is active while the judge
+ input is built and the verdict made; a variant this tree no longer ships warns and replays on the base."""
+ import codeverse3d.judges.vlm_judge as vj
+ from codeverse3d.prompts.variants import active_variant
+ from tests.flywheel_cli.conftest import _judgment, make_fake_run
+
+ runs = tmp_path / "runs"
+ ws, rec = make_fake_run(runs, "stool_v")
+ rec.spec.options.variant = "argon"
+ ws.write_json(ws.record_path, rec)
+ ws.write_json(ws.spec_path, rec.spec)
+ _write_stool_plan(ws)
+ seen: list[str] = []
+
+ class _Judge:
+ def __init__(self, *, rubric=None, **kw):
+ self.rubric = rubric
+
+ def judge(self, inp):
+ seen.append(active_variant())
+ return _judgment(0.7, False, [])
+
+ monkeypatch.setattr(vj, "VlmJudge", _Judge)
+ assert runner.invoke(app, ["judge", "stool_v", "--runs-dir", str(runs)]).exit_code == 0
+ assert seen == ["argon"]
+ rec.spec.options.variant = "retired"
+ ws.write_json(ws.record_path, rec)
+ r = runner.invoke(app, ["judge", "stool_v", "--runs-dir", str(runs)])
+ assert r.exit_code == 0 and "base prompts" in r.output and "retired" in r.output
+ assert seen == ["argon", ""]
+
+
def test_a_zero_minute_budget_is_refused(made_run, tmp_path: Path):
"""--max-minutes 0 planned (paid) and stopped at the first clock check with no round."""
r = runner.invoke(app, ["make", "a cup", "--max-minutes", "0", "--no-run", "--runs-dir", str(tmp_path / "z"), "--slug", "z"])
diff --git a/harness/tests/judges/test_calibration.py b/harness/tests/judges/test_calibration.py
index 5a22033e..f5ce3f90 100644
--- a/harness/tests/judges/test_calibration.py
+++ b/harness/tests/judges/test_calibration.py
@@ -93,6 +93,37 @@ def test_calibrate_offline(tmp_path):
calibrate([empty], model_id="fake:fake-1", out_dir=tmp_path / "out", chat_model=model)
+def test_calibration_takes_the_judges_thinking_from_the_settings(tmp_path, monkeypatch):
+ """``calibrate(thinking=None)`` judges at ``Settings.judge.thinking`` — the level the loop runs
+ (D105: argon thinks only from medium) — and a stated level still wins; the CLI's default is None."""
+ import codeverse3d.addons.calibration as cal
+ from codeverse3d.config import Settings, get_settings
+
+ run = _fake_run(tmp_path, "runA")
+ levels: list[str] = []
+ real = cal.make_judge
+
+ def spy(spec, rubric_name, model_id, n, **options):
+ levels.append(options["thinking"])
+ return real(spec, rubric_name, model_id, n, **options)
+
+ monkeypatch.setattr(cal, "make_judge", spy)
+ s = Settings(judge={"thinking": "medium"})
+ monkeypatch.setattr(cal, "get_settings", lambda: s)
+ model = FakeChatModel(default=lambda req: good_reply(R, ["A1", "A2"], 0.7))
+ calibrate([run], model_id="fake:fake-1", n_samples=1, out_dir=tmp_path / "out", geometry_mode=None, chat_model=model, max_workers=1)
+ calibrate([run], model_id="fake:fake-1", n_samples=1, out_dir=tmp_path / "out", geometry_mode=None, chat_model=model, max_workers=1,
+ thinking="high")
+ assert levels == ["medium"] * 2 + ["high"] * 2 # make_judge once per case (two rounds), per call
+ assert all(r.thinking == "medium" for r in model.requests[:2]) and model.requests[-1].thinking == "high"
+ get_settings.cache_clear()
+ import argparse
+
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--thinking", default=None, choices=("off", "low", "medium", "high"))
+ assert ap.parse_args([]).thinking is None # the shape cal.main declares: None = the settings' level
+
+
def test_run_labels_stay_distinct_across_battery_layouts():
"""V9c: bench cells all end in .../run; their labels (and judgment sidecars) must not collide."""
from codeverse3d.addons.calibration import _run_label
diff --git a/harness/tests/judges/test_caps.py b/harness/tests/judges/test_caps.py
index bb17a5ba..415ef0d6 100644
--- a/harness/tests/judges/test_caps.py
+++ b/harness/tests/judges/test_caps.py
@@ -14,7 +14,8 @@ from codeverse3d.judges.rubrics import (
R = load_rubric("static_object_v1")
A = load_rubric("articulated_v1")
-S = load_rubric("scene_v1")
+S = load_rubric("scene_v2")
+S1 = load_rubric("scene_v1") # frozen: what a recorded v1 round replays under
POSE = [RenderView(name="pose_rest", path="p")]
@@ -50,9 +51,31 @@ E, W = Severity.ERROR, Severity.WARN
{"views": POSE}, 0.6, {"floating_part"}),
(S, [], {"console_errors": ["TypeError: x is undefined"]}, 0.6, {"console_error"}),
(S, [_gate("shader_probe", E, "GLSL compile failed in water.js", kind="shader")], {}, 0.5, {"shader_error"}),
- # the older floating_part rule (gate *, cap 0.6) fires too; the tighter cap wins
+ # scene_v2: ONE cap per placement kind, by the finding's typed kind (the v1 gate-'*' floating_part
+ # twin that fired beside floating_or_sunken_asset is gone — a floating ERROR is a single 0.60 cap)
+ (S, [_gate("scene_placement", E, "Pondside/Lantern is floating 0.30 m above PondWater", target="Pondside/Lantern",
+ kind="floating", gap_m=0.30)], {"defects_present": {}}, 0.6, {"floating_asset"}),
+ (S, [_gate("scene_placement", E, "Quay/Crate is sunken 0.25 m into Ground", target="Quay/Crate", kind="sunken", sunk_m=0.25)],
+ {}, 0.65, {"sunken_asset"}),
+ (S, [_gate("scene_placement", E, "interpenetration: Quay/Bench and Quay/Wall overlap (41% of the smaller box)",
+ target="Quay/Bench", kind="interpenetration", overlap=0.41)], {}, 0.7, {"interpenetration"}),
+ (S, [_gate("scene_placement", E, "Quay/Door measures 9.00 m but the plan sized door at ~2.00 m (4.5x)", target="Quay/Door",
+ kind="scale", factor=4.5)], {}, 0.75, {"wrong_scale"}),
+ (S, [_gate("scene_placement", E, "6 of 10 placed assets are tagged placement='free'", target="scene", kind="free_exempt")],
+ {}, 0.75, {"free_exempt"}),
+ # a v1-era record without a typed kind: the message decides, as for the object rows above
(S, [_gate("scene_placement", E, "Pondside/Lantern is floating 0.30 m above PondWater", target="Pondside/Lantern")],
- {"defects_present": {}}, 0.6, {"floating_or_sunken_asset"}),
+ {}, 0.6, {"floating_asset"}),
+ # the camera rule names the kinds scene_frames really emits; a blocked TARGET is not a buried camera
+ (S, [_gate("scene_frames", E, "camera inside geometry", target="Establishing", kind="camera_in_geometry")], {}, 0.5,
+ {"camera_in_geometry"}),
+ (S, [_gate("scene_frames", E, "camera 2.1 m under the ground", target="Establishing", kind="camera_underground")], {}, 0.5,
+ {"camera_in_geometry"}),
+ (S, [_gate("scene_frames", E, "the subject is hidden by a wall", target="Establishing", kind="camera_target_blocked")], {}, 0.9,
+ set()),
+ # the frozen v1 rubric still replays its recorded rounds the old way
+ (S1, [_gate("scene_placement", E, "Pondside/Lantern is floating 0.30 m above PondWater", target="Pondside/Lantern")],
+ {"defects_present": {}}, 0.6, {"floating_or_sunken_asset", "floating_part"}),
])
def test_gate_caps(rubric, gates, kw, overall, rules):
res = apply_caps(rubric, 0.9, gates, {}, [], **kw)
@@ -61,6 +84,20 @@ def test_gate_caps(rubric, gates, kw, overall, rules):
assert applied == rules if rules == set() else rules <= applied
+def test_scene_v2_placement_caps_fire_one_each_and_the_tightest_wins():
+ """Three measured placement ERRORs = three ledger lines (one per kind) and the 0.60 floor."""
+ gates = [GateReport(gate="scene_placement", passed=False, findings=[
+ GateFinding(gate="scene_placement", severity=E, target="A", message="A is floating 0.12 m", data={"kind": "floating", "gap_m": 0.12}),
+ GateFinding(gate="scene_placement", severity=E, target="B", message="B is sunken 0.3 m", data={"kind": "sunken", "sunk_m": 0.3}),
+ GateFinding(gate="scene_placement", severity=E, target="C", message="interpenetration: C and D", data={"kind": "interpenetration", "overlap": 0.5}),
+ GateFinding(gate="scene_placement", severity=E, target="env", message="scene.fog is not set", data={"kind": "no_fog"}),
+ ])]
+ res = apply_caps(S, 0.9, gates, {}, [])
+ assert res.overall == 0.6
+ assert [c.rule for c in res.caps_applied] == ["floating_asset", "sunken_asset", "interpenetration"]
+ assert "[A]" in res.caps_applied[0].evidence and "[C]" in res.caps_applied[2].evidence
+
+
PASSED = _connectivity(True, ("info", "all 9 parts are connected (9 contacts, gap <= 2 mm)"),
("warn", "'Seat' and 'Leg' overlap by 1.4 mm (weld)"))
CONTRACT_ERR = GateReport(gate="contract", passed=False, findings=[GateFinding(
@@ -77,14 +114,79 @@ CONTRACT_ERR = GateReport(gate="contract", passed=False, findings=[GateFinding(
# a contract ERROR about the bbox does not switch off the veto connectivity earned
(R, "floating_part", [CONTRACT_ERR, _connectivity(True, ("info", "all 4 parts are connected"))], True),
(R, "interpenetration", [CONTRACT_ERR, _connectivity(True, ("info", "all 4 parts are connected"))], True),
- (S, "floating_or_sunken_asset", [GateReport(gate="scene_placement", passed=True, findings=[GateFinding(
+ (S1, "floating_or_sunken_asset", [GateReport(gate="scene_placement", passed=True, findings=[GateFinding(
gate="scene_placement", severity=Severity.INFO, target="scene", message="13 assets checked: 0 floating")])], True),
+ # a failed report that names no ERROR finding cannot say what failed: not clean
+ (R, "floating_part", [GateReport(gate="connectivity", passed=False, findings=[])], False),
])
def test_measured_absent(rubric, defect, gates, absent):
"""Gates decide geometry (law 3): a passed gate vetoes the VLM's claim of what it measured."""
assert measured_absent(rubric, defect, gates) is absent
+def _placement(passed: bool, *findings: tuple[Severity, str, str, dict]) -> GateReport:
+ """A scene_placement report: the gate's summary INFO + typed findings (sev, kind, target, data)."""
+ rows = [GateFinding(gate="scene_placement", severity=Severity.INFO, target="scene", message="13 assets checked",
+ data={"kind": "summary", "counts": {"floating": 0, "sunken": 0, "unsupported": 0, "interpenetration": 0}})]
+ rows += [GateFinding(gate="scene_placement", severity=sev, target=target, message=f"{target} {kind}", data={"kind": kind, **data})
+ for sev, kind, target, data in findings]
+ return GateReport(gate="scene_placement", passed=passed, findings=rows)
+
+
[email protected](("defect", "gates", "absent"), [
+ # a passed gate measured nothing of the kind: the claim is vetoed
+ ("floating_asset", [_placement(True)], True),
+ ("sunken_asset", [_placement(True)], True),
+ ("interpenetration", [_placement(True)], True),
+ ("wrong_scale", [_placement(True)], True),
+ # a WARN-band hover with gap_m 0.08 keeps the VLM tick: the veto line is the 0.02 m INDOOR tolerance
+ # (Placement.floating_indoor_m = contact_m), so every floating / unsupported WARN the gate raises reaches it
+ ("floating_asset", [_placement(True, (W, "floating", "Quay/Lantern", {"gap_m": 0.08}))], False),
+ # ...so does a 3 cm "unsupported" hover (outdoors: past contact_m, within floating_outdoor_m) and a 3 cm
+ # indoor floating WARN — the line was the OUTDOOR 0.05 until 2026-10-15 and vetoed both although the gate
+ # had flagged them (review findings 4 / 17)
+ ("floating_asset", [_placement(True, (W, "unsupported", "Quay/Crate", {"gap_m": 0.03}))], False),
+ ("floating_asset", [_placement(True, (W, "floating", "Dining/Vase", {"gap_m": 0.03}))], False),
+ # under the line the gate's verdict stands (it raises no such WARN: a gap within contact_m is seated)
+ ("floating_asset", [_placement(True, (W, "floating", "Dining/Vase", {"gap_m": 0.01}))], True),
+ # a no_fog ERROR in the same report does NOT cancel the floating veto (scoring version 4: scoped to the kind)
+ ("floating_asset", [_placement(False, (E, "no_fog", "env", {}))], True),
+ ("interpenetration", [_placement(False, (E, "missing_content", "Quay", {"missing": ["Bollard"]}))], True),
+ # ...a floating ERROR does, and so does an ERROR of the kind alone among WARNs of others
+ ("floating_asset", [_placement(False, (E, "floating", "Quay/Lantern", {"gap_m": 0.2}))], False),
+ ("floating_asset", [_placement(False, (W, "sunken", "Quay/Post", {"sunk_m": 0.15}), (E, "floating", "Quay/Lantern", {"gap_m": 0.2}))], False),
+ # the kinds are scoped: a sunken ERROR vetoes nothing about floating, a floating ERROR nothing about sunken
+ ("floating_asset", [_placement(False, (E, "sunken", "Quay/Post", {"sunk_m": 0.4}))], True),
+ ("sunken_asset", [_placement(False, (E, "floating", "Quay/Lantern", {"gap_m": 0.2}))], True),
+ # WARN magnitudes against each rule's own line: sunk 0.10 m, overlap 0.20, any scale factor
+ ("sunken_asset", [_placement(True, (W, "sunken", "Quay/Post", {"sunk_m": 0.12}))], False),
+ ("interpenetration", [_placement(True, (W, "interpenetration", "Quay/Bench", {"overlap": 0.15}))], True),
+ ("interpenetration", [_placement(True, (W, "interpenetration", "Quay/Bench", {"overlap": 0.25}))], False),
+ ("wrong_scale", [_placement(True, (W, "scale", "Quay/Door", {"factor": 0.35}))], False),
+ ("wrong_scale", [_placement(True, (W, "scale", "Quay/Door", {"factor": 3.0}))], False),
+ # nothing measures the composition claims or a hero's place
+ ("hero_misplaced", [_placement(True)], False),
+ ("flat_ground", [_placement(True)], False),
+ # the gate did not run
+ ("floating_asset", [GateReport(gate="scene_frames", passed=True)], False),
+])
+def test_scene_v2_veto_is_scoped_to_the_rules_kinds(defect, gates, absent):
+ assert measured_absent(S, defect, gates) is absent
+
+
+def test_scene_v2_veto_rides_through_aggregate_samples():
+ """The vote marks floating_asset; the passed placement gate switches it off (no penalty, no cap),
+ and a no_fog ERROR in the same report changes nothing about that."""
+ sample = JudgeOutput(criteria={c.id: CriterionScore(score=0.9, evidence="") for c in S.criteria},
+ defects={d.id: d.id == "floating_asset" for d in S.defects})
+ clean = aggregate_samples(S, [sample], gates=[_placement(True)], acceptance_items=[])
+ assert clean.overall == pytest.approx(0.9) and "contradicted by a passed gate" in clean.summary
+ foggy = aggregate_samples(S, [sample], gates=[_placement(False, (E, "no_fog", "env", {}))], acceptance_items=[])
+ assert foggy.overall == pytest.approx(0.9) and "floating_asset" in foggy.summary
+ hover = aggregate_samples(S, [sample], gates=[_placement(True, (W, "floating", "Quay/Lantern", {"gap_m": 0.08}))], acceptance_items=[])
+ assert hover.overall == pytest.approx(0.6) and "defect:floating_asset≤0.60" in hover.summary
+
+
def test_graded_acceptance_cap_keeps_the_gradient_but_not_the_pass():
ten = [AcceptanceItem(id=f"M{i}", text="x", priority="must") for i in range(10)]
nine_ok = {a.id: True for a in ten} | {"M3": False}
@@ -94,7 +196,8 @@ def test_graded_acceptance_cap_keeps_the_gradient_but_not_the_pass():
assert apply_caps(R, 0.99, [], {"M0": True}, ten[:2]).overall == pytest.approx(0.8)
should = [AcceptanceItem(id="S1", text="y", priority="should")]
assert apply_caps(R, 0.9, [], {"S1": False}, should).overall == 0.9, "a should item never caps"
- assert apply_caps(S, 0.99, [], nine_ok, ten).overall == 0.6, "an ungraded rule keeps its flat cap"
+ assert apply_caps(S1, 0.99, [], nine_ok, ten).overall == 0.6, "an ungraded rule (scene_v1, frozen) keeps its flat cap"
+ assert apply_caps(S, 0.99, [], nine_ok, ten).overall == pytest.approx(0.96), "scene_v2 grades it like the object rubrics"
# pass/fail is the owner's policy: the verdict still fails on must_missing
sample = JudgeOutput(criteria={c.id: CriterionScore(score=0.99, evidence="") for c in R.criteria},
acceptance={k: AcceptanceVerdict(verified=v) for k, v in nine_ok.items()},
diff --git a/harness/tests/judges/test_defects.py b/harness/tests/judges/test_defects.py
index 6b8b083b..36e8d8dc 100644
--- a/harness/tests/judges/test_defects.py
+++ b/harness/tests/judges/test_defects.py
@@ -30,7 +30,7 @@ def _reply(score=0.9, defects=None):
def test_rubrics_declare_defects_with_costs():
- for name in ("static_object_v1", "articulated_v1", "scene_v1", "asset_v1", "reference_v1"):
+ for name in ("static_object_v1", "articulated_v1", "scene_v1", "scene_v2", "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)
@@ -100,7 +100,7 @@ def test_defect_vote_ties_are_absent(judge_input, cache_dir, caplog):
assert raw["defect_votes"]["render_artifacts"] == [True, False]
assert raw["defects"]["render_artifacts"] is False and j.overall == pytest.approx(0.9)
assert raw["tie_broken"] == ["render_artifacts"]
- assert raw["scoring_version"] == 3 and raw["overridden"] == []
+ assert raw["scoring_version"] == 4 and raw["overridden"] == [] # 4: the kind-scoped veto (scene_v2, 2026-10-14)
clean_first = FakeChatModel(by_label={":s0": [_reply(0.9)], ":s1": [_reply(0.9, ["render_artifacts"])]})
j2 = VlmJudge("static_object_v1", chat_model=clean_first, n_samples=2, cache_dir=cache_dir).judge(judge_input)
diff --git a/harness/tests/judges/test_detail_anchors.py b/harness/tests/judges/test_detail_anchors.py
index 74974d45..ede3fd6d 100644
--- a/harness/tests/judges/test_detail_anchors.py
+++ b/harness/tests/judges/test_detail_anchors.py
@@ -34,7 +34,7 @@ def test_physical_plausibility_caps_are_untouched() -> None:
assert defects["wrong_object"].cap == 0.25
[email protected]("rubric", ["static_object_v1", "articulated_v1"])
[email protected]("rubric", ["static_object_v1", "articulated_v1", "scene_v2"])
def test_acceptance_cap_is_graded_with_the_floor_pinned(rubric: str) -> None:
"""D46 b: the acceptance cap is graded, 0.6 + 0.4·verified/total — the flag and the floor pinned."""
rule = next(c for c in load_rubric(rubric).caps if c.id == "missing_must_acceptance")
diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.py
index 9dcd62f4..96f776df 100644
--- a/harness/tests/judges/test_prompt_builder.py
+++ b/harness/tests/judges/test_prompt_builder.py
@@ -80,10 +80,13 @@ def test_scene_rig_paragraph(judge_input, cache_dir):
from codeverse3d.contracts.common import Language, Track
judge_input.spec = judge_input.spec.model_copy(update={"track": Track.SCENE, "language": Language.SCENE_THREEJS})
judge_input.renders.console_errors = ["ReferenceError: foo"]
- _, msgs = build_judge_messages(judge_input, load_rubric("scene_v1"), cache_dir=cache_dir)
+ _, msgs = build_judge_messages(judge_input, load_rubric("scene_v2"), cache_dir=cache_dir)
text = _parts(msgs)[0].text
assert "overview_*" in text and "console error" in text
- assert len(_images(msgs)) == 2 # montage + centre crop only (no ground band for scenes)
+ # scene_v2: the rig paragraph says what the overview tiles hide and what a CONTACT CROP is
+ assert "room ceilings lifted" in text and "CONTACT CROP images are diagnostic close-ups" in text
+ assert "must name its view and its asset" in text
+ assert len(_images(msgs)) == 2 # montage + centre crop only: no placement finding, no contact crop
def test_view_az_el_geometry():
diff --git a/harness/tests/judges/test_scene_judge.py b/harness/tests/judges/test_scene_judge.py
new file mode 100644
index 00000000..49ef5259
--- /dev/null
+++ b/harness/tests/judges/test_scene_judge.py
@@ -0,0 +1,427 @@
+"""scene_v2 (2026-10-14): what the scene judge is shown — the gate facts in the scene branch, the
+MEASURED PLACEMENT line, the contact crops cut around measured placement findings, and the rubric's
+own numbers. The object branch of every helper is pinned byte-identical in test_prompt_builder."""
+
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse3d.config import Placement
+from codeverse3d.contracts.artifacts import GateFinding, GateReport, RenderSet, RenderView, Severity
+from codeverse3d.contracts.chat import ImagePart
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.judges.base import JudgeInput
+from codeverse3d.judges.prompt_builder import (
+ CONTACT_CROP_MIN_FRAC,
+ RIG_RULES,
+ build_judge_messages,
+ gates_section,
+ judge_prompt_hash,
+ placement_block,
+ placement_findings_for_crops,
+ plan_contact_crops,
+ plan_detail_crops,
+ plan_montages,
+ project_box,
+ view_rig_section,
+)
+from codeverse3d.judges.rubrics import load_rubric, measured_absent
+from codeverse3d.spatial.scene_placement import placement_findings
+from tests.judges.conftest import draw_chair, make_spec
+
+E, W, INFO = Severity.ERROR, Severity.WARN, Severity.INFO
+G = "scene_placement"
+S = load_rubric("scene_v2")
+
+
+# --------------------------------------------------------------------------- fixtures
+def _f(sev: Severity, kind: str, target: str, msg: str, **data) -> GateFinding:
+ return GateFinding(gate=G, severity=sev, target=target, message=msg, data={"kind": kind, **data})
+
+
+def _summary(**over) -> GateFinding:
+ data = {"kind": "summary", "counts": {"floating": 1, "sunken": 0, "unsupported": 1, "interpenetration": 1},
+ "checked": 12, "total": 15, "exempt": {"free": 1, "backdrop": 2}, "truncated": False}
+ data.update(over)
+ return GateFinding(gate=G, severity=INFO, target="scene", message="12 assets checked (15 placed, 3 exempt)", data=data)
+
+
+def _box(center, size) -> dict:
+ return {"center": list(center), "size": list(size)}
+
+
+LANTERN = _f(E, "floating", "Pondside/Lantern", "Pondside/Lantern is floating 0.12 m above Ground (touches nothing)",
+ gap_m=0.12, zone="Pondside", bbox=_box((2.0, 0.6, -1.0), (0.4, 1.2, 0.4)))
+CRATE = _f(W, "unsupported", "Quay/Crate", "Quay/Crate is unsupported: hovers 0.04 m above Ground", gap_m=0.04, zone="Quay",
+ bbox=_box((-3.0, 0.5, 2.0), (1.0, 1.0, 1.0)))
+BENCH = _f(W, "interpenetration", "Quay/Bench", "interpenetration: Quay/Bench and Quay/Wall overlap (15% of the smaller box)",
+ overlap=0.15, inside_frac=0.1, other="Quay/Wall", zone="Quay", bbox=_box((1.0, 0.4, 3.0), (1.8, 0.8, 0.6)))
+NO_FOG = _f(E, "no_fog", "env", "scene.fog is not set — frames read as thin_atmosphere")
+NO_BOX = _f(E, "floating", "Quay/Ghost", "Quay/Ghost is floating 0.30 m above Ground", gap_m=0.30)
+
+
+def _placement(*findings: GateFinding, passed: bool | None = None, summary: GateFinding | None = None) -> GateReport:
+ rows = [summary or _summary(), *findings]
+ return GateReport(gate=G, passed=not any(f.severity == E for f in rows) if passed is None else passed, findings=rows)
+
+
+def _frames(*findings: GateFinding) -> GateReport:
+ return GateReport.of("scene_frames", findings)
+
+
+def _frame(sev: Severity, kind: str, view: str, msg: str) -> GateFinding:
+ return GateFinding(gate="scene_frames", severity=sev, target=view, message=msg, data={"kind": kind, "view": view})
+
+
+LINT = GateReport(gate="lint:scene_threejs", passed=True, findings=[
+ GateFinding(gate="lint:scene_threejs", severity=W, target="src/zones/quay.js", message="unused import", data={"kind": "layout"})])
+
+
+def _cam(name: str, position, look_at, *, fov: float = 50.0, time_s: float = 0.0, path: str = "/x.png", wh=(1024, 576)) -> RenderView:
+ return RenderView(name=name, path=path, width=wh[0], height=wh[1], camera_position=position, look_at=look_at, fov=fov, time_s=time_s)
+
+
+#: a rig around a 12 m scene: the three high overviews and the ground-level contact camera
+def _rig(root: Path | None = None, *, time_s: float = 0.0) -> list[RenderView]:
+ def path(name: str) -> str:
+ if root is None:
+ return f"/x/{name}.png"
+ return str(draw_chair(root / f"{name}_t{time_s:g}.png"))
+
+ return [
+ _cam("overview_front_right", (9.0, 9.0, 11.0), (0.0, 0.5, 0.0), path=path("overview_front_right"), time_s=time_s),
+ _cam("overview_back_left", (-9.0, 9.0, -11.0), (0.0, 0.5, 0.0), path=path("overview_back_left"), time_s=time_s),
+ _cam("overview_top", (0.0, 30.0, 0.5), (0.0, 0.0, 0.0), path=path("overview_top"), time_s=time_s),
+ _cam("overview_low_front", (5.0, 0.4, 14.0), (2.0, 0.0, 6.0), path=path("overview_low_front"), time_s=time_s),
+ ]
+
+
+# --------------------------------------------------------------------------- the gates section
+def test_scene_gates_section_lists_placement_first_then_frames_then_the_rest_and_groups_warns():
+ gates = [LINT, _placement(LANTERN, CRATE, BENCH, NO_FOG), _frames(_frame(E, "dark_frame", "Establishing", "frame too dark: mean luminance 0.07"),
+ _frame(W, "content_small", "overview_top", "overview rig sees sparse content"))]
+ text = gates_section(gates, scene=True)
+ lines = text.splitlines()
+ assert lines[0] == "GATE FINDINGS (deterministic; treat as facts): scene_placement=FAIL, scene_frames=FAIL, lint:scene_threejs=pass"
+ assert lines[1] == "errors (3):"
+ assert lines[2] == "- scene_placement [Pondside/Lantern]: Pondside/Lantern is floating 0.12 m above Ground (touches nothing)"
+ assert lines[3] == "- scene_placement [env]: scene.fog is not set — frames read as thin_atmosphere"
+ assert lines[4] == "- scene_frames [Establishing]: frame too dark: mean luminance 0.07"
+ assert lines[5].startswith("MEASURED PLACEMENT (scene_placement gate")
+ assert ("12 assets checked of 15 placed, 3 exempt (1 tagged free): 1 floating (worst 0.12 m), 0 sunken, "
+ "1 unsupported (worst 0.04 m), 1 interpenetrating (worst 15% of the smaller box).") in lines[5]
+ assert "PLACEMENT PASSED" not in text
+ # the WARNs: grouped by (gate, kind), placement before frames before lint
+ assert lines[6] == "warnings (4), grouped by kind:"
+ assert lines[7] == "- scene_placement/unsupported ×1: [Quay/Crate] Quay/Crate is unsupported: hovers 0.04 m above Ground"
+ assert lines[8].startswith("- scene_placement/interpenetration ×1: [Quay/Bench] interpenetration: Quay/Bench and Quay/Wall overlap")
+ assert lines[9] == "- scene_frames/content_small ×1: [overview_top] overview rig sees sparse content"
+ assert lines[10] == "- lint:scene_threejs/layout ×1: [src/zones/quay.js] unused import"
+ assert len(lines) == 11
+ # the object branch is untouched by the flag (its byte-identity is pinned in test_prompt_builder)
+ obj = gates_section(gates)
+ assert "MEASURED PLACEMENT" not in obj and obj.startswith("GATE FINDINGS (deterministic; treat as facts): lint:scene_threejs=pass, scene_placement=FAIL")
+ assert gates_section([], scene=True) == "GATE FINDINGS: (no gates run)"
+
+
+def test_scene_gates_section_clean_round_states_placement_passed():
+ summary = _summary(counts={"floating": 0, "sunken": 0, "unsupported": 0, "interpenetration": 0}, exempt={},
+ thresholds={"contact_m": 0.02, "floating_m": 0.05, "floating_error_m": 0.08, "overlap_warn": 0.1})
+ text = gates_section([_placement(summary=summary), _frames(), LINT.model_copy(update={"findings": []})], scene=True)
+ assert "no errors or warnings — every checked asset is seated, the frames are exposed and the contracts hold." in text
+ block = placement_block([_placement(summary=summary)])
+ assert "12 assets checked of 15 placed, 0 exempt (0 tagged free): 0 floating, 0 sunken, 0 unsupported, 0 interpenetrating." in block
+ assert "Thresholds: contact_m 0.02, floating_error_m 0.08, floating_m 0.05, overlap_warn 0.1." in block
+ assert "PLACEMENT PASSED: no checked asset floats, sinks or overlaps another beyond the thresholds." in block
+ assert "mark floating_asset / sunken_asset / interpenetration present only where a render VISIBLY shows it" in block
+ # a WARN of a placement kind on a passed report: measured, named, no PASSED sentence
+ hover = placement_block([_placement(CRATE, summary=summary)])
+ assert "1 unsupported (worst 0.04 m)" in hover and "PLACEMENT PASSED" not in hover
+ # no gate / a probe that failed: nothing measured, nothing claimed
+ assert placement_block([_frames()]) == ""
+ failed = GateReport(gate=G, passed=True, findings=[_f(W, "probe_failed", "scene", "placement probe failed: boom")])
+ assert placement_block([failed]) == "" and "probe_failed" in gates_section([failed], scene=True)
+
+
+def test_placement_block_names_a_free_exempt_share_and_a_cantilevered_row():
+ free = _f(E, "free_exempt", "scene", "6 of 10 placed assets are tagged placement='free'")
+ cant = _f(W, "cantilevered", "Quay/Jetty", "Quay/Jetty rests on 1 of 6 columns", gap_max_m=0.31, columns_resting=1)
+ block = placement_block([_placement(free, cant)])
+ assert "The share of assets tagged placement='free' is over the line" in block
+ assert "1 cantilevered (worst 0.31 m)" in block and "PLACEMENT PASSED" not in block
+
+
+# --------------------------------------------------------------------------- projection
+def test_project_box_through_a_pinhole_camera():
+ """A camera at z=10 looking at the origin with a 90° vertical fov and a square frame: the
+ origin lands mid-frame, a 2 m box at the origin spans 10 % of the frame (±1 m over a ±10 m
+ half-frame at that depth) each way."""
+ cam = _cam("c", (0.0, 0.0, 10.0), (0.0, 0.0, 0.0), fov=90.0, wh=(512, 512))
+ assert project_box(cam, (0.0, 0.0, 0.0), (2.0, 2.0, 0.0)) == pytest.approx((0.45, 0.45, 0.55, 0.55))
+ # +X is screen-right (u grows), +Y is screen-up (v shrinks)
+ left, top, right, bottom = project_box(cam, (5.0, 5.0, 0.0), (0.0, 0.0, 0.0))
+ assert left == right == pytest.approx(0.75) and top == bottom == pytest.approx(0.25)
+ # behind the lens, outside the frame, or an unknown camera: no projection
+ assert project_box(cam, (0.0, 0.0, 20.0), (1.0, 1.0, 1.0)) is None
+ assert project_box(cam, (30.0, 0.0, 0.0), (1.0, 1.0, 1.0)) is None
+ assert project_box(RenderView(name="x", path="/x.png"), (0.0, 0.0, 0.0), (1.0, 1.0, 1.0)) is None
+ # a 16:9 frame halves the horizontal fraction of the same box; the rig's 50° is the fov fallback
+ wide = _cam("w", (0.0, 0.0, 10.0), (0.0, 0.0, 0.0), fov=90.0, wh=(1024, 576))
+ l2, _, r2, _ = project_box(wide, (0.0, 0.0, 0.0), (2.0, 2.0, 0.0))
+ assert (r2 - l2) == pytest.approx(0.1 * 9 / 16)
+ nofov = RenderView(name="n", path="/x.png", camera_position=(0.0, 0.0, 10.0), look_at=(0.0, 0.0, 0.0))
+ half = math.tan(math.radians(25.0)) * 10.0
+ assert project_box(nofov, (0.0, 0.0, 0.0), (2 * half, 2 * half, 0.0)) == pytest.approx((0.5 - 0.5 * 9 / 16, 0.0, 0.5 + 0.5 * 9 / 16, 1.0))
+ # a vertical (top-down) camera rolls like THREE's lookAt: −Z is screen-up
+ top = _cam("t", (0.0, 10.0, 0.0), (0.0, 0.0, 0.0), fov=90.0, wh=(512, 512))
+ _, t_top, _, b_top = project_box(top, (0.0, 0.0, -5.0), (0.0, 0.0, 0.0))
+ assert t_top == b_top == pytest.approx(0.25)
+
+
+# --------------------------------------------------------------------------- contact crops
+def test_contact_crops_are_cut_from_the_tile_that_shows_the_asset_largest_error_first():
+ gates = [_placement(CRATE, BENCH, LANTERN, NO_BOX, NO_FOG)]
+ # order: ERROR first, then the larger magnitude; one per asset; only findings with a box
+ assert [f.target for f in placement_findings_for_crops(gates)] == ["Pondside/Lantern", "Quay/Bench", "Quay/Crate"]
+ crops = plan_contact_crops(_rig(), gates)
+ assert [m.title for m in crops] == ["CONTACT CROP — Pondside/Lantern (gate: floating 0.12 m)",
+ "CONTACT CROP — Quay/Bench (gate: interpenetration 15%)",
+ "CONTACT CROP — Quay/Crate (gate: unsupported 0.04 m)"]
+ assert all(m.is_detail and m.crop is not None and len(m.tiles) == 1 for m in crops)
+ # the lantern projects 0.087 of the frame tall in the contact tile and 0.088 in overview_front_right:
+ # the contact tile's 1.5× weight (it exists for this) decides
+ assert crops[0].tiles[0].name == "overview_low_front"
+ assert "cut from overview_low_front" in crops[0].hint and "judge the CONTACT" in crops[0].hint
+ for m in crops:
+ x0, y0, x1, y1 = m.crop
+ assert 0.0 <= x0 < x1 <= 1.0 and 0.0 <= y0 < y1 <= 1.0
+ assert x1 - x0 >= CONTACT_CROP_MIN_FRAC - 1e-6 and y1 - y0 >= CONTACT_CROP_MIN_FRAC - 1e-6
+ # the crop window holds the projected box centre
+ view, (cx, cy, cz), size = crops[0].tiles[0], LANTERN.data["bbox"]["center"], LANTERN.data["bbox"]["size"]
+ left, top, right, bottom = project_box(view, (cx, cy, cz), size)
+ x0, y0, x1, y1 = crops[0].crop
+ assert x0 <= (left + right) / 2 <= x1 and y0 <= (top + bottom) / 2 <= y1
+
+
+def test_contact_crops_prefer_a_low_tile_over_the_top_down_one_and_skip_what_no_tile_sees():
+ # only the top-down tile and one high overview: the high one wins even when the top projects larger
+ rig = [_rig()[2], _rig()[0]]
+ crops = plan_contact_crops(rig, [_placement(LANTERN)])
+ assert len(crops) == 1 and crops[0].tiles[0].name == "overview_front_right"
+ # the two high overviews alone: the larger projection wins (back_left is farther from the lantern)
+ assert plan_contact_crops([_rig()[1], _rig()[0]], [_placement(LANTERN)])[0].tiles[0].name == "overview_front_right"
+ # an asset behind every camera / outside every frame: no crop, no error
+ far = _f(E, "floating", "Far/Rock", "floating", gap_m=0.5, bbox=_box((400.0, 0.0, 400.0), (1.0, 1.0, 1.0)))
+ assert plan_contact_crops(_rig(), [_placement(far)]) == []
+ # no overview tile with a camera (a legacy record), or no rig at all: nothing
+ legacy = [RenderView(name="overview_front_right", path="/x.png"), RenderView(name="Establishing", path="/y.png")]
+ assert plan_contact_crops(legacy, [_placement(LANTERN)]) == []
+ assert plan_contact_crops([RenderView(name="Establishing", path="/y.png")], [_placement(LANTERN)]) == []
+ # the eye rig never reaches the judge, so it is never a crop source
+ eye = [_cam("eye_front", (0.0, 1.6, 14.0), (0.0, 0.5, 0.0))]
+ assert plan_contact_crops(eye, [_placement(LANTERN)]) == []
+ # a box that fills the tile needs no crop from that tile
+ huge = _f(E, "floating", "Big/Hall", "floating", gap_m=0.2, bbox=_box((0.0, 3.0, 0.0), (20.0, 6.0, 20.0)))
+ assert plan_contact_crops(_rig(), [_placement(huge)]) == []
+ # the later time's tiles are not crop sources: crops cite the t=0 tile
+ both = [*_rig(time_s=1.5), *_rig(time_s=0.0)]
+ assert all(m.tiles[0].time_s == 0.0 for m in plan_contact_crops(both, [_placement(LANTERN)]))
+
+
+def test_plan_detail_crops_scene_is_centre_plus_contact_crops_under_the_dial(tmp_path):
+ shaded = [_cam("Establishing", (6.0, 2.0, 12.0), (0.0, 1.0, 0.0)), *_rig()]
+ gates = [_placement(LANTERN, BENCH, CRATE)]
+ three = plan_detail_crops(shaded, scene=True, gates=gates, limit=2)
+ assert [m.title.split(" — ")[0] for m in three] == ["DETAIL CROP", "CONTACT CROP", "CONTACT CROP"]
+ assert three[0].tiles[0].name == "Establishing" and three[0].crop == (0.25, 0.25, 0.75, 0.75)
+ assert len(plan_detail_crops(shaded, scene=True, gates=gates, limit=5)) == 4 # centre + all three
+ assert len(plan_detail_crops(shaded, scene=True, gates=gates, limit=1)) == 2
+ assert plan_detail_crops(shaded, scene=True, gates=gates, limit=0) == [] # the dial at 0: no crop at all
+ assert [m.title for m in plan_detail_crops(shaded, scene=True, limit=2)] == ["DETAIL CROP — centre of Establishing at 2×"]
+ # the object branch: centre + ground band, cut to the limit, never a contact crop
+ obj = [RenderView(name=n, path="/x.png") for n in ("front_right_high", "front_right_low")]
+ assert [m.title.split(" — ")[1][:6] for m in plan_detail_crops(obj, scene=False, gates=gates, limit=2)] == ["centre", "ground"]
+ assert len(plan_detail_crops(obj, scene=False, limit=1)) == 1 and plan_detail_crops(obj, scene=False, limit=0) == []
+ # through plan_montages: the grids, then the crops (the pairwise judge's detail_crops=0 sends none)
+ ms = plan_montages(RenderSet(views=shaded), scene=True, gates=gates, detail_crops=2)
+ assert [m.kind for m in ms] == ["shaded", "shaded", "detail", "detail", "detail"]
+ assert all(not m.is_detail for m in plan_montages(RenderSet(views=shaded), scene=True, gates=gates, detail_crops=0))
+
+
+def test_a_scene_verdict_sends_the_contact_crops_after_the_centre_crop(tmp_path, cache_dir):
+ rig = _rig(tmp_path)
+ authored = _cam("Establishing", (6.0, 2.0, 12.0), (0.0, 1.0, 0.0), path=str(draw_chair(tmp_path / "est.png")))
+ spec = make_spec(track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a quay at dusk")
+ inp = JudgeInput(spec=spec, renders=RenderSet(views=[authored, *rig]), gates=[_placement(LANTERN, CRATE, NO_FOG), _frames()],
+ plan_summary="Zones: Quay, Pondside. Assets: Lantern, Crate.")
+ _, msgs = build_judge_messages(inp, S, cache_dir=cache_dir)
+ images = [p for p in msgs[0].parts if isinstance(p, ImagePart)]
+ labels = [p.label for p in images]
+ assert len(images) == 2 + 1 + 2 # two grids (5 views) + the centre crop + two contact crops
+ assert labels[2].startswith("DETAIL CROP — centre of Establishing at 2× [1/3]")
+ assert labels[3].startswith("CONTACT CROP — Pondside/Lantern (gate: floating 0.12 m) [2/3] — diagnostic close-up cut from overview_low_front")
+ assert labels[4].startswith("CONTACT CROP — Quay/Crate (gate: unsupported 0.04 m) [3/3]")
+ with Image.open(images[3].path) as im:
+ assert max(im.size) <= 768 and min(im.size) > 100
+ text = msgs[0].parts[0].text
+ assert "MEASURED PLACEMENT (scene_placement gate" in text and "1 floating (worst 0.12 m)" in text
+ assert "- detail crop 2: CONTACT CROP — Pondside/Lantern (gate: floating 0.12 m)" in text
+ assert "plus 3 DETAIL CROP(s)" in text and RIG_RULES["scene_contact"] in text
+ assert text.index("scene_placement=FAIL") < text.index("scene_frames=pass")
+ # an object verdict never gets the scene text
+ obj = JudgeInput(spec=make_spec(), renders=RenderSet(views=[authored]), gates=[_placement(LANTERN)])
+ _, omsgs = build_judge_messages(obj, load_rubric("static_object_v1"), cache_dir=cache_dir)
+ otext = omsgs[0].parts[0].text
+ assert "MEASURED PLACEMENT" not in otext and "CONTACT CROP" not in otext and RIG_RULES["object"] in otext
+
+
+def test_view_rig_counts_contact_crops_as_detail_crops():
+ rs = RenderSet(views=_rig())
+ montages = plan_montages(rs, scene=True, gates=[_placement(LANTERN)], detail_crops=2)
+ text = view_rig_section(rs, montages, scene=True)
+ assert text.startswith("VIEW RIG: 1 MONTAGE image(s) follow plus 2 DETAIL CROP(s).")
+ assert "- detail crop 2: CONTACT CROP — Pondside/Lantern (gate: floating 0.12 m)" in text
+
+
+# --------------------------------------------------------------------------- the rubric
+def test_scene_v2_numbers_are_pinned():
+ """What moved from v1 (eval/docs/EVAL.md §6, 2026-10-14) — and what stayed."""
+ caps = {c.id: c for c in S.caps}
+ assert S.version == 2 and S.pass_threshold == 0.70
+ assert {k: (c.cap, tuple(c.kinds), tuple(c.measures), c.veto_warn_keys) for k, c in caps.items() if c.gate == G} == {
+ "floating_asset": (0.60, ("floating", "unsupported"), ("floating_asset",), {"gap_m": 0.02}),
+ "sunken_asset": (0.65, ("sunken",), ("sunken_asset",), {"sunk_m": 0.10}),
+ "interpenetration": (0.70, ("interpenetration",), ("interpenetration",), {"overlap": 0.20}),
+ "wrong_scale": (0.75, ("scale",), ("wrong_scale",), {"factor": 0.0}),
+ "free_exempt": (0.75, ("free_exempt",), ("free_exempt",), {}),
+ }
+ # the veto lines are the gate's own tolerances (config.Placement), not numbers of their own: gap_m is
+ # the INDOOR tolerance — the outdoor 0.05 (until 2026-10-15) let a 2-5 cm indoor hover the gate had
+ # flagged be vetoed — and no larger than contact_m, so every floating / unsupported WARN the gate raises
+ # (gap > contact_m) reaches it; sunk_m is where a sunken WARN starts; the overlap line sits inside the
+ # WARN band on purpose (a 10 % box overlap is not yet a visible intersection)
+ p = Placement()
+ assert caps["floating_asset"].veto_warn_keys["gap_m"] == p.floating_indoor_m <= p.contact_m
+ assert caps["sunken_asset"].veto_warn_keys["sunk_m"] == p.sunk_m
+ assert p.overlap_warn < caps["interpenetration"].veto_warn_keys["overlap"] < p.overlap_error
+ assert "floating_part" not in caps and "floating_or_sunken_asset" not in caps
+ assert caps["camera_in_geometry"].kinds == ["camera_in_geometry", "camera_underground", "camera_blocked"]
+ assert caps["missing_must_acceptance"].graded and caps["missing_must_acceptance"].cap == 0.6
+ assert {k: caps[k].cap for k in ("build_error", "shader_error", "console_error", "dark_frame", "blown_frame", "flat_frame", "content_small")} == {
+ "build_error": 0.0, "shader_error": 0.5, "console_error": 0.6, "dark_frame": 0.55, "blown_frame": 0.6, "flat_frame": 0.65, "content_small": 0.6}
+ defects = {d.id: (d.penalty, d.cap) for d in S.defects}
+ assert "floating_or_sunken_asset" not in defects
+ assert {k: defects[k] for k in ("floating_asset", "sunken_asset", "interpenetration", "wrong_scale", "hard_edged_particles",
+ "missing_planned_element", "hero_misplaced")} == {
+ "floating_asset": (0.10, 0.60), "sunken_asset": (0.08, 0.65), "interpenetration": (0.08, 0.70), "wrong_scale": (0.06, 0.75),
+ "hard_edged_particles": (0.04, None), "missing_planned_element": (0.06, None), "hero_misplaced": (0.06, None)}
+ # six anchors on every criterion; the weights are v1's
+ for c in S.criteria:
+ assert sorted(c.anchors, key=float) == ["0.1", "0.4", "0.55", "0.7", "0.85", "1.0"], c.id
+ assert {c.id: c.weight for c in S.criteria} == {c.id: c.weight for c in load_rubric("scene_v1").criteria}
+ notes = S.extra_instructions
+ for phrase in ("CALIBRATION", "at most 0.35", "around 0.55", "0.80 or more", "at least 0.3 apart", "room ceilings lifted",
+ "CONTACT CROP images are diagnostic close-ups", "must name the VIEW"):
+ assert phrase in notes, phrase
+ # the object rubrics did not move: no veto_warn_keys, the same content hash as their YAML
+ for name in ("static_object_v1", "articulated_v1", "reference_v1"):
+ assert all(not c.veto_warn_keys for c in load_rubric(name).caps), name
+ assert judge_prompt_hash(S) != judge_prompt_hash(load_rubric("scene_v1"))
+
+
+# --------------------------------------------------------------------------- the real gate → the judge
+def _row(name: str, zone: str, lo: tuple[float, float, float], hi: tuple[float, float, float], **fields: object) -> dict:
+ """One census placement row as host_placement.mjs writes it (spatial.scene_placement.AssetRow): the
+ box is min / max in the GLB frame — the gate turns it into the center / size the contact crops read."""
+ return {"name": name, "zone": zone, "bbox": {"min": list(lo), "max": list(hi)}, "columns": 1, **fields}
+
+
+#: an outdoor quay for the REAL gate: a lantern 12 cm up (floating ERROR), a crate 4 cm up (unsupported
+#: WARN — past contact_m, within the outdoor tolerance), a bench overlapping the wall by 15 %
+#: (interpenetration WARN) and two of six placed things tagged free (a free_exempt WARN at 33 %)
+QUAY = {
+ "assets": [
+ _row("Lantern", "Pondside", (1.8, 0.12, -1.2), (2.2, 1.32, -0.8), ground_gap_m=0.12, support="ground_y"),
+ _row("Crate", "Quay", (-3.5, 0.04, 1.5), (-2.5, 1.04, 2.5), ground_gap_m=0.04, support="ground_y"),
+ _row("Bench", "Quay", (0.1, 0.0, 2.7), (1.9, 0.8, 3.3), ground_gap_m=0.0, support="ground_y"),
+ _row("Wall", "Quay", (0.0, 0.0, 3.2), (6.0, 1.2, 3.5), ground_gap_m=0.0, support="ground_y"),
+ _row("Gull", "Pondside", (3.0, 2.0, 0.0), (3.3, 2.2, 0.3), exempt="free"),
+ _row("Bunting", "Quay", (-2.0, 2.5, 0.0), (2.0, 2.6, 0.2), exempt="free"),
+ ],
+ "interpenetrations": [{"a": "Bench", "b": "Wall", "zone_a": "Quay", "zone_b": "Quay", "aabb_overlap": 0.15, "inside_frac": 0.1}],
+ "total": 6, "checked": 4, "exempt": {"free": 2}, "ground_y": 0.0,
+}
+
+
+def test_the_real_placement_report_reaches_the_judge_as_counts_and_contact_crops(tmp_path, cache_dir):
+ """The one test that feeds a report the REAL gate wrote (spatial.scene_placement.placement_findings),
+ not this file's hand-written fakes, into placement_block / plan_contact_crops / build_judge_messages:
+ the summary's counts / checked / total / exempt / thresholds and every finding's bbox / gap_m /
+ overlap are bare string keys on both sides, and a rename on either would leave both suites green
+ while the judge saw 0 floating and no crop (review 2026-10-15)."""
+ rep = placement_findings(QUAY, indoor=False, thresholds=Placement())
+ assert rep.gate == G and not rep.passed
+ assert {(f.severity, f.data["kind"], f.target) for f in rep.findings} == {
+ (INFO, "summary", "scene"), (E, "floating", "Pondside/Lantern"), (W, "unsupported", "Quay/Crate"),
+ (W, "interpenetration", "Quay/Bench"), (W, "free_exempt", "scene")}
+ # the measured block: the gate's own counts (every ASSET_KIND — cantilevered too, which the fakes above
+ # omit), the worst magnitudes, the free share and the thresholds it recorded; no PASSED sentence
+ block = placement_block([rep])
+ assert ("4 assets checked of 6 placed, 2 exempt (2 tagged free): 1 floating (worst 0.12 m), 0 sunken, "
+ "1 unsupported (worst 0.04 m), 1 interpenetrating (worst 15% of the smaller box), 0 cantilevered.") in block
+ assert "The share of assets tagged placement='free' is over the line" in block
+ assert "contact_m 0.02" in block and "floating_m 0.05" in block and "floating_error_m 0.08" in block
+ assert "PLACEMENT PASSED" not in block
+ # one contact crop per finding that carries a box (ERROR first, then the larger magnitude), each cut from
+ # the ground-level overview around the centre of the box the gate derived from the row's min / max
+ crops = plan_contact_crops(_rig(), [rep])
+ assert [m.title for m in crops] == ["CONTACT CROP — Pondside/Lantern (gate: floating 0.12 m)",
+ "CONTACT CROP — Quay/Bench (gate: interpenetration 15%)",
+ "CONTACT CROP — Quay/Crate (gate: unsupported 0.04 m)"]
+ assert [m.tiles[0].name for m in crops] == ["overview_low_front"] * 3
+ boxes = [((2.0, 0.72, -1.0), (0.4, 1.2, 0.4)), ((1.0, 0.4, 3.0), (1.8, 0.8, 0.6)), ((-3.0, 0.54, 2.0), (1.0, 1.0, 1.0))]
+ for m, (center, size) in zip(crops, boxes, strict=True):
+ left, top, right, bottom = project_box(m.tiles[0], center, size)
+ x0, y0, x1, y1 = m.crop
+ assert x0 <= (left + right) / 2 <= x1 and y0 <= (top + bottom) / 2 <= y1, m.title
+ # the verdict payload: the measured line in the text, the three crops after the centre crop, in that order
+ rig = _rig(tmp_path)
+ authored = _cam("Establishing", (6.0, 2.0, 12.0), (0.0, 1.0, 0.0), path=str(draw_chair(tmp_path / "est.png")))
+ spec = make_spec(track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a quay at dusk")
+ inp = JudgeInput(spec=spec, renders=RenderSet(views=[authored, *rig]), gates=[rep], plan_summary="Zones: Quay, Pondside.")
+ _, msgs = build_judge_messages(inp, S, cache_dir=cache_dir, detail_crops=3)
+ labels = [p.label for p in msgs[0].parts if isinstance(p, ImagePart)]
+ assert len(labels) == 2 + 1 + 3
+ assert labels[3].startswith("CONTACT CROP — Pondside/Lantern (gate: floating 0.12 m) [2/4] — diagnostic close-up cut from overview_low_front")
+ assert labels[4].startswith("CONTACT CROP — Quay/Bench (gate: interpenetration 15%) [3/4] — diagnostic close-up cut from overview_low_front")
+ assert labels[5].startswith("CONTACT CROP — Quay/Crate (gate: unsupported 0.04 m) [4/4] — diagnostic close-up cut from overview_low_front")
+ text = msgs[0].parts[0].text
+ assert "scene_placement=FAIL" in text and "MEASURED PLACEMENT (scene_placement gate" in text
+ assert "1 floating (worst 0.12 m), 0 sunken, 1 unsupported (worst 0.04 m), 1 interpenetrating (worst 15% of the smaller box)" in text
+ assert "plus 4 DETAIL CROP(s)" in text and "- detail crop 4: CONTACT CROP — Quay/Crate (gate: unsupported 0.04 m)" in text
+ # and the arithmetic veto reads the same report: the floating ERROR keeps the claim, nothing sunken was measured
+ assert measured_absent(S, "floating_asset", [rep]) is False and measured_absent(S, "sunken_asset", [rep]) is True
+
+
+def test_a_hover_the_real_gate_warned_about_is_never_vetoed_indoors_or_out():
+ """Review 2026-10-15 (findings 4 / 17): the veto line was the OUTDOOR tolerance (0.05 m), so an interior's
+ floating WARN of 2-5 cm — raised against floating_indoor_m 0.02 — read as 'clean' and switched off the
+ judge's floating_asset tick although the gate itself had flagged the asset. The line is the indoor
+ tolerance now: whatever floating / unsupported WARN the real gate raises keeps the tick, and a seated
+ report (the gap within contact_m: no finding) still vetoes."""
+ def report(gap: float, *, indoor: bool) -> GateReport:
+ vase = _row("Vase", "Dining", (-0.05, gap, -0.05), (0.05, gap + 0.3, 0.05), ground_gap_m=gap, support="Table")
+ return placement_findings({"assets": [vase], "total": 1, "checked": 1, "ground_y": 0.0}, indoor=indoor,
+ thresholds=Placement())
+
+ for gap, indoor, kind in ((0.03, True, "floating"), (0.04, False, "unsupported"), (0.06, False, "floating")):
+ rep = report(gap, indoor=indoor)
+ assert rep.passed and [(f.data["kind"], f.data["gap_m"]) for f in rep.findings if f.severity == W] == [(kind, gap)]
+ assert measured_absent(S, "floating_asset", [rep]) is False, (gap, indoor)
+ seated = report(0.01, indoor=True)
+ assert seated.passed and [f.severity for f in seated.findings] == [INFO]
+ assert measured_absent(S, "floating_asset", [seated]) is True
diff --git a/harness/tests/judges/test_vlm_judge.py b/harness/tests/judges/test_vlm_judge.py
index 20e289e0..3f58c33e 100644
--- a/harness/tests/judges/test_vlm_judge.py
+++ b/harness/tests/judges/test_vlm_judge.py
@@ -168,22 +168,55 @@ def test_a_sample_stops_when_its_budget_is_spent(judge_input, cache_dir, monkeyp
j = _judge(model, cache_dir=cache_dir).judge(judge_input)
assert j.passed and [r.max_wait_s for r in model.requests] == [SAMPLE_BUDGET_S, SAMPLE_MIN_WAIT_S]
-def test_scene_and_graphics_keep_the_pre_d47_montage_ceiling():
- """D47's 5 montages were measured on the object rig only; the other tracks keep 3."""
+def test_per_track_montage_ceilings():
+ """D47's 5 montages were measured on the object rig only: graphics keeps 3; the scene rig
+ takes 4 since scene_v2 (the fourth overview is the contact camera the crops are cut from)."""
from codeverse3d.contracts.artifacts import RenderSet
from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.spec import Spec
from codeverse3d.judges.base import JudgeInput
- from codeverse3d.judges.vlm_judge import VlmJudge
+ from codeverse3d.judges.vlm_judge import TRACK_MONTAGE_CAP, VlmJudge
def inp(track, language):
spec = Spec(id="t", track=track, language=language, prompt="p")
return JudgeInput(spec=spec, renders=RenderSet(), gates=[], acceptance=[])
- j = VlmJudge("scene_v1", model_id="fake:fake-1")
- assert j._montages_for(inp(Track.SCENE, Language.SCENE_THREEJS)) == 3
+ assert TRACK_MONTAGE_CAP == {"scene": 4, "graphics": 3}
+ j = VlmJudge("scene_v2", model_id="fake:fake-1")
+ assert j._montages_for(inp(Track.SCENE, Language.SCENE_THREEJS)) == 4
+ assert j._montages_for(inp(Track.SCENE, Language.SCENE_BLENDER)) == 4
assert j._montages_for(inp(Track.GRAPHICS, Language.GLSL_SHADER)) == 3
jo = VlmJudge("static_object_v1", model_id="fake:fake-1")
assert jo._montages_for(inp(Track.STATIC_OBJECT, Language.BLENDER)) == 5
- explicit = VlmJudge("scene_v1", model_id="fake:fake-1", max_montages=5)
+ explicit = VlmJudge("scene_v2", model_id="fake:fake-1", max_montages=5)
assert explicit._montages_for(inp(Track.SCENE, Language.SCENE_THREEJS)) == 5
+
+
+# ----------------------------------------------------------------------------- thinking (D105)
+def test_judge_thinking_comes_from_the_settings_unless_stated(monkeypatch):
+ """``VlmJudge(thinking=None)`` reads ``Settings.judge.thinking`` (C3D_JUDGE__THINKING): the run,
+ `3dcode judge --thinking` and the calibration tool take the level from one place, and the
+ record's sampling snapshot (``BaseTrack.sampling``) carries what was used."""
+ from types import SimpleNamespace
+
+ from codeverse3d.config import Settings, get_settings
+ from codeverse3d.contracts.common import Track
+ from codeverse3d.judges.vlm_judge import VlmJudge
+ from codeverse3d.tracks.lifecycle import BaseTrack
+
+ assert VlmJudge("scene_v2", model_id="fake:fake-1").thinking == Settings().judge.thinking == "low"
+ s = Settings(judge={"thinking": "medium"})
+ monkeypatch.setattr("codeverse3d.judges.vlm_judge.get_settings", lambda: s)
+ j = VlmJudge("scene_v2", model_id="fake:fake-1")
+ assert j.thinking == "medium"
+ assert VlmJudge("scene_v2", model_id="fake:fake-1", thinking="high").thinking == "high" # a stated level wins
+ with pytest.raises(ValueError, match="judge thinking must be one of"):
+ VlmJudge("scene_v2", model_id="fake:fake-1", thinking="max")
+ assert BaseTrack.sampling(SimpleNamespace(track=Track.SCENE), j)["judge"]["thinking"] == "medium"
+ get_settings.cache_clear()
+
+
+def test_the_judge_sends_its_thinking_level(judge_input, cache_dir):
+ model = FakeChatModel([good_reply(R, IDS, 0.8)])
+ _judge(model, cache_dir=cache_dir, thinking="medium").judge(judge_input)
+ assert model.requests[0].thinking == "medium"
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index 7bd69813..3244c2a8 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -27,15 +27,15 @@ from codeverse3d.contracts.artifacts import (
Severity,
)
from codeverse3d.contracts.chat import ChatRequest, ChatResponse
-from codeverse3d.contracts.common import Language, Track, Usage
+from codeverse3d.contracts.common import ENTRY_FILE, TRACK_LANGUAGES, Language, Track, Usage
from codeverse3d.contracts.plan import Plan, ScenePlan
from codeverse3d.contracts.run import RunRecord
from codeverse3d.conventions import to_snake
from codeverse3d.languages import get_runtime
-from codeverse3d.languages.base import SceneRuntime
from codeverse3d.models.base import ModelError
from codeverse3d.tracks.common import Services
from codeverse3d.tracks.planner import plan_example
+from codeverse3d.tracks.scene import ENV_FILES
from codeverse3d.workspace import Workspace
FAIL_MARK = "RAISE_BUILD_ERROR"
@@ -52,13 +52,20 @@ class FakeRuntime:
def __init__(self, language: Language = Language.THREEJS):
self.language = language
- self.entry_globs = ("src/**/*.js",) if language in (Language.THREEJS, Language.SCENE_THREEJS) else ("src/model.py",)
+ if language in (Language.THREEJS, Language.SCENE_THREEJS):
+ self.entry_globs: tuple[str, ...] = ("src/**/*.js",)
+ elif language is Language.SCENE_BLENDER:
+ self.entry_globs = ("src/scene.py", "src/zones/*.py", "src/assets/*.py", "src/env.py")
+ else:
+ self.entry_globs = ("src/model.py",)
self.builds = 0
self.lock = threading.Lock()
layout = get_runtime(language)
self.expected_files, self.files_for = layout.expected_files, layout.files_for
- if isinstance(layout, SceneRuntime):
+ if language in TRACK_LANGUAGES[Track.SCENE]:
self.zone_file, self.asset_file = layout.zone_file, layout.asset_file
+ # the runtime's word, else the track's typed table (tracks/scene.env_file does the same)
+ self.env_file: str = getattr(layout, "env_file", None) or ENV_FILES[language]
def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
out = []
@@ -90,6 +97,28 @@ class FakeRuntime:
f = ws.src / "assets" / f"{to_snake(a.name)}.js"
f.write_text(f"// skeleton asset {a.name}\nexport function build{a.name}(THREE) {{ return null; }}\n")
out.append(f)
+ elif self.language is Language.SCENE_BLENDER:
+ # the bpy layout (languages/scene_blender): harness data at src/scene.py, env, a stub per
+ # zone and per `bpy` module — the same shape the real skeleton leaves
+ f = ws.root / "src" / "scene.py"
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text("# skeleton src/scene.py (harness data)\nZONES = {}\nASSETS = {}\nHEROES = {}\nCAMERAS = []\n")
+ out.append(f)
+ f = ws.src / "env.py"
+ f.write_text("import bpy # skeleton src/env.py\n\n\ndef height_at(x, y):\n return 0.0\n\n\ndef build_env(ctx):\n return {}\n")
+ out.append(f)
+ (ws.src / "zones").mkdir(exist_ok=True)
+ (ws.src / "assets").mkdir(exist_ok=True)
+ for z in getattr(plan, "zones", []) or []:
+ f = ws.src / "zones" / f"{to_snake(z.name)}.py"
+ f.write_text(f"import bpy # skeleton zone {z.name}\n\n\ndef build(ctx):\n return ctx.collection\n")
+ out.append(f)
+ for a in getattr(plan, "assets", []) or []:
+ if a.kind == "bpy":
+ f = ws.src / "assets" / f"{to_snake(a.name)}.py"
+ f.write_text(f"import bpy # skeleton asset {a.name}\n\n\ndef build_{to_snake(a.name)}(ctx, variant=0):\n"
+ " return ctx.collection\n")
+ out.append(f)
else:
f = ws.src / "model.py"
f.write_text("# skeleton model.py\nimport bpy\n")
@@ -281,11 +310,12 @@ def bill_verdict(cost: float, round_index: int) -> Usage:
return usage
-def small_scene() -> ScenePlan:
- """The example scene without its Blender hero (every asset a three.js module — the only kind
- FakeRuntime builds)."""
- plan = ScenePlan.model_validate(plan_example(Track.SCENE))
- plan.assets = [a for a in plan.assets if a.kind == "threejs"]
+def small_scene(language: Language = Language.SCENE_THREEJS) -> ScenePlan:
+ """The example scene without its Blender hero (every asset a module of ``language`` — the only
+ kind FakeRuntime builds: ``threejs`` for scene_threejs, ``bpy`` for scene_blender)."""
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE, language))
+ module_kind = "bpy" if language is Language.SCENE_BLENDER else "threejs"
+ plan.assets = [a for a in plan.assets if a.kind == module_kind]
for z in plan.zones:
z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
return plan
@@ -425,7 +455,12 @@ class FakeServices(Services):
def assemble_scene(self, runtime, ws: Workspace, plan: Plan) -> Any:
if not self.assemble:
raise ServiceUnavailable("no assembler in tests")
- (ws.src / "scene.js").write_text("// assembled by fake\nexport function createScene(){}\n")
+ if runtime.language is Language.SCENE_BLENDER: # the entry of a bpy scene is harness DATA
+ zones = ", ".join(f'"{to_snake(z.name)}": "{z.name}"' for z in plan.zones)
+ (ws.root / ENTRY_FILE[Language.SCENE_BLENDER]).write_text(
+ f"# assembled by fake\nZONES = {{{zones}}}\nASSETS = {{}}\nHEROES = {{}}\nCAMERAS = []\n")
+ else:
+ (ws.src / "scene.js").write_text("// assembled by fake\nexport function createScene(){}\n")
return {"zones": [z.name for z in plan.zones]}
def finalize_record(self, ws: Workspace, record: RunRecord) -> None:
diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.py
index d0a7dc06..42dc5d86 100644
--- a/harness/tests/orchestrator_tracks/test_cost_latency.py
+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py
@@ -142,7 +142,7 @@ def _scene_ctx(tmp_path, settings, *, services, agent=None, plan=None, agent_id=
rt = FakeRuntime(Language.SCENE_THREEJS)
ctx = RunContext(spec=spec, ws=ws, events=EventLog(ws.events_path), settings=settings,
budget=BudgetGuard(spec.budget, soft_fraction=0.55), runtime=rt, services=services,
- state=RunState(), policy=RoundPolicy(), track=Track.SCENE, rubric="scene_v1",
+ state=RunState(), policy=RoundPolicy(), track=Track.SCENE, rubric="scene_v2",
agent_id=agent_id, plan=plan, agent=agent, contract_text="CONTRACT")
rt.skeleton(ws, plan)
ws.commit("skeleton")
diff --git a/harness/tests/orchestrator_tracks/test_likeness_routing.py b/harness/tests/orchestrator_tracks/test_likeness_routing.py
index 14225770..15775142 100644
--- a/harness/tests/orchestrator_tracks/test_likeness_routing.py
+++ b/harness/tests/orchestrator_tracks/test_likeness_routing.py
@@ -48,7 +48,8 @@ def test_make_judge_routes_photos_to_the_likeness_judge_and_a_replay_picks_the_s
from codeverse3d.judges.vlm_judge import LikenessJudge, ReferenceJudge, VlmJudge, judge_for
assert judge_for(Track.GRAPHICS, "shader_v2", references=True) is LikenessJudge
- assert judge_for(Track.SCENE, "scene_v1", references=True) is LikenessJudge
+ assert judge_for(Track.SCENE, "scene_v2", references=True) is LikenessJudge
+ assert judge_for(Track.SCENE, "scene_v1", references=True) is LikenessJudge # a replay of a v1 round
assert judge_for(Track.STATIC_OBJECT, "reference_v1", references=True) is ReferenceJudge
assert judge_for(Track.STATIC_OBJECT, "reference_v1", references=False) is ReferenceJudge # measured criteria
assert judge_for(Track.GRAPHICS, "shader_v2", references=False) is VlmJudge
diff --git a/harness/tests/orchestrator_tracks/test_plan_features.py b/harness/tests/orchestrator_tracks/test_plan_features.py
index 68e3ff25..7b2a1b49 100644
--- a/harness/tests/orchestrator_tracks/test_plan_features.py
+++ b/harness/tests/orchestrator_tracks/test_plan_features.py
@@ -13,10 +13,11 @@ from codeverse3d.tracks.plan_features import (
def test_every_settings_field_is_a_live_switch_and_anything_else_is_dead():
live = [f"C3D_{name.upper()}" for name in Settings.model_fields]
- live += [f"C3D_{section.upper()}__{name.upper()}" for section in ("rate", "render", "limits", "judge")
+ live += [f"C3D_{section.upper()}__{name.upper()}" for section in ("rate", "render", "limits", "judge", "placement")
for name in Settings.model_fields[section].annotation.model_fields]
live += [*Settings.FLAT, *NODE_SIDE_ENV, *GENERATION_SIDE_ENV]
assert dead_env_keys(dict.fromkeys(live, "1")) == []
+ assert {"C3D_VARIANT", "C3D_VARIANTS"} <= set(live), "the variant switches (D105) are Settings fields"
retired = ["C3D_PLAN_FEATURES", "C3D_FEWER_TURNS", "C3D_DETAIL_ROUNDS", "C3D_RATE__STORM_GATE",
"C3D_RATE__TPM_PER_KEY", "C3D_MYSTERY_KNOB"]
assert dead_env_keys({**dict.fromkeys(retired, "1"), "C3D_PLAN_BRIEF": "off"}) == sorted(retired)
@@ -32,3 +33,7 @@ def test_pin_plan_refuses_only_live_switches_not_known_to_act_after_planning():
"C3D_PLAN_BRIEF is not known to act after planning"]
assert pin_plan_blockers({"GEMINI_CLI_HOME": "/x"}) == [
"GEMINI_CLI_HOME is not known to act after planning"]
+ # a variant overlays the planner templates and keys the plan stage (D105): never shared across arms
+ assert pin_plan_blockers({"C3D_VARIANT": "argon"}) == ["C3D_VARIANT is not known to act after planning"]
+ assert pin_plan_blockers({"C3D_VARIANTS": '{"agy:gemini-4-argon": "argon"}'}) == [
+ "C3D_VARIANTS is not known to act after planning"]
diff --git a/harness/tests/orchestrator_tracks/test_tracks.py b/harness/tests/orchestrator_tracks/test_tracks.py
index 41585a84..c8752ba6 100644
--- a/harness/tests/orchestrator_tracks/test_tracks.py
+++ b/harness/tests/orchestrator_tracks/test_tracks.py
@@ -178,3 +178,51 @@ def test_a_render_timeout_degrades_the_round_instead_of_failing_the_run(tmp_path
assert "render failed" in r1.notes
kinds = [e["event"] for e in EventLog(ws.events_path).read()]
assert "render.failed" in kinds and "run.done" in kinds and "run.failed" not in kinds
+
+
+# ----------------------------------------------------------------------------- scene_blender
+def _bpy_scene_writer(job, ws):
+ """The scene_blender twin of ``_scene_writer``: every session writes the ``.py`` files it owns,
+ each defining the function the wrapper calls (``build_env`` / ``build`` / ``build_<snake>``)."""
+ out = {}
+ for rel in job.files_hint:
+ stem = rel.rsplit("/", 1)[-1][:-3]
+ if rel.startswith("src/assets/"):
+ out[rel] = f"import bpy # {job.label}\n\n\ndef build_{stem}(ctx, variant=0):\n return ctx.collection\n"
+ elif rel == "src/env.py":
+ out[rel] = f"import bpy # {job.label}\n\n\ndef height_at(x, y):\n return 0.0\n\n\ndef build_env(ctx):\n return {{}}\n"
+ else:
+ out[rel] = f"import bpy # {job.label}\n\n\ndef build(ctx):\n return ctx.collection\n"
+ return out
+
+
+def test_scene_blender_runs_the_same_stages_with_bpy_prompts_and_files(tmp_path, settings):
+ """A scene_blender run is the scene track over the bpy templates and the runtime's file table:
+ every stage session owns ``.py`` files, reads the bpy briefs (the wrapper's hooks, the bpy asset
+ API, plan numbers in the Z-up frame) and the module assets go through the bpy ladder."""
+ plan = small_scene(Language.SCENE_BLENDER)
+ assert {a.kind for a in plan.assets} == {"bpy"}
+ spec = make_spec(Track.SCENE, Language.SCENE_BLENDER, max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "harbour_bpy")
+ agent = FakeAgent(_bpy_scene_writer)
+ track = SceneTrack(services=FakeServices(assemble=True), judge=FakeJudge(scores=(0.6, 0.7), targets=("Quay", "Water")), agent=agent,
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_BLENDER))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.MAX_ROUNDS and [r.kind for r in rec.rounds] == ["baseline", "refine"]
+ jobs = {j.label: j for j in agent.jobs}
+ env = jobs["env"]
+ assert env.files_hint == ["src/env.py"] and "build_env(ctx)" in env.prompt and "env.js" not in env.prompt
+ # the plan's bounds, centre (0, 5, 0) Y-up, reach the bpy author as (0, 0, 5): Z up (D12)
+ assert "centre (0.000, 0.000, 5.000) m" in env.prompt
+ zones = next(j for label, j in jobs.items() if label.startswith("zones_"))
+ assert zones.files_hint == ["src/zones/quay.py", "src/zones/water.py"] and "def build(ctx)" in zones.prompt
+ assert "ctx.assets['bollard']" in zones.prompt and "import {" not in zones.prompt
+ assets = [j for label, j in jobs.items() if label.startswith("asset_")]
+ assert {j.files_hint[0] for j in assets} == {"src/assets/fishing_boat.py", "src/assets/bollard.py"}
+ assert all("variant=0" in j.prompt and "ctx.collection" in j.prompt for j in assets)
+ refine = next(j for label, j in jobs.items() if label.startswith("refine"))
+ assert refine.files_hint and all(f.endswith(".py") for f in refine.files_hint) and "src/env.py" in refine.prompt
+ events = [e for e in EventLog(ws.events_path).read() if e["event"] == "asset.generated"]
+ assert {e["asset"]: e["ok"] for e in events} == {"FishingBoat": True, "Bollard": True}
+ assert (ws.root / "src" / "scene.py").read_text().startswith("# assembled by fake")
diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.py
index 6e62c871..d05bba03 100644
--- a/harness/tests/prompts/manifest.py
+++ b/harness/tests/prompts/manifest.py
@@ -67,7 +67,6 @@ from codeverse3d.languages import get_runtime
from codeverse3d.languages._gl_common import finish_build, judge_times
from codeverse3d.languages.glsl_shader import GlslShaderRuntime
from codeverse3d.languages.opengl_python import OpenGLPythonRuntime
-from codeverse3d.languages.scene_threejs import asset_file, zone_file
from codeverse3d.models.base import ModelError
from codeverse3d.orchestrator import BudgetGuard
from codeverse3d.spatial.gl_render import GlFrame, GlResult, gif_times
@@ -76,6 +75,7 @@ from codeverse3d.texturing.plan import PackEntry, ScenePack
from codeverse3d.tracks import get_track, scene_assets
from codeverse3d.tracks.common import Services
from codeverse3d.tracks.planner import plan_example
+from codeverse3d.tracks.scene import ENV_FILES
from codeverse3d.tracks.scene_assets import AssetCheck
from codeverse3d.tracks.zone_layout import validate_layout
from codeverse3d.workspace import Workspace, WorkspaceGitError
@@ -128,6 +128,7 @@ def isolated(root: Path) -> Iterator[None]:
(BudgetGuard, "elapsed_minutes", lambda self: 0.0),
(ledger, "_fallback", ledger.CostLedger(root / "process.jsonl")),
(scene_assets, "check_threejs_asset", _asset_check),
+ (scene_assets, "check_bpy_asset", _bpy_asset_check),
(Workspace, "_git", _git_through_short_reads)):
stack.enter_context(mock.patch.object(target, name, value))
os.chdir(root) # no ./3dcodeverse.yaml
@@ -170,6 +171,16 @@ def _asset_check(ctx: Any, rel: str, pascal: str, *, timeout_s: float = 60.0,
errors=[f"missing export: this file must `export function build{pascal}(THREE, opts = {{}})`"])
+def _bpy_asset_check(ctx: Any, rel: str, snake: str, *, expected_size_m: tuple[float, float, float] | None = None,
+ timeout_s: float | None = None) -> AssetCheck:
+ """``scene_assets.check_bpy_asset`` without Blender: a module passes when it defines its builder."""
+ path = ctx.ws.root / rel
+ if path.is_file() and f"def build_{snake}(" in path.read_text():
+ return AssetCheck(ok=True, ran=True, size_m=expected_size_m, tris=480, meshes=3, materials=2)
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"missing builder: this file must define `build_{snake}(ctx, variant=0)`"])
+
+
class StableJudge(FakeJudge):
"""A verdict scored by what it judges (round, candidate), never by call order: the candidates,
the assets and the scene stages judge from threads."""
@@ -286,16 +297,17 @@ class Rig:
def single_shot_files(self, label: str) -> list[str]:
"""The files a single-shot answer for ``label`` returns (an agent job names them in ``files_hint``)."""
- if isinstance(self.plan, ScenePlan):
+ if isinstance(self.plan, ScenePlan): # the scene language's own file table (D101)
+ rt = get_runtime(self.language)
if label == "env":
- return ["src/env.js"]
+ return [getattr(rt, "env_file", None) or ENV_FILES[self.language]]
if label.startswith("zone"):
- return [zone_file(z.name) for z in self.plan.zones]
+ return [rt.zone_file(z.name) for z in self.plan.zones]
if label.startswith("asset_"):
asset = self.asset(label)
- if asset.kind == "threejs":
- return [asset_file(asset)]
- return get_runtime(Language.BLENDER).expected_files(StaticPlan.model_validate(plan_example(Track.STATIC_OBJECT)))
+ if asset.kind == "blender_glb":
+ return get_runtime(Language.BLENDER).expected_files(StaticPlan.model_validate(plan_example(Track.STATIC_OBJECT)))
+ return [rt.asset_file(asset)]
return get_runtime(self.language).expected_files(self.plan)
def asset(self, label: str) -> Any:
@@ -318,6 +330,14 @@ class Rig:
out[rel] = PROGRAM.format(tag=tag)
elif rel.endswith(".urdf"):
out[rel] = f"<robot name='x'/>\n<!-- {tag} -->\n"
+ elif rel.startswith("src/assets/") and rel.endswith(".py"): # a scene_blender module: its builder, or none
+ snake = Path(rel).stem
+ fn = "build" if single_shot and to_pascal(snake) in self.broken_assets else f"build_{snake}"
+ out[rel] = f"import bpy # {tag}\n\n\ndef {fn}(ctx, variant=0):\n return ctx.collection\n"
+ elif rel == "src/env.py":
+ out[rel] = f"import bpy # {tag}\n\n\ndef height_at(x, y):\n return 0.0\n\n\ndef build_env(ctx):\n return {{}}\n"
+ elif rel.startswith("src/zones/") and rel.endswith(".py"):
+ out[rel] = f"import bpy # {tag}\n\n\ndef build(ctx):\n return ctx.collection\n"
elif rel.endswith(".py"):
out[rel] = f"import bpy # {tag}\n"
else:
@@ -416,12 +436,20 @@ SCENARIOS: dict[str, tuple[Track, Language, dict[str, Any], Callable[[Rig], None
_two_runs(1, 2)),
"scene.scene_threejs.agent.textures": (SC, Language.SCENE_THREEJS, {"plan": small_scene()}, _scene_textures),
"scene.scene_threejs.agent.no_layouts": (SC, Language.SCENE_THREEJS, {"plan": small_scene()}, _switched("C3D_ZONE_LAYOUTS", "off", 0)),
+ # the argon variant (D105) ships EMPTY overlays: every payload equals the fresh scene's, only the
+ # plan stage key carries the variant name — iteration 0 of the loop measures exactly this
+ "scene.scene_threejs.agent.variant_argon": (SC, Language.SCENE_THREEJS, {"plan": small_scene()}, _switched("C3D_VARIANT", "argon", 1)),
"scene.scene_threejs.agent.hero": (SC, Language.SCENE_THREEJS, {"scores": (0.6, 0.7)}, lambda r: r.run(rounds=0)),
# the zones never build again: repairs and the rebuild own scene.js/env.js, not the zone files
"scene.scene_threejs.agent.rebuild": (SC, Language.SCENE_THREEJS, {"plan": small_scene(), "fail": frozenset({"zones_quay_water"})},
lambda r: r.run(rounds=1)),
"scene.scene_threejs.single_shot.fresh": (SC, Language.SCENE_THREEJS, {"plan": small_scene(), "broken_assets": frozenset({"Bollard"})},
lambda r: r.run(rounds=1, single_shot=True)),
+ # the bpy scene language over the same harbour (lane B1, 2026-10-14): the bpy templates, the bpy asset ladder
+ "scene.scene_blender.agent.fresh": (SC, Language.SCENE_BLENDER, {"plan": small_scene(Language.SCENE_BLENDER), "broken_assets": frozenset({"Bollard"})},
+ _two_runs(1, 2)),
+ "scene.scene_blender.single_shot.fresh": (SC, Language.SCENE_BLENDER, {"plan": small_scene(Language.SCENE_BLENDER), "broken_assets": frozenset({"Bollard"})},
+ lambda r: r.run(rounds=1, single_shot=True)),
"graphics.glsl_shader.agent.fresh": (G, Language.GLSL_SHADER, {}, _two_runs(1, 2)),
"graphics.glsl_shader.agent.best_of_2": (G, Language.GLSL_SHADER, {}, lambda r: r.run(rounds=0, candidates=2)),
"graphics.glsl_shader.agent.rebuild": (G, Language.GLSL_SHADER, {"fail": REBUILD}, lambda r: r.run(rounds=1)),
@@ -453,16 +481,11 @@ def run_scenario(name: str, root: Path) -> Result:
return Result(capture(rig), stage_keys(rig))
-#: a language whose agent-facing payloads are not blessed yet: scene_blender's tool list is blessed by
-#: the lane that ships its prompts and scenarios (DESIGN phase 3), which deletes this entry
-UNBLESSED_LANGUAGES = frozenset({Language.SCENE_BLENDER})
-
-
def mcp_tools() -> dict[str, str]:
"""The tool list an MCP session is offered, per (track, language)."""
return {f"mcp_tools:{t.value}/{lang.value}": _json([{"name": d.name, "cost": d.cost_hint, "description": d.description,
"schema": d.schema()} for d in list_tools(track=t.value, language=lang.value)])
- for t, langs in TRACK_LANGUAGES.items() for lang in langs if lang not in UNBLESSED_LANGUAGES}
+ for t, langs in TRACK_LANGUAGES.items() for lang in langs}
def capture(rig: Rig) -> dict[str, str]:
diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.py
index 96d105a6..0302ba95 100644
--- a/harness/tests/prompts/test_files.py
+++ b/harness/tests/prompts/test_files.py
@@ -23,16 +23,12 @@ def test_prompt_file_contract(rel: str) -> None:
assert seq not in raw, f"{rel} contains {seq!r} which breaks jinja rendering"
-#: languages whose prompt files have not landed yet — scene_blender's are DESIGN phase 3 (lane C),
-#: which deletes this entry when prompts/scene_blender/ ships
-PROMPTS_PENDING = frozenset({Language.SCENE_BLENDER})
-
-
def test_every_language_ships_a_system_prompt_a_contract_and_a_cookbook() -> None:
- """A missing per-language file silently reads as "" through ``language_text``."""
+ """A missing per-language file silently reads as "" through ``language_text`` — every language,
+ scene_blender included (its prompts landed with the argon scene-tuning program, 2026-10-14)."""
from codeverse3d.tracks.prompting import language_system_prompt
- for lang in (lang for lang in Language if lang not in PROMPTS_PENDING):
+ for lang in Language:
text = language_system_prompt(lang)
assert text.strip(), f"{lang.value}: empty system prompt"
for name in ("system.md", "contract.md", "cookbook.md"):
diff --git a/harness/tests/prompts/test_snippets_run.py b/harness/tests/prompts/test_snippets_run.py
index f40ac088..a016de3a 100644
--- a/harness/tests/prompts/test_snippets_run.py
+++ b/harness/tests/prompts/test_snippets_run.py
@@ -8,8 +8,11 @@
from __future__ import annotations
+from pathlib import Path
+
import pytest
+from codeverse3d.config import get_settings
from tests.prompts.conftest import (
blocks,
js_prelude,
@@ -239,3 +242,102 @@ def test_scene_cookbook_sky_shader_compiles() -> None:
)
code, out = compile_scene(scene, ("environment.js", "sky.js"))
assert code == 0, f"sky shader failed to compile:\n{out}"
+
+
+# --------------------------------------------------------------------- scene_blender
+#: what the scene_blender cookbook's header promises every zone-body snippet has in scope
+_BPY_PRELUDE = "import math\n\nimport bmesh\nimport bpy\nfrom mathutils import Euler, Matrix, Vector, noise\n"
+#: a block that is module-level ``src/env.py`` code instead (the world is only ever built there)
+BPY_ENV_ROLE = "# role: env"
+
+
+def bpy_snippet_modules(rel: str) -> tuple[str, dict[str, str]]:
+ """``(src/env.py source, {zone snake: zone module source})`` for the python blocks of ``rel``: the
+ ``# role: env`` blocks concatenated in order into ONE env module, every other block the body of its
+ own zone's ``build(ctx)`` under the prelude the cookbook header states."""
+ env_blocks: list[str] = []
+ zones: dict[str, str] = {}
+ for i, body in enumerate(blocks(rel, "python")):
+ if body.lstrip().startswith(BPY_ENV_ROLE):
+ env_blocks.append(body)
+ continue
+ indented = "".join((" " + line) if line.strip() else line for line in body.splitlines(keepends=True))
+ zones[f"snippet_{i:02d}"] = (f'"""block {i} of {rel}, run as a zone by tests/prompts/test_snippets_run.py."""\n'
+ + _BPY_PRELUDE + "\n\ndef build(ctx):\n rng = ctx.rng(7)\n" + indented
+ + ("" if indented.endswith("\n") else "\n") + " return ctx.collection\n")
+ return "\n\n".join(env_blocks), zones
+
+
+def _bpy_workspace(tmp_path):
+ """The scratch workspace the scene_blender snippets run in: the skeleton of the bpy worked example
+ (its two module assets build first → ``ctx.assets``), through the real runtime."""
+ from codeverse3d.contracts.common import Language, Track
+ from codeverse3d.contracts.plan import ScenePlan
+ from codeverse3d.languages import get_runtime
+ from codeverse3d.tracks.planner import plan_example
+ from codeverse3d.workspace import Workspace
+
+ if not get_settings().resolve_blender():
+ pytest.skip("no Blender binary configured")
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE, Language.SCENE_BLENDER))
+ ws = Workspace(tmp_path / "ws")
+ rt = get_runtime(Language.SCENE_BLENDER)
+ rt.skeleton(ws, plan)
+ return ws, rt, plan
+
+
+def test_scene_blender_cookbook_runs_inside_zones_and_lints_clean(tmp_path) -> None:
+ """The bpy cookbook's promise: every snippet runs in Blender 5.2.2 under the ctx the wrapper hands
+ out (one process for all of them) and passes the scene lint for its role with no WARN."""
+ from codeverse3d.contracts.artifacts import Severity
+ from codeverse3d.conventions import to_pascal
+ from codeverse3d.languages.scene_blender import lint_scene_source
+
+ ws, rt, _ = _bpy_workspace(tmp_path)
+ env_src, zones = bpy_snippet_modules("scene_blender/cookbook.md")
+ assert env_src and len(zones) >= 10
+ (ws.src / "env.py").write_text(env_src)
+ for name, src in zones.items():
+ (ws.src / "zones" / f"{name}.py").write_text(src)
+ bad = {}
+ for rel, src, role in [("src/env.py", env_src, "env"), *((f"src/zones/{n}.py", s, "zone") for n, s in zones.items())]:
+ findings = [f for f in lint_scene_source(src, target=rel, role=role) if f.severity is not Severity.INFO]
+ if findings:
+ bad[rel] = [(f.severity.value, f.message) for f in findings]
+ assert not bad, bad
+ run = rt.run_wrapper(ws, ws.artifacts, zones={n: to_pascal(n) for n in zones}, blend=False, timeout_s=600)
+ errors = [(e.get("stage"), e.get("name"), e.get("error_file"), e.get("error_line"), e.get("error_message")) for e in run.report.get("errors") or []]
+ assert run.result.ok and not errors, (run.result.error_type, run.result.error_message, errors)
+ assert sorted(run.report["zones_ok"]) == sorted(zones)
+ assert not run.report.get("warnings"), run.report.get("warnings")
+
+
+def test_scene_blender_contract_examples_build_through_the_runtime(tmp_path) -> None:
+ """The contract's two COMPLETE files (built on the shipped bpy library, D51) lint clean, assemble,
+ build and seat what they place — through the real runtime, gates included."""
+ from codeverse3d.contracts.artifacts import Severity
+ from codeverse3d.languages import scene_blender as sb
+ from tests.scene_runtime.conftest import browser_available
+
+ lib = Path(sb.__file__).resolve().parent / "starter" / "src" / "lib"
+ if not lib.is_dir():
+ pytest.skip("the scene_blender starter library (lane B2) is not in this tree yet")
+ if not browser_available():
+ pytest.skip("puppeteer/chrome required for the census probe")
+ ws, rt, plan = _bpy_workspace(tmp_path)
+ files = labelled_files("scene_blender/contract.md", tag="python")
+ assert set(files) == {"src/env.py", "src/zones/quay.py"}
+ for rel, body in files.items():
+ (ws.root / rel).write_text(body)
+ rep = rt.lint(ws)
+ assert not [f for f in rep.findings if f.severity is not Severity.INFO], [(f.target, f.message) for f in rep.findings]
+ asm = rt.assemble(ws, plan)
+ assert "quay" in asm.zones_included and not asm.zones_failed and asm.env_ok, asm
+ res = rt.build(ws)
+ assert res.ok, res.stdout_tail
+ rows = {r["name"]: r for r in res.census["placement"]["assets"]}
+ assert rows["QuayDeck"]["supported"] and not rows["QuayDeck"]["floating"]
+ assert all(rows[f"Bollard_{i}"]["supported"] for i in range(6)), {k: v for k, v in rows.items() if k.startswith("Bollard")}
diff --git a/harness/tests/prompts/test_variants.py b/harness/tests/prompts/test_variants.py
new file mode 100644
index 00000000..22c37ffd
--- /dev/null
+++ b/harness/tests/prompts/test_variants.py
@@ -0,0 +1,469 @@
+"""The variant layer (D105): selection, the prompt overlay, caches, activation, knobs, the record."""
+
+from __future__ import annotations
+
+import json
+import shutil
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+import pytest
+from jinja2 import FileSystemLoader, TemplateNotFound
+
+from codeverse3d import prompts
+from codeverse3d.config import Settings, get_settings
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.spec import RunOptions
+from codeverse3d.prompts import variants as V
+from codeverse3d.prompts.variants import (
+ VARIANTS_DIR,
+ activate,
+ active_variant,
+ apply_variant_knobs,
+ knobs_applied,
+ list_variants,
+ resolve_variant,
+ variant_hash,
+ variant_info,
+)
+from tests.prompts.conftest import PROMPT_FILES, PROMPTS_DIR, is_template
+
+TV_TOML = ('[variant]\nname = "tv"\nversion = 3\ngenerators = ["agy:gemini-4-argon"]\n'
+ 'description = "a test variant"\n\n[knobs]\nskills_max = 4\nskills_only = "c3d-part-contact"\n')
+
+
+def _clear() -> None:
+ prompts._load.cache_clear()
+ prompts._env_for.cache_clear()
+ get_settings.cache_clear()
+
+
[email protected](autouse=True)
+def _no_process_variant(monkeypatch):
+ """No variant from this machine's environment, and no cached overlay from another test."""
+ monkeypatch.delenv("C3D_VARIANT", raising=False)
+ monkeypatch.delenv("C3D_VARIANTS", raising=False)
+ _clear()
+ yield
+ _clear()
+
+
+def overlay(tmp_path: Path, monkeypatch) -> Path:
+ """A tmp ``VARIANTS_DIR`` holding ``tv``: a cookbook that shadows blender's, a template only the
+ variant ships, and a role template that includes a BASE file (the ChoiceLoader fall-through)."""
+ root = tmp_path / "variants"
+ shutil.copytree(VARIANTS_DIR / "argon", root / "argon") # the shipped one stays known beside tv
+ tv = root / "tv"
+ for d in ("blender", "tracks", "system"):
+ (tv / d).mkdir(parents=True)
+ (tv / "variant.toml").write_text(TV_TOML)
+ (tv / "README.md").write_text("docs only\n")
+ (tv / "blender" / "cookbook.md").write_text("# OVERLAY COOKBOOK\n")
+ (tv / "tracks" / "only_in_variant.j2").write_text("overlay {{ x }}\n")
+ (tv / "system" / "role_repair.j2").write_text("OVERLAY ROLE {{ contract }}\n{% include 'system/singleshot_format.md' %}")
+ monkeypatch.setattr(V, "VARIANTS_DIR", root)
+ _clear()
+ return root
+
+
+# --------------------------------------------------------------------------- selection
+def test_resolution_order_including_the_served_model_lookup(overlay):
+ """settings.variant > variants[id as typed] > variants['<kind>:<served model>'] > base; plain lookups."""
+ table = {"agy:gemini-4-argon": "tv", "agy:gemini-4-argon-low": "argon", "claude-code:claude-opus-5": "tv"}
+ assert resolve_variant(Settings(variant="argon", variants=table), "agy:gemini-4-argon") == "argon"
+ assert resolve_variant(Settings(variants=table), "agy:gemini-4-argon-low") == "argon", "the id as typed wins"
+ assert resolve_variant(Settings(variants=table), "agy:gemini-4-argon-high") == "tv", "then the served model"
+ assert resolve_variant(Settings(variants=table), "agy:gemini-4-argon") == "tv"
+ assert resolve_variant(Settings(variants=table), "claude-code:claude-opus-5") == "tv"
+ assert resolve_variant(Settings(variants=table), "codex:gpt-6.1-sol") == ""
+ assert resolve_variant(Settings(variants=table), "single-shot:gemini:gemini-4-argon") == "", "no served spelling"
+ assert resolve_variant(Settings(), "agy:gemini-4-argon") == ""
+ assert resolve_variant(Settings(variant=" tv "), "x") == "tv"
+ assert V.served_id("agy:gemini-4-argon-medium") == "agy:gemini-4-argon" and V.served_id("nocolon") == ""
+
+
+def test_an_unknown_name_raises_and_names_the_known_ones(overlay):
+ for call in (lambda: resolve_variant(Settings(variant="bogus"), "agy:x"),
+ lambda: resolve_variant(Settings(variants={"agy:x": "bogus"}), "agy:x"),
+ lambda: variant_info("bogus"), lambda: variant_hash("bogus")):
+ with pytest.raises(ValueError, match=r"unknown variant 'bogus' \(known: argon, tv\)"):
+ call()
+ with pytest.raises(ValueError, match="unknown variant"), activate("bogus"):
+ pass
+ with pytest.raises(ValueError, match="plain directory name"):
+ V.variant_root("../escape")
+ assert list(list_variants()) == ["argon", "tv"] and list_variants()["tv"].version == 3
+
+
[email protected]("toml, problem", [
+ ('[variant]\nname = "other"\nversion = 1\n', "must equal the directory name"),
+ ('[variant]\nname = "tv"\nversion = 0\n', "version must be an integer >= 1"),
+ ('[variant]\nname = "tv"\nversion = "1"\n', "version must be an integer"),
+ ('[variant]\nname = "tv"\ngenerators = "agy:x"\n', "generators must be a list"),
+ ('[variant]\nname = "tv"\n[knobs]\nrounds = 3\n', "is not a variant knob"),
+ ('[variant]\nname = "tv"\n[knobs]\nskills_max = "four"\n', "skills_max must be a int >= 0"),
+ ('[variant]\nname = "tv"\n[knobs]\nskills_max = true\n', "skills_max must be a int"),
+ ('[variant]\nname = "tv"\n[knobs]\nskills_only = 4\n', "skills_only must be a str"),
+ ('[variant]\nname = "tv"\n[extra]\nx = 1\n', "unknown table"),
+ ('[variant]\nname = "tv"\nmodel = "x"\n', "unknown \\[variant\\] key"),
+ ('name = "tv"\n', "missing the \\[variant\\] table"),
+ ('[variant\nname = "tv"\n', "not valid TOML"),
+])
+def test_variant_toml_is_type_checked(overlay, toml, problem):
+ (overlay / "tv" / "variant.toml").write_text(toml)
+ with pytest.raises(ValueError, match=problem):
+ variant_info("tv")
+
+
+# --------------------------------------------------------------------------- the prompt overlay
+def test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):
+ base_cookbook = (PROMPTS_DIR / "blender" / "cookbook.md").read_text()
+ base_contract = (PROMPTS_DIR / "blender" / "contract.md").read_text()
+ with activate("tv"):
+ assert prompts.load_text("blender/cookbook.md") == "# OVERLAY COOKBOOK\n"
+ assert prompts.load_text("blender/contract.md") == base_contract, "no overlay copy: the base file"
+ assert prompts.prompt_root("blender/cookbook.md") == overlay / "tv" / "blender" / "cookbook.md"
+ assert prompts.prompt_root("blender/contract.md") == PROMPTS_DIR / "blender" / "contract.md"
+ assert prompts.render("tracks/only_in_variant.j2", x=1) == "overlay 1\n"
+ rendered = prompts.render("system/role_repair.j2", contract="C")
+ assert rendered.startswith("OVERLAY ROLE C\n")
+ assert (PROMPTS_DIR / "system" / "singleshot_format.md").read_text().strip() in rendered, "a base include"
+ # the catalog resolves through the same loader: callers do not change
+ from codeverse3d.prompts.catalog import language_text
+
+ assert language_text(Language.BLENDER, "cookbook.md") == "# OVERLAY COOKBOOK\n"
+ assert language_text(Language.BLENDER, "contract.md") == base_contract
+ with pytest.raises(FileNotFoundError):
+ prompts.load_text("blender/nowhere.md")
+ assert prompts.load_text("blender/cookbook.md") == base_cookbook
+ with pytest.raises(TemplateNotFound):
+ prompts.render("tracks/only_in_variant.j2", x=1)
+
+
+def test_base_rendering_is_untouched_and_byte_identical_under_an_empty_overlay():
+ """The base environment is the single FileSystemLoader it always was (the manifest pins every
+ payload); the shipped argon overlay is empty, so under it every static prompt file reads the same."""
+ assert isinstance(prompts._env.loader, FileSystemLoader) and prompts._env.loader.searchpath == [str(PROMPTS_DIR)]
+ assert prompts._env_for("") == (prompts._env, prompts._lenient_env)
+ static = [rel for rel in PROMPT_FILES if not is_template(rel)]
+ assert static
+ base = {rel: (prompts.load_text(rel), prompts.render(rel)) for rel in static}
+ with activate("argon"):
+ assert active_variant() == "argon"
+ for rel in static:
+ assert (prompts.load_text(rel), prompts.render(rel)) == base[rel], rel
+ assert prompts.prompt_root(rel) == PROMPTS_DIR / rel
+
+
+def test_caches_are_isolated_per_variant_in_process(overlay):
+ base = prompts.load_text("blender/cookbook.md")
+ assert base != "# OVERLAY COOKBOOK\n"
+ with activate("tv"):
+ assert prompts.load_text("blender/cookbook.md") == "# OVERLAY COOKBOOK\n"
+ strict, lenient = prompts._env_for("tv")
+ assert strict is not prompts._env and lenient is not prompts._lenient_env
+ assert prompts._env_for("tv") == (strict, lenient), "one environment per variant"
+ assert prompts.load_text("blender/cookbook.md") == base
+ with activate("tv"):
+ assert prompts.load_text("blender/cookbook.md") == "# OVERLAY COOKBOOK\n"
+
+
+def test_activate_nests_and_falls_back_to_the_process_switch(overlay, monkeypatch):
+ assert active_variant() == ""
+ with activate("argon"):
+ assert active_variant() == "argon"
+ with activate("tv"):
+ assert active_variant() == "tv"
+ assert active_variant() == "argon"
+ with activate(""):
+ assert active_variant() == "", "'' inside a block is the base, whatever the process says"
+ assert active_variant() == ""
+ monkeypatch.setenv("C3D_VARIANT", "argon")
+ get_settings.cache_clear()
+ assert active_variant() == "argon", "outside any block: get_settings().variant"
+ with activate(""):
+ assert active_variant() == ""
+ assert active_variant() == "argon"
+ monkeypatch.setenv("C3D_VARIANT", "../escape")
+ get_settings.cache_clear()
+ assert active_variant() == "", "a name that is not a plain directory name is the base, never a path"
+
+
+def test_an_exception_inside_the_block_still_resets(overlay):
+ with pytest.raises(RuntimeError), activate("tv"):
+ raise RuntimeError("boom")
+ assert active_variant() == ""
+
+
+# --------------------------------------------------------------------------- provenance
+def test_variant_hash_covers_both_overlays_and_ignores_readmes(overlay, tmp_path, monkeypatch):
+ skills = tmp_path / "skills"
+ (skills / "variants" / "tv").mkdir(parents=True)
+ (skills / "variants" / "tv" / "routes.toml").write_text("")
+ monkeypatch.setenv("C3D_SKILLS_DIR", str(skills))
+ get_settings.cache_clear()
+ assert variant_hash("") == ""
+ h0 = variant_hash("tv")
+ assert len(h0) == 12 and int(h0, 16) >= 0
+ (overlay / "tv" / "README.md").write_text("edited docs\n")
+ assert variant_hash("tv") == h0, "README.md is documentation, not prompt material"
+ (overlay / "tv" / "blender" / "cookbook.md").write_text("# OVERLAY COOKBOOK v2\n")
+ h1 = variant_hash("tv")
+ assert h1 != h0
+ (skills / "variants" / "tv" / "routes.toml").write_text('[[boost]]\nskill = "c3d-part-contact"\ndelta = 5\n')
+ h2 = variant_hash("tv")
+ assert h2 not in (h0, h1), "the skills half counts too"
+ (overlay / "tv" / "variant.toml").write_text(TV_TOML.replace("version = 3", "version = 4"))
+ assert variant_hash("tv") not in (h0, h1, h2), "a version bump moves it"
+ assert V.variant_block("tv") == {"name": "tv", "version": 4, "hash": variant_hash("tv")}
+ assert V.variant_block("") == {"name": "", "version": 0, "hash": ""}
+ assert V.variant_block("gone") == {"name": "gone", "version": 0, "hash": ""}
+
+
+def test_the_argon_variant_ships_the_iteration_1_overlays():
+ """Iteration 0 of the loop measured the base prompts under the plumbing (an empty overlay);
+ iteration 1 (2026-10-15) shadows the two zone briefs and boosts the two placement skills — the
+ whole overlay is these files, nothing else, and the hash covers them."""
+ from codeverse3d.skills import variant_dir, variants_table
+
+ info = variant_info("argon")
+ assert info.name == "argon" and info.version == 1 and info.generators == ("agy:gemini-4-argon",) and info.knobs == {}
+ assert info.description.startswith("gemini-4-argon on the scene track (threejs + blender)")
+ assert "argon" in list_variants()
+ assert sorted(p.name for p in (VARIANTS_DIR / "argon").iterdir()) == ["README.md", "tracks", "variant.toml"]
+ assert sorted(p.name for p in (VARIANTS_DIR / "argon" / "tracks").iterdir()) == ["scene_zone.j2", "scene_zone_bpy.j2"]
+ for name in ("scene_zone.j2", "scene_zone_bpy.j2"):
+ text = (VARIANTS_DIR / "argon" / "tracks" / name).read_text(encoding="utf-8")
+ assert "## Before you return" in text and text.index("## Before you return") < text.index("## DON'T")
+ assert sorted(p.name for p in variant_dir("argon").iterdir()) == ["README.md", "routes.toml"]
+ table = variants_table("argon")
+ assert not table.empty and table.variant == "argon" and not table.routes and not table.disabled
+ assert {(b.skill, b.delta) for b in table.boosts} == {("c3d-scene-composition", 14), ("c3d-bpy-scene-placement", 9)}
+ assert len(variant_hash("argon")) == 12
+
+
+# --------------------------------------------------------------------------- knobs
+def test_knobs_apply_as_defaults_and_a_user_stated_field_wins(overlay, monkeypatch):
+ info = variant_info("tv")
+ assert info.knobs == {"skills_max": 4, "skills_only": "c3d-part-contact"}
+ monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)
+ s = Settings()
+ before = set(s.model_fields_set)
+ assert apply_variant_knobs(s, info) == {"skills_max": 4, "skills_only": "c3d-part-contact"}
+ assert (s.skills_max, s.skills_only) == (4, "c3d-part-contact")
+ assert set(s.model_fields_set) == before, "a knob is a default, never a statement"
+ # stated by the user: an explicit kwarg (config.yaml) and the environment both win
+ s = Settings(skills_max=2)
+ assert apply_variant_knobs(s, info) == {"skills_only": "c3d-part-contact"} and s.skills_max == 2
+ monkeypatch.setenv("C3D_SKILLS_MAX", "3")
+ monkeypatch.setenv("C3D_SKILLS_ONLY", "c3d-scene-water")
+ s = Settings()
+ assert apply_variant_knobs(s, info) == {} and (s.skills_max, s.skills_only) == (3, "c3d-scene-water")
+ # re-application and a later variant still see an unstated field
+ monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)
+ s = Settings()
+ apply_variant_knobs(s, info)
+ other = info.model_copy(update={"knobs": {"skills_max": 7}})
+ assert apply_variant_knobs(s, other) == {"skills_max": 7} and s.skills_max == 7
+
+
+def test_knobs_applied_restores_the_values_and_the_field_set_even_when_the_block_raises(overlay, monkeypatch):
+ """The block form the run uses: the knobs hold inside it and nothing of them survives it — not the
+ values, not the field-set membership that would make a leaked value look like a default."""
+ monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)
+ info = variant_info("tv")
+ default_max = Settings().skills_max
+ s = Settings(skills_only="c3d-scene-water") # stated by the user: never touched, stays stated
+ with knobs_applied(s, info) as applied:
+ assert applied == {"skills_max": 4} and (s.skills_max, s.skills_only) == (4, "c3d-scene-water")
+ assert (s.skills_max, s.skills_only) == (default_max, "c3d-scene-water")
+ assert set(s.model_fields_set) & V.KNOB_FIELDS == {"skills_only"}
+ s = Settings()
+ with pytest.raises(RuntimeError), knobs_applied(s, info):
+ assert (s.skills_max, s.skills_only) == (4, "c3d-part-contact")
+ raise RuntimeError("boom")
+ assert (s.skills_max, s.skills_only) == (default_max, "") and not set(s.model_fields_set) & V.KNOB_FIELDS
+ # nested on ONE object (the singleton is also the injected Settings): the outer block's prior wins
+ with knobs_applied(s, info), knobs_applied(s, info):
+ assert s.skills_max == 4
+ assert s.skills_max == default_max and not set(s.model_fields_set) & V.KNOB_FIELDS
+ with knobs_applied(s, None) as applied:
+ assert applied == {} and s.skills_max == default_max, "no variant: nothing applied, nothing to undo"
+
+
+# --------------------------------------------------------------------------- the run
+def test_plan_stage_key_is_unchanged_without_a_variant_and_names_one_when_set(overlay):
+ from codeverse3d.tracks.lifecycle import plan_stage_inputs, plan_stage_key
+ from tests.orchestrator_tracks.conftest import make_spec
+
+ spec = make_spec()
+ base = plan_stage_key(spec, Track.STATIC_OBJECT)
+ assert base == {"spec": plan_stage_inputs(spec), "track": "static_object"}, "the default key never moves"
+ with activate("tv"):
+ assert plan_stage_key(spec, Track.STATIC_OBJECT) == {**base, "variant": "tv"}
+ frozen = make_spec(options=RunOptions(variant="argon"))
+ assert plan_stage_key(frozen, Track.STATIC_OBJECT) == {**base, "variant": "argon"}
+ with activate("tv"):
+ assert plan_stage_key(frozen, Track.STATIC_OBJECT)["variant"] == "argon", "the spec's frozen choice wins"
+
+
+def _writer(job: Any, ws: Any) -> dict[str, str]:
+ return {"src/object.js": f"// {job.label} r{job.round}\nexport function build(THREE) {{ return new THREE.Group(); }}\n"}
+
+
+def _run(tmp_path: Path, monkeypatch, *, options: RunOptions | None = None, env: dict[str, str] | None = None,
+ settings: Settings | None = None, on_generate: Callable[[Settings], None] | None = None) -> tuple[Any, Any, Settings]:
+ """One judged baseline of the static track through the fakes, under ``env``. With ``settings`` the
+ run reuses that object AND the process singleton as they are (no cache clear): the second run of
+ one process, the way a manifest rig or a bench cell follows the run before it. ``on_generate``
+ is called with the injected Settings every time the fake agent generates — a probe INSIDE the run."""
+ from codeverse3d.tracks.planner import plan_example
+ from codeverse3d.tracks.static_object import StaticObjectTrack
+ from codeverse3d.workspace import Workspace
+ from tests.orchestrator_tracks.conftest import make_spec
+ from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+ _planner,
+ )
+
+ monkeypatch.setenv("C3D_PLAN_BRIEF", "off") # one canned plan per planner request
+ for k, v in (env or {}).items():
+ monkeypatch.setenv(k, v)
+ spec = make_spec(max_rounds=0, **({"options": options} if options is not None else {}))
+ if settings is None:
+ get_settings.cache_clear()
+ settings = Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")
+ injected = settings
+
+ def writer(job: Any, ws: Any) -> dict[str, str]:
+ if on_generate is not None:
+ on_generate(injected)
+ return _writer(job, ws)
+
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(writer),
+ planner_model=_planner(plan_example(Track.STATIC_OBJECT)), settings=settings,
+ runtime=FakeRuntime(Language.THREEJS))
+ ws = Workspace(tmp_path / "runs" / "r")
+ return track.run(spec, ws), ws, settings
+
+
+def _events(ws: Any) -> list[dict[str, Any]]:
+ from codeverse3d.proc import EventLog
+
+ return EventLog(ws.events_path).read()
+
+
+def test_a_run_records_the_variant_it_activated(tmp_path, monkeypatch):
+ from codeverse3d.orchestrator import hash_inputs
+ from codeverse3d.proc import read_jsonl_lenient
+ from codeverse3d.record.telemetry import settings_snapshot
+ from codeverse3d.tracks.lifecycle import plan_stage_key
+
+ rec, ws, _ = _run(tmp_path, monkeypatch, options=RunOptions(variant="argon"))
+ h = variant_hash("argon")
+ assert rec.environment["variant"] == "argon"
+ assert rec.extra["variant"] == {"name": "argon", "version": 1, "hash": h}
+ assert rec.prompt_hashes["variant"] == h and "generate" in rec.prompt_hashes
+ snap = settings_snapshot(rec)
+ assert (snap.variant, snap.variant_version, snap.variant_hash) == ("argon", 1, h)
+ events = _events(ws)
+ assert next(e for e in events if e["event"] == "run.start")["variant"] == "argon"
+ active = next(e for e in events if e["event"] == "variant.active")
+ assert (active["name"], active["version"], active["hash"], active["knobs"]) == ("argon", 1, h, {})
+ attached = [e for e in events if e["event"] == "skills.attached"]
+ assert attached and {e["variant"] for e in attached} == {"argon"}
+ rows = read_jsonl_lenient(ws.root / "telemetry" / "skills.jsonl")
+ assert rows and {r["variant"] for r in rows} == {"argon"}
+ # the plan was cached under a key that names the variant
+ stored = json.loads((ws.root / "stages" / "plan.json").read_text())["inputs_hash"]
+ with activate("argon"):
+ assert stored == hash_inputs(plan_stage_key(rec.spec, Track.STATIC_OBJECT))
+ assert stored != hash_inputs(plan_stage_key(rec.spec.model_copy(update={"options": RunOptions()}), Track.STATIC_OBJECT))
+ assert active_variant() == "", "the activation ends with the run"
+
+
+def test_a_base_run_records_no_variant(tmp_path, monkeypatch):
+ from codeverse3d.record.telemetry import settings_snapshot
+
+ rec, ws, _ = _run(tmp_path, monkeypatch)
+ assert rec.environment["variant"] == "" and "variant" not in rec.prompt_hashes
+ assert rec.extra["variant"] == {"name": "", "version": 0, "hash": ""}
+ snap = settings_snapshot(rec)
+ assert (snap.variant, snap.variant_version, snap.variant_hash) == ("", 0, "")
+ events = _events(ws)
+ assert next(e for e in events if e["event"] == "run.start")["variant"] == ""
+ assert not [e for e in events if e["event"] == "variant.active"]
+ assert {e["variant"] for e in events if e["event"] == "skills.attached"} == {""}
+
+
+def test_a_run_honours_the_process_switch_when_the_spec_says_nothing(tmp_path, monkeypatch):
+ """What the manifest scenario ``scene.scene_threejs.agent.variant_argon`` relies on: a direct
+ ``track.run`` under ``C3D_VARIANT`` (an A/B arm's environment) runs the variant — and the spec on
+ disk still says nothing (the CLI is what freezes a choice; the record names what ran)."""
+ from codeverse3d.contracts.spec import Spec
+
+ rec, ws, _ = _run(tmp_path, monkeypatch, env={"C3D_VARIANT": "argon"})
+ assert rec.environment["variant"] == "argon" and rec.extra["variant"]["name"] == "argon"
+ assert Spec.model_validate_json(ws.spec_path.read_text()).options.variant == ""
+ with pytest.raises(ValueError, match="unknown variant 'bogus'"):
+ _run(tmp_path / "again", monkeypatch, env={"C3D_VARIANT": "bogus"})
+
+
+def _knobs(s: Settings) -> tuple[int, str, int, str]:
+ """What the injected Settings and the process singleton say right now."""
+ return s.skills_max, s.skills_only, get_settings().skills_max, get_settings().skills_only
+
+
+def test_a_run_applies_the_variants_knobs_to_the_process_and_the_injected_settings(tmp_path, monkeypatch, overlay):
+ monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)
+ seen: list[tuple[int, str, int, str]] = []
+ rec, ws, settings = _run(tmp_path, monkeypatch, options=RunOptions(variant="tv"),
+ on_generate=lambda s: seen.append(_knobs(s)))
+ active = next(e for e in _events(ws) if e["event"] == "variant.active")
+ assert active["knobs"] == {"skills_max": 4, "skills_only": "c3d-part-contact"} and active["version"] == 3
+ assert seen and set(seen) == {(4, "c3d-part-contact", 4, "c3d-part-contact")}, "held on both objects while it ran"
+ assert (settings.skills_max, settings.skills_only) == (Settings().skills_max, ""), "and for the run only"
+ assert rec.extra["variant"]["name"] == "tv"
+ # the sessions routed through the knob: only the one bundle, and only when it applies
+ attached = [e for e in _events(ws) if e["event"] == "skills.attached"]
+ assert attached and all(set(e["skills"]) <= {"c3d-part-contact"} for e in attached)
+ # a field the user stated survives the knob
+ seen.clear()
+ rec, ws, settings = _run(tmp_path / "stated", monkeypatch, options=RunOptions(variant="tv"), env={"C3D_SKILLS_MAX": "2"},
+ on_generate=lambda s: seen.append(_knobs(s)))
+ assert next(e for e in _events(ws) if e["event"] == "variant.active")["knobs"] == {"skills_only": "c3d-part-contact"}
+ assert seen and set(seen) == {(2, "c3d-part-contact", 2, "c3d-part-contact")}
+ assert (settings.skills_max, settings.skills_only) == (2, ""), "the statement stays; the knob does not"
+
+
+def test_a_variants_knobs_do_not_outlive_the_run_the_next_run_of_the_process_starts_from_the_base(tmp_path, monkeypatch, overlay):
+ """The overlays are ContextVar-scoped, but the knobs are written onto Settings objects that outlive
+ the run — the process singleton ``attach_skills`` reads, a rig's injected Settings. Left there, the
+ base run that followed a variant run in one process (a manifest rig, a bench cell after a variant
+ cell, any script calling ``track.run`` twice) routed at most the variant's ``skills_max`` and ONLY its
+ ``skills_only`` — and ``model_fields_set`` called the leaked value a default."""
+ monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)
+ default_max, default_only = Settings().skills_max, Settings().skills_only
+ rec, ws, settings = _run(tmp_path, monkeypatch, options=RunOptions(variant="tv"))
+ attached = [e for e in _events(ws) if e["event"] == "skills.attached"]
+ assert attached and all(set(e["skills"]) <= {"c3d-part-contact"} for e in attached), "the knobs held during the run"
+ singleton = get_settings() # the object the run applied the knobs to: not cleared since
+ for s in (settings, singleton):
+ assert (s.skills_max, s.skills_only) == (default_max, default_only)
+ assert not set(s.model_fields_set) & V.KNOB_FIELDS, "nothing left that looks like a user statement"
+ # the base run that follows, on the same injected Settings and the same singleton
+ rec, ws, same = _run(tmp_path / "base", monkeypatch, settings=settings)
+ assert same is settings and get_settings() is singleton and rec.environment["variant"] == ""
+ listed = {n for e in _events(ws) if e["event"] == "skills.attached" for n in e["skills"]}
+ assert listed - {"c3d-part-contact"}, f"the base run routed only what the variant's knobs allowed: {listed}"
+ assert (settings.skills_max, settings.skills_only) == (default_max, default_only)
diff --git a/harness/tests/scene_blender/test_build.py b/harness/tests/scene_blender/test_build.py
index 84ddff78..81e16fbe 100644
--- a/harness/tests/scene_blender/test_build.py
+++ b/harness/tests/scene_blender/test_build.py
@@ -92,6 +92,7 @@ def test_the_skeleton_builds_and_passes(tmp_ws) -> None:
plan = ScenePlan.model_validate(plan_example(Track.SCENE))
rt = _rt()
rt.skeleton(tmp_ws, plan)
+ assert (tmp_ws.src / "lib" / "terrain.py").is_file() # the env below is built FROM the library
assert rt.lint(tmp_ws).passed
asm = rt.assemble(tmp_ws, plan)
assert set(asm.zones_included) == {"quay", "water"} and not asm.zones_failed
@@ -101,6 +102,10 @@ def test_the_skeleton_builds_and_passes(tmp_ws) -> None:
assert c["fog"]["type"] == "VolumeBox" and c["background"] == "sky:MULTIPLE_SCATTERING"
assert "Atmosphere" in c["bpy"]["glb"]["volumes_skipped"]
assert {g["name"] for g in c["groups"]} >= {"Quay", "Water", "Ground"}
+ assert c["light_types"] == {"SUN": 1} and c["bpy"]["drivers_invalid"] == []
+ # every planned asset the stubs placed (lib.scatter.instance) is seated on the library's ground
+ placed = [r for r in c["placement"]["assets"] if r["zone"] in ("Quay", "Water") and not r["exempt"]]
+ assert placed and all(r["supported"] and not r["floating"] and r["sunk_m"] <= 0.10 for r in placed), placed
probe = json.loads((tmp_ws.artifacts / "scene_probe.json").read_text())
# the plan's cameras, named as scene_threejs's assembler names them
assert [cam["name"] for cam in probe["boot"]["cameras"]] == [to_snake(c.name) for c in plan.cameras[:6]]
diff --git a/harness/tests/scene_blender/test_layout.py b/harness/tests/scene_blender/test_layout.py
index e6111552..ebb2e5f1 100644
--- a/harness/tests/scene_blender/test_layout.py
+++ b/harness/tests/scene_blender/test_layout.py
@@ -20,7 +20,15 @@ from codeverse3d.conventions import (
)
from codeverse3d.languages import get_runtime
from codeverse3d.languages.base import SceneRuntime
-from codeverse3d.languages.scene_blender import frame_of, render_scene_py, write_skeleton
+from codeverse3d.languages.scene_blender import (
+ ENV_FILE,
+ SceneBlenderRuntime,
+ frame_of,
+ lib_files,
+ render_scene_py,
+ write_example,
+ write_skeleton,
+)
from codeverse3d.spatial.probes import _census_findings, merge_facts
from codeverse3d.tracks.planner import plan_example
@@ -47,6 +55,7 @@ def test_the_file_table() -> None:
assert rt.files_for(plan, "fog") == ["src/env.py"]
assert rt.files_for(plan, "cameras") == ["src/scene.py"]
assert rt.expected_files(plan) == ["src/scene.py", "src/env.py"]
+ assert rt.env_file == ENV_FILE == "src/env.py" # the SceneRuntime protocol's env hint
def test_asset_kind_bpy_loads() -> None:
@@ -94,6 +103,28 @@ def test_the_skeleton_writes_the_layout(tmp_ws) -> None:
for n in re.findall(r'place\(ctx, "\w+", "(\w+)"', (tmp_ws.src / "zones" / f"{z}.py").read_text())]
assert names
assert len(names) == len(set(names))
+ # the library ships with the plan skeleton (D51: a catalog with no src/lib/ to import from
+ # made every library import a build error on the three.js side), and the env / stubs USE it
+ lib = {p.rsplit("/", 1)[1] for p in paths if p.startswith("src/lib/")}
+ assert lib == {p.name for p in lib_files()} | {"__init__.py"} and len(lib) == 14
+ assert "from lib import architecture, lighting, materials, sky, terrain" in (tmp_ws.src / "env.py").read_text()
+ assert "from lib.scatter import instance" in (tmp_ws.src / "zones" / "quay.py").read_text()
+ assert "from lib.mesh import Batch" in (tmp_ws.src / "assets" / "bollard.py").read_text()
+
+
+def test_the_plan_less_skeleton_is_the_example_scene(tmp_ws) -> None:
+ """``write_skeleton(ws, None)`` is ``write_example``: the complete lakeside hamlet (three
+ zones, two assets, the entry, the env and the library), like scene_threejs's meadow."""
+ paths = {p.relative_to(tmp_ws.src).as_posix() for p in write_skeleton(tmp_ws, None)}
+ assert {"scene.py", "env.py", "zones/hamlet.py", "zones/lakeside.py", "zones/orchard.py", "assets/crate.py",
+ "assets/lantern_post.py", "lib/mesh.py", "lib/__init__.py"} <= paths
+ assert paths == {p.relative_to(tmp_ws.src).as_posix() for p in write_example(tmp_ws)}
+ ns: dict = {}
+ exec(compile((tmp_ws.src / "scene.py").read_text(), "scene.py", "exec"), ns) # data only
+ assert set(ns["ZONES"]) == {"hamlet", "lakeside", "orchard"} and set(ns["ASSETS"]) == {"crate", "lantern_post"}
+ assert len(ns["CAMERAS"]) == 3 and (tmp_ws.public / "assets").is_dir()
+ with pytest.raises(TypeError, match="ScenePlan"):
+ SceneBlenderRuntime().skeleton(tmp_ws, object()) # type: ignore[arg-type]
# --------------------------------------------------------------------------- the offline census gate
@@ -146,13 +177,21 @@ def test_each_scene_language_plans_its_own_asset_kinds() -> None:
scene_threejs's (its prompts are byte-identical), a scene_blender planner swaps its own in."""
from typing import get_args
- from codeverse3d.contracts.plan import SCENE_ASSET_KINDS
+ from codeverse3d.contracts.plan import SCENE_ASSET_KINDS, scene_plan_schema
kinds = set(get_args(AssetPlan.model_fields["kind"].annotation))
assert {lang.value for lang in TRACK_LANGUAGES[Track.SCENE]} == set(SCENE_ASSET_KINDS)
assert all(set(v) <= kinds for v in SCENE_ASSET_KINDS.values())
enum = ScenePlan.model_json_schema()["$defs"]["AssetPlan"]["properties"]["kind"]["enum"]
assert enum == list(SCENE_ASSET_KINDS["scene_threejs"])
+ # the swap the planner hands out (lane B1, 2026-10-14): scene_threejs's schema IS the default, byte for
+ # byte; a scene_blender planner is offered bpy / blender_glb and never threejs, with the kind documented
+ assert scene_plan_schema(Language.SCENE_THREEJS) == ScenePlan.model_json_schema()
+ bpy_kind = scene_plan_schema("scene_blender")["$defs"]["AssetPlan"]["properties"]["kind"]
+ assert bpy_kind["enum"] == list(SCENE_ASSET_KINDS["scene_blender"]) == ["bpy", "blender_glb"]
+ assert bpy_kind["description"].startswith("bpy = ")
+ with pytest.raises(KeyError):
+ scene_plan_schema(Language.BLENDER) # not a scene language
def test_the_adapter_and_the_host_agree_on_the_census_url() -> None:
diff --git a/harness/tests/scene_blender/test_library.py b/harness/tests/scene_blender/test_library.py
new file mode 100644
index 00000000..1c1ef715
--- /dev/null
+++ b/harness/tests/scene_blender/test_library.py
@@ -0,0 +1,619 @@
+"""The bpy starter library (D51 for scene_blender): the effects catalog indexes exactly it and prints
+every signature as the lib declares it (the names AND the keyword-only ``*`` boundary — a parameter
+printed positional that the lib takes by keyword only is a TypeError in every scene that trusts the
+row), the cookbook and the bpy skills never print one positionally either, the signatures the cookbook
+cites hold, a glazed room shell is glass on a frame that lets the sun in, and ONE Blender build proves
+that every factory seats what it makes (the placement gate's own rows), names nothing twice and stays
+under its triangle ceiling."""
+
+from __future__ import annotations
+
+import ast
+import json
+import re
+import struct
+from pathlib import Path
+
+import pytest
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.common import Language
+from codeverse3d.contracts.plan import CameraPlan
+from codeverse3d.languages import get_runtime
+from codeverse3d.languages.scene_blender import LIB_DIR, lib_files, render_scene_py, write_example
+from codeverse3d.prompts.catalog import language_text
+from codeverse3d.skills import skills_dir
+from tests.scene_runtime.conftest import needs_browser
+
+MODULES: dict[str, Path] = {p.stem: p for p in lib_files()}
+CATALOG = language_text(Language.SCENE_BLENDER, "effects_catalog.md")
+_ROW_MODULE = re.compile(r"`lib/([a-z_]+)\.py`")
+_SPAN = re.compile(r"`([^`]+)`")
+_CALL = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)\(")
+_METHOD = re.compile(r"^\.([a-z_][a-z0-9_]*)\(")
+needs_blender = pytest.mark.skipif(not get_settings().resolve_blender(), reason="no Blender binary")
+
+
+def _tree(stem: str) -> ast.Module:
+ return ast.parse(MODULES[stem].read_text(), filename=str(MODULES[stem]))
+
+
+def _defs(stem: str) -> tuple[dict[str, ast.FunctionDef], dict[str, dict[str, ast.FunctionDef]]]:
+ """Top-level functions and {class: {method}} of a module."""
+ funcs: dict[str, ast.FunctionDef] = {}
+ classes: dict[str, dict[str, ast.FunctionDef]] = {}
+ for node in _tree(stem).body:
+ if isinstance(node, ast.FunctionDef):
+ funcs[node.name] = node
+ elif isinstance(node, ast.ClassDef):
+ classes[node.name] = {n.name: n for n in node.body if isinstance(n, ast.FunctionDef)}
+ return funcs, classes
+
+
+def _boundary(fn: ast.FunctionDef) -> tuple[list[str], list[str], bool]:
+ """(positional names, keyword-only names, takes ``**kwargs``) of a def, ``self`` dropped."""
+ a = fn.args
+ return [p.arg for p in a.posonlyargs + a.args if p.arg != "self"], [p.arg for p in a.kwonlyargs], a.kwarg is not None
+
+
+def _params(fn: ast.FunctionDef) -> list[str]:
+ """The parameter names with the keyword-only boundary as ``"*"``: the shape a caller must honour,
+ not just the names (review 2026-10-15 finding 3: a name-only pin let 15 catalog rows print a
+ required keyword-only parameter as positional)."""
+ pos, kw, _ = _boundary(fn)
+ return pos + (["*", *kw] if kw else [])
+
+
+_MORE = "_more" # what a printed "…" parses as
+
+
+def _printed(span: str) -> ast.FunctionDef | None:
+ """A printed signature — ``instance(collection, source, *, height_at, …)``, ``.box(mat, loc, size)``,
+ ``lib.place.seat(obj, height_at)`` — parsed as a def; None when the span is not one."""
+ if "(" not in span or not span.endswith(")"):
+ return None
+ body = (span[1:] if span.startswith(".") else span).replace("…", _MORE).replace("...", _MORE)
+ head, _, rest = body.partition("(")
+ try:
+ node = ast.parse(f"def {head.rsplit('.', 1)[-1]}({rest}: pass").body[0]
+ except SyntaxError:
+ return None
+ return node if isinstance(node, ast.FunctionDef) else None
+
+
+def _faults(printed: ast.FunctionDef, lib: ast.FunctionDef, *, strict: bool) -> list[str]:
+ """How a printed signature misleads a caller of ``lib``: a parameter printed positional that the
+ lib takes by keyword only (bare always; printed with a default only under ``strict``, the
+ catalog's rule), a ``*`` anywhere but at the lib's boundary (or missing under ``strict``), a name
+ the lib does not have. ``…`` stands for "and the rest"; a head of ``…`` means "keywords only";
+ the lib spells a shadowing ``rng`` as ``rng_``, which a positional caller never sees; a printed
+ keyword the lib takes through ``**kwargs`` is a pass-through."""
+ a = printed.args
+ names = [p.arg for p in a.posonlyargs + a.args]
+ n_bare = len(names) - len(a.defaults)
+ star, abbreviated = bool(a.kwonlyargs), bool(names) and names[0] == _MORE
+ lpos, lkw, var_kw = _boundary(lib)
+ out: list[str] = []
+ for i, p in enumerate([] if abbreviated else names):
+ if p == _MORE:
+ continue
+ if i >= n_bare and not strict: # `size=…` in prose is a keyword wherever it is printed
+ if p not in lpos and p not in lkw and not var_kw:
+ out.append(f"{p!r} is not a parameter of the lib")
+ elif i < len(lpos):
+ if p.rstrip("_") != lpos[i].rstrip("_"):
+ out.append(f"positional #{i + 1} is {p!r}, the lib's is {lpos[i]!r}")
+ elif p in lkw:
+ out.append(f"{p!r} is printed positional but the lib takes it by keyword only")
+ elif not (var_kw and i >= n_bare):
+ out.append(f"{p!r} is not a parameter of the lib")
+ if star and not lkw:
+ out.append("a `*` is printed but the lib has no keyword-only parameters")
+ elif star and not abbreviated:
+ printed_pos = [p for p in names if p != _MORE]
+ if [p.rstrip("_") for p in printed_pos] != [p.rstrip("_") for p in lpos]:
+ out.append(f"the `*` is printed after {printed_pos}, the lib's boundary is after {lpos}")
+ elif strict and lkw:
+ out.append(f"the lib's `*` before {lkw} is not printed")
+ out += [f"{p.arg!r} is not a parameter of the lib" for p in a.kwonlyargs
+ if p.arg != _MORE and p.arg not in lkw and p.arg not in lpos and not var_kw]
+ return out
+
+
+# --------------------------------------------------------------------------- the tree itself
+def test_the_library_is_thirteen_modules_under_the_starter_tree() -> None:
+ assert LIB_DIR.name == "lib" and (LIB_DIR / "__init__.py").is_file()
+ assert set(MODULES) == {"noise", "mesh", "materials", "terrain", "sky", "lighting", "water", "vegetation",
+ "architecture", "scatter", "place", "figure", "motion"}
+ for stem, path in MODULES.items():
+ lines = path.read_text().splitlines()
+ assert len(lines) < 500, f"{stem}: {len(lines)} lines (the catalog promises small modules)"
+ doc = ast.get_docstring(_tree(stem)) or ""
+ assert doc.startswith(f"lib/{stem}.py"), f"{stem}: the module docstring names another file"
+
+
+# --------------------------------------------------------------------------- the catalog
+def test_the_catalog_has_one_row_per_module_naming_only_real_calls() -> None:
+ """The catalog is the model's only index of the library: a call it names that does not
+ exist is a build error in every scene that trusts it, and a module it leaves out is dead
+ weight in every workspace."""
+ rows = [line for line in CATALOG.splitlines() if line.startswith("| ") and "`lib/" in line]
+ named: list[str] = []
+ for row in rows:
+ mods = _ROW_MODULE.findall(row)
+ assert len(mods) == 1, f"a row names {mods}: one module per row\n{row[:120]}"
+ stem = mods[0]
+ assert stem in MODULES, f"{stem}: no such module"
+ named.append(stem)
+ funcs, classes = _defs(stem)
+ methods = {m for cls in classes.values() for m in cls}
+ for span in _SPAN.findall(row):
+ if m := _CALL.match(span):
+ assert m.group(1) in funcs or m.group(1) in classes, f"lib/{stem}.py has no {m.group(1)!r}"
+ elif m := _METHOD.match(span):
+ assert m.group(1) in methods, f"lib/{stem}.py's class has no method {m.group(1)!r}"
+ assert sorted(named) == sorted(MODULES), (sorted(set(MODULES) - set(named)), sorted(set(named) - set(MODULES)))
+ assert "| Want | Call |" in CATALOG and "## What differs on this renderer" in CATALOG
+
+
+def test_the_catalog_prints_every_signature_with_the_libs_keyword_only_boundary() -> None:
+ """Review 2026-10-15 finding 3: 15 rows printed a REQUIRED keyword-only parameter as if positional
+ (`instance(collection, source, name, x, y, height_at, …)` for a lib `…, x, y, *, height_at`) and 44
+ more an optional one; a zone written from the row raised ``TypeError`` and was dropped from the
+ build. Every printed signature carries the lib's ``*`` exactly where the lib has it, its
+ positional names in the lib's order, and no name the lib lacks."""
+ faults: list[str] = []
+ checked = 0
+ for row in [line for line in CATALOG.splitlines() if line.startswith("| ") and "`lib/" in line]:
+ stem = _ROW_MODULE.findall(row)[0]
+ funcs, classes = _defs(stem)
+ methods = {m: fn for cls in classes.values() for m, fn in cls.items()}
+ for span in _SPAN.findall(row):
+ printed = _printed(span)
+ if printed is None:
+ continue
+ lib = methods.get(printed.name) if span.startswith(".") else (funcs.get(printed.name) or classes.get(printed.name, {}).get("__init__"))
+ if lib is not None:
+ checked += 1
+ faults += [f"lib/{stem}.py `{span}`: {f}" for f in _faults(printed, lib, strict=True)]
+ assert checked > 100, checked
+ assert not faults, "\n".join(faults)
+
+
+def _prose_spans(text: str):
+ """(line, span) for every backticked span of a markdown text outside its fenced code."""
+ in_code = False
+ for n, line in enumerate(text.splitlines(), 1):
+ if line.startswith("```"):
+ in_code = not in_code
+ elif not in_code:
+ for span in _SPAN.findall(line):
+ yield n, span
+
+
+def test_the_cookbook_and_the_bpy_skills_never_print_a_keyword_only_parameter_positionally() -> None:
+ """The weaker rule for prose the catalog does not own (the cookbook's snippets RUN in Blender —
+ tests/prompts/test_snippets_run.py — so only its printed signatures can mislead): a keyword-only
+ parameter is never printed bare, a printed ``*`` sits where the lib's is, every name exists.
+ Lib names are unique across the modules, so a bare name finds its def."""
+ funcs: dict[str, ast.FunctionDef] = {}
+ methods: dict[str, ast.FunctionDef] = {}
+ for stem in MODULES:
+ fs, classes = _defs(stem)
+ for name, fn in fs.items():
+ assert name.startswith("_") or name not in funcs, f"{name!r} is defined in two lib modules"
+ funcs[name] = fn
+ for cls, ms in classes.items():
+ funcs[cls] = ms.get("__init__", funcs.get(cls))
+ methods.update(ms)
+ texts = {"scene_blender/cookbook.md": language_text(Language.SCENE_BLENDER, "cookbook.md")}
+ texts |= {str(md.relative_to(skills_dir().parent)): md.read_text() for md in sorted(skills_dir().glob("c3d-bpy-scene-*/**/*.md"))}
+ assert len(texts) >= 4, sorted(texts) # the cookbook and three SKILL.md at least
+ faults: list[str] = []
+ for where, text in texts.items():
+ for n, span in _prose_spans(text):
+ printed = _printed(span)
+ lib = None if printed is None else (methods.get(printed.name) if span.startswith(".") else funcs.get(printed.name))
+ if lib is not None:
+ faults += [f"{where}:{n} `{span}`: {f}" for f in _faults(printed, lib, strict=False)]
+ assert not faults, "\n".join(faults)
+
+
+# --------------------------------------------------------------------------- the signatures the cookbook cites
+SIGNATURES = [
+ ("noise", "fbm2", ["x", "y", "*", "octaves", "lacunarity", "gain", "seed"]),
+ ("noise", "mountain_height", ["x", "y", "*", "seed", "amplitude", "frequency"]),
+ ("mesh", "Batch.finish", ["collection", "*", "bevel", "parent", "name_prefix"]),
+ ("mesh", "Batch.beam", ["mat", "a", "b", "radius", "end", "sides"]),
+ ("mesh", "curve_object", ["name", "points", "radius", "mat", "collection", "*", "cyclic"]),
+ ("materials", "material", ["name", "color", "roughness", "metal", "*", "noise_scale", "bump", "emission"]),
+ ("materials", "water", ["name", "color", "roughness", "scale", "*", "flow", "ctx"]),
+ ("terrain", "make_height_at", ["*", "seed", "relief", "scale", "flat_radius", "base"]),
+ ("terrain", "ground", ["name", "collection", "*", "size", "segments", "height_at", "material", "center", "smooth"]),
+ ("sky", "sun_world", ["scene", "*", "elevation_deg", "azimuth_deg", "strength", "dust"]),
+ ("sky", "haze", ["collection", "loc", "size", "density", "color", "name"]),
+ ("lighting", "sun", ["collection", "*", "azimuth_deg", "elevation_deg", "color", "energy", "angle_deg", "name"]),
+ ("water", "water_surface", ["name", "collection", "*", "size", "level", "material", "ripple", "seed", "height_fn"]),
+ ("vegetation", "tree", ["batch", "loc", "height", "bark", "foliage", "*", "seed", "kind", "max_leaves"]),
+ ("vegetation", "grass_patch", ["name", "collection", "surface", "*", "blade", "density", "seed", "height", "color"]),
+ ("architecture", "room_shell", ["collection", "mat", "*", "center", "extents", "thickness", "openings", "glazed"]),
+ ("architecture", "text_mesh", ["name", "collection", "body", "loc", "size", "mat", "*", "rotation", "align", "extrude"]),
+ ("scatter", "instance", ["collection", "source", "name", "x", "y", "*", "height_at", "rot_z", "scale", "sink"]),
+ ("scatter", "gn_scatter", ["name", "collection", "surface", "instance_obj", "*", "density", "seed", "align_normal", "scale_range"]),
+ ("place", "seat", ["obj", "height_at", "*", "sink", "columns"]),
+ ("place", "clear_of", ["objs", "min_gap", "*", "overlap"]),
+ ("figure", "figure", ["batch", "cloth", "skin", "center", "*", "scale", "heading", "pose"]),
+ ("motion", "spin", ["obj", "axis", "turns_per_s", "ctx"]),
+ ("motion", "shape_key_sweep", ["obj", "key_name", "ctx", "*", "from_value", "to_value"]),
+]
+
+
[email protected](("stem", "name", "params"), SIGNATURES, ids=[f"{s}.{n}" for s, n, _ in SIGNATURES])
+def test_the_signatures_the_catalog_and_cookbook_cite(stem: str, name: str, params: list[str]) -> None:
+ """Names AND the keyword-only boundary (``"*"``): the prompts cite these by position."""
+ funcs, classes = _defs(stem)
+ fn = classes[name.split(".")[0]][name.split(".")[1]] if "." in name else funcs[name]
+ assert _params(fn) == params
+
+
+def test_every_factory_takes_its_collection_or_batch_explicitly() -> None:
+ """Nothing reads ``bpy.context.collection`` / ``bpy.context.object``: a factory links where it
+ is told (the zone's collection); ``bpy.ops`` never appears (it needs a UI context the build
+ has none of, and rebuilds the scene state on every call); no deprecated ``use_nodes``, no
+ ``ShaderNodeMixRGB`` (the 5.x node is ``ShaderNodeMix``). Read off the AST, not the prose."""
+ from codeverse3d.languages._ast_lint import dotted
+
+ for stem in MODULES:
+ names: set[str] = set()
+ consts: set[str] = set()
+ for node in ast.walk(_tree(stem)):
+ if isinstance(node, (ast.Attribute, ast.Name)):
+ names.add(dotted(node))
+ elif isinstance(node, ast.Constant) and isinstance(node.value, str):
+ consts.add(node.value)
+ assert not [n for n in names if n.startswith(("bpy.ops.", "bpy.context.collection", "bpy.context.object"))], stem
+ assert not [n for n in names if n.endswith(".use_nodes")], stem
+ assert "ShaderNodeMixRGB" not in consts, stem
+
+
+# --------------------------------------------------------------------------- one Blender build
+#: every module exercised in one zone; each thing its own placement row (the gate's unit)
+LIB_CHECK = '''"""lib_check: one representative call per library module, each its own placement row."""
+from lib import architecture, figure, lighting, materials, mesh, motion, place, scatter, sky, terrain, vegetation, water
+from mathutils import Matrix
+
+SEED = 3
+
+
+def build(ctx):
+ rng = ctx.rng(SEED)
+ h = ctx.height_at
+ rock = materials.mineral_surface("CheckRock", "6F6A60", stone=True)
+ wood = materials.woodgrain(materials.material("CheckWood", "6B4A2B"))
+ stone = materials.ashlar("CheckStone", "A89F8C")
+ lime = materials.limestone("CheckLime", "C9BFA8")
+ brick = materials.masonry("CheckBrick", "8B4A3A")
+ alloy = materials.worn_alloy("CheckAlloy", "8C8C90", seed=2)
+ paint = materials.chipped_paint(materials.material("CheckPaint", "2F5F8F"), "2F5F8F", "7A7A72")
+ bark = materials.material("CheckBark", "4A3524", roughness=0.9, noise_scale=6.0)
+ leaves = materials.foliage("CheckLeaf", "4A7A2A", variants=3)
+ coats = [materials.material("CheckCoat", "8A3A3A"), materials.tint(materials.material("CheckCoat2", "3A3A8A"), 0.3),
+ materials.material("CheckSkin", "D9A880")]
+ glow = materials.emissive("CheckGlow", "FFB270", 5.0)
+ glass = materials.glass("CheckGlass")
+ clear = materials.clear_water("CheckClear")
+ foam = water.foam_shader("CheckFoam")
+ materials.snow("CheckSnow")
+ materials.ice("CheckIce")
+ materials.water("CheckFlow", ctx=ctx)
+
+ # mesh: every primitive, a transformed view, a bevel; seated afterwards, spun by a driver
+ b = mesh.Batch("Prims_0")
+ b.box(wood, (-30.0, 24.0, 0.5), (1.0, 0.6, 1.0), rotation=0.3)
+ b.sphere(rock, (-28.0, 24.0, 0.5), 0.5, subdivision=2)
+ b.lathe(alloy, (-26.0, 24.0), [(0.0, 0.0), (0.4, 0.0), (0.3, 0.8), (0.45, 1.2), (0.0, 1.25)], sides=24)
+ b.cone(paint, (-24.0, 24.0, 0.0), 0.4, 1.2, top=0.1)
+ b.beam(wood, (-22.0, 24.0, 0.1), (-21.5, 24.3, 1.5), 0.08, end=0.04)
+ b.torus(alloy, (-20.0, 24.0, 0.3), 0.5, 0.08)
+ b.ring(alloy, (-18.0, 24.0, 0.64), (0.0, 1.0, 0.0), 0.6, 0.04)
+ b.transformed(Matrix.Translation((-16.0, 24.0, 0.0))).box(brick, (0.0, 0.0, 0.5), (1.0, 1.0, 1.0))
+ prims = b.finish(ctx.collection, bevel=0.02)
+ place.seat(prims[0], h)
+ motion.spin(prims[0], "Z", 0.25, ctx)
+ mesh.curve_object("Rope_0", [(-30.0, 28.0, 0.03), (-29.5, 28.5, 0.03), (-29.0, 28.0, 0.03)], 0.03, wood, ctx.collection)
+ tri = mesh.mesh_object("Tri_0", [(-12.0, 24.0, 0.0), (-11.0, 24.0, 0.0), (-12.0, 25.0, 0.0), (-11.5, 24.5, 1.0)],
+ [(0, 1, 3), (1, 2, 3), (2, 0, 3), (0, 2, 1)], rock, ctx.collection)
+ mesh.parent_under([tri], ctx.collection, "Parented_0")
+
+ # terrain recipes stand on h
+ r = mesh.Batch("Rocks_0")
+ terrain.boulder(r, rock, (-8.0, 28.0, h(-8.0, 28.0)), 1.2, seed=1)
+ terrain.rock_field(r, rock, (-4.0, 28.0), 3.0, 10, h, rng)
+ terrain.talus(r, rock, (0.0, 24.0, h(0.0, 24.0)), 2.5, 2)
+ terrain.basalt_column(r, [rock, lime], (4.0, 29.0, h(4.0, 29.0)), 1.6, 2.5, rng, lean=(0.05, 0.0))
+ r.finish(ctx.collection)
+ assert 0.0 <= terrain.shoreline_mask(1.0, 1.0, -0.3, h) <= 1.0
+
+ # vegetation: the four tree kinds, the small plants, a cloud, a stand
+ for i, kind in enumerate(("broadleaf", "oak", "cypress", "pine")):
+ t = mesh.Batch(f"Tree{kind.title()}_0")
+ x = 10.0 + 6.0 * i
+ vegetation.tree(t, (x, 24.0, h(x, 24.0)), 7.0, bark, leaves[i % 3], seed=i, kind=kind, max_leaves=2500)
+ t.finish(ctx.collection)
+ p = mesh.Batch("Plants_0")
+ vegetation.shrub(p, bark, leaves[0], (10.0, 30.0, h(10.0, 30.0)), scale=1.2, seed=4)
+ vegetation.leaf_spray(p, leaves[1], (13.0, 30.0, h(13.0, 30.0) + 0.5), rng)
+ vegetation.fern(p, leaves[2], (16.0, 30.0, h(16.0, 30.0)), seed=2)
+ vegetation.tropical(p, leaves[0], bark, (19.0, 30.0, h(19.0, 30.0)), seed=5)
+ vegetation.grass_clump(p, leaves, 22.0, 30.0, h(22.0, 30.0), rng)
+ vegetation.perennial_bed(p, (26.0, 30.0), 1.5, h, leaves[1], coats[0], rng)
+ p.finish(ctx.collection)
+ patch = terrain.ground("MeadowSurface", ctx.collection, size=6.0, segments=6, height_at=h, material=None, center=(-20.0, 32.0))
+ patch.hide_render = True
+ patch.hide_viewport = True
+ vegetation.grass_patch("Meadow_0", ctx.collection, patch, density=8.0, seed=1)
+ vegetation.tree_stand(ctx.collection, mesh.Batch("Copse_0"), [(-6.0, 40.0), (-3.0, 42.0), (-9.0, 42.0)], h, rng,
+ bark=bark, foliage=leaves[2], height=5.0, kind="oak", max_leaves=600)
+
+ # architecture
+ house = mesh.Batch("CheckHouse_0") # the example already has a House_0: names are global
+ architecture.timber_house(house, {"tile": brick, "trim": wood}, -28.0, 33.0, 6.0, 5.0, 2,
+ {"wall": lime, "timber": wood, "door": paint, "window": glass}, rng, 1)
+ place.seat(house.finish(ctx.collection)[0], h)
+ bridge = mesh.Batch("Bridge_0")
+ architecture.stone_bridge(bridge, stone, rock, center=(-16.0, 38.0, h(-16.0, 38.0)), span=12.0, width=3.0, rise=2.0, height_at=h)
+ bridge.finish(ctx.collection)
+ foot = mesh.Batch("CheckFootbridge_0")
+ architecture.arched_footbridge(foot, wood, stone, start=(2.0, 36.0, h(2.0, 36.0)), end=(7.0, 38.0, h(7.0, 38.0)), rise=1.0, height_at=h)
+ foot.finish(ctx.collection)
+ pav = mesh.Batch("Paving_0")
+ architecture.paving(pav, [lime, stone], center=(12.0, 36.0, h(12.0, 36.0)), inner_r=0.6, rings=3, seed=1)
+ architecture.paving_grid(pav, [lime, stone], (12.0, 40.0, h(12.0, 40.0)), 3.0, 0.5, 0.03, rng)
+ pav.finish(ctx.collection)
+ tow = mesh.Batch("Tower_0")
+ architecture.tower(tow, stone, (18.0, 36.0), 1.5, h(18.0, 36.0), h(18.0, 36.0) + 6.0, glass, count=6)
+ tow.finish(ctx.collection)
+ win = mesh.Batch("Window_0")
+ architecture.fret_window(win, wood, glass, 24.0, 36.0, h(24.0, 36.0), 1.2, 1.6, -90.0, pattern=1)
+ win.finish(ctx.collection)
+ arch = mesh.Batch("Arch_0")
+ architecture.arched_opening(arch, stone, (28.0, 32.0, h(28.0, 32.0)), 2.0, 3.0)
+ roof = arch.transformed(Matrix.Translation((0.0, 0.0, 3.6)))
+ architecture.clay_roof(roof, wood, brick, wood, (28.0, 32.0, h(28.0, 32.0)), 3.0, 2.0, 0.8, rng)
+ architecture.tiled_roof(roof, brick, wood, (28.0, 36.5, h(28.0, 36.5)), 3.0, 2.0, 0.8, rng)
+ arch.finish(ctx.collection)
+ lan = mesh.Batch("Lantern_0")
+ architecture.lantern(lan, glow, wood, (16.0, 44.0, 2.0))
+ hung = lan.finish(ctx.collection)[0]
+ hung["placement"] = "free"
+ motion.sway(hung, "X", 0.1, 2.0, ctx)
+ sign = architecture.text_mesh("Sign_0", ctx.collection, "LIB", (20.0, 42.0, h(20.0, 42.0)), 0.6, paint)
+ place.seat(sign, h)
+ # a glazed room shell (the env's recipe) stood on the ground, so the gate measures it as ONE row
+ cabin = architecture.room_shell(ctx.collection, alloy, center=(0.0, -28.0, h(0.0, -28.0) + 1.6), extents=(4.0, 3.0, 2.8),
+ openings=(("front", 0.0, 1.2, 0.0, 2.2),), glazed=True)
+ assert [o.name for o in cabin[:4]] == ["RoomShell", "RoomShellFloor", "Ceiling", "CeilingGlass"]
+
+ # water
+ fall = water.waterfall("Fall_0", ctx.collection, (6.0, 44.0, h(6.0, 44.0)), width=2.0, height=3.0, ctx=ctx)
+ assert len(fall) == 5
+ water.hanging_fall("Spout_0", ctx.collection, (12.0, 44.0, h(12.0, 44.0) + 2.5), (0.0, -1.0), (1.0, 0.0), width=0.6, height=2.5, ctx=ctx)
+ fountain = mesh.Batch("Fountain_0")
+ spray = water.fountain_jets(fountain, ctx.collection, clear, center=(-2.0, 44.0, h(-2.0, 44.0)), nozzle_r=0.3, landing_r=1.4,
+ count=10, ctx=ctx, seed=3)
+ water.droplets(fountain, foam, (-2.0, 44.0, h(-2.0, 44.0) + 0.3), 1.0, h(-2.0, 44.0), rng, count=60)
+ fountain.finish(ctx.collection)
+ assert spray is not None and spray["placement"] == "free"
+ assert water.pool_height(0.0, 0.0, level=-0.25) == -0.25
+
+ # figures, lights, sky dressing
+ folk = mesh.Batch("Visitors_0")
+ figure.figure(folk, coats[0], coats[2], (-12.0, 44.0, h(-12.0, 44.0)), heading=place.heading((-12.0, 44.0), (0.0, 0.0)), pose=0.5)
+ figure.visitor(folk, coats[1], coats, (-11.0, 45.0, h(-11.0, 45.0)), variant=1)
+ figure.crowd(folk, coats, [(-13.0, 43.0, h(-13.0, 43.0))], rng)
+ folk.finish(ctx.collection)
+ lighting.point_light(ctx.collection, "CheckBulb", (-2.0, 44.0, 2.0), "FFD9A0", 60.0)
+ lighting.spot(ctx.collection, "CheckSpot", (3.0, 40.0, 4.0), "FFFFFF", 300.0, target=(2.0, 36.0, 0.0))
+ lighting.practical(ctx.collection, "CheckPractical", (16.0, 44.0, 1.7))
+ sky.aurora("AuroraSky_0", ctx.collection, (0.0, 80.0, 120.0), ctx=ctx)
+ stars = mesh.Batch("Stars_0")
+ sky.stars(stars, glow, seed=1, count=200)
+ stars.finish(ctx.collection)[0]["placement"] = "free"
+
+ # scatter + place: an instance, a scatter, a stack, the self-checks, a keyframed drift
+ crate = ctx.assets["crate"]
+ one = scatter.instance(ctx.collection, crate, "LibCrate_0", -14.0, 44.0, height_at=h, rot_z=0.4)
+ yaw = place.face_toward(one, (0.0, 0.0))
+ place.keep_inside(one, ((-14.0, 44.0, 0.0), (6.0, 6.0, 6.0)))
+ # the same size and yaw as the base: a smaller or turned crate's corner columns overhang the
+ # open-topped base, which the gate (rightly) reads as floating
+ top = scatter.instance(ctx.collection, crate, "StackedCrate_0", -14.0, 44.0, height_at=h, rot_z=yaw, scale=1.0)
+ place.rest_on(top, one)
+ pts = scatter.poisson(rng, area=(0.0, 40.0, 4.0, 43.0), min_dist=1.4, max_count=2, mask=lambda x, y: 1.0)
+ assert len(pts) == 2
+ scatter.scatter(ctx.collection, crate, "CheckCrate", pts, height_at=h, rng=rng, scale=(0.8, 1.1))
+ assert len(scatter.along_path([(0.0, 0.0), (10.0, 0.0)], 5, jitter=0.2, rng=rng)) == 5
+ assert len(scatter.grid((0.0, 0.0), 4.0, 2.0, rng)) == 4
+ assert place.clear_of([prims[0], one, hung]) == []
+ motion.drift(one, (0.0, 0.5, 0.0), ctx)
+ flag = mesh.mesh_object("Flag_0", [(24.0, 40.0, 0.0), (25.0, 40.0, 0.0), (25.0, 40.0, 1.2), (24.0, 40.0, 1.2)], [(0, 1, 2, 3)],
+ coats[1], ctx.collection)
+ flag.shape_key_add(name="Basis")
+ key = flag.shape_key_add(name="Wave")
+ key.data[2].co.y += 0.3
+ motion.shape_key_sweep(flag, "Wave", ctx)
+ return ctx.collection
+'''
+
+#: the catalog's per-call ceilings, on the GLB the gate reads (evaluated triangles per root)
+CEILINGS = {
+ "Prims_0": 12_000, "Rocks_0": 4_000, "TreeBroadleaf_0": 9_000, "TreeOak_0": 9_000, "TreeCypress_0": 9_000, "TreePine_0": 600,
+ "Plants_0": 3_000, "Copse_0": 5_000, "CheckHouse_0": 14_000, "Bridge_0": 1_500, "CheckFootbridge_0": 2_000, "Paving_0": 4_000,
+ "Tower_0": 1_500, "Window_0": 400, "Arch_0": 6_000, "Lantern_0": 800, "Sign_0": 2_000, "Fall_0": 2_500, "Spout_0": 600,
+ "Fountain_0": 6_000, "Visitors_0": 2_000, "Stars_0": 600, "RoomShell": 2_000,
+}
+SEATED = {"Prims_0", "Rope_0", "Parented_0", "Rocks_0", "TreeBroadleaf_0", "TreeOak_0", "TreeCypress_0", "TreePine_0", "Plants_0",
+ "Copse_0", "CheckHouse_0", "Bridge_0", "CheckFootbridge_0", "Paving_0", "Tower_0", "Window_0", "Arch_0", "Sign_0",
+ "Fall_0", "Spout_0", "Fountain_0", "Visitors_0", "LibCrate_0", "StackedCrate_0", "CheckCrate_0", "CheckCrate_1", "Flag_0",
+ "RoomShell"}
+EXEMPT = {"Meadow_0": "instanced", "Lantern_0": "free", "Fountain_0Spray_0": "free", "AuroraSky_0": "free", "Stars_0": "free"}
+
+
+def _glb_json(path: Path) -> dict:
+ data = path.read_bytes()
+ assert data[:4] == b"glTF"
+ length = struct.unpack_from("<I", data, 12)[0]
+ return json.loads(data[20:20 + length])
+
+
+def _subtree_tris(g: dict, ix: int) -> int:
+ node = g["nodes"][ix]
+ n = 0
+ if "mesh" in node:
+ per = sum(g["accessors"][p["indices"]]["count"] // 3 for p in g["meshes"][node["mesh"]]["primitives"])
+ inst = node.get("extensions", {}).get("EXT_mesh_gpu_instancing")
+ n += per * (g["accessors"][inst["attributes"]["TRANSLATION"]]["count"] if inst else 1)
+ return n + sum(_subtree_tris(g, c) for c in node.get("children", []))
+
+
+@needs_blender
+@needs_browser
+def test_one_blender_build_seats_what_every_factory_makes(tmp_ws) -> None:
+ """The example scene plus a zone that calls every module, built ONCE through the wrapper
+ and measured by the gate's own placement table: every root rests on what is under it
+ (no floating, no burial past the 10 cm WARN), the clouds and hanging things carry their
+ exemption, no name was deduplicated, every driver is simple, nothing touched the render
+ settings, and each root stays under the catalog's triangle ceiling."""
+ rt = get_runtime(Language.SCENE_BLENDER)
+ write_example(tmp_ws)
+ (tmp_ws.src / "zones" / "lib_check.py").write_text(LIB_CHECK)
+ cams = [CameraPlan(name="overview", position=(0.0, 28.0, 75.0), look_at=(0.0, 0.0, -20.0), fov=50.0)]
+ (tmp_ws.src / "scene.py").write_text(render_scene_py(["hamlet", "lakeside", "orchard", "lib_check"], ["crate", "lantern_post"], [], cams))
+ assert rt.lint(tmp_ws).passed
+ res = rt.build(tmp_ws)
+ assert res.ok, res.stdout_tail
+ report = json.loads((tmp_ws.artifacts / "bpy_build.json").read_text())
+ assert report["errors"] == [] and not [w for w in report["warnings"] if "render settings" in w], report
+ assert res.census["bpy"]["drivers_invalid"] == [] and res.census["bpy"]["handlers"] == []
+ rows = {r["name"]: r for r in res.census["placement"]["assets"]}
+ check = {n: r for n, r in rows.items() if r.get("zone") == "LibCheck"}
+ assert set(check) >= SEATED, sorted(SEATED - set(check))
+ for name in SEATED:
+ r = check[name]
+ assert r["supported"] and not r["floating"], (name, r)
+ assert r["sunk_m"] <= 0.10, (name, r["sunk_m"], r["sunk_into"])
+ for name, why in EXEMPT.items():
+ assert check[name]["exempt"] == why, (name, check[name].get("exempt"))
+ assert check["StackedCrate_0"]["support"] == "LibCrate_0"
+ # the example's own rows are seated too, and nothing interpenetrates
+ for r in rows.values():
+ if not r["exempt"]:
+ assert r["supported"] and not r["floating"] and r["sunk_m"] <= 0.10, r
+ assert res.census["placement"]["interpenetrations"] == []
+ # names: no Blender dedupe suffix anywhere, every root once
+ g = _glb_json(tmp_ws.artifacts / "census.glb")
+ zone = next(n for n in g["nodes"] if n["name"] == "LibCheck")
+ roots = [g["nodes"][c]["name"] for c in zone["children"]]
+ assert len(roots) == len(set(roots)) and not [n for n in roots if re.search(r"\.\d{3}$", n)], roots
+ tris = {g["nodes"][c]["name"]: _subtree_tris(g, c) for c in zone["children"]}
+ over = {n: (tris[n], cap) for n, cap in CEILINGS.items() if tris[n] > cap}
+ assert not over, over
+ assert all(tris[n] > 0 for n in CEILINGS)
+
+
+# --------------------------------------------------------------------------- the glazed room shell
+#: the real ``room_shell`` twice in one factory scene — glazed and opaque, the same doors — and the
+#: share of the floor a high sun cannot reach, walked through the panes (they cast no shadow)
+GLAZED_CHECK = r'''
+import json
+import math
+import sys
+
+import bpy
+
+sys.path.insert(0, sys.argv[sys.argv.index("--") + 1])
+from lib.architecture import room_shell
+from lib.materials import material
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+iron = material("Iron", "1F2B24", roughness=0.55, metal=0.6)
+wall = material("Wall", "B8AE9A", roughness=0.85)
+doors = (("front", 2.0, 3.0, 0.0, 3.0), ("left", -1.0, 2.0, 1.0, 2.6))
+glazed = room_shell(sc.collection, iron, center=(0.0, 0.0, 5.0), extents=(20.0, 16.0, 10.0), openings=doors, glazed=True)
+opaque = room_shell(sc.collection, wall, center=(100.0, 0.0, 5.0), extents=(20.0, 16.0, 10.0), openings=doors)
+dg = bpy.context.evaluated_depsgraph_get()
+n = math.sqrt(1.0 + 0.25 + 1.96)
+sun = (1.0 / n, 0.5 / n, 1.4 / n) # towards a high sun
+
+
+def shaded(cx):
+ """The share of floor points whose ray to the sun a shadow-casting object stops."""
+ blocked = total = 0
+ for i in range(-4, 5):
+ for j in range(-3, 4):
+ origin, total = (cx + i * 1.9, j * 1.9, 0.02), total + 1
+ for _ in range(8): # walk on through a pane: it casts no shadow
+ hit, loc, _normal, _index, ob, _matrix = sc.ray_cast(dg, origin, sun)
+ if not hit:
+ break
+ if ob.visible_shadow:
+ blocked += 1
+ break
+ origin = tuple(loc[k] + sun[k] * 0.01 for k in range(3))
+ return blocked / total
+
+
+def row(ob, dedupe=""):
+ me = ob.data
+ return {"name": ob.name.removesuffix(dedupe), "parent": ob.parent.name if ob.parent else None, "shadow": ob.visible_shadow,
+ "material": me.materials[0].name if me and me.materials else None, "verts": len(me.vertices) if me else 0,
+ "dims": [max(v.co[k] for v in me.vertices) - min(v.co[k] for v in me.vertices) for k in range(3)] if me else None}
+
+
+pane = bpy.data.materials["RoomShellGlass"].node_tree.nodes["Principled BSDF"].inputs["Transmission Weight"].default_value
+# names are global in Blender: the second shell's came back deduped (RoomShell.001); the first's are the pin
+print("C3D " + json.dumps({"glazed": [row(o) for o in glazed], "opaque": [row(o, ".001") for o in opaque], "transmission": pane,
+ "shaded": shaded(0.0), "shaded_opaque": shaded(100.0)}))
+'''
+
+
+@needs_blender
+def test_a_glazed_room_shell_is_glass_on_an_iron_frame_that_lets_the_sun_in(tmp_path: Path) -> None:
+ """Review 2026-10-15 findings 1 / 7: the glass-house env brief called ``room_shell(…, glazed=True)``
+ and the lib had no such option (a ``TypeError`` dropped the whole env stage). Now it has: the
+ same panels under the same names (the lid still ``Ceiling`` under ``RoomShell``, for the rig),
+ each a frame of ``mat`` bars plus a 2 cm ``materials.glass`` twin (``…Glass``) that casts no
+ shadow, the floor an opaque slab of ``mat`` — and between the bars the sun reaches the floor
+ that the opaque shell shades completely (the three.js ``roomShell`` test's own measure)."""
+ from codeverse3d.languages.blender import blender_env
+ from codeverse3d.languages.scene_blender import STARTER_DIR
+ from codeverse3d.proc import run_subprocess
+
+ script = tmp_path / "glazed_check.py"
+ script.write_text(GLAZED_CHECK)
+ proc = run_subprocess([get_settings().resolve_blender(), "-b", "--factory-startup", "--python", str(script), "--", str(STARTER_DIR)],
+ cwd=tmp_path, env=blender_env(), timeout_s=180)
+ assert proc.returncode == 0, proc.stderr[-2000:] + proc.stdout[-2000:]
+ got = json.loads(next(line[4:] for line in proc.stdout.splitlines() if line.startswith("C3D ")))
+ glazed = {r["name"]: r for r in got["glazed"]}
+ opaque = {r["name"]: r for r in got["opaque"]}
+ panels = set(opaque) - {"RoomShell", "RoomShellFloor"}
+ assert {"Ceiling", "RoomShellWallBack", "RoomShellWallFront_0", "RoomShellWallFront_0Lintel", "RoomShellWallLeft_0Sill"} <= panels, sorted(panels)
+ assert set(glazed) == set(opaque) | {f"{n}Glass" for n in panels}, sorted(set(glazed) ^ set(opaque))
+ assert [r["name"] for r in got["glazed"][:4]] == ["RoomShell", "RoomShellFloor", "Ceiling", "CeilingGlass"]
+ assert all(r["parent"] == "RoomShell" for n, r in glazed.items() if n != "RoomShell")
+ floor = glazed["RoomShellFloor"]
+ assert (floor["material"], floor["shadow"], floor["verts"]) == ("Iron", True, 8) and floor["dims"] == pytest.approx(opaque["RoomShellFloor"]["dims"], abs=1e-3)
+ for n in panels:
+ frame, pane, slab = glazed[n], glazed[f"{n}Glass"], opaque[n]
+ thin = 2 if n == "Ceiling" else 1 if "Front" in n or "Back" in n else 0
+ assert frame["material"] == "Iron" and frame["shadow"] and frame["verts"] >= 32 and frame["verts"] % 8 == 0, (n, frame) # ≥ 4 edge bars
+ assert pane["material"] == "RoomShellGlass" and not pane["shadow"] and pane["verts"] == 8, (n, pane)
+ assert pane["dims"][thin] == pytest.approx(0.02, abs=1e-3) and slab["dims"][thin] == pytest.approx(0.2, abs=1e-3), (n, pane["dims"], slab["dims"])
+ assert [pane["dims"][k] for k in range(3) if k != thin] == pytest.approx([slab["dims"][k] for k in range(3) if k != thin], abs=1e-3), n
+ assert got["transmission"] == 1.0
+ assert got["shaded_opaque"] == 1.0 and got["shaded"] < 0.3, (got["shaded"], got["shaded_opaque"])
diff --git a/harness/tests/scene_blender/test_lint.py b/harness/tests/scene_blender/test_lint.py
index 2b7c14e3..4a58e1f7 100644
--- a/harness/tests/scene_blender/test_lint.py
+++ b/harness/tests/scene_blender/test_lint.py
@@ -4,15 +4,17 @@ from __future__ import annotations
import pytest
-from codeverse3d.contracts.artifacts import Severity
+from codeverse3d.contracts.artifacts import LintKind, Severity
from codeverse3d.contracts.common import Track
from codeverse3d.contracts.plan import ScenePlan
from codeverse3d.languages._ast_lint import BASE_FORBIDDEN_IMPORTS
from codeverse3d.languages.scene_blender import (
FORBIDDEN_IMPORTS,
+ lib_files,
lint,
lint_scene_source,
simple_driver,
+ write_example,
write_skeleton,
)
from codeverse3d.tracks.planner import plan_example
@@ -133,6 +135,27 @@ def test_the_skeleton_lints_clean(tmp_ws) -> None:
assert rep.passed and not [f for f in rep.findings if f.severity is not Severity.INFO], rep.findings
+def test_the_example_scene_lints_clean(tmp_ws) -> None:
+ """The plan-less starter is what an agent reads as the worked example of the library."""
+ write_example(tmp_ws)
+ rep = lint(tmp_ws)
+ assert rep.passed and not [f for f in rep.findings if f.severity is not Severity.INFO], rep.findings
+
+
[email protected]("path", lib_files(), ids=[p.stem for p in lib_files()])
+def test_the_library_passes_the_agent_lint_itself(path) -> None:
+ """The workspace gate reads ``src/lib/`` for syntax only — but agents COPY what they read, so
+ every module must also pass the policy an agent's file is held to: no trap API, no unseeded
+ randomness, no bpy.ops, no clock or file access. ``sky.py`` holds the world setters, which
+ only ``src/env.py`` may call, so it is linted in the env role (minus the env's own
+ ``build_env`` / ``height_at`` export requirement)."""
+ role = "env" if path.stem == "sky" else "helper"
+ findings = lint_scene_source(path.read_text(), target=f"src/lib/{path.name}", role=role)
+ bad = [f for f in findings if f.severity is not Severity.INFO
+ and not (role == "env" and f.data.get("kind") == LintKind.LAYOUT.value)]
+ assert not bad, [(f.severity.value, f.message) for f in bad]
+
+
def test_a_missing_entry_is_a_lint_error(tmp_ws) -> None:
rep = lint(tmp_ws)
assert not rep.passed and rep.errors[0].target == "src/scene.py"
diff --git a/harness/tests/scene_blender/test_prompts.py b/harness/tests/scene_blender/test_prompts.py
new file mode 100644
index 00000000..2c9fa9a4
--- /dev/null
+++ b/harness/tests/scene_blender/test_prompts.py
@@ -0,0 +1,460 @@
+"""scene_blender's prompt corpus and the track plumbing behind it (offline): the files a bpy session
+reads, the chapters the stages inline, the bpy templates over a bpy plan (Z-up numbers, D12), the
+planner's template / example / schema per language, the asset stage's ``bpy`` dispatch and check,
+the per-language asset API / shims / catalog rows, the env-file lookup, the stage transport retry and
+the two manifest scenarios (unblessed here; the integrator blesses)."""
+
+from __future__ import annotations
+
+import ast
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from codeverse3d.contracts.agent import AgentResult
+from codeverse3d.contracts.common import Language, Track, Usage
+from codeverse3d.contracts.plan import ScenePlan, ZoneLayout
+from codeverse3d.languages.scene_blender import LIB_DIR
+from codeverse3d.proc import EventLog
+from codeverse3d.prompts import PROMPTS_DIR, render
+from codeverse3d.prompts.catalog import language_text
+from codeverse3d.prompts.sections import find_section, split_sections
+from codeverse3d.skills import skills_dir
+from codeverse3d.tracks import scene_assets as SA
+from codeverse3d.tracks.planner import (
+ build_system_prompt,
+ plan,
+ plan_example,
+ plan_schema,
+ plan_template,
+)
+from codeverse3d.tracks.prompting import cookbook_sections, language_system_prompt
+from codeverse3d.tracks.scene import (
+ ENV_FILES,
+ ENV_RECIPES,
+ SCENE_TEMPLATES,
+ ZONE_RECIPES,
+ SceneTrack,
+ _guess_target,
+ env_file,
+ plan_bbox_line,
+ refine_recipes,
+ scene_templates,
+)
+from codeverse3d.tracks.scene_assets import (
+ AssetCheck,
+ asset_api_summary,
+ library_rows,
+ run_asset_stage,
+ write_variant_shims,
+)
+from codeverse3d.tracks.zone_layout import layout_block
+from codeverse3d.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeChatModel,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+ _planner,
+ small_scene,
+)
+from tests.orchestrator_tracks.test_prompts_assets import _ctx
+
+BPY = Language.SCENE_BLENDER
+
+
+def settings(tmp_path):
+ from codeverse3d.config import Settings
+
+ return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")
+
+
+# --------------------------------------------------------------------------- the files
+def test_the_language_ships_its_four_prompt_files_and_the_system_prompt_knows_about_tools() -> None:
+ for name in ("system.md", "contract.md", "cookbook.md", "asset.md"):
+ assert language_text(BPY, name).strip(), name
+ with_tools, without = language_system_prompt(BPY, tools=True), language_system_prompt(BPY, tools=False)
+ assert "check_placement" in with_tools and "single-shot" not in with_tools
+ assert "single-shot" in without and "`build` →" not in without
+ assert "Blender 5.2" in with_tools
+ for text in (language_text(BPY, "contract.md"), language_text(BPY, "cookbook.md")):
+ assert "use_nodes" in text and "MULTIPLE_SCATTERING" in text # Blender 5.2 facts (D104), not 4.x ones
+ assert "Action.fcurves" in text and "mod.properties.inputs" in text
+
+
+def test_the_cookbook_has_every_chapter_the_stages_inline() -> None:
+ """``cookbook_sections`` finds a chapter by title (exact, then substring): every ENV / ZONE recipe
+ must resolve to ITS chapter, not to the word-overlap fallback."""
+ md = language_text(BPY, "cookbook.md")
+ sections = split_sections(md)
+ for title in (*ENV_RECIPES, *ZONE_RECIPES):
+ found = find_section(sections, title)
+ assert found is not None and title.lower() in found.title.lower(), (title, found and found.title)
+ ctx = SimpleNamespace(cookbook_text=md)
+ env_text, zone_text = cookbook_sections(ctx, ENV_RECIPES), cookbook_sections(ctx, ZONE_RECIPES)
+ assert "# role: env" in env_text and "MULTIPLE_SCATTERING" in env_text and "TIME_OF_DAY" in env_text
+ for token in ("tree_mesh", "clustered_points", "camera_mask", "keyframe_linear", "along_seam", "rock_geometry"):
+ assert token in zone_text, token
+ assert len(zone_text) > 12_000 and "# role: env" not in zone_text
+
+
+def _clear_of_loops(text: str) -> list[ast.For]:
+ """Every ``for … in clear_of(…)`` header ``text`` shows (fenced or not), parsed as the code a model copies."""
+ loops: list[ast.For] = []
+ for line in text.splitlines():
+ head = line.strip()
+ if head.startswith("for ") and "clear_of(" in head:
+ try:
+ node = ast.parse(head + "\n pass").body[0]
+ except SyntaxError:
+ pytest.fail(f"{head!r} is not a python loop header")
+ assert isinstance(node, ast.For), head
+ loops.append(node)
+ return loops
+
+
+def test_every_clear_of_loop_a_model_is_shown_unpacks_the_libs_three_names() -> None:
+ """``lib.place.clear_of`` returns ``(name_a, name_b, fraction)`` rows — NAMES, not objects: a
+ ``for a, b in clear_of(…)`` copied from a prompt raises on the first overlap it was meant to
+ report and the wrapper drops the zone. Every loop the prompt files, the bpy templates and the
+ placement skill show unpacks three names, and the contract's example states the library's own
+ overlap threshold (read off ``lib/place.py``, not restated)."""
+ sources = (sorted((PROMPTS_DIR / "scene_blender").glob("*.md")) + sorted((PROMPTS_DIR / "tracks").glob("*_bpy.j2"))
+ + sorted((skills_dir() / "c3d-bpy-scene-placement").rglob("*.md")))
+ loops = {p.name: _clear_of_loops(p.read_text(encoding="utf-8")) for p in sources}
+ assert loops["contract.md"] and loops["finding-to-fix.md"], loops # the two worked examples are there to be checked
+ for name, found in loops.items():
+ for node in found:
+ assert isinstance(node.target, ast.Tuple) and len(node.target.elts) == 3, \
+ f"{name}: {ast.unparse(node).splitlines()[0]} must unpack (name_a, name_b, fraction)"
+ place = ast.parse((LIB_DIR / "place.py").read_text(encoding="utf-8"))
+ fn = next(n for n in place.body if isinstance(n, ast.FunctionDef) and n.name == "clear_of")
+ overlap = dict(zip([a.arg for a in fn.args.kwonlyargs], fn.args.kw_defaults, strict=True))["overlap"]
+ assert isinstance(overlap, ast.Constant)
+ assert f"more than {round(overlap.value * 100)} % of the smaller box" in language_text(BPY, "contract.md")
+
+
+# --------------------------------------------------------------------------- the templates over a bpy plan
+def _bpy_ctx(tmp_ws, settings, *, agent=None, agent_id="fake:x", services=None):
+ plan_obj = small_scene(BPY)
+ spec = make_spec(Track.SCENE, BPY)
+ ctx = _ctx(tmp_ws, settings, spec, plan_obj, agent_id=agent_id, services=services, agent=agent)
+ ctx.cookbook_text = language_text(BPY, "cookbook.md")
+ ctx.extra["asset_api"] = asset_api_summary(plan_obj, {}, language=BPY)
+ return ctx, plan_obj
+
+
+def test_the_bpy_templates_render_with_the_plan_in_the_z_up_frame(tmp_ws, settings) -> None:
+ """The plan stays Y-up (D12); every number the bpy author reads is converted: the harbour's
+ bounds centre (0, 5, 0) prints as (0, 0, 5), the Quay zone (-20, 1.2, 0) / 40 × 3 × 60 as
+ (-20, 0, 1.2) / 40 × 60 × 3, a camera at (45, 18, 55) as (45, -55, 18)."""
+ ctx, plan_obj = _bpy_ctx(tmp_ws, settings)
+ st = SceneTrack(services=ctx.services)
+ t = scene_templates(BPY)
+ quay = plan_obj.zones[0]
+ env = render(t.env, **st._ctx(ctx, recipes=cookbook_sections(ctx, ENV_RECIPES)))
+ assert "write `src/env.py`" in env and "centre (0.000, 0.000, 5.000) m" in env and "build_env(ctx)" in env
+ assert "# role: env" in env # the recipes travel inside the brief
+ zone = render(t.zone, **st._ctx(ctx, recipes="", zone_name=quay.name, zone_description=quay.description,
+ zone_bbox=plan_bbox_line(quay.bbox, BPY), zone_contents=quay.contents, zone_file="src/zones/quay.py",
+ neighbours=[], layout=layout_block({"zone": "Quay", "placements": [
+ {"asset": "Bollard", "count": 2, "cluster": [3.0, -4.0], "spread_m": 0.5}]}, language=BPY)))
+ assert "centre (-20.000, 0.000, 1.200) m, extents (40.000, 60.000, 3.000) m" in zone
+ assert "position (45.0, -55.0, 18.0)" in zone and "2x Bollard around (3.0, 4.0)" in zone
+ assert "ctx.assets['bollard']" in zone and "def build(ctx)" in zone and "import {" not in zone
+ refine = render(t.refine, **st._ctx(ctx, recipes=refine_recipes(ctx, ["src/env.py"]), round_index=1, tasks=["t"], targets=["Quay"],
+ files=["src/env.py"], edit_only_these=False, judge_summary="j", current_files={}))
+ assert "src/env.py" in refine and "src/scene.py" in refine and "Horizon: the world must not end" in refine
+ # the three.js templates still print the plan's own numbers (the identity conversion): byte-identical prompts
+ assert "centre (0.000, 5.000, 0.000) m" in plan_bbox_line(plan_obj.bounds, Language.SCENE_THREEJS)
+ assert SCENE_TEMPLATES[Language.SCENE_THREEJS].env == "tracks/scene_env.j2"
+
+
+def test_layout_block_prints_ground_points_in_the_authoring_frame() -> None:
+ lay = ZoneLayout(zone="Quay", placements=[{"asset": "Bollard", "count": 3, "cluster": (3.0, -4.0), "spread_m": 1.0},
+ {"asset": "Crate", "count": 2, "cluster": (3.0, 0.0), "spread_m": 1.0}],
+ path_points=[(1.0, 2.0), (-5.0, 0.5), (2.0, 0.0)])
+ js, py = layout_block(lay), layout_block(lay, language="scene_blender")
+ assert "around (3.0, -4.0)" in js and "around (3.0, 0.0)" in js and "(1.0, 2.0) -> (-5.0, 0.5) -> (2.0, 0.0)" in js
+ assert "around (3.0, 4.0)" in py and "around (3.0, 0.0)" in py and "(1.0, -2.0) -> (-5.0, -0.5) -> (2.0, 0.0)" in py
+ assert "-0.0" not in py # z = 0 is the director's default cluster line: the negated zero is folded, never printed
+ assert layout_block(lay, language=Language.SCENE_THREEJS) == js
+
+
+# --------------------------------------------------------------------------- the planner
+def test_the_planner_picks_the_bpy_template_example_and_schema_per_language(tmp_ws) -> None:
+ assert plan_template(Track.SCENE, BPY) == "tracks/plan_scene_bpy.j2"
+ assert plan_template(Track.SCENE, Language.SCENE_THREEJS) == plan_template(Track.SCENE) == "tracks/plan_scene.j2"
+ js, py = plan_example(Track.SCENE), plan_example(Track.SCENE, BPY)
+ assert {a["kind"] for a in py["assets"]} == {"bpy", "blender_glb"}
+ assert py["bounds"] == js["bounds"] and py["zones"] == js["zones"] and py["cameras"] == js["cameras"] # the same Y-up numbers
+ spec = make_spec(Track.SCENE, BPY)
+ system = build_system_prompt(spec, ScenePlan)
+ assert "SHIPPED BPY LIBRARY" in system and '"kind": "bpy"' in system and "Y-up GLB frame" in system
+ schema = plan_schema(spec, ScenePlan)
+ assert schema["$defs"]["AssetPlan"]["properties"]["kind"]["enum"] == ["bpy", "blender_glb"]
+ # ...and the planner CALL carries that schema (a scene_threejs call carries the model's own)
+ model = FakeChatModel(lambda req: py)
+ out = plan(spec, "fake:planner", ScenePlan, tmp_ws, model=model)
+ assert {a.kind for a in out.assets} == {"bpy", "blender_glb"}
+ assert model.requests[-1].response_schema["$defs"]["AssetPlan"]["properties"]["kind"]["enum"] == ["bpy", "blender_glb"]
+ model_js = FakeChatModel(lambda req: js)
+ plan(make_spec(Track.SCENE, Language.SCENE_THREEJS), "fake:planner", ScenePlan, tmp_ws, model=model_js)
+ assert model_js.requests[-1].response_schema == ScenePlan.model_json_schema()
+
+
+# --------------------------------------------------------------------------- the asset stage
+def _bpy_module(job, ws):
+ rel = job.files_hint[0]
+ return {rel: f"import bpy # {job.label}\n\n\ndef build_{rel.rsplit('/', 1)[-1][:-3]}(ctx, variant=0):\n return ctx.collection\n"}
+
+
+def test_bpy_assets_climb_the_ladder_through_check_bpy_asset_and_are_reused(tmp_ws, settings, monkeypatch) -> None:
+ seen: list[tuple[str, str]] = []
+
+ def fake_check(ctx, rel, snake, *, expected_size_m=None, timeout_s=None):
+ seen.append((rel, snake))
+ ok = f"def build_{snake}(" in (ctx.ws.root / rel).read_text()
+ return AssetCheck(ok=ok, ran=True, fatal=not ok, size_m=expected_size_m, tris=300, meshes=2, materials=2,
+ errors=[] if ok else ["no builder"])
+
+ monkeypatch.setattr(SA, "check_bpy_asset", fake_check)
+ agent = FakeAgent(_bpy_module)
+ ctx, plan_obj = _bpy_ctx(tmp_ws, settings, agent=agent)
+ ctx.runtime.skeleton(tmp_ws, plan_obj)
+ tmp_ws.commit("skeleton")
+ results = run_asset_stage(ctx)
+ assert {n: (r.ok, r.path, r.strategy) for n, r in results.items()} == {
+ "FishingBoat": (True, "src/assets/fishing_boat.py", "agent"), "Bollard": (True, "src/assets/bollard.py", "agent")}
+ assert results["Bollard"].size_m == plan_obj.assets[1].approx_size_m
+ assert set(seen) == {("src/assets/fishing_boat.py", "fishing_boat"), ("src/assets/bollard.py", "bollard")}
+ for job in agent.jobs: # the bpy asset sheet + the bpy asset system prompt, edit-only in the shared workspace
+ assert "variant=0" in job.prompt and "ctx.collection" in job.prompt and "THREE" not in job.prompt
+ assert "instanced by the Blender zones" in job.system_append and job.edit_only
+ n_jobs = len(agent.jobs)
+ again = run_asset_stage(ctx) # S2 reuse: a committed module whose check passes is not re-paid
+ assert len(agent.jobs) == n_jobs and {r.strategy for r in again.values()} == {"reused"}
+ events = [e for e in EventLog(tmp_ws.events_path).read() if e["event"] == "asset.generated"]
+ assert [e["strategy"] for e in events] == ["agent", "agent", "reused", "reused"]
+
+
+def test_check_bpy_asset_without_a_blender_runtime_and_its_throw_away_workspace(tmp_ws, settings) -> None:
+ ctx, plan_obj = _bpy_ctx(tmp_ws, settings)
+ missing = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")
+ assert missing.ran and missing.fatal and "was not written" in missing.errors[0]
+ ctx.runtime.skeleton(tmp_ws, plan_obj)
+ unavailable = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard") # FakeRuntime has no run_wrapper
+ assert unavailable.ok and not unavailable.ran and "checker unavailable" in unavailable.warnings[0]
+ (tmp_ws.src / "lib").mkdir(parents=True)
+ (tmp_ws.src / "lib" / "place.py").write_text("def seat(obj, height_at):\n return 0.0\n")
+ scratch = SA._bpy_check_workspace(tmp_ws, "src/assets/bollard.py", "bollard")
+ assert scratch.root == (tmp_ws.root / "_assets" / "bollard_check").resolve()
+ entry = (scratch.root / "src" / "scene.py").read_text()
+ assert 'ASSETS = {\n "bollard": "Bollard",\n}' in entry and "ZONES = {}" in entry and "HEROES = {}" in entry
+ assert (scratch.src / "assets" / "bollard.py").read_text() == (tmp_ws.src / "assets" / "bollard.py").read_text()
+ assert (scratch.src / "lib" / "place.py").is_file()
+ probe = (scratch.src / "zones" / f"{SA.BPY_CHECK_ZONE}.py").read_text()
+ assert "ctx.assets['bollard']" in probe and 'instance_type = "COLLECTION"' in probe
+ # the wrapper's isolated-stage report maps to the check: a raise is fatal with its line, a clean build is measured
+
+ class _Run:
+ def __init__(self, report, ok=True, *, error_type="Timeout", harness_failure=False):
+ self.report, self.facts = report, {"unique_tris": 12}
+ self.result = SimpleNamespace(ok=ok, error_type=error_type if not ok else "", error_message="killed" if not ok else "",
+ harness_failure=harness_failure)
+
+ class _Runtime(FakeRuntime):
+ def __init__(self, report, ok=True, **result):
+ super().__init__(BPY)
+ self._report, self._ok, self._result = report, ok, result
+
+ def run_wrapper(self, ws, out_dir, *, zones=None, blend=True, timeout_s=None):
+ assert zones == {SA.BPY_CHECK_ZONE: "Check"} and blend is False and ws.root.name == "bollard_check"
+ return _Run(self._report, self._ok, **self._result)
+
+ ctx.runtime = _Runtime({"errors": [{"stage": "asset", "name": "bollard", "error_type": "KeyError", "error_message": "'x'",
+ "error_file": "src/assets/bollard.py", "error_line": 7}]})
+ raised = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")
+ assert raised.fatal and raised.errors == ["src/assets/bollard.py:7: KeyError: 'x'"]
+ ctx.runtime = _Runtime({"errors": []}, ok=False)
+ killed = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")
+ assert killed.fatal and "did not finish" in killed.errors[0] and "Timeout" in killed.errors[0]
+ # the harness's own census-GLB writer failed AFTER the module built (run_bpy_scene's CensusGlbError →
+ # BuildResult.harness_failure): not the module's doing, so the ladder spends no repair rung on it
+ ctx.runtime = _Runtime({"errors": [], "error_type": "CensusGlbError"}, ok=False, error_type="CensusGlbError", harness_failure=True)
+ census = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")
+ assert census.ok and not census.ran and not census.fatal and census.warnings == ["checker unavailable: CensusGlbError"]
+ module_error = {"stage": "asset", "name": "bollard", "error_type": "KeyError", "error_message": "'x'",
+ "error_file": "src/assets/bollard.py", "error_line": 7}
+ ctx.runtime = _Runtime({"errors": [module_error], "error_type": "CensusGlbError"}, ok=False, error_type="CensusGlbError",
+ harness_failure=True)
+ both = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard") # the module's own raise still wins
+ assert both.fatal and both.errors == ["src/assets/bollard.py:7: KeyError: 'x'"]
+ ctx.runtime = _Runtime({"errors": [{"stage": "zone", "name": SA.BPY_CHECK_ZONE, "error_type": "KeyError", "error_message": "'bollard'"}]})
+ nothing = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")
+ assert nothing.fatal and "returned no Collection" in nothing.errors[0]
+
+
+def test_the_asset_api_speaks_each_scene_language(tmp_ws, settings) -> None:
+ plan_obj = ScenePlan.model_validate(plan_example(Track.SCENE, BPY))
+ boat, bollard, crate = plan_obj.assets
+ results = {"FishingBoat": SA.AssetResult(name="FishingBoat", kind="bpy", ok=True, path="src/assets/fishing_boat.py", size_m=(8.0, 3.5, 3.0)),
+ "Crate": SA.AssetResult(name="Crate", kind="blender_glb", ok=True, path="public/assets/crate.glb", clips=1)}
+ api = asset_api_summary(plan_obj, results, {"Bollard": "FishingBoat"}, language=BPY)
+ lines = api.splitlines()
+ assert lines[0].startswith("Sizes are width × height × depth") and "lib.scatter.instance" in lines[0]
+ assert "- FishingBoat: `ctx.assets['fishing_boat']` — built by the harness from `src/assets/fishing_boat.py` (`build_fishing_boat(ctx, variant=0)`), 8.00×3.50×3.00 m (w×h×d)" in api
+ assert "- Bollard: `ctx.assets['bollard']` — variant fishing_boat builds" in api and "harness shim onto `build_fishing_boat`" in api
+ assert "- Crate: `ctx.assets['crate']` — the hero GLB `public/assets/crate.glb` imported by the harness" in api
+ assert "carries 1 keyframed motion clip(s)" in api and "NOT AVAILABLE" not in api
+ assert "[NOT AVAILABLE — do not reference]" in asset_api_summary(plan_obj, {}, language=BPY)
+ # the three.js wording is untouched (its tests pin it): no header line, import + clone instructions
+ js = asset_api_summary(plan_example_scene(), {})
+ assert js.startswith("- FishingBoat: `import { buildFishingBoat }") and "Sizes are" not in js
+
+
+def plan_example_scene() -> ScenePlan:
+ return ScenePlan.model_validate(plan_example(Track.SCENE))
+
+
+def test_variant_shims_and_catalog_rows_per_language(tmp_ws, monkeypatch) -> None:
+ alias = {"PondRock": "SteppingStone"}
+ py = write_variant_shims(tmp_ws, alias, {"SteppingStone"}, language=BPY)
+ assert py == ["src/assets/pond_rock.py"]
+ shim = (tmp_ws.src / "assets" / "pond_rock.py").read_text()
+ assert "from assets.stepping_stone import build_stepping_stone" in shim and "def build_pond_rock(ctx, variant=1):" in shim
+ compile(shim, "pond_rock.py", "exec")
+ js = write_variant_shims(tmp_ws, alias, {"SteppingStone"})
+ assert js == ["src/assets/pond_rock.js"] and "buildSteppingStone(THREE, { variant: 1, ...opts })" in (tmp_ws.src / "assets" / "pond_rock.js").read_text()
+ assert write_variant_shims(tmp_ws, alias, set(), language=BPY) == [] # a survivor that failed shims nothing
+ catalog = ("| Want | Call |\n| --- | --- |\n"
+ "| a tree | `tree(batch, loc, height, bark, foliage, *, seed=0, kind=\"broadleaf\")` — `lib/vegetation.py` |\n"
+ "| a boulder | `boulder(batch, mat, center, scale, *, seed=0)` — `lib/terrain.py` |\n")
+ monkeypatch.setattr(SA, "language_text", lambda lang, name: catalog if (lang, name) == (BPY, "effects_catalog.md") else "")
+ assert "lib/vegetation.py" in library_rows("a shrine with a tree beside it", BPY)
+ assert "lib/terrain.py" in library_rows("a well ringed by lib/terrain.py boulders", BPY)
+ assert library_rows("a plain bench", BPY) == "" and library_rows("a shrine with a tree", Language.BLENDER) == ""
+
+
+# --------------------------------------------------------------------------- track plumbing
+def test_env_file_recipes_and_console_targets_follow_the_runtime(tmp_ws, settings) -> None:
+ ctx, plan_obj = _bpy_ctx(tmp_ws, settings)
+ assert env_file(ctx) == ENV_FILES[BPY] == "src/env.py" and ctx.runtime.env_file == "src/env.py"
+ ctx.runtime = SimpleNamespace(zone_file=ctx.runtime.zone_file) # a runtime without the attribute: the typed table
+ assert env_file(ctx) == "src/env.py"
+ assert _guess_target("Traceback: src/env.py:12 ValueError", ctx) == "env"
+ assert _guess_target("KeyError in src/scene.py", ctx) == "composition"
+ assert _guess_target("zone quay raised KeyError", ctx) == "Quay" and _guess_target("nothing named", ctx) == "overall"
+ env_only = refine_recipes(ctx, ["src/env.py"])
+ zones_only = refine_recipes(ctx, ["src/zones/quay.py"])
+ assert "# role: env" in env_only and "tree_mesh" not in env_only
+ assert "tree_mesh" in zones_only and "# role: env" not in zones_only
+ assert refine_recipes(ctx, ["src/assets/bollard.py"]) == zones_only # neither env nor a zone: the zone chapters
+
+
+class _TransientOnceAgent(FakeAgent):
+ """The first session with ``label`` dies of a provider failure (typed transient); the rest work."""
+
+ def __init__(self, writer, label: str, *, transient: bool = True):
+ super().__init__(writer)
+ self.label, self.transient, self.died = label, transient, False
+
+ def run(self, job):
+ if job.label == self.label and not self.died:
+ self.died = True
+ self.jobs.append(job)
+ return AgentResult(ok=False, exit_reason="error", errors=["rc=247; 503 UNAVAILABLE"], usage=Usage(cost_usd=0.01),
+ transient=self.transient)
+ return super().run(job)
+
+
+def _zone_writer(job, ws):
+ return {rel: f"import bpy # {job.label}\n\n\ndef build(ctx):\n return ctx.collection\n" for rel in job.files_hint} or {
+ "src/env.py": f"import bpy # {job.label}\n\n\ndef height_at(x, y):\n return 0.0\n\n\ndef build_env(ctx):\n return {{}}\n"}
+
+
[email protected]("transient", [True, False], ids=["transient", "declined"])
+def test_an_env_session_killed_by_the_provider_is_retried_once(tmp_path, settings, transient: bool) -> None:
+ """The round loop's transport-retry rule, applied to a stage session (env / zones): ONE re-run under
+ the ``.a2`` label when the session died transient and the budget allows; a non-transient failure
+ is the stage's verdict."""
+ # no assets: the asset stage runs beside the env stage, and a file it writes during the env session would be
+ # attributed to the env task (generation._attributed_fallback), which is a different story from this one
+ plan_obj = small_scene(BPY).model_copy(update={"assets": []})
+ for zone in plan_obj.zones:
+ zone.contents = []
+ agent = _TransientOnceAgent(_zone_writer, "env", transient=transient)
+ ws = Workspace(tmp_path / "runs" / "retry")
+ track = SceneTrack(services=FakeServices(assemble=True), judge=FakeJudge(scores=(0.6,)), agent=agent,
+ planner_model=_planner(plan_obj.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(BPY))
+ track.run(make_spec(Track.SCENE, BPY, max_rounds=0), ws)
+ labels = [j.label for j in agent.jobs if j.label.startswith("env")]
+ events = [e for e in EventLog(ws.events_path).read() if e["event"] == "stage.transport_retry"]
+ stage = json.loads((ws.root / "stages" / "env.json").read_text())["result"] # the cached stage: what a resume serves
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ if transient:
+ assert labels == ["env", "env.a2"] and [(e["stage"], e["label"]) for e in events] == [("env", "env")]
+ assert stage["ok"] is True and "src/env.py" in stage["files"] and "generate.silent_bail" not in kinds
+ else:
+ # a session that merely declined gets the generation layer's own silent-bail nudge (same label), never
+ # the transport retry: the stage's second session is that nudge
+ assert labels == ["env", "env"] and events == [] and "generate.silent_bail" in kinds
+
+
+def test_check_bpy_asset_measures_a_module_in_blender(tmp_ws, settings) -> None:
+ """The real check: the skeleton's one-box stub builds in its throw-away workspace, measures at the plan's
+ size (Y-up w × h × d off the census GLB) and fails the placeholder rule; a two-part module passes."""
+ from codeverse3d.config import get_settings
+ from codeverse3d.languages import get_runtime
+
+ if not get_settings().resolve_blender():
+ pytest.skip("no Blender binary configured")
+ ctx, plan_obj = _bpy_ctx(tmp_ws, settings)
+ ctx.runtime = get_runtime(BPY)
+ ctx.runtime.skeleton(tmp_ws, plan_obj)
+ bollard = next(a for a in plan_obj.assets if a.name == "Bollard")
+ stub = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard", expected_size_m=bollard.approx_size_m)
+ assert stub.ran and not stub.fatal and not stub.ok and stub.size_m == pytest.approx(bollard.approx_size_m, abs=0.01)
+ assert stub.tris == 12 and stub.meshes == 1 and "single low-poly box" in stub.errors[0]
+ assert (tmp_ws.root / "_assets" / "bollard_check" / "artifacts" / "census.glb").is_file()
+ (tmp_ws.src / "assets" / "bollard.py").write_text(
+ "import bmesh\nimport bpy\n\n\ndef _part(ctx, name, size, z, rgb):\n"
+ " mat = bpy.data.materials.new(name + 'Mat')\n"
+ " mat.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (*rgb, 1.0)\n"
+ " me = bpy.data.meshes.new(name)\n bm = bmesh.new()\n bmesh.ops.create_cube(bm, size=1.0)\n"
+ " bmesh.ops.scale(bm, vec=size, verts=bm.verts)\n bmesh.ops.translate(bm, vec=(0.0, 0.0, z), verts=bm.verts)\n"
+ " bm.to_mesh(me)\n bm.free()\n me.materials.append(mat)\n"
+ " ctx.collection.objects.link(bpy.data.objects.new(name, me))\n\n\n"
+ "def build_bollard(ctx, variant=0):\n"
+ " _part(ctx, 'BollardBase', (0.3, 0.3, 0.1), 0.05, (0.2, 0.2, 0.22))\n"
+ " _part(ctx, 'BollardPost', (0.2, 0.2, 0.4), 0.3, (0.1, 0.1, 0.12))\n"
+ " return ctx.collection\n")
+ good = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard", expected_size_m=bollard.approx_size_m)
+ # (FakeServices.measure counts no materials; the real measure does — the placeholder rule reads meshes + tris here)
+ assert good.ok and good.ran and good.meshes == 2 and good.tris == 24 and good.min_y == pytest.approx(0.0, abs=0.01), good
+ (tmp_ws.src / "assets" / "bollard.py").write_text("import bpy\n\n\ndef build_bollard(ctx, variant=0):\n raise KeyError('x')\n")
+ raised = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")
+ assert raised.fatal and raised.errors[0].startswith("src/assets/bollard.py:5: KeyError")
+
+
+def test_the_scene_blender_manifest_scenarios_run(tmp_path) -> None:
+ """Both scenarios run end to end offline and capture the bpy payloads (their hashes are blessed by
+ the integrator: tests/prompts/test_manifest.py is expected red until then)."""
+ from tests.prompts.manifest import run_scenario
+
+ agent = run_scenario("scene.scene_blender.agent.fresh", tmp_path / "agent").payloads
+ assert "src/env.py" in agent["job:env@r00/prompt"] and "build_env(ctx)" in agent["job:env@r00/prompt"]
+ assert "def build(ctx)" in agent["job:zones_quay_water@r00/prompt"]
+ assert "bpy" in agent["chat:planner:planner/sampling"] and '"threejs"' not in agent["chat:planner:planner/sampling"]
+ assert any(k.startswith("chat:model:asset_bollard") for k in agent), sorted(agent)[:20] # the single-shot rung ran
+ single = run_scenario("scene.scene_blender.single_shot.fresh", tmp_path / "single").payloads
+ assert "src/env.py" in single["chat:model:env:r00/messages"] and "bpy" in single["chat:planner:planner/sampling"]
+ systems = {k: v for k, v in single.items() if k.startswith("chat:model:") and k.endswith("/system")}
+ assert systems and all("Blender bpy author" in v and "three.js + GLSL author" not in v for k, v in systems.items()
+ if k.startswith(("chat:model:env", "chat:model:zones")))
+ assert all("bpy asset module" in v for k, v in systems.items() if k.startswith("chat:model:asset_"))
diff --git a/harness/tests/scene_gates/test_frame_metrics.py b/harness/tests/scene_gates/test_frame_metrics.py
index 71425baa..4daa2c37 100644
--- a/harness/tests/scene_gates/test_frame_metrics.py
+++ b/harness/tests/scene_gates/test_frame_metrics.py
@@ -107,7 +107,7 @@ def test_content_small_roles():
def test_scene_rubric_caps_fire_on_frame_kinds():
- rubric = load_rubric("scene_v1")
+ rubric = load_rubric("scene_v2")
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}
@@ -230,3 +230,16 @@ def test_a_slow_blender_frame_set_warns_and_names_the_heaviest_zone():
# a three.js payload (no blender block) never reads render_ms
three = {k: v for k, v in payload(60_000).items() if k not in ("blender", "language")}
assert not [f for f in frame_findings(three).findings if f.data.get("kind") == "slow_frame"]
+
+
+def test_the_hero_size_is_one_instance_and_names_its_copies():
+ """`glb_assets[].size_m` is ONE placed instance (scene_host glbUsage, 2026-10-14; the union of every
+ clone read "6.5 m across" for a 2.2 m sofa placed three times) and the text says how many copies."""
+ url = "/assets/athanor.glb"
+ rows = [{"url": url, "meshes": 9, "meshes_in_scene": 9, "in_scene": True, "size_m": 2.2, "instances": 3}]
+ rep = frame_findings({"census": {"glb_assets": rows}, "camera_checks": [_chk("AthanorDetail", glb_frac={url: 0.0})]})
+ msg = next(f.message for f in rep.findings if f.data["kind"] == "hero_unseen")
+ assert "(2.2 m across as placed, 3 copies)" in msg
+ rows[0]["instances"] = 1
+ rep = frame_findings({"census": {"glb_assets": rows}, "camera_checks": [_chk("AthanorDetail", glb_frac={url: 0.0})]})
+ assert "(2.2 m across as placed)" in next(f.message for f in rep.findings if f.data["kind"] == "hero_unseen")
diff --git a/harness/tests/scene_gates/test_judge_views.py b/harness/tests/scene_gates/test_judge_views.py
index d275d440..b2c26bb9 100644
--- a/harness/tests/scene_gates/test_judge_views.py
+++ b/harness/tests/scene_gates/test_judge_views.py
@@ -19,14 +19,16 @@ def _rs(times=(0.0, 1.5), authored=AUTHORED, orbit=True) -> RenderSet:
def test_default_selection_is_authored_plus_overviews():
rs = _rs()
- assert len(rs.views) == 18
+ assert len(rs.views) == 2 * (3 + 7)
sel = select_judge_views(rs)
- assert len(sel.views) == 8 <= JUDGE_MAX_VIEWS == 10
+ # 3 authored + the 4 overview tiles (scene_v2: the contact camera is the fourth) + 2 at t=1.5
+ assert len(sel.views) == 9 <= JUDGE_MAX_VIEWS == 10
keys = [(v.name, v.time_s) for v in sel.views]
# authored t=0, the overview rig t=0, first two authored at t=1.5
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 and ("overview_top", 0.0) in keys
+ for n in ("overview_front_right", "overview_back_left", "overview_top", "overview_low_front"):
+ assert (n, 0.0) in keys, n
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)
@@ -34,7 +36,20 @@ def test_default_selection_is_authored_plus_overviews():
assert not any(n.startswith("eye_") for n, _ 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
+ assert len(rs.views) == 20 and sel.contact_sheet == rs.contact_sheet
+
+
+def test_the_rig_has_four_judged_overviews_and_the_contact_camera_is_the_fourth():
+ """scene_v2: ``overview_low_front`` (az 20°, el 7°) is in the rig, judged, and fitted as the
+ contact camera (orbit.mjs takes elevation < 10° to fitContactCamera); the eye rig stays diagnostic."""
+ from codeverse3d.spatial.render_scene import MAX_JUDGE_OVERVIEWS
+
+ overviews = [v for v in SCENE_VIEWS if v.name.startswith("overview")]
+ assert [v.name for v in overviews] == ["overview_front_right", "overview_back_left", "overview_top", "overview_low_front"]
+ assert MAX_JUDGE_OVERVIEWS == len(overviews) == 4
+ low = next(v for v in SCENE_VIEWS if v.name == "overview_low_front")
+ assert (low.azimuth_deg, low.elevation_deg) == (20.0, 7.0) and low.elevation_deg < 10
+ assert all(10 <= v.elevation_deg <= 20 for v in SCENE_VIEWS if v.name.startswith("eye_"))
def test_small_sets_pass_through():
diff --git a/harness/tests/scene_gates/test_live_frames.py b/harness/tests/scene_gates/test_live_frames.py
index 322863ae..34daf81b 100644
--- a/harness/tests/scene_gates/test_live_frames.py
+++ b/harness/tests/scene_gates/test_live_frames.py
@@ -75,9 +75,10 @@ def test_example_scene_passes_frame_gate_and_judge_subset(starter_ws: Workspace)
assert rs.out_dir == str(out)
assert all(v.judge is not None for v in rs.views)
stamped = {(v.name, v.time_s) for v in rs.views if v.judge}
- # 3 authored at t=0 + the 3 overview-rig tiles + the first two authored at t=1.5;
- # the harness's eye-level rig is a diagnostic and never reaches the judge
- assert len(stamped) == 8 <= JUDGE_MAX_VIEWS
+ # 3 authored at t=0 + the 4 overview-rig tiles (scene_v2: the contact camera is the fourth)
+ # + the first two authored at t=1.5; the harness's eye-level rig is a diagnostic and never
+ # reaches the judge
+ assert len(stamped) == 9 <= JUDGE_MAX_VIEWS
assert not any(n.startswith("eye_") for n, _ in stamped)
assert stamped == {(v.name, v.time_s) for v in select_judge_views(rs).views}
# motion is measured from the written frames and persisted for the gate / judge context
diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.py
index 45b2e459..d16aa4bf 100644
--- a/harness/tests/scene_gates/test_placement.py
+++ b/harness/tests/scene_gates/test_placement.py
@@ -7,9 +7,11 @@ from types import SimpleNamespace
import pytest
+from codeverse3d.config import Placement, get_settings
from codeverse3d.contracts.artifacts import BuildResult, Severity
from codeverse3d.contracts.common import Language
from codeverse3d.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
+from codeverse3d.spatial.node import runtime_js_dir
from codeverse3d.spatial.scene_placement import (
GATE,
infer_indoor,
@@ -20,10 +22,16 @@ from codeverse3d.spatial.scene_placement import (
from codeverse3d.tracks.scene import ScenePipeline
-def _row(name, zone="Yard", gap=0.0, support="Ground", sunk=0.0, into="", water=False, attached=(), h=1.0, exempt=""):
- return {"name": name, "zone": zone, "exempt": exempt, "meshes": 1, "columns": 3,
- "bbox": {"min": [0, 0, 0], "max": [1, h, 1], "size": [1, h, 1]}, "ground_gap_m": gap, "support": support,
- "sunk_m": sunk, "sunk_into": into, "on_water": water, "attached": list(attached)}
+def _row(name, zone="Yard", gap=0.0, support="Ground", sunk=0.0, into="", water=False, attached=(), h=1.0, exempt="",
+ columns=3, gap_max=None, resting=None, tilt=None):
+ row = {"name": name, "zone": zone, "exempt": exempt, "meshes": 1, "columns": columns,
+ "bbox": {"min": [0, 0, 0], "max": [1, h, 1], "size": [1, h, 1]}, "ground_gap_m": gap, "support": support,
+ "sunk_m": sunk, "sunk_into": into, "on_water": water, "attached": list(attached)}
+ # the column measures host_placement.mjs added on 2026-10-14; a row without them is an older census
+ for key, v in (("gap_max_m", gap_max), ("columns_resting", resting), ("tilt_m", tilt)):
+ if v is not None:
+ row[key] = v
+ return row
def _table(*rows, pairs=(), **over):
@@ -38,16 +46,47 @@ def _by_kind(report, kind):
def test_floating_severity_by_gap_then_by_count():
- r = placement_findings(_table(_row("Lantern", gap=0.3), _row("Cup", gap=0.08, support="Table")))
+ """Settings.placement (strict since 2026-10-14): a hover past floating_error_m 0.08 m is an ERROR,
+ under it a WARN — and more than floating_error_count 2 hovers make every one an ERROR."""
+ p = get_settings().placement
+ assert (p.floating_error_m, p.floating_error_count) == (0.08, 2)
+ r = placement_findings(_table(_row("Lantern", gap=0.3), _row("Cup", gap=0.07, support="Table")))
fl = _by_kind(r, "floating")
assert {f.target: f.severity for f in fl} == {"Yard/Lantern": Severity.ERROR, "Yard/Cup": Severity.WARN}
lantern = next(f for f in fl if f.target == "Yard/Lantern")
assert "floating 0.30 m above Ground" in lantern.message and "lower Yard/Lantern by 0.30 m" in lantern.fix_hint
assert "userData.placement = 'free'" in lantern.fix_hint
assert not r.passed
- # more than FLOATING_ERROR_COUNT small hovers → every one is an ERROR
- many = placement_findings(_table(*[_row(f"P{i}", gap=0.07) for i in range(4)]))
- assert all(f.severity == Severity.ERROR for f in _by_kind(many, "floating")) and not many.passed
+ # a 9 cm hover is past the strict line (a WARN under the 2026-09 0.15 m)
+ assert _by_kind(placement_findings(_table(_row("Cup", gap=0.09, support="Table"))), "floating")[0].severity == Severity.ERROR
+ # up to floating_error_count small hovers are WARNs; one more and every one is an ERROR
+ two = placement_findings(_table(*[_row(f"P{i}", gap=0.07) for i in range(2)]))
+ assert all(f.severity == Severity.WARN for f in _by_kind(two, "floating")) and two.passed
+ three = placement_findings(_table(*[_row(f"P{i}", gap=0.07) for i in range(3)]))
+ assert all(f.severity == Severity.ERROR for f in _by_kind(three, "floating")) and not three.passed
+
+
+def test_thresholds_are_read_from_settings_when_the_gate_runs(switch):
+ """An A/B child's ``C3D_PLACEMENT__*`` is what its rounds are judged by (read at call time, never
+ at import); an explicit ``thresholds=`` wins over the process settings; the summary records them."""
+ t = _table(_row("Lantern", gap=0.3))
+ assert _by_kind(placement_findings(t), "floating")[0].severity == Severity.ERROR
+ switch("C3D_PLACEMENT__FLOATING_ERROR_M", "0.5")
+ lenient = placement_findings(t)
+ assert _by_kind(lenient, "floating")[0].severity == Severity.WARN
+ assert lenient.findings[0].data["thresholds"]["floating_error_m"] == 0.5
+ assert "ERROR past 50 cm" in lenient.findings[0].message
+ strict = placement_findings(t, thresholds=Placement(floating_error_m=0.1))
+ assert _by_kind(strict, "floating")[0].severity == Severity.ERROR
+ assert strict.findings[0].data["thresholds"]["floating_error_m"] == 0.1
+
+
+def test_the_probe_s_overlap_floor_is_the_default_warn_level():
+ """host_placement.mjs reports pairs past OVERLAP_MIN_FRAC and the gate WARNs past overlap_warn:
+ the two are one number, or the strict WARN band would have nothing to read (0.20 → 0.10, D105)."""
+ js = (runtime_js_dir() / "lib" / "host_placement.mjs").read_text(encoding="utf-8")
+ assert f"export const OVERLAP_MIN_FRAC = {Placement().overlap_warn:.2f};" in js
+ assert Placement().overlap_warn == 0.10 and Placement().overlap_error == 0.35
@pytest.mark.parametrize("row", [
@@ -71,10 +110,13 @@ def test_indoor_tolerance_is_tighter():
def test_sunken_thresholds_height_fraction_and_name_words():
+ """sunk_m 0.10 WARN; sunk_error_m 0.20 AND sunk_error_frac 20 % of the height ERROR (the strict
+ 2026-10-14 numbers; 0.30 + 25 % before); name words from placement_words.json."""
r = placement_findings(_table(
- _row("Bench", sunk=0.15, into="Terrain", h=0.9), # WARN: > 0.10 m
- _row("Statue", sunk=0.35, into="Terrain", h=2.0), # WARN: > 0.30 m but only 17 % of its height
- _row("Lantern", sunk=0.4, into="Terrain", h=0.6), # ERROR: > 0.30 m and > 25 %
+ _row("Bench", sunk=0.15, into="Terrain", h=0.9), # WARN: > 0.10 m but under 0.20
+ _row("Statue", sunk=0.35, into="Terrain", h=2.0), # WARN: > 0.20 m but only 17 % of its height
+ _row("Crate", sunk=0.25, into="Terrain", h=1.0), # ERROR: > 0.20 m and 25 % (a WARN under 0.30 + 25 %)
+ _row("Lantern", sunk=0.4, into="Terrain", h=0.6), # ERROR: > 0.20 m and > 20 %
_row("Rock", sunk=0.45, into="Terrain", h=1.2), # starter-scene rock: 37 % buried is fine
_row("Boulder", sunk=0.8, into="Terrain", h=1.0), # 80 % buried → ERROR even for a rock
_row("PondBasin", sunk=1.4, into="Terrain", h=1.2), # dug in by definition
@@ -83,7 +125,8 @@ def test_sunken_thresholds_height_fraction_and_name_words():
_row("Jetty", sunk=0.97, into="Terrain", h=1.1, water=True), # posts in the pond bed
))
sev = {f.target: f.severity for f in _by_kind(r, "sunken")}
- assert sev == {"Yard/Bench": Severity.WARN, "Yard/Statue": Severity.WARN, "Yard/Lantern": Severity.ERROR, "Yard/Boulder": Severity.ERROR}
+ assert sev == {"Yard/Bench": Severity.WARN, "Yard/Statue": Severity.WARN, "Yard/Crate": Severity.ERROR,
+ "Yard/Lantern": Severity.ERROR, "Yard/Boulder": Severity.ERROR}
lantern = next(f for f in r.findings if f.target == "Yard/Lantern")
assert "sunken 0.40 m into Terrain" in lantern.message and "raise Yard/Lantern by 0.40 m" in lantern.fix_hint
@@ -93,7 +136,11 @@ def test_findings_are_capped_per_kind_and_the_summary_counts_them():
fl = _by_kind(r, "floating")
assert len(fl) == 8 and fl[0].data["gap_m"] >= fl[-1].data["gap_m"] # worst first
assert any(f.data.get("kind") == "truncated" and "4 more floating" in f.message for f in r.findings)
- assert "8 floating" in r.findings[0].message
+ # the summary counts what was MEASURED (the judge's measured block, the loop's diagnosis) and
+ # says how many the per-kind cap left in the prompt
+ summary = r.findings[0]
+ assert "12 (8 listed) floating" in summary.message
+ assert summary.data["counts"]["floating"] == 12 and summary.data["listed"]["floating"] == 8
def test_probe_error_is_a_warning_that_passes():
@@ -242,6 +289,21 @@ def test_interpenetration_pairs_report_once_at_worst_overlap():
assert len(inter) == 1 and "70%" in inter[0].message and inter[0].severity == Severity.ERROR
+def test_interpenetration_bands_are_the_strict_ones():
+ """overlap_warn 0.10 / overlap_error 0.35 (0.20 / 0.60 before): a 12 % overlap is a WARN now
+ that the probe measures it at all, a 40 % one an ERROR; an arm that raises overlap_warn
+ filters what the probe reported below it."""
+ rows = (_row("Crate"), _row("Wall"), _row("Bench"), _row("Tree"))
+ pairs = [{"a": "Crate", "b": "Wall", "zone_a": "Yard", "zone_b": "Yard", "aabb_overlap": 0.12, "inside_frac": 0.11},
+ {"a": "Bench", "b": "Tree", "zone_a": "Yard", "zone_b": "Yard", "aabb_overlap": 0.4, "inside_frac": 0.3}]
+ sev = {f.target: f.severity for f in _by_kind(placement_findings(_table(*rows, pairs=pairs)), "interpenetration")}
+ assert sev == {"Yard/Crate": Severity.WARN, "Yard/Bench": Severity.ERROR}
+ hint = _by_kind(placement_findings(_table(*rows, pairs=pairs)), "interpenetration")[0].fix_hint
+ assert "share ≤ 10%" in hint
+ lenient = placement_findings(_table(*rows, pairs=pairs), thresholds=Placement(overlap_warn=0.3, overlap_error=0.6))
+ assert {f.target: f.severity for f in _by_kind(lenient, "interpenetration")} == {"Yard/Bench": Severity.WARN}
+
+
def test_density_gate_fires_on_a_zone_far_under_its_layout_budget():
layouts = {"Yard": {"placements": [{"asset": "Lantern", "count": 6}],
"mid_props": 20, "small_props": 40, "ground_cover": 400},
@@ -323,3 +385,92 @@ def test_blender_census_gets_bpy_words_in_placement_hints():
gate = placement_gate_safe(census, plan={"title": "t", "setting": "outdoor", "zones": []})
no_fog = next(f for f in gate.findings if f.data.get("kind") == "no_fog")
assert "Volume" in no_fog.fix_hint and "THREE.Fog" not in no_fog.fix_hint
+
+
+# --------------------------------------------------------------------- the strict pass (2026-10-14)
+def test_free_exempt_share_is_one_finding_naming_the_tagged_assets():
+ """'free' exempts an asset from every check; w1_tearoom (argon) tagged 17 of 36. The share of
+ tagged assets among those that would otherwise be checked is a WARN past free_exempt_warn (25 %)
+ and an ERROR past free_exempt_error (50 %), once at least two are tagged; per-language fix."""
+ p = get_settings().placement
+ assert (p.free_exempt_warn, p.free_exempt_error) == (0.25, 0.5)
+ stood = [_row(f"Bench{i}") for i in range(6)]
+ quiet = placement_findings(_table(*stood, _row("Lantern", exempt="free"), _row("Bird", exempt="free"))) # 2 of 8 = 25 %
+ assert _by_kind(quiet, "free_exempt") == [] and quiet.findings[0].data["free"] == 2
+ warn = placement_findings(_table(*stood, *[_row(f"Kite{i}", exempt="free") for i in range(3)])) # 3 of 9 = 33 %
+ f = _by_kind(warn, "free_exempt")
+ assert len(f) == 1 and f[0].severity == Severity.WARN and f[0].target == "scene"
+ assert "3 of 9 placed assets are tagged placement='free' (33%)" in f[0].message and "Yard/Kite0, Yard/Kite1, Yard/Kite2" in f[0].message
+ assert "hanging / airborne things only" in f[0].fix_hint and "heightAt(x, z)" in f[0].fix_hint
+ assert f[0].data["names"] == ["Yard/Kite0", "Yard/Kite1", "Yard/Kite2"] and f[0].data["share"] == 0.333
+ error = placement_findings(_table(_row("Bench"), _row("Table"), *[_row(f"Prop{i}", exempt="free") for i in range(4)]),
+ language="scene_blender") # 4 of 6 = 67 %
+ f = _by_kind(error, "free_exempt")
+ assert f[0].severity == Severity.ERROR and not error.passed and 'obj["placement"] = "free"' in f[0].fix_hint
+ assert "4 tagged free (67%)" in error.findings[0].message
+ # one hanging lantern beside one bench is 50 % — the floor of two tagged rows keeps it quiet
+ assert _by_kind(placement_findings(_table(_row("Bench"), _row("Lantern", exempt="free"))), "free_exempt") == []
+ # the levels are Settings
+ assert _by_kind(placement_findings(_table(*stood, _row("A", exempt="free"), _row("B", exempt="free")),
+ thresholds=Placement(free_exempt_warn=0.2)), "free_exempt")[0].severity == Severity.WARN
+
+
+def test_cantilevered_rests_on_one_of_four_columns():
+ """Seated at its lowest column, hanging at the others (a crate seated by its lowest corner on a
+ slope): a WARN naming the columns and the far hang; not for slope-following names, fewer than
+ four columns, a hang within the floating tolerance, an attached asset, or an older row."""
+ crate = _row("Crate", gap=0.0, columns=4, gap_max=0.36, resting=1, tilt=0.36)
+ r = placement_findings(_table(crate))
+ f = _by_kind(r, "cantilevered")
+ assert len(f) == 1 and f[0].severity == Severity.WARN and r.passed
+ assert f[0].message == "Yard/Crate rests on 1 of its 4 foot columns: the others hang up to 0.36 m above Ground (tilt 0.36 m)"
+ assert "seat every foot" in f[0].fix_hint and "userData.placement = 'free'" in f[0].fix_hint
+ assert f[0].data["gap_max_m"] == 0.36 and f[0].data["columns_resting"] == 1 and f[0].data["bbox"]["size"] == [1, 1, 1]
+ assert "1 cantilevered" in r.findings[0].message and r.findings[0].data["counts"]["cantilevered"] == 1
+ # a rock buried at one corner and hanging elsewhere is the same lean
+ rock = _row("Rock", gap=0.0, sunk=0.05, into="Ground", columns=5, gap_max=0.3, resting=1, tilt=0.3)
+ assert len(_by_kind(placement_findings(_table(rock)), "cantilevered")) == 1
+ for quiet in (
+ _row("GardenStairs", gap=0.0, columns=4, gap_max=0.36, resting=1, tilt=0.36), # slope-ok: uneven by construction
+ _row("Crate", gap=0.0, columns=3, gap_max=0.36, resting=1, tilt=0.36), # an edge or a corner of three
+ _row("Crate", gap=0.0, columns=4, gap_max=0.04, resting=1, tilt=0.04), # within the floating tolerance
+ _row("Crate", gap=0.0, columns=4, gap_max=0.36, resting=2, tilt=0.36), # an edge rests
+ _row("Shelf", gap=0.0, columns=4, gap_max=0.36, resting=1, tilt=0.36, attached=("Wall",)), # mounted
+ _row("Crate", gap=0.0, columns=4), # a census from before the measure
+ ):
+ assert _by_kind(placement_findings(_table(quiet)), "cantilevered") == [], quiet["name"]
+ # the hang threshold is the outdoor floating tolerance from Settings
+ assert _by_kind(placement_findings(_table(crate), thresholds=Placement(floating_outdoor_m=0.4)), "cantilevered") == []
+
+
+def test_every_asset_and_pair_finding_carries_its_box():
+ """``data.bbox`` = GLB-frame centre + size from the row: the judge's contact crops aim at it."""
+ far = _row("FarCrate")
+ far["bbox"] = {"min": [100, 0, 100], "max": [101, 1, 101], "size": [1, 1, 1]}
+ census = {"fog": {"type": "Fog"}, "background": "#aabbcc", "placement": _table(
+ _row("Lantern", gap=0.3, h=3.0), _row("Cup", gap=0.03, support="Table"), _row("Bench", sunk=0.25, into="Terrain"),
+ _row("Crate", gap=0.0, columns=4, gap_max=0.36, resting=1, tilt=0.36), _row("Planter"), _row("Arbor"), far,
+ pairs=[{"a": "Planter", "b": "Arbor", "zone_a": "Yard", "zone_b": "Yard", "aabb_overlap": 0.5, "inside_frac": 0.4}])}
+ rep = placement_gate_safe(census, plan=_contract_plan())
+ per_asset = {"floating", "unsupported", "sunken", "cantilevered", "interpenetration", "scale", "out_of_bounds"}
+ boxes = {f.data["kind"]: f.data.get("bbox") for f in rep.findings if f.data["kind"] in per_asset}
+ assert set(boxes) == per_asset
+ assert boxes["floating"] == {"center": [0.5, 1.5, 0.5], "size": [1.0, 3.0, 1.0]} # the 3 m lantern
+ assert boxes["out_of_bounds"] == {"center": [100.5, 0.5, 100.5], "size": [1.0, 1.0, 1.0]}
+ assert all(b is not None and set(b) == {"center", "size"} for b in boxes.values()), boxes
+ # a zone-level finding (House placed nothing) is about no one box and carries none
+ assert next(f for f in rep.findings if f.data["kind"] == "zone_empty").data.get("bbox") is None
+ # a row whose box is nulls (a census group with no geometry) carries None, not a crash
+ ghost = _row("Ghost", gap=0.3)
+ ghost["bbox"] = {"min": [None, None, None], "max": [None, None, None], "size": [None, None, None]}
+ g = _by_kind(placement_findings(_table(ghost)), "floating")[0]
+ assert g.data["bbox"] is None
+
+
+def test_the_summary_records_the_thresholds_and_the_probe_s():
+ t = _table(_row("Bench"), _row("Bird", exempt="free"), thresholds={"contact_m": 0.02, "floating_m": 0.05, "sunk_m": 0.1, "overlap_min": 0.1})
+ s = placement_findings(t, indoor=True).findings[0]
+ assert s.data["kind"] == "summary" and s.data["thresholds"]["indoor"] is True and s.data["thresholds"]["floating_m"] == 0.02
+ assert s.data["thresholds"]["sunk_error_frac"] == 0.2 and s.data["probe_thresholds"]["overlap_min"] == 0.1
+ assert s.data["free"] == 1 and s.data["free_share"] == 0.5 and s.data["counts"]["cantilevered"] == 0
+ assert "1 tagged free (50%)" in s.message and "indoor tolerance 2 cm" in s.message
diff --git a/harness/tests/scene_prompts/test_bpy_templates.py b/harness/tests/scene_prompts/test_bpy_templates.py
new file mode 100644
index 00000000..57653cb3
--- /dev/null
+++ b/harness/tests/scene_prompts/test_bpy_templates.py
@@ -0,0 +1,69 @@
+"""The bpy scene templates teach the hooks the Blender wrapper actually calls (the twin of
+test_prompt_assembler_contract for scene_blender), and carry the library catalog where the three.js
+templates do."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse3d.languages.wrappers import run_bpy_scene
+from codeverse3d.prompts import PROMPTS_DIR, load_text, render
+
+BASE = dict(title="t", spec_prompt="p", setting="s", mood="m", bounds="b", environment="e", frame_doc="", contract="",
+ zones_table="", cameras="", effects="", animation="", asset_api="", textures="", recipes="", constraints_text="",
+ references="", skills="", tool_cards="", zone_name="Z", zone_description="d", zone_bbox="bb", zone_contents=[],
+ zone_file="src/zones/z.py", neighbours=[], layout="", env_file="src/env.py", entry_file="src/scene.py",
+ single_shot=False, output_format="OUT", effects_catalog="")
+
+
+def test_the_bpy_templates_teach_the_hooks_the_wrapper_calls() -> None:
+ """Guard the three call sites the prompts promise against the wrapper's source (if the wrapper
+ changes its names, the prompts must)."""
+ wrapper = Path(run_bpy_scene.__file__).read_text()
+ assert 'getattr(mod, "build_env", None)' in wrapper and 'getattr(mod, "height_at", None)' in wrapper
+ assert 'getattr(mod, f"build_{snake}", None)' in wrapper and 'getattr(mod, "build", None)' in wrapper
+ env, zone, asset = (load_text(f"tracks/scene_{n}_bpy.j2") for n in ("env", "zone", "asset"))
+ assert "build_env(ctx)" in env and "height_at(x, y)" in env and "buildEnv" not in env and "SUN_AZIMUTH_DEG" in env
+ assert "def build(ctx)" in zone and "userData" not in zone and "ctx.frame(0.0)" in zone and "ctx.collection" in zone
+ assert "variant=0" in asset and "ctx.collection" in asset and "ctx.frame(0.0)" in asset
+ # the historical three.js hooks that nothing calls here must not leak into the bpy briefs
+ for text in (env, zone, asset, load_text("tracks/scene_refine_bpy.j2")):
+ assert "userData.update" not in text and "createScene" not in text and "THREE" not in text
+
+
+def test_the_catalog_reaches_env_zone_and_refine_but_not_the_asset_sheet() -> None:
+ """A bpy asset session gets the rows its sheet names (``library_rows``), never the whole catalog —
+ exactly the three.js split (tests/scene_runtime/test_skeleton.py)."""
+ tpl = PROMPTS_DIR / "tracks"
+ for name in ("scene_env_bpy.j2", "scene_zone_bpy.j2", "scene_refine_bpy.j2"):
+ assert "effects_catalog" in (tpl / name).read_text(), name
+ asset = (tpl / "scene_asset_bpy.j2").read_text()
+ assert "effects_catalog" not in asset and "library_rows" in asset
+
+
+def test_the_bpy_env_and_zone_briefs_hand_the_enclosure_to_env_for_an_interior() -> None:
+ """Six interior runs were "not enclosed": the env brief owns the shell only when the plan says interior."""
+ env_in = render("tracks/scene_env_bpy.j2", **BASE, interior=True, glazed=False)
+ env_glass = render("tracks/scene_env_bpy.j2", **BASE, interior=True, glazed=True)
+ env_out = render("tracks/scene_env_bpy.j2", **BASE, interior=False, glazed=False)
+ assert "the enclosure is yours" in env_in and "room_shell" in env_in and "openings" in env_in
+ assert "GLASS HOUSE" in env_glass and "glazed=True" in env_glass
+ assert "enclosure is yours" not in env_out
+ zone_in = render("tracks/scene_zone_bpy.j2", **BASE, interior=True)
+ zone_out = render("tracks/scene_zone_bpy.j2", **BASE, interior=False)
+ assert "never build walls or a roof" in zone_in and "flush against the inner face" in zone_in
+ assert "never build walls" not in zone_out
+
+
+def test_the_bpy_refine_brief_names_the_cookbook_chapters_the_stages_inline() -> None:
+ """The defect → chapter table must point at chapters that exist (``cookbook_sections`` finds them
+ by title), or a refine session is sent to a recipe that is not in its prompt."""
+ from codeverse3d.prompts.sections import find_section, split_sections
+ from codeverse3d.tracks.scene import ENV_RECIPES, ZONE_RECIPES
+
+ sections = split_sections(load_text("scene_blender/cookbook.md"))
+ refine = load_text("tracks/scene_refine_bpy.j2")
+ for title in (*ENV_RECIPES, *ZONE_RECIPES, "Placement self-check", "Materials: Principled recipes", "Water", "Traps"):
+ assert f'"{title.split(":")[0]}' in refine, title # quoted as the chapter's name (its head before any colon)
+ found = find_section(sections, title)
+ assert found is not None and title.lower() in found.title.lower(), (title, found and found.title)
diff --git a/harness/tests/scene_prompts/test_quality_teaching.py b/harness/tests/scene_prompts/test_quality_teaching.py
index 4216b7e5..91b66bff 100644
--- a/harness/tests/scene_prompts/test_quality_teaching.py
+++ b/harness/tests/scene_prompts/test_quality_teaching.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import pytest
+
from codeverse3d.judges.rubrics import load_rubric
from codeverse3d.prompts import load_text
@@ -10,12 +12,22 @@ COMPOSITION_DEFECTS = ("flat_ground", "monotonous_vegetation", "empty_midground"
def test_scene_rubric_craft_defects_inform_and_cannot_zero_a_scene() -> None:
- r = load_rubric("scene_v1")
+ r = load_rubric("scene_v2")
assert set(COMPOSITION_DEFECTS) <= {d.id for d in r.defects}
for did in COMPOSITION_DEFECTS:
d = r.defect(did)
assert 0.0 < d.penalty <= 0.05 and d.cap is None, did
- assert sum(d.penalty for d in r.defects) <= 0.62
+ # the five craft items together take at most 0.20: they inform, they cannot sink a scene
+ assert sum(r.defect(did).penalty for did in COMPOSITION_DEFECTS) == pytest.approx(0.18)
+ # scene_v2 (2026-10-14): the whole checklist sums to 1.02 (was 0.60 under v1's 0.62 bound). The
+ # 0.42 that moved is the placement / detail items — floating 0.10, sunken 0.08, interpenetration
+ # 0.08, wrong_scale 0.06, missing_planned_element 0.06, hero_misplaced 0.06, hard-edged particles
+ # 0.04 — the same weights the object rubric gives floating_part / interpenetration, and each of
+ # the four measured ones also caps (0.60-0.75) so the penalty only matters under the cap. A
+ # scene with EVERY item present is a wrong, unlit, floating, clipping world: zero is its score.
+ total = sum(d.penalty for d in r.defects)
+ assert total == pytest.approx(1.02) and total <= 1.05
+ assert sum(d.penalty for d in load_rubric("scene_v1").defects) <= 0.62 # the frozen replay rubric
def test_cookbook_sections_inlines_whole_chapters_and_clips_safely(tmp_path) -> None:
diff --git a/harness/tests/scene_runtime/blender_scene_fixture.py b/harness/tests/scene_runtime/blender_scene_fixture.py
index deb7e02b..432fe8de 100644
--- a/harness/tests/scene_runtime/blender_scene_fixture.py
+++ b/harness/tests/scene_runtime/blender_scene_fixture.py
@@ -5,6 +5,10 @@ Until the language's build wrapper exists this stands in for its outputs: ``arti
authored cameras with ``c3d_look_at`` and ``scene["c3d_cameras"]``), the geometry as a GLB, a
host entry that loads it (the shape of the census-GLB adapter), and ``artifacts/census.json``
from the unchanged probe. Blender frame: Z-up, -Y front; the GLB and every spec are Y-up.
+
+``build_room_shell`` is the interior case: the starter library's own ``room_shell`` (a red
+shell, its floor swapped green) under a sun, so a top-down ``no_fog`` view shows the floor only
+when the driver lifts the lid.
"""
from __future__ import annotations
@@ -121,6 +125,49 @@ def build_fixture(ws: Workspace, *, moving: bool = True, probe: bool = True) ->
return ws
+#: a 6 x 6 x 3 m room on the ground, built by the REAL ``lib.architecture.room_shell`` (so the
+#: names the driver's lid rule reads — root ``RoomShell``, lid ``Ceiling`` — are the library's,
+#: not the test's); the shell is red, the floor green, a near-vertical sun lights the inside
+ROOM_SHELL_BPY = r'''
+import sys
+import bpy
+
+argv = sys.argv[sys.argv.index("--") + 1:]
+blend, starter = argv[0], argv[1]
+sys.path.insert(0, starter)
+from lib.architecture import room_shell
+from lib.materials import material
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+sc = bpy.context.scene
+red = material("ShellRed", (0.8, 0.08, 0.08), roughness=0.9)
+green = material("FloorGreen", (0.08, 0.8, 0.08), roughness=0.9)
+root, floor, ceiling, *walls = room_shell(sc.collection, red, center=(0.0, 0.0, 1.5), extents=(6.0, 6.0, 3.0), thickness=0.2)
+floor.data.materials[0] = green
+assert root.name == "RoomShell" and ceiling.name == "Ceiling" and ceiling.parent is root
+sun = bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN"))
+sun.data.energy = 5.0
+sun.rotation_euler = (0.15, 0.1, 0.0)
+sc.collection.objects.link(sun)
+bpy.ops.wm.save_as_mainfile(filepath=blend, compress=True)
+'''
+
+
+def build_room_shell(root: Path) -> Path:
+ """Write ``root/scene.blend``: the room-shell interior; returns the .blend's path."""
+ from codeverse3d.languages.scene_blender import STARTER_DIR
+
+ root.mkdir(parents=True, exist_ok=True)
+ script = root / "build_room_shell.py"
+ script.write_text(ROOM_SHELL_BPY)
+ blend = root / "scene.blend"
+ blender = get_settings().resolve_blender()
+ proc = run_subprocess([blender, "-b", "--factory-startup", "--python", str(script), "--", str(blend), str(STARTER_DIR)],
+ cwd=root, env=blender_env(), timeout_s=120)
+ assert proc.returncode == 0 and blend.is_file(), proc.stderr[-2000:]
+ return blend
+
+
def blender_available() -> bool:
b = get_settings().resolve_blender()
return bool(b) and Path(b).exists()
diff --git a/harness/tests/scene_runtime/test_glb_asset_naming.py b/harness/tests/scene_runtime/test_glb_asset_naming.py
index 5e772016..bca3f0b9 100644
--- a/harness/tests/scene_runtime/test_glb_asset_naming.py
+++ b/harness/tests/scene_runtime/test_glb_asset_naming.py
@@ -14,7 +14,8 @@ import pytest
from codeverse3d.contracts.plan import CameraPlan
from codeverse3d.languages.scene_threejs import render_scene_js
from codeverse3d.spatial.node import run_node
-from tests.scene_runtime.conftest import needs_node
+from tests.scene_runtime.conftest import needs_browser, needs_node
+from tests.scene_runtime.glb_fixture import write_box_glb
pytestmark = [pytest.mark.node, needs_node]
@@ -94,3 +95,32 @@ def test_a_procedural_asset_is_rendered_on_the_hero_rig(tmp_ws):
rs = SceneThreeJsRuntime().render_asset(tmp_ws, "Crate", out)
assert rs.contact_sheet and (out / "sheet.png").is_file() and len(rs.views) >= 4
assert (tmp_ws.artifacts / "asset_export" / "crate" / "artifacts" / "object.glb").is_file()
+
+
+HERO_CLONES = """
+ const hero = (await loaders.gltf.loadAsync('/assets/hero_cube.glb')).scene;
+ hero.name = 'HeroCube';
+ const row = new THREE.Group(); row.name = 'HeroRow'; scene.add(row);
+ for (const [x, z] of [[10, 14], [-12, 8], [6, -10]]) { const c = hero.clone(); c.position.set(x, 2, z); row.add(c); }
+"""
+
+
+@needs_browser
+def test_a_hero_s_size_is_one_instance_not_the_union_of_its_clones(starter_ws):
+ """`census.glb_assets[].size_m` is the largest SINGLE placed instance (2026-10-14): three clones
+ of a 4 m cube 20 m apart read as "24 m across as placed" to the frames gate and the judge
+ before, and `instances` says how many stand in the scene. `.clone()` shares geometry, so the
+ file's uuids are grouped per clone root, not per uuid."""
+ from codeverse3d.spatial.probes import probe_scene
+
+ write_box_glb(starter_ws.public / "assets" / "hero_cube.glb", size=(4.0, 4.0, 4.0))
+ scene = starter_ws.src / "scene.js"
+ text = scene.read_text()
+ text = text.replace("export function createScene(", "export async function createScene(")
+ assert " ctx.env = env;\n" in text
+ scene.write_text(text.replace(" ctx.env = env;\n", " ctx.env = env;\n" + HERO_CLONES, 1))
+ res = probe_scene(starter_ws)
+ assert res.ok and res.census, res.errors
+ row = next(r for r in res.census["glb_assets"] if r["url"] == "/assets/hero_cube.glb")
+ assert row["in_scene"] and row["meshes_in_scene"] == 1 and row["instances"] == 3, row
+ assert abs(row["size_m"] - 4.0) < 0.05, row
diff --git a/harness/tests/scene_runtime/test_js_named_imports.py b/harness/tests/scene_runtime/test_js_named_imports.py
new file mode 100644
index 00000000..9bde7c7b
--- /dev/null
+++ b/harness/tests/scene_runtime/test_js_named_imports.py
@@ -0,0 +1,95 @@
+"""The named-import half of the JS import policy (``languages/_js_lint``): text parsing and
+the per-lint export cache, no node. The scene-level behaviour is in ``test_lint.py``."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse3d.contracts.artifacts import GateFinding, Severity
+from codeverse3d.languages._js_lint import (
+ NamedImport,
+ check_named_imports,
+ describe_exports,
+ exported_names,
+ module_exports,
+ named_import_specs,
+)
+
+
+def test_named_import_specs_forms():
+ src = (
+ "import * as THREE from 'three';\n" # namespace: no names
+ "import d from './d.js';\n" # default only: no names
+ "import x, { a, b as c } from './m.js';\n" # default + named: the IMPORTED names
+ "import {\n p,\n q as r,\n} from \"./multi.js\";\n"
+ "// import { gone } from './gone.js';\n"
+ "/* import { gone2 } from './gone.js'; */\n"
+ "import{s}from'./tight.js';\n"
+ "import {} from './empty.js';\n"
+ "const later = import('./dyn.js');\n"
+ )
+ assert named_import_specs(src) == [
+ NamedImport("./m.js", ("a", "b"), 3),
+ NamedImport("./multi.js", ("p", "q"), 4),
+ NamedImport("./tight.js", ("s",), 10),
+ ]
+
+
+def test_module_exports_forms():
+ src = (
+ "export function f() {}\nexport async function g() {}\nexport function* h() {}\n"
+ "export class C {}\nexport const k = 1;\nexport let l = 2;\nexport var v = 3;\n"
+ "const a = 1, b = 2;\nexport { a, b as bee };\nexport { z as zed } from './z.js';\n"
+ "export * as ns from './ns.js';\nexport default function () {}\n"
+ "// export const commented = 1;\nconst s = 'export const inString = 1';\n"
+ )
+ assert module_exports(src) == frozenset({"f", "g", "h", "C", "k", "l", "v", "a", "bee", "zed", "ns", "default"})
+ assert module_exports("const x = 1;\n") == frozenset()
+ # not enumerable from the text: another module's surface, or a destructuring pattern
+ assert module_exports("export * from './all.js';\nexport const x = 1;\n") is None
+ assert module_exports("export const { a, b } = obj;\n") is None
+
+
+def test_exported_names_reads_the_file_or_says_unknown(tmp_path: Path):
+ p = tmp_path / "m.js"
+ p.write_text("export const one = 1;\n")
+ assert exported_names(p) == frozenset({"one"})
+ assert exported_names(tmp_path / "missing.js") is None
+
+
+def test_describe_exports_lists_at_most_twelve_sorted():
+ assert describe_exports(frozenset()) == "it exports nothing"
+ assert describe_exports(frozenset({"b", "a"})) == "it exports: a, b"
+ many = frozenset(f"n{i:02d}" for i in range(15))
+ assert describe_exports(many) == "it exports: " + ", ".join(f"n{i:02d}" for i in range(12)) + ", …"
+
+
+def _finding(spec: str, name: str, line: int, names: frozenset[str]) -> GateFinding:
+ return GateFinding(gate="t", severity=Severity.ERROR, target=f"z.js:{line}", message=f"{spec}:{name}:{describe_exports(names)}")
+
+
+def test_check_named_imports_only_judges_resolved_js_targets_and_reads_each_once(tmp_path: Path):
+ src_root = tmp_path / "src"
+ (src_root / "lib").mkdir(parents=True)
+ (src_root / "zones").mkdir()
+ materials = src_root / "lib" / "materials.js"
+ materials.write_text("export const brick = 1;\nexport const granite = 2;\n")
+ (src_root / "lib" / "all.js").write_text("export * from './materials.js';\n")
+ (src_root / "lib" / "data.json").write_text("{}")
+ zone = src_root / "zones" / "z.js"
+ zone.write_text(
+ "import { brick, concrete } from '../lib/materials.js';\n"
+ "import { anything } from '../lib/all.js';\n" # star re-export: unknown surface, never reported
+ "import { x } from '../lib/missing.js';\n" # missing target: check_imports's finding, not ours
+ "import { Vector3, Nope } from 'three';\n" # not ours to read
+ "import { y } from '../../outside.js';\n" # escapes src/: not ours
+ "import { d } from '../lib/data.json';\n" # not a JS module
+ "import { granite as g } from '../lib/materials.js';\n"
+ )
+ cache: dict[Path, frozenset[str] | None] = {}
+ out = check_named_imports(zone.read_text(), zone, src_root, make_finding=_finding, exports=cache)
+ assert [(f.target, f.message) for f in out] == [("z.js:1", "../lib/materials.js:concrete:it exports: brick, granite")]
+ assert cache == {materials.resolve(): frozenset({"brick", "granite"}), (src_root / "lib" / "all.js").resolve(): None}
+ # the cache is the lint's one read of each target: a later call trusts it over the file
+ cache[materials.resolve()] = frozenset({"brick", "granite", "concrete"})
+ assert check_named_imports(zone.read_text(), zone, src_root, make_finding=_finding, exports=cache) == []
diff --git a/harness/tests/scene_runtime/test_lint.py b/harness/tests/scene_runtime/test_lint.py
index d3c3f3bc..b019b565 100644
--- a/harness/tests/scene_runtime/test_lint.py
+++ b/harness/tests/scene_runtime/test_lint.py
@@ -82,3 +82,99 @@ def test_large_file_warning(ws):
rep = lint(ws)
assert any("large file" in m for _, m in _msgs(rep, Severity.WARN))
+
+# ------------------------------------------------- named imports (argon loop iter 0, 2026-10-15)
+MATERIALS_JS = (
+ "import * as THREE from 'three';\n"
+ "export const brick = (o = {}) => new THREE.MeshStandardMaterial(o);\n"
+ "export const granite = (o = {}) => new THREE.MeshStandardMaterial(o);\n"
+ "export function weather(mat) { return mat; }\n"
+)
+SCENE_JS = "export function createScene() { return {}; }\n"
+CATALOG_HINT = "import only names the module actually exports (for src/lib modules: the names the effects catalog lists)"
+
+
+def _lib(ws, name: str, text: str) -> None:
+ (ws.src / "lib").mkdir(exist_ok=True)
+ (ws.src / "lib" / name).write_text(text)
+
+
+def _zone(ws, name: str, head: str) -> None:
+ (ws.src / "zones").mkdir(exist_ok=True)
+ (ws.src / "zones" / f"{name}.js").write_text(head + "export function build(ctx) { return new ctx.THREE.Group(); }\n")
+
+
+def _zone_errors(ws, zone: str) -> list[tuple[str, str, str]]:
+ return [(f.target, f.message, f.fix_hint) for f in lint(ws).findings
+ if f.severity == Severity.ERROR and f.target.startswith(f"src/zones/{zone}.js")]
+
+
+def test_importing_a_name_the_lib_module_does_not_export_is_an_error(ws):
+ """it00_scene_threejs_r1_18: two zones did ``import { concrete } from '../lib/materials.js'``.
+ The FILE exists, so the import lint passed it — and the browser threw a SyntaxError at
+ module link, the assembler dropped both zones, the run scored 0.47."""
+ (ws.src / "scene.js").write_text(SCENE_JS)
+ _lib(ws, "materials.js", MATERIALS_JS)
+ _zone(ws, "yard", "import * as THREE from 'three';\nimport { brick, concrete } from '../lib/materials.js';\n")
+ errs = _zone_errors(ws, "yard")
+ assert errs == [("src/zones/yard.js:2",
+ "import { concrete } from '../lib/materials.js': that module exports no 'concrete' (it exports: brick, granite, weather)",
+ CATALOG_HINT)], errs
+ assert all(f.data["kind"] == "bad_import" for f in lint(ws).findings if f.target.startswith("src/zones/"))
+ # the library module is read as a TARGET, never linted as agent code
+ assert not [f for f in lint(ws).findings if f.target.startswith("src/lib/")]
+
+
+def test_every_export_form_is_recognised(ws):
+ (ws.src / "scene.js").write_text(SCENE_JS)
+ _lib(ws, "forms.js",
+ "const x = 1;\nexport { x as y };\nexport const k = 2;\nexport class Thing {}\n"
+ "export async function load() {}\nexport let cur = 0;\nexport function* gen() {}\nexport default 3;\n")
+ _zone(ws, "ok", "import { y, k, Thing, load, cur, gen, default as three } from '../lib/forms.js';\n")
+ assert _zone_errors(ws, "ok") == []
+ # ``export { x as y }`` exports y: importing the LOCAL name x is the error
+ _zone(ws, "bad", "import { x } from '../lib/forms.js';\n")
+ assert [m for _, m, _ in _zone_errors(ws, "bad")] == [
+ "import { x } from '../lib/forms.js': that module exports no 'x' (it exports: Thing, cur, default, gen, k, load, y)"]
+
+
+def test_namespace_and_default_imports_are_not_checked(ws):
+ (ws.src / "scene.js").write_text(SCENE_JS)
+ _lib(ws, "m.js", "export const a = 1;\nexport default 2;\n")
+ _zone(ws, "ns", "import * as m from '../lib/m.js';\nimport d from '../lib/m.js';\nimport d2, { a } from '../lib/m.js';\n")
+ assert _zone_errors(ws, "ns") == []
+ # the named half of a default+named import IS checked
+ _zone(ws, "mix", "import d3, { b } from '../lib/m.js';\n")
+ assert [m for _, m, _ in _zone_errors(ws, "mix")] == [
+ "import { b } from '../lib/m.js': that module exports no 'b' (it exports: a, default)"]
+
+
+def test_a_star_reexporting_module_never_reports(ws):
+ """``export * from`` is not resolved transitively: that module's surface is unknown, so
+ nothing is reported against it (its own named exports included)."""
+ (ws.src / "scene.js").write_text(SCENE_JS)
+ _lib(ws, "materials.js", MATERIALS_JS)
+ _lib(ws, "index.js", "export * from './materials.js';\nexport const extra = 1;\n")
+ _zone(ws, "z", "import { brick, concrete, whatever, extra } from '../lib/index.js';\n")
+ assert _zone_errors(ws, "z") == []
+
+
+def test_a_commented_out_bad_import_is_ignored(ws):
+ (ws.src / "scene.js").write_text(SCENE_JS)
+ _lib(ws, "materials.js", MATERIALS_JS)
+ _zone(ws, "z", "// import { concrete } from '../lib/materials.js';\n"
+ "/*\nimport { marble } from '../lib/materials.js';\n*/\n"
+ "import { brick } from '../lib/materials.js';\n")
+ assert _zone_errors(ws, "z") == []
+
+
+def test_multi_line_import_reports_the_import_line_and_a_missing_file_only_once(ws):
+ (ws.src / "scene.js").write_text(SCENE_JS)
+ _lib(ws, "materials.js", MATERIALS_JS)
+ _zone(ws, "z", "import {\n brick,\n concrete as cement,\n} from '../lib/materials.js';\n"
+ "import { nope } from '../lib/missing.js';\n")
+ errs = _zone_errors(ws, "z")
+ assert sorted(t for t, _, _ in errs) == ["src/zones/z.js:1", "src/zones/z.js:5"], errs
+ assert [m for _, m, _ in errs if "missing file" in m] == ["import of missing file '../lib/missing.js'"]
+ assert [m for _, m, _ in errs if "exports no" in m] == [
+ "import { concrete } from '../lib/materials.js': that module exports no 'concrete' (it exports: brick, granite, weather)"]
diff --git a/harness/tests/scene_runtime/test_orbit.py b/harness/tests/scene_runtime/test_orbit.py
index dffa97e8..c7bc2dc0 100644
--- a/harness/tests/scene_runtime/test_orbit.py
+++ b/harness/tests/scene_runtime/test_orbit.py
@@ -70,3 +70,31 @@ console.log(JSON.stringify({{
assert cam["position"][0] > 40 and cam["position"][1] > 0.5
assert cam["lookAt"] == [0, 4, 0]
assert 80 < math.dist(cam["position"], cam["lookAt"]) < 200 # corner-frustum fit, not a loose sphere fit
+
+
+def test_contact_camera_stands_at_ground_level_outside_the_content(tmp_path):
+ """scene_v2's ``overview_low_front`` (elevation < 10°): 1.2× the content span from the centre,
+ 0.4 m above the ground, aimed at the ground edge of the content box; fog kept."""
+ body = f"""
+import {{ fitOrbitCameras, fitContactCamera }} from './lib/orbit.mjs';
+const low = {{ name: 'overview_low_front', azimuth: 20, elevation: 7 }};
+console.log(JSON.stringify({{
+ rig: fitOrbitCameras({json.dumps(BBOX)}, [low], {{ groundY: 0.0 }}),
+ raised: fitContactCamera({json.dumps(BBOX)}, {{ azimuth: 20, floor: 3.0 }}),
+ tiny: fitContactCamera({{ min: [-2, 0, -2], max: [2, 1, 2], size: [4, 1, 4] }}, {{ azimuth: 90, floor: 0 }}),
+}}));
+"""
+ out = run_node_json(body)
+ cam = out["rig"][0]
+ assert cam["name"] == "overview_low_front" and cam["kind"] == "orbit" and cam["noFog"] is False
+ # eye: 1.2 × 80 m from the centre on the azimuth-20° side, 0.4 m up
+ assert math.hypot(cam["position"][0], cam["position"][2]) == pytest.approx(96.0, abs=0.01)
+ assert cam["position"][0] == pytest.approx(96 * math.sin(math.radians(20)), abs=0.01) and cam["position"][1] == pytest.approx(0.4)
+ # aim: where the view line leaves the footprint (z = 40 on the +Z side), at ground height
+ assert cam["lookAt"][2] == pytest.approx(40.0, abs=0.01) and cam["lookAt"][1] == pytest.approx(0.0)
+ assert cam["lookAt"][0] == pytest.approx(40 * math.tan(math.radians(20)), abs=0.01)
+ assert cam["fov"] == 50
+ # the floor moves the eye and the aim together
+ assert out["raised"]["position"][1] == pytest.approx(3.4) and out["raised"]["lookAt"][1] == pytest.approx(3.0)
+ # a tiny box: never closer than the footprint edge + 2 m
+ assert out["tiny"]["position"][0] == pytest.approx(4.8) and out["tiny"]["lookAt"] == [2, 0, 0]
diff --git a/harness/tests/scene_runtime/test_placement_census.py b/harness/tests/scene_runtime/test_placement_census.py
index bd6dd480..791bc4a4 100644
--- a/harness/tests/scene_runtime/test_placement_census.py
+++ b/harness/tests/scene_runtime/test_placement_census.py
@@ -4,6 +4,9 @@ from __future__ import annotations
import pytest
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.artifacts import Severity
+from codeverse3d.spatial.scene_placement import placement_findings
from tests.scene_runtime.conftest import needs_node, run_node_json
pytestmark = [pytest.mark.node, needs_node]
@@ -39,6 +42,11 @@ zone.add(box('Bench', 1.6, 0.9, 0.5, 16, 0, 15));
zone.add(box('Boat', 2, 0.6, 0.8, -20, 0.0, -20));
const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.6, 1), mat); rock.name = 'Rock'; rock.position.set(8, 0.2, -8); zone.add(rock);
const inst = new THREE.InstancedMesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), mat, 50); inst.name = 'Pebbles'; zone.add(inst);
+// the env's room shell: a lid and a lintel whose box runs INTO the lid (a 3.2 m door head in a 3 m room) —
+// one enclosure, never placed assets (2026-10-15: half the Blender interpenetration ERRORs of loop iteration 0)
+const shell = new THREE.Group(); shell.name = 'RoomShell'; scene.add(shell);
+shell.add(box('Ceiling', 8.4, 0.2, 6.4, -30, 3.0, 30));
+shell.add(box('RoomShellWallBack_0Lintel', 1.2, 0.5, 0.2, -30, 2.8, 33.1));
scene.updateMatrixWorld(true);
const c = sceneCensus(scene, THREE, { placement: true });
console.log(JSON.stringify({ ground_y: c.ground_y, placement: c.placement, plain_has_placement: 'placement' in sceneCensus(scene, THREE) }));
@@ -59,12 +67,17 @@ def _row(table, name):
def test_counts_exemptions_and_budget(table):
- assert table["total"] == 17 and table["checked"] == 12 and table["truncated"] is False
- assert table["exempt"] == {"backdrop": 3, "free": 1, "instanced": 1}
+ assert table["total"] == 19 and table["checked"] == 12 and table["truncated"] is False
+ assert table["exempt"] == {"backdrop": 3, "enclosure": 2, "free": 1, "instanced": 1}
assert {a["name"] for a in table["assets"] if a["exempt"] == "backdrop"} == {"Ground", "SkyDome", "PondWater"}
assert _row(table, "Bird")["exempt"] == "free" and _row(table, "Pebbles")["exempt"] == "instanced"
assert table["duration_ms"] < 2000 and table["notes"] == []
- assert table["thresholds"] == {"contact_m": 0.02, "floating_m": 0.05, "sunk_m": 0.1, "overlap_min": 0.2}
+ # what the probe MEASURES at = what the gate grades the default scene at (Settings.placement);
+ # the pair floor is the default overlap_warn, or the strict WARN band would be unmeasured
+ p = get_settings().placement
+ assert table["thresholds"] == {"contact_m": p.contact_m, "floating_m": p.floating_outdoor_m, "sunk_m": p.sunk_m,
+ "overlap_min": p.overlap_warn}
+ assert table["thresholds"]["overlap_min"] == 0.1
def test_supported_floating_and_sunk_boxes(table):
@@ -74,11 +87,25 @@ def test_supported_floating_and_sunk_boxes(table):
lantern = _row(table, "Lantern")
assert lantern["ground_gap_m"] == pytest.approx(0.3, abs=1e-3) and lantern["floating"] and lantern["touches_nothing"]
assert lantern["support"] == "Ground" and lantern["sunk_m"] == 0 and not lantern["supported"]
+ # the column measures (2026-10-14): every foot of the lantern hangs 0.3 m, every foot of the crate rests
+ assert lantern["gap_max_m"] == pytest.approx(0.3, abs=1e-3) and lantern["columns_resting"] == 0 and lantern["tilt_m"] == pytest.approx(0, abs=1e-3)
+ # (a level box yields 3 columns: its lowest vertex coincides with one of the four corner extremes)
+ assert crate["gap_max_m"] == 0 and crate["columns_resting"] == crate["columns"] >= 3 and crate["tilt_m"] == 0
anvil = _row(table, "Anvil")
assert anvil["sunk_m"] == pytest.approx(0.5, abs=1e-3) and anvil["sunk_into"] == "Ground" and anvil["ground_gap_m"] == pytest.approx(-0.5, abs=1e-3)
assert anvil["supported"] and not anvil["floating"]
+def test_the_room_shells_members_are_the_enclosure_not_placed_assets(table):
+ """Walls, lid, sills and lintels under a `RoomShell…` root abut and overlap each other by
+ construction (a lintel runs into the lid here): they are exempt as the enclosure, so they get
+ no seating row and no interpenetration pair (24 of 41 Blender ERRORs in loop iteration 0)."""
+ for name in ("Ceiling", "RoomShellWallBack_0Lintel"):
+ row = _row(table, name)
+ assert row["zone"] == "RoomShell" and row["exempt"] == "enclosure"
+ assert not [p for p in table["interpenetrations"] if "RoomShell" in (p["zone_a"], p["zone_b"])]
+
+
def test_interpenetration_is_a_pair_not_a_burial(table):
pairs = table["interpenetrations"]
assert [(p["a"], p["b"], p["aabb_overlap"]) for p in pairs] == [("CrateA", "CrateB", 0.5)]
@@ -159,3 +186,43 @@ def test_settle_leaves_exempt_water_partial_and_mounted_alone(settled):
assert after["Bird"]["exempt"] == "free" # tagged free: untouched
assert after["Boat"]["supported"] # on water: untouched
assert after["Rock"]["sunk"] == pytest.approx(0.6, abs=5e-3) # half-buried rock stays half-buried
+
+
+# ---------------------------------------------------------------------------- a lean on a slope
+#: a 17° hillside (the ground plane rotated about x; its height is -z·tan 0.3) with a crate yawed 45°
+#: and seated by its UPHILL corner — what seating by the lowest vertex produces — and a level crate
+#: seated the same way, which rests on an edge
+SLOPE_JS = """
+import * as THREE from 'three';
+import { sceneCensus } from './lib/host_census.mjs';
+const mat = new THREE.MeshStandardMaterial();
+const scene = new THREE.Scene();
+const env = new THREE.Group(); env.name = 'Environment'; scene.add(env);
+const ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60, 64, 64), mat); ground.name = 'Ground';
+ground.rotation.x = -Math.PI / 2 + 0.3; env.add(ground);
+const zone = new THREE.Group(); zone.name = 'Yard'; scene.add(zone);
+const t = Math.tan(0.3);
+const yawed = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), mat); yawed.name = 'Crate';
+yawed.rotation.y = Math.PI / 4; yawed.position.set(0, Math.SQRT1_2 * t + 0.5, 0); zone.add(yawed);
+const level = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), mat); level.name = 'LevelCrate';
+level.position.set(6, 0.5 * t + 0.5, 0); zone.add(level);
+scene.updateMatrixWorld(true);
+const c = sceneCensus(scene, THREE, { placement: true });
+console.log(JSON.stringify({ placement: c.placement }));
+"""
+
+
+def test_a_crate_seated_by_one_corner_on_a_slope_is_cantilevered():
+ table = run_node_json(SLOPE_JS)["placement"]
+ yawed = _row(table, "Crate")
+ t = 0.30934 # tan 0.3
+ assert yawed["columns"] == 4 and yawed["columns_resting"] == 1, yawed
+ assert yawed["ground_gap_m"] == pytest.approx(0, abs=5e-3) and yawed["supported"] and not yawed["floating"]
+ assert yawed["gap_max_m"] == pytest.approx(2 * 0.70711 * t, abs=0.01) and yawed["tilt_m"] == pytest.approx(yawed["gap_max_m"], abs=5e-3)
+ level = _row(table, "LevelCrate")
+ assert level["columns_resting"] >= 2 or level["columns"] < 4, level # an edge rests: not a lean
+ # the gate reads the measure: a WARN that names the hang, and nothing for the level crate
+ rep = placement_findings(table)
+ lean = [f for f in rep.findings if f.data.get("kind") == "cantilevered"]
+ assert [f.target for f in lean] == ["Yard/Crate"] and lean[0].severity == Severity.WARN and rep.passed
+ assert "rests on 1 of its 4 foot columns" in lean[0].message
diff --git a/harness/tests/scene_runtime/test_render_blender.py b/harness/tests/scene_runtime/test_render_blender.py
index 78979509..1066dbaf 100644
--- a/harness/tests/scene_runtime/test_render_blender.py
+++ b/harness/tests/scene_runtime/test_render_blender.py
@@ -12,7 +12,7 @@ import time
from pathlib import Path
import pytest
-from PIL import Image
+from PIL import Image, ImageStat
from codeverse3d.config import get_settings
from codeverse3d.contracts.artifacts import Severity
@@ -22,7 +22,11 @@ from codeverse3d.spatial import render_blender as rb
from codeverse3d.spatial.frame_metrics import frame_findings
from codeverse3d.spatial.render_scene import SceneRenderError, render_scene
from codeverse3d.workspace import Workspace
-from tests.scene_runtime.blender_scene_fixture import blender_available, build_fixture
+from tests.scene_runtime.blender_scene_fixture import (
+ blender_available,
+ build_fixture,
+ build_room_shell,
+)
from tests.scene_runtime.conftest import needs_browser
needs_blender = pytest.mark.skipif(not blender_available(), reason="Blender binary required")
@@ -68,9 +72,12 @@ def test_a_fixture_scene_renders_two_cameras_at_two_times(moving):
for v in rs.views:
with Image.open(v.path) as im:
assert im.size == (W, H)
- # the three overviews get pixels at t0 only; the eye-level rig is measured, never rendered
+ # the four overviews (scene_v2: the contact camera overview_low_front is the fourth) get pixels
+ # at t0 only; the eye-level rig is measured, never rendered
rig = sorted((v.name, v.time_s) for v in rs.views if v.name.startswith(("overview", "eye")))
- assert rig == [("overview_back_left", 0.0), ("overview_front_right", 0.0), ("overview_top", 0.0)]
+ assert rig == [("overview_back_left", 0.0), ("overview_front_right", 0.0), ("overview_low_front", 0.0), ("overview_top", 0.0)]
+ low = next(v for v in rs.views if v.name == "overview_low_front")
+ assert 0.2 < low.camera_position[1] < 1.0, "the contact camera stands 0.4 m above the ground (GLB frame, Y-up)"
checks = {c["name"]: c for c in m["camera_checks"]}
assert set(checks) >= {"Front", "Side", "overview_top", "eye_front", "eye_right", "eye_back_left"}
assert set(checks["Front"]) >= STAT_KEYS and not STAT_KEYS & set(checks["eye_front"])
@@ -81,7 +88,7 @@ def test_a_fixture_scene_renders_two_cameras_at_two_times(moving):
assert front["position"] == pytest.approx([0, 4, 14]) and front["lookAt"] == pytest.approx([0, 1, 0])
assert front["fov"] == pytest.approx(40.107, abs=0.01)
assert m["language"] == "scene_blender" and m["blender"]["device"] == "CPU" and m["blender"]["samples"] == 4
- assert m["blender"]["engine"] == "cycles" and len(m["blender"]["frame_ms"]) == 7
+ assert m["blender"]["engine"] == "cycles" and len(m["blender"]["frame_ms"]) == 2 * 2 + 4
assert "Blender" in rs.renderer and "cycles" in rs.renderer
assert rs.console_errors == [] and rs.contact_sheet and Path(rs.contact_sheet).is_file()
judged = {(v.name, v.time_s) for v in rs.views if v.judge}
@@ -208,6 +215,45 @@ def test_a_held_gpu_slot_sends_a_real_render_to_the_cpu(tmp_path, monkeypatch):
assert free["device"] == "GPU" or free["fallback"] == "no CUDA device"
+def _centre_rgb(path: Path) -> tuple[float, float, float]:
+ """The mean colour of the middle 10 % of the frame."""
+ with Image.open(path) as im:
+ w, h = im.size
+ r, g, b = ImageStat.Stat(im.convert("RGB").crop((int(w * 0.45), int(h * 0.45), int(w * 0.55), int(h * 0.55)))).mean
+ return r, g, b
+
+
+@needs_blender
+def test_a_no_fog_view_lifts_the_room_shells_lid_and_the_next_view_gets_it_back(tmp_path, monkeypatch):
+ """Review 2026-10-14 finding 8: the rubric tells the judge the high overviews show interiors
+ with the lid off and the bpy prompts promise the author that (``RoomShell…`` / ``Ceiling…``),
+ but only the three.js host lifted it (``scene_host.skyLayersBelow``). The real starter
+ ``room_shell`` under a top-down camera: the ``no_fog`` view names the lid in ``hidden`` and
+ its centre is the green floor; the same camera WITHOUT ``no_fog``, rendered next, sees the
+ red lid again — the restore in the driver's ``finally``."""
+ _cpu_env(monkeypatch, tmp_path / "cache")
+ blend = build_room_shell(tmp_path / "room")
+ out = tmp_path / "out"
+ out.mkdir()
+ top = {"name": "overview_top", "kind": "orbit", "position": [0.0, 0.0, 14.0], "look_at": [0.0, 0.0, 1.5], "fov": 40.0,
+ "no_fog": True, "times": [0.0]}
+ lid_on = {**top, "name": "lid_on", "no_fog": False}
+ inside = {**top, "name": "inside", "position": [0.0, 0.0, 1.6], "look_at": [0.0, 0.0, 3.0]} # under the lid, looking up
+ job = {"out": str(out), "result": str(out / rb.RESULT_NAME), "engine": "cycles", "samples": 4, "width": 96,
+ "height": 54, "times": [0.0], "authored": False, "cameras": [top, lid_on, inside]}
+ res = rb.render_frames(blend, out, job, timeout_s=180)
+ assert res["errors"] == [] and [f["name"] for f in res["frames"]] == ["overview_top", "lid_on", "inside"]
+ hidden = {f["name"]: f["hidden"] for f in res["frames"]}
+ assert hidden == {"overview_top": ["Ceiling"], "lid_on": [], "inside": []}, hidden
+ lifted, kept = _centre_rgb(out / "overview_top_t0.png"), _centre_rgb(out / "lid_on_t0.png")
+ # AgX desaturates: the floor's green and the lid's red lead their other channels by a margin, not a ratio
+ assert lifted[1] > max(lifted[0], lifted[2]) + 25, f"the lifted top view must show the green floor, got {lifted}"
+ assert kept[0] > max(kept[1], kept[2]) + 25, f"the lid-on view must show the red lid, got {kept}"
+ assert sum(abs(a - b) for a, b in zip(lifted, kept, strict=True)) > 60, (lifted, kept)
+ assert "hidden" not in rb._glb_view(res["frames"][0]), "views.json keeps the three.js schema"
+
+
def test_a_missing_blend_is_an_empty_renderset_that_says_why(tmp_path):
ws = Workspace(tmp_path / "run").create()
rs = rb.render_blender_scene(ws, tmp_path / "out")
diff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.py
index 3844173f..4a06ad94 100644
--- a/harness/tests/scene_runtime/test_skeleton.py
+++ b/harness/tests/scene_runtime/test_skeleton.py
@@ -140,3 +140,20 @@ def test_the_catalog_names_every_library_module_and_no_other():
named = set(re.findall(r"`lib/([a-z_]+\.js)`", catalog))
modules = {p.name for p in lib_files()}
assert named == modules, (sorted(modules - named), sorted(named - modules))
+
+
+def test_the_bpy_catalog_names_every_bpy_library_module_and_no_other():
+ """scene_blender's twin: its catalog (``prompts/scene_blender/effects_catalog.md``, reached
+ through ``language_text`` like the three.js one) indexes exactly ``src/lib/*.py``; the calls
+ it names are checked against the modules' defs in tests/scene_blender/test_library.py."""
+ import re
+
+ from codeverse3d.contracts.common import Language
+ from codeverse3d.languages.scene_blender import lib_files
+ from codeverse3d.prompts.catalog import language_text
+
+ catalog = language_text(Language.SCENE_BLENDER, "effects_catalog.md")
+ assert "| Want | Call |" in catalog and "from lib.materials import material" in catalog
+ named = set(re.findall(r"`lib/([a-z_]+\.py)`", catalog))
+ modules = {p.name for p in lib_files()}
+ assert named == modules, (sorted(modules - named), sorted(named - modules))
diff --git a/harness/tests/skills/test_routing_property.py b/harness/tests/skills/test_routing_property.py
index 6116b28b..28c16573 100644
--- a/harness/tests/skills/test_routing_property.py
+++ b/harness/tests/skills/test_routing_property.py
@@ -13,7 +13,7 @@ LIBRARY = all_skills()
TRACKS = ("static_object", "articulated_object", "scene", "graphics")
LANGUAGES = ("blender", "cadquery", "threejs", "urdf_blender", "scene_threejs",
- "glsl_shader", "opengl_python")
+ "glsl_shader", "opengl_python", "scene_blender")
KINDS = ("baseline", "part", "refine", "rebuild", "repair", "env", "zone",
"asset", "asset_fix", "reference")
#: every plan signal plan_signals() produces — a route requiring any other can never fire
diff --git a/harness/tests/skills/test_targets.py b/harness/tests/skills/test_targets.py
index 2f6f42c7..90183946 100644
--- a/harness/tests/skills/test_targets.py
+++ b/harness/tests/skills/test_targets.py
@@ -15,6 +15,7 @@ from codeverse3d.addons.skill_targets import (
SOURCES,
SRC_GATE,
TARGETS,
+ Target,
gate_kinds_claimed,
target_for,
)
@@ -83,11 +84,15 @@ def test_target_rows_and_bundle_metadata_are_complete():
def test_no_two_bundles_claim_the_same_quantity():
"""Two bundles sharing a metric means an A/B cannot say which one moved it."""
assert len(METRICS) == len(TARGETS)
- seen: dict[str, str] = {}
+ seen: dict[str, list[Target]] = {}
for t in TARGETS:
for k in t.kinds:
- assert k not in seen, f"{t.skill} and {seen[k]} both count {k}"
- seen[k] = t.skill
+ # a run has ONE language: two bundles may count the same kind over disjoint languages
+ # (c3d-scene-lighting vs c3d-bpy-scene-lighting, 2026-10-14) and an A/B still names one owner
+ for other in seen.get(k, []):
+ shared = not t.languages or not other.languages or set(t.languages) & set(other.languages)
+ assert not shared, f"{t.skill} and {other.skill} both count {k} over one language"
+ seen.setdefault(k, []).append(t)
def test_3dcode_skills_list_shows_every_bundles_claim():
diff --git a/harness/tests/skills/test_variants.py b/harness/tests/skills/test_variants.py
new file mode 100644
index 00000000..e749c53f
--- /dev/null
+++ b/harness/tests/skills/test_variants.py
@@ -0,0 +1,341 @@
+"""The skills half of a variant (D105): overlay bundles, the typed routes.toml, boosts, disabled
+rules, extra rows, the claims lookup and what attach_skills stamps."""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from types import SimpleNamespace as NS
+
+import pytest
+
+from codeverse3d.config import get_settings
+from codeverse3d.prompts import variants as V
+from codeverse3d.prompts.variants import activate
+from codeverse3d.skills import (
+ RouteBoost,
+ VariantRoutes,
+ all_skills,
+ bundle_dirs,
+ library_roots,
+ load_skill,
+ parse_routes,
+ variant_dir,
+ variants_table,
+)
+from codeverse3d.skills.registry import (
+ GATE_FIRED_PRIORITY,
+ ROUTED_SKILLS,
+ ROUTES,
+ Route,
+ effective_priority,
+ select,
+)
+from tests.skills.conftest import write_bundle
+
+ROUTES_TOML = """
+[[boost]]
+skill = "c3d-repeats-and-mirrors"
+delta = 20
+
+[[disable]]
+rule = "R3"
+
+[[route]]
+rule = "V1"
+skill = "c3d-new-sheet"
+priority = 80
+tracks = ["static_object"]
+kinds = ["baseline"]
+why = "a test row"
+"""
+
+
+def _plan(n: int = 3, instances: int = 1):
+ return NS(parts=[NS(name=f"P{i}", instances=instances, symmetry="none", children=[]) for i in range(n)], summary="")
+
+
+def variant(tmp_path: Path, monkeypatch) -> Path:
+ """A tmp library (every routed bundle, measured) with the overlay ``variants/tv/``: a shadowing
+ ``c3d-part-contact``, a new ``c3d-new-sheet``, its own ``_claims`` and ``routes.toml``; plus the prompts
+ half (``variant.toml``) so ``activate("tv")`` is legal."""
+ lib = tmp_path / "lib"
+ for name in ROUTED_SKILLS:
+ write_bundle(lib, name)
+ overlay = lib / "variants" / "tv"
+ write_bundle(overlay, "c3d-part-contact", body="OVERLAY RULES: seat every part.")
+ write_bundle(overlay, "c3d-new-sheet", description="A sheet only the variant ships. Use it when routed.")
+ (overlay / "_claims").mkdir()
+ (overlay / "_claims" / "c3d-part-contact.toml").write_text("claim = []\n")
+ (overlay / "routes.toml").write_text(ROUTES_TOML)
+ (overlay / "README.md").write_text("docs\n")
+ (lib / "_claims").mkdir()
+ (lib / "_claims" / "c3d-bbox-contract.toml").write_text("claim = []\n")
+ monkeypatch.setenv("C3D_SKILLS_DIR", str(lib))
+ monkeypatch.delenv("C3D_VARIANT", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_ONLY", raising=False)
+ monkeypatch.delenv("C3D_SKILLS_MAX", raising=False)
+ prompts_root = tmp_path / "prompt_variants"
+ (prompts_root / "tv").mkdir(parents=True)
+ (prompts_root / "tv" / "variant.toml").write_text('[variant]\nname = "tv"\nversion = 1\n')
+ monkeypatch.setattr(V, "VARIANTS_DIR", prompts_root)
+ get_settings.cache_clear()
+ yield lib
+ get_settings.cache_clear()
+
+
+# --------------------------------------------------------------------------- the overlay library
+def test_an_overlay_bundle_shadows_the_base_and_a_new_name_is_added(variant):
+ assert library_roots() == [variant]
+ assert "OVERLAY" not in all_skills()["c3d-part-contact"].body and "c3d-new-sheet" not in all_skills()
+ with activate("tv"):
+ assert library_roots() == [variant, variant_dir("tv")]
+ lib = all_skills()
+ assert "OVERLAY RULES: seat every part." in lib["c3d-part-contact"].body
+ assert lib["c3d-part-contact"].dir == variant_dir("tv") / "c3d-part-contact"
+ assert lib["c3d-new-sheet"].dir.parent == variant_dir("tv")
+ assert set(lib) == set(ROUTED_SKILLS) | {"c3d-new-sheet"}
+ assert "OVERLAY RULES: seat every part." in load_skill("c3d-part-contact").body
+ assert load_skill("c3d-bbox-contract").dir.parent == variant, "a bundle the overlay lacks: the base"
+ assert all_skills(variant)["c3d-part-contact"].dir.parent == variant, "an explicit root is that root alone"
+ assert library_roots("tv") == [variant, variant_dir("tv")] and library_roots("none") == [variant]
+ assert [d.name for d in bundle_dirs()] == sorted(ROUTED_SKILLS), "variants/ has no SKILL.md: never listed"
+ assert "OVERLAY" not in load_skill("c3d-part-contact").body
+
+
+def test_claims_are_looked_up_beside_an_overlay_bundle_first(variant):
+ from codeverse3d.addons.skill_targets import claims_path, load_claims
+
+ with activate("tv"):
+ lib = all_skills()
+ assert claims_path(lib["c3d-part-contact"]) == variant_dir("tv") / "_claims" / "c3d-part-contact.toml"
+ assert claims_path(lib["c3d-bbox-contract"]) == variant / "_claims" / "c3d-bbox-contract.toml"
+ assert claims_path(lib["c3d-new-sheet"]) == variant / "_claims" / "c3d-new-sheet.toml", "no own file: the base path"
+ assert claims_path("c3d-part-contact") == variant / "_claims" / "c3d-part-contact.toml", "a bare name: the base"
+ assert load_claims(lib["c3d-part-contact"]) == [] and load_claims("c3d-new-sheet") == []
+
+
+# --------------------------------------------------------------------------- the router
+def test_boosts_move_the_ranking_but_never_cross_the_gate_fired_floor(library, caplog):
+ r3 = next(r for r in ROUTES if r.rule == "R3") # standing, 65
+ r4 = next(r for r in ROUTES if r.rule == "R4") # gate-fired, 95
+ assert effective_priority(r3, {}) == 65 and effective_priority(r3, {"c3d-bbox-contract": 10}) == 75
+ with caplog.at_level(logging.WARNING, logger="codeverse3d.skills.registry"):
+ assert effective_priority(r3, {"c3d-bbox-contract": 40}) == GATE_FIRED_PRIORITY - 1
+ assert "clamped" in caplog.text and "R3" in caplog.text
+ assert effective_priority(r4, {"c3d-bbox-contract": -40}) == GATE_FIRED_PRIORITY
+ assert effective_priority(r4, {"c3d-bbox-contract": 3}) == 98
+ assert effective_priority(r3, {"c3d-bbox-contract": -80}) == 0
+ plan = _plan(instances=2) # R1 part-contact 70, R3 bbox 65, R6 repeats 55, R8 blender-forms 75
+ from codeverse3d.skills.registry import plan_signals
+
+ base = [s.name for s in select("static_object", "blender", "baseline", signals=plan_signals(plan), library=library)]
+ assert base == ["c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract", "c3d-repeats-and-mirrors"]
+ got = select("static_object", "blender", "baseline", signals=plan_signals(plan), library=library,
+ boosts={"c3d-repeats-and-mirrors": 20})
+ # 55 + 20 = 75 ties R8's 75, and R6 sits before R8 in the table: the tie keeps the table order
+ assert [s.name for s in got] == ["c3d-repeats-and-mirrors", "c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract"]
+ boosted = got[0]
+ assert boosted.priority == 75 and not boosted.gate_fired and "(variant boost +20)" in boosted.reason
+ # a boost big enough to reach 90 is clamped: a standing row never reads as gate-fired in telemetry
+ got = select("static_object", "blender", "baseline", signals=plan_signals(plan), library=library,
+ boosts={"c3d-repeats-and-mirrors": 60})
+ assert got[0].name == "c3d-repeats-and-mirrors" and got[0].priority == 89 and not got[0].gate_fired
+
+
+def test_disabled_rules_are_skipped(library):
+ from codeverse3d.skills.registry import plan_signals
+
+ got = select("static_object", "blender", "baseline", signals=plan_signals(_plan()), library=library,
+ disabled=frozenset({"R1", "R3"}))
+ assert [s.name for s in got] == ["c3d-blender-forms"]
+ fired = select("static_object", "blender", "repair", findings=["connectivity/penetration"], library=library,
+ disabled=frozenset({"R2"}))
+ assert "c3d-part-contact" not in [s.name for s in fired]
+
+
+def test_extra_routes_are_appended_after_the_base_rows(library):
+ """A tie with a base row keeps the base order; a fresh skill reaches the session through its row."""
+ water = Route("V1", "c3d-scene-water", 75, tracks=("scene",), languages=("scene_threejs",), kinds=("baseline",),
+ why="test")
+ got = select("scene", "scene_threejs", "baseline", library=library, routes=(*ROUTES, water), max_skills=2)
+ assert [s.name for s in got] == ["c3d-scene-composition", "c3d-scene-water"] # R14 at 75 first
+ assert got[1].rules == ("V1",) and got[1].reason.startswith("V1: test")
+ assert "c3d-scene-water" not in [s.name for s in select("scene", "scene_threejs", "baseline", library=library, max_skills=2)]
+
+
+# --------------------------------------------------------------------------- routes.toml
+def test_routes_toml_parses_into_typed_records(variant):
+ table = variants_table("tv")
+ assert table.variant == "tv" and not table.empty
+ assert table.boosts == (RouteBoost(skill="c3d-repeats-and-mirrors", delta=20),)
+ assert table.boost_map == {"c3d-repeats-and-mirrors": 20} and table.disabled == frozenset({"R3"})
+ (route,) = table.routes
+ assert route == Route("V1", "c3d-new-sheet", 80, tracks=("static_object",), kinds=("baseline",), why="a test row")
+ assert variants_table("") == VariantRoutes() and variants_table("").empty
+ assert variants_table("nothing").empty and variants_table("nothing").variant == "nothing"
+ assert variants_table("argon").empty, "the shipped overlay routes nothing yet"
+ summed = parse_routes(_write(variant, '[[boost]]\nskill = "a"\ndelta = 5\n[[boost]]\nskill = "a"\ndelta = -2\n'))
+ assert summed.boost_map == {"a": 3}
+
+
+def _write(lib: Path, text: str) -> Path:
+ p = lib / "variants" / "tv" / "routes.toml"
+ p.write_text(text)
+ return p
+
+
[email protected]("text, problem", [
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = "high"\n', r"\[\[route\]\] #0: priority must be an integer"),
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 70\ntrack = "scene"\n', "unknown key"),
+ ('[[route]]\nrule = "V1"\npriority = 70\n', "skill is required"),
+ ('[[route]]\nrule = "R1"\nskill = "x"\npriority = 70\n', "rule id 'R1' is already taken"),
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 70\n[[route]]\nrule = "V1"\nskill = "y"\npriority = 70\n',
+ "rule id 'V1' is already taken"),
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 95\n', "standing row .* must stay below 90"),
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 50\nfindings = ["lint/*"]\n', "gate-fired row .* needs priority >= 90"),
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = 70\ntracks = "scene"\n', "tracks must be a list of non-empty strings"),
+ ('[[route]]\nrule = "V1"\nskill = "x"\npriority = true\n', "priority must be an integer"),
+ ('[[boost]]\nskill = "x"\ndelta = 1.5\n', r"\[\[boost\]\] #0: delta must be an integer"),
+ ('[[boost]]\nskill = "x"\n', "delta must be an integer"),
+ ('[[disable]]\nrule = 27\n', "rule must be a string"),
+ ('[[disable]]\nrule = ""\n', "rule is required"),
+ ('[[routes]]\nrule = "V1"\n', "unknown table"),
+ ('boost = 3\n', r"\[\[boost\]\] must be an array of tables"),
+ ('[[boost]\nskill = "x"\n', "not valid TOML"),
+])
+def test_routes_toml_typing_errors_are_refused(variant, text, problem):
+ with pytest.raises(ValueError, match=problem):
+ parse_routes(_write(variant, text))
+ with pytest.raises(ValueError, match=problem):
+ variants_table("tv")
+
+
+# --------------------------------------------------------------------------- the CLIs walk the overlays
+BROKEN_SKILL = "---\nname: c3d-bbox-contract\ndescription: the closing fence is missing\n# body\n"
+
+
+def _cli(*args: str, width: int = 300):
+ """``3dcode skills ...`` through typer's runner, the CLI console wide enough for one table row per
+ line: an xdist worker runs under ``COLUMNS=80``, which rich pins on the console when it is built, so
+ the width is set on the console itself (and restored) rather than through the environment."""
+ from unittest import mock
+
+ from typer.testing import CliRunner
+
+ from codeverse3d.cli import _common
+ from codeverse3d.cli.main import app
+
+ with mock.patch.object(_common.console, "_width", width):
+ return CliRunner().invoke(app, ["skills", *args])
+
+
+def test_skills_validate_walks_every_shipped_overlay_and_a_broken_overlay_bundle_fails(variant):
+ """A loop iteration writes bundles into ``skills/variants/<v>/`` and they are routed the moment the
+ variant is active — so ``skills validate`` must see them, labelled by their variant, and a malformed
+ one must FAIL here instead of vanishing from a session with a logged warning (the row that named
+ it then routes nothing)."""
+ n = len(ROUTED_SKILLS) + 2
+ r = _cli("validate")
+ assert r.exit_code == 0, r.output
+ assert "ok tv/c3d-part-contact" in r.output and "ok tv/c3d-new-sheet" in r.output
+ assert "ok c3d-part-contact" in r.output and f"{n}/{n} bundles valid" in r.output
+ bad = variant_dir("tv") / "c3d-bbox-contract"
+ bad.mkdir()
+ (bad / "SKILL.md").write_text(BROKEN_SKILL)
+ r = _cli("validate")
+ assert r.exit_code == 1
+ assert "FAIL tv/c3d-bbox-contract" in r.output and "frontmatter" in r.output
+ assert "ok c3d-bbox-contract" in r.output, "the base bundle it shadows is still fine"
+ assert f"{n}/{n + 1} bundles valid" in r.output
+ (bad / "SKILL.md").unlink()
+ bad.rmdir()
+ # the overlay's table is checked too: a row that does not type-check is a FAIL named by the variant...
+ _write(variant, '[[route]]\nrule = "V1"\nskill = "x"\npriority = "high"\n')
+ r = _cli("validate")
+ assert r.exit_code == 1 and "FAIL tv/routes.toml" in r.output and "priority must be an integer" in r.output
+ # ...and a row routing a bundle nobody ships gets the base's yellow line, red under --strict
+ _write(variant, '[[route]]\nrule = "V1"\nskill = "c3d-nowhere"\npriority = 70\n')
+ r = _cli("validate")
+ assert r.exit_code == 0 and "tv/routes.toml" in r.output and "V1 -> c3d-nowhere" in r.output
+ assert _cli("validate", "--strict").exit_code == 1
+
+
+def test_skills_list_labels_the_overlay_rows_with_their_variant(variant):
+ r = _cli("list", "--routes")
+ assert r.exit_code == 0, r.output
+ lines = r.output.splitlines()
+ contact = [ln for ln in lines if "c3d-part-contact" in ln]
+ assert len(contact) == 2, "the base bundle and the overlay's shadow of it"
+ assert sum(" tv " in ln for ln in contact) == 1
+ (new_sheet,) = [ln for ln in lines if "c3d-new-sheet" in ln]
+ assert " tv " in new_sheet and "V1" in new_sheet, "an overlay-only bundle, routed by the overlay's own row"
+ assert sum(" tv " in ln for ln in lines) == 2
+
+
+# --------------------------------------------------------------------------- attach_skills + the hook
+def ws(tmp_path: Path) -> Path:
+ root = tmp_path / "ws"
+ root.mkdir()
+ (root / "AGENTS.md").write_text("# body\n")
+ return root
+
+
+def test_attach_skills_routes_through_the_variant_table_and_stamps_the_variant(variant, ws):
+ from codeverse3d.skills.materialize import attach_skills
+
+ kw = {"track": "static_object", "language": "blender", "kind": "baseline", "plan": _plan(instances=2)}
+ base = attach_skills(ws, **kw)
+ assert base.variant == "" and base.listed == ["c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract",
+ "c3d-repeats-and-mirrors"]
+ with activate("tv"):
+ got = attach_skills(ws, **kw)
+ # V1 at 80 leads; the boosted R6 (55+20) ties R8 at 75 and keeps the base order; R3 is disabled
+ assert got.variant == "tv"
+ assert got.listed == ["c3d-new-sheet", "c3d-repeats-and-mirrors", "c3d-blender-forms", "c3d-part-contact"]
+ assert "(variant boost +20)" in got.reasons["c3d-repeats-and-mirrors"] and got.reasons["c3d-new-sheet"].startswith("V1:")
+ contact = next(s for s in got.selections if s.name == "c3d-part-contact")
+ assert "OVERLAY RULES" in contact.skill.body, "the overlay bundle, not the base one"
+ assert "OVERLAY RULES" in (ws / ".agents" / "skills" / "c3d-part-contact" / "SKILL.md").read_text()
+ assert (ws / ".claude" / "skills" / "c3d-new-sheet" / "SKILL.md").is_file()
+
+
+def test_a_broken_routes_toml_costs_the_overlay_not_the_round(variant, ws, caplog):
+ from codeverse3d.skills.materialize import attach_skills
+
+ _write(variant, '[[route]]\nrule = "V1"\nskill = "x"\npriority = "high"\n')
+ with caplog.at_level(logging.WARNING, logger="codeverse3d.skills.materialize"), activate("tv"):
+ got = attach_skills(ws, track="static_object", language="blender", kind="baseline", plan=_plan(instances=2))
+ assert "routes.toml rejected" in caplog.text and "priority must be an integer" in caplog.text
+ assert got.variant == "tv"
+ assert got.listed == ["c3d-blender-forms", "c3d-part-contact", "c3d-bbox-contract", "c3d-repeats-and-mirrors"]
+ assert "OVERLAY RULES" in next(s for s in got.selections if s.name == "c3d-part-contact").skill.body, \
+ "the overlay BUNDLES still shadow: only the table fell back"
+
+
+class _Events(list):
+ def emit(self, name, **kw):
+ self.append((name, kw))
+
+
+def test_the_hook_carries_the_variant_into_the_event_and_the_telemetry_row(variant, ws, monkeypatch):
+ from codeverse3d.proc import read_jsonl_lenient
+ from codeverse3d.tracks import skills_hook as H
+
+ monkeypatch.setenv("C3D_SKILLS", "on")
+ hashes: dict[str, str] = {}
+ ctx = NS(ws=NS(root=ws), spec=NS(track=NS(value="static_object")), language=NS(value="blender"),
+ agent_id="agy:gemini-4-argon", agent_kind="agy", plan=_plan(instances=2), single_shot=False, extra={},
+ events=_Events(), prompt_hashes=hashes, record_prompt=lambda name, text: hashes.__setitem__(name, text))
+ with activate("tv"):
+ got = H.attach_for_round(ctx, index=0, kind="baseline")
+ assert got is not None and got.variant == "tv"
+ usage = H.record_usage(ctx, index=0, kind="baseline")
+ assert usage is not None
+ attached = next(kw for name, kw in ctx.events if name == "skills.attached")
+ assert attached["variant"] == "tv" and attached["skills"] == got.listed
+ assert "OVERLAY RULES" in hashes["skill:c3d-part-contact"], "the body a session saw is what is hashed"
+ (row,) = read_jsonl_lenient(ws / "telemetry" / "skills.jsonl")
+ assert row["variant"] == "tv" and row["agent"] == "agy:gemini-4-argon" and row["listed"] == got.listed
diff --git a/harness/tests/texturing/test_gate.py b/harness/tests/texturing/test_gate.py
index 3d44518c..e556e279 100644
--- a/harness/tests/texturing/test_gate.py
+++ b/harness/tests/texturing/test_gate.py
@@ -17,7 +17,7 @@ def _asset(tid: str, seam: float, ok_path: Path) -> TextureAsset:
@pytest.mark.parametrize(("rubric", "criterion"), [
("static_object_v1", "materials"), ("reference_v1", "material_color"), ("asset_v1", "material_truth"),
- ("scene_v1", "materials_shaders_effects"), ("articulated_v1", ""), ("shader_v2", ""),
+ ("scene_v1", "materials_shaders_effects"), ("scene_v2", "materials_shaders_effects"), ("articulated_v1", ""), ("shader_v2", ""),
])
def test_the_rubric_flags_its_materials_criterion(rubric, criterion):
"""N64: the gate sniffed criterion ids by prefix (law 4); a rubric now says which one it is."""
diff --git a/harness/tests/threejs_render/test_lint.py b/harness/tests/threejs_render/test_lint.py
index 3d032e3a..eeb65d60 100644
--- a/harness/tests/threejs_render/test_lint.py
+++ b/harness/tests/threejs_render/test_lint.py
@@ -88,3 +88,15 @@ def test_syntax_error_reported_with_line(stool_ws: Workspace):
rep = lint_workspace(stool_ws)
assert not rep.passed
assert any("seat.js:13" in m and "SyntaxError" in m for m in _msgs(rep, Severity.ERROR))
+
+
+def test_importing_a_name_the_part_does_not_export(stool_ws: Workspace, no_node_syntax):
+ """The file exists, so the import lint passed it; node then fails to link the module."""
+ (stool_ws.src / "object.js").write_text(
+ "import * as THREE from 'three';\nimport { buildSeat, buildCushion } from './parts/seat.js';\n"
+ "export function build(THREE_) { const root = new THREE.Group(); root.add(buildSeat(THREE)); return root; }\n")
+ rep = lint_workspace(stool_ws)
+ assert _msgs(rep, Severity.ERROR) == [
+ "src/object.js:2: import { buildCushion } from './parts/seat.js': that module exports no 'buildCushion' (it exports: buildSeat)"]
+ f = next(f for f in rep.findings if "buildCushion" in f.message)
+ assert f.data["kind"] == "bad_import" and f.target == "src/object.js" and "build<Pascal>" in f.fix_hint
diff --git a/toolkits/curation/articraft/driver_urdf_render.py b/toolkits/curation/articraft/driver_urdf_render.py
index ece0fb21..05f0e10a 100644
--- a/toolkits/curation/articraft/driver_urdf_render.py
+++ b/toolkits/curation/articraft/driver_urdf_render.py
@@ -3,7 +3,7 @@
import os, subprocess, glob, sys, time
from concurrent.futures import ThreadPoolExecutor
-BL="./tools/blender-5.0.1-linux-x64/blender"
+BL="./tools/blender-5.2.2-linux-x64/blender"
N=int(sys.argv[1]) if len(sys.argv)>1 else 8
SCOPE=sys.argv[2] if len(sys.argv)>2 else "all" # all | geo | tex
FORCE=len(sys.argv)>3 and sys.argv[3]=="force" # 重渲已完成的