Official Codebase of 3DCodeVerse
Python
Harness cleanup for v0.1: delete image-generation residue, pre-rename names, unused starter-lib modules and dead code; halve the offline test suite
gaoypengf5d4add93b89
diff --git a/eval/bench/_oneshot.py b/eval/bench/_oneshot.pyindex ab2aa8a8..1e1a0530 100644--- a/eval/bench/_oneshot.py+++ b/eval/bench/_oneshot.py@@ -460,7 +460,7 @@ class ClaudeOneShot:ok = False# the provider's failure, by the harness's own reading of the same stream (N76): a 529 or a spent# usage limit drops the cell instead of scoring the arm 0 for someone else's outage- end = claude_end(proc, env, stream, text)+ end = claude_end(proc, env, text)(out_dir / "response.md").write_text(text)return OneShotResult(ok=ok, text=text, usage=usage, tool_calls=usage.tool_calls, notes=notes,infra_failed=not ok and (end.transient or end.quota or end.stalled),diff --git a/harness/CLAUDE.md b/harness/CLAUDE.mdindex a739846d..c3b0be47 100644--- a/harness/CLAUDE.md+++ b/harness/CLAUDE.md@@ -11,8 +11,7 @@ review), then reads the result. The harness's OWN api use is planning,judging, and single-shot file generation (Gemini/Anthropic/OpenAI).It does not implement an agent loop: the in-process `api-agent` was deleted2026-08-28 (owner's call — reimplementing what the vendors already ship was never-this project's job). Plus a data-flywheel record per run. There is no-image-generation step (owner, 2026-11-03: not a feature for now).+this project's job). Plus a data-flywheel record per run.Read `docs/ARCHITECTURE.md` (design, package map, authoring contracts, what a runreally does, known limits), `docs/INTERFACES.md` (binding cross-package signatures as@@ -54,7 +53,7 @@ push, with `set -o pipefail` so a `| tail` cannot swallow a red exit. The versi## Environment (this machine)- 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+ or `./3dcodeverse.yaml`, env prefix `C3D_` (thegrammar 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.2.2 LTS headless: `~/.local/bin/blender-5.2` (always `--factory-startup`; clear scene). The judged-framediff --git a/harness/README.md b/harness/README.mdindex eba594c2..6cbe2844 100644--- a/harness/README.md+++ b/harness/README.md@@ -19,7 +19,7 @@ renders, judges, refines and records every run as data-flywheel material.a calibration harness (`addons/calibration.py`).* **Flywheel:** git-versioned `src/` per round, `record.json`, sample export withquality tiers + dedupe (+ parquet, tar locators), preference/repair/cross-backend- pairs, captions, sqlite index, HTML gallery.+ pairs, captions, HTML gallery.* **Looking at results:** `3dcode gallery serve` — a local page over `runs/` +`eval/bench/out/*/runs` with filters, a per-filter summary strip and a detail page per run;it serves the run directories too, so every link (sheet, renders, `src/`, `object.glb`@@ -50,13 +50,12 @@ codeverse3d/spatial/ the measurement/render toolbox behind every gate and MCP tooljudges/ rubric VLM judge on labelled montages, pairwise, reference/likenessreference.py a user `--image` against the render: proportion check, mismatch diff- texturing/ the PBR material-family table (languages/blender reads it)cost/ append-only ledger, metering, per-block tallies, pre-call estimatesskills/ typed skill routes + materialisation + read telemetryrecord/ what every run writes: record.json, deliverable/, telemetryaddons/ optional tools that READ finished runs — nothing a run needs:gallery (the runs browser), dataset (export, tiers, preference/repair pairs,- captions, sqlite index), costreport (`3dcode cost`), calibration, skill_targets+ captions), costreport (`3dcode cost`), calibration, skill_targetscli/ the typer CLI · doctor.py the environment checks behind `3dcode doctor`../eval/bench/ the evaluation harness around the harness: run_bench, compare_backends(A/B matrix), ab_plan, infra-failure classificationdiff --git a/harness/codeverse3d/__init__.py b/harness/codeverse3d/__init__.pyindex 6608d63c..723428a0 100644--- a/harness/codeverse3d/__init__.py+++ b/harness/codeverse3d/__init__.py@@ -27,22 +27,4 @@ Package map (each sub-package has its own docstring):- ``cli`` ``3dcode`` command line."""-import os as _os-__version__ = "0.1.0"---def _adopt_legacy_env() -> None:- """``CV3D_`` was the settings prefix until D78 (2026-09-22). A shell or a script that still- sets ``CV3D_X`` keeps working: each one with no ``C3D_X`` beside it is copied over once, at- first import — before anything reads a switch — and named in one warning."""- old = sorted(k for k in _os.environ if k.startswith("CV3D_") and "C3D_" + k[5:] not in _os.environ)- for k in old:- _os.environ["C3D_" + k[5:]] = _os.environ[k]- if old:- import logging-- logging.getLogger(__name__).warning("the CV3D_ prefix is now C3D_; read as C3D_: %s", ", ".join(old))---_adopt_legacy_env()diff --git a/harness/codeverse3d/addons/costreport/caching.py b/harness/codeverse3d/addons/costreport/caching.pyindex 67739265..c245aaa5 100644--- a/harness/codeverse3d/addons/costreport/caching.py+++ b/harness/codeverse3d/addons/costreport/caching.py@@ -51,14 +51,12 @@ class SessionCache:def session_key(label: str) -> str:- """Collapse a per-call label to its session: ``api-agent:refine_legs:t7`` →+ """Collapse a per-call label to its session: ``refine_legs:t7`` →``refine_legs``, ``judge:static_object:r02:s1`` → ``judge:static_object``.A session is what shares a prompt prefix: every turn of one agent session,every sample of one verdict."""parts = [p for p in (label or "").split(":") if p]- if parts and parts[0] == "api-agent": # historical ledgers only (backend deleted 2026-08-28)- parts = parts[1:]while parts and len(parts[-1]) > 1 and parts[-1][0] in "tsr" and parts[-1][1:].isdigit():parts = parts[:-1]return ":".join(parts)diff --git a/harness/codeverse3d/addons/dataset/__init__.py b/harness/codeverse3d/addons/dataset/__init__.pyindex bb43b772..35bbfb8f 100644--- a/harness/codeverse3d/addons/dataset/__init__.py+++ b/harness/codeverse3d/addons/dataset/__init__.py@@ -5,7 +5,6 @@* ``pairs`` ``build_pairs(runs_dir, out_jsonl, min_delta=..)`` → n* ``refine`` the refine-transition rows (``RefineTransition``)* ``captions`` ``caption_sample(ws, record, model_id)`` → ``Captions``-* ``index`` ``build_index(runs_dir, out_sqlite)`` + query helpers* ``sample`` one run → one dataset sample (the code files of its picked round)* ``quality`` ``quality_tier`` (A/B/C/D) · ``prompt_id`` · code fingerprints, duplicate groups"""diff --git a/harness/codeverse3d/addons/dataset/index.py b/harness/codeverse3d/addons/dataset/index.pydeleted file mode 100644index ec81323f..00000000--- a/harness/codeverse3d/addons/dataset/index.py+++ /dev/null@@ -1,148 +0,0 @@-"""Small SQLite index over run records (runs / rounds / usage) for dashboards.--``build_index(runs_dir, out_sqlite)`` rebuilds the database from scratch;-query helpers return plain dicts so a dashboard / notebook needs no ORM. A run's-row describes the round every reader shows (``picked_round`` = ``select.summarise().round``:-the pick, else ``select.fallback_round``; a NULL ``picked_score`` marks it unjudged); a run has no-pass/fail — the ``rounds`` table carries the judge's own verdict per round.-"""--from __future__ import annotations--import sqlite3-from pathlib import Path-from typing import Any--from codeverse3d.addons import select-from codeverse3d.addons.dataset.quality import prompt_id, quality_tier-from codeverse3d.addons.dataset.sample import gate_error_summary-from codeverse3d.contracts.run import RoundRecord, RunId, RunRecord-from codeverse3d.record.record import effective_judgment, iter_runs, skip_unreadable-from codeverse3d.workspace import Workspace--_SCHEMA = """-CREATE TABLE runs (- slug TEXT PRIMARY KEY, workspace TEXT, track TEXT, language TEXT, prompt TEXT, prompt_hash TEXT,- generator TEXT, planner TEXT, judge TEXT, status TEXT, -- status: why the run stopped- baseline_score REAL, picked_score REAL, picked_round INTEGER, n_rounds INTEGER,- cost_usd REAL, input_tokens INTEGER, output_tokens INTEGER,- started_at TEXT, finished_at TEXT, minutes REAL, error TEXT, has_captions INTEGER,- gate_errors INTEGER, quality_tier TEXT, picked_commit TEXT,- rel TEXT, arm TEXT, cell TEXT -- run dir relative to the scan root + battery layout segments-);-CREATE TABLE rounds (- slug TEXT, round_index INTEGER, kind TEXT, commit_sha TEXT, agent_backend TEXT,- build_ok INTEGER, gate_errors INTEGER, score REAL, passed INTEGER, n_issues INTEGER,- cost_usd REAL, minutes REAL, started_at TEXT,- PRIMARY KEY (slug, round_index)-);-CREATE TABLE usage (- slug TEXT, round_index INTEGER, role TEXT, backend TEXT, model TEXT, -- role: round (agent+judge) | judge- input_tokens INTEGER, output_tokens INTEGER, cached_tokens INTEGER, thoughts_tokens INTEGER,- tool_calls INTEGER, cost_usd REAL, latency_ms INTEGER-);-CREATE INDEX idx_runs_track ON runs(track, language);-CREATE INDEX idx_runs_prompt ON runs(prompt_hash);-CREATE INDEX idx_rounds_slug ON rounds(slug);-"""---def _run_row(ws: Workspace, rec: RunRecord, rid: RunId) -> tuple:- s = select.summarise(ws.root, record=rec)- picked = next((r for r in rec.rounds if r.index == s.round), None)- j = effective_judgment(picked) if picked is not None else None # degraded → unjudged- n_err = sum(gate_error_summary(picked).values())- tier = quality_tier(passed=j.passed if j else None, gate_errors=n_err, score=j.overall if j else None)- return (- rid.slug, str(ws.root), rec.spec.track.value, rec.spec.language.value, rec.spec.prompt,- prompt_id(rec.spec.prompt), rec.spec.backends.generator, rec.spec.backends.planner,- rec.spec.backends.judge, s.stop_reason, s.baseline_score, s.picked_score, s.round,- len(rec.rounds), rec.total_usage.cost_usd, rec.total_usage.input_tokens,- rec.total_usage.output_tokens, rec.started_at.isoformat(),- rec.finished_at.isoformat() if rec.finished_at else None, rec.minutes, rec.error,- int(bool((rec.extra.get("captions") or {}).get("detailed"))),- n_err, tier, picked.commit if picked is not None else "",- rid.rel, rid.arm, rid.cell,- )---def _round_row(slug: str, r: RoundRecord) -> tuple:- j = effective_judgment(r) # degraded → unscored- return (- slug, r.index, r.kind, r.commit, r.agent_backend,- None if r.build is None else int(r.build.ok), sum(len(g.errors) for g in r.gates),- j.overall if j is not None else None,- None if j is None else int(j.passed), 0 if j is None else len(j.issues),- r.usage.cost_usd, r.minutes, r.started_at.isoformat(),- )---def _usage_rows(slug: str, r: RoundRecord) -> list[tuple]:- """``round`` = the round's total (agent session + its judge call); ``judge`` = the judge part of it."""- rows = [(slug, r.index, "round", r.usage.backend, r.usage.model, r.usage.input_tokens, r.usage.output_tokens,- r.usage.cached_tokens, r.usage.thoughts_tokens, r.usage.tool_calls, r.usage.cost_usd, r.usage.latency_ms)]- if r.judgment is not None:- u = r.judgment.usage- rows.append((slug, r.index, "judge", u.backend, u.model, u.input_tokens, u.output_tokens, u.cached_tokens,- u.thoughts_tokens, u.tool_calls, u.cost_usd, u.latency_ms))- return rows---def build_index(runs_dir: Path | str, out_sqlite: Path | str) -> int:- """(Re)build the SQLite index; returns the number of runs indexed."""- out = Path(out_sqlite)- out.parent.mkdir(parents=True, exist_ok=True)- tmp = out.with_suffix(out.suffix + ".tmp")- if tmp.exists():- tmp.unlink()- n = 0- con = sqlite3.connect(tmp)- try:- con.executescript(_SCHEMA)- seen: dict[str, str] = {}- for ws, rec, rid in iter_runs(runs_dir, on_error=skip_unreadable):- slug = rid.slug- try:- con.execute(f"INSERT INTO runs VALUES ({','.join('?' * 28)})", _run_row(ws, rec, rid))- except sqlite3.IntegrityError as e:- # never INSERT OR REPLACE: a silent overwrite is the bug this guards- raise sqlite3.IntegrityError(- f"duplicate run slug {slug!r}: {seen.get(slug, '<unknown>')} and {ws.root}"- ) from e- seen[slug] = str(ws.root)- con.executemany(f"INSERT INTO rounds VALUES ({','.join('?' * 13)})", [_round_row(slug, r) for r in rec.rounds])- con.executemany(f"INSERT INTO usage VALUES ({','.join('?' * 12)})",- [row for r in rec.rounds for row in _usage_rows(slug, r)])- n += 1- con.commit()- finally:- con.close()- tmp.replace(out)- return n---# --------------------------------------------------------------------------- queries-def _connect(db: Path | str) -> sqlite3.Connection:- con = sqlite3.connect(f"file:{Path(db)}?mode=ro", uri=True)- con.row_factory = sqlite3.Row- return con---def query(db: Path | str, sql: str, params: tuple = ()) -> list[dict[str, Any]]:- con = _connect(db)- try:- return [dict(r) for r in con.execute(sql, params).fetchall()]- finally:- con.close()---def summary(db: Path | str) -> list[dict[str, Any]]:- """Per (track, language, generator): n, mean baseline / picked score and their delta, cost."""- return query(- db,- "SELECT track, language, generator, COUNT(*) AS n, "- "AVG(baseline_score) AS baseline_mean, AVG(picked_score) AS picked_mean, "- "AVG(picked_score - baseline_score) AS delta_mean, SUM(cost_usd) AS cost_usd, "- "AVG(n_rounds) AS rounds_mean, SUM(quality_tier = 'A') AS n_tier_a, SUM(quality_tier = 'B') AS n_tier_b "- "FROM runs GROUP BY track, language, generator ORDER BY track, language",- )diff --git a/harness/codeverse3d/addons/dataset/refine.py b/harness/codeverse3d/addons/dataset/refine.pyindex a2fe43bb..c9b37657 100644--- a/harness/codeverse3d/addons/dataset/refine.py+++ b/harness/codeverse3d/addons/dataset/refine.py@@ -139,7 +139,7 @@ def transitions(runs_dir: Path | str, *, threshold: float = MIN_PREFERENCE_DELTAA run reachable through more than one path (54 of 239 under ``eval/bench/out``, where thebatteries symlink each other's cells) is found once (``find_run_dirs``), at the path itphysically lives at. A row is named by its ``RunId`` (``battery``, ``run`` = the slug), the- key of ``index.sqlite`` and of the exported samples."""+ key of the exported samples."""drops = drops if drops is not None else Counter()root = Path(runs_dir)for found in iter_runs(root, on_error=lambda p, e: drops.update([f"unreadable_record: {type(e).__name__}"])):diff --git a/harness/codeverse3d/addons/gallery/index.py b/harness/codeverse3d/addons/gallery/index.pyindex 7d7dd11d..5c4310cd 100644--- a/harness/codeverse3d/addons/gallery/index.py+++ b/harness/codeverse3d/addons/gallery/index.py@@ -160,8 +160,6 @@ def entry_links(ws: Workspace, rec: RunRecord | None, picked: int | None) -> lisif gif:links.append(RunLink(label="preview.gif", rel=gif))frames = ("deliverable/frames", f"artifacts/renders/r{picked:02d}") if rnd is not None else ("artifacts/frames",)- if rnd is not None and out == ws.artifacts:- frames += ("artifacts/frames",) # the one round an old run rebuilt thereframes_rel = next((f for f in frames if any((run / f).glob("f*_t*.png")) or any((run / f).glob("frame_t*.png"))), "")if frames_rel:links.append(RunLink(label="frames/", rel=frames_rel, kind="dir"))diff --git a/harness/codeverse3d/addons/gallery/model.py b/harness/codeverse3d/addons/gallery/model.pyindex c5809f96..175fc172 100644--- a/harness/codeverse3d/addons/gallery/model.py+++ b/harness/codeverse3d/addons/gallery/model.py@@ -94,7 +94,7 @@ def humanize_view(name: str) -> str:LinkKind = Literal["file", "dir", "code", "viewer"]RunState = Literal["ok", "pending", "broken"]-#: filter names the index page and ``/api/runs`` both understand+#: filter names the index page understandsFILTER_KEYS = ("q", "track", "lang", "tier", "backend", "verdict", "battery")diff --git a/harness/codeverse3d/addons/gallery/server.py b/harness/codeverse3d/addons/gallery/server.pyindex 0276bd85..f9fb41ac 100644--- a/harness/codeverse3d/addons/gallery/server.py+++ b/harness/codeverse3d/addons/gallery/server.py@@ -18,7 +18,6 @@ Safety model (see also ``gallery/urls.py``):from __future__ import annotationsimport contextlib-import jsonimport osimport threadingfrom dataclasses import dataclass, field@@ -32,14 +31,13 @@ from codeverse3d.addons.gallery import viewer as viewer_pagefrom codeverse3d.addons.gallery.compare import MAX_COMPARE, export_csv, parse_keys, render_comparefrom codeverse3d.addons.gallery.detail import render_broken_detail, render_detailfrom codeverse3d.addons.gallery.index import build_index, entry_from_record-from codeverse3d.addons.gallery.model import FILTER_KEYS, RunEntry, match, sort_entries, summarize+from codeverse3d.addons.gallery.model import FILTER_KEYS, RunEntry, match, sort_entriesfrom codeverse3d.addons.gallery.page import render_indexfrom codeverse3d.addons.gallery.theme import esc, footer, page_shell, top_barfrom codeverse3d.addons.gallery.urls import PathError, UrlMaker, content_type, safe_joinDEFAULT_HOST = "127.0.0.1"DEFAULT_PORT = 8765-LOOPBACK = {"127.0.0.1", "::1", "localhost", "0:0:0:0:0:0:0:1"}STREAM_CHUNK = 256 * 1024#: /file/ content types a browser would EXECUTE: served with ``CSP: sandbox`` so an#: LLM-authored HTML/SVG artifact never runs same-origin with the gallery. An@@ -52,19 +50,6 @@ class GalleryError(RuntimeError):"""The server cannot start (bad host, port in use, no roots)."""-def resolve_host(host: str | None, *, explicit: bool = False) -> str:- """Loopback unless the user explicitly asked for something else.-- A default, an env var or a config file can never move the gallery off- 127.0.0.1: only ``explicit=True`` (the ``--host`` flag was typed) does."""- if host is None or not host.strip():- return DEFAULT_HOST- h = host.strip()- if h not in LOOPBACK and not explicit:- raise GalleryError(f"refusing to bind {h}: pass --host {h} explicitly to leave loopback")- return h--@dataclassclass Response:"""What a route produced: either a body or a file to stream."""@@ -79,15 +64,6 @@ class Response:def html(cls, markup: str, status: int = 200) -> Response:return cls(status=status, body=markup.encode("utf-8"))- @classmethod- def json(cls, payload: Any, status: int = 200) -> Response:- return cls(status=status, content_type="application/json; charset=utf-8",- body=json.dumps(payload, default=str).encode("utf-8"))-- @classmethod- def text(cls, text: str, status: int = 200) -> Response:- return cls(status=status, content_type="text/plain; charset=utf-8", body=text.encode("utf-8"))-@classmethoddef csv(cls, text: str, filename: str = "runs.csv") -> Response:return cls(content_type="text/csv; charset=utf-8", body=text.encode("utf-8"),@@ -187,16 +163,12 @@ class GalleryApp:self.index, self.urls, title=self.title, flt=self._filters(query),sort=query.get("sort", "score"), view=query.get("view", "cards")))head, rest = parts[0], parts[1:]- if head == "healthz":- return Response.text("ok")if head == "compare":entries, urls, note = self._picked(query)return Response.html(render_compare(entries, urls, note=note))if head in ("export.csv", "export"):entries, _, _note = self._picked(query)return Response.csv(export_csv(entries or self.selected(query)))- if head == "api":- return self._api(rest, query)if head == "vendor":target = viewer_page.vendor_path("/".join(rest), self.runtime_js)if target is None:@@ -266,19 +238,6 @@ class GalleryApp:return (ordered[i - 1] if i > 0 else None,ordered[i + 1] if i + 1 < len(ordered) else None)- def _api(self, rest: list[str], query: dict[str, str]) -> Response:- self.refresh()- what = rest[0] if rest else "runs"- if what == "runs":- rows = self.selected(query)- return Response.json({"n": len(rows), "total": len(self.index.entries()),- "runs": [e.model_dump(mode="json") for e in rows]})- if what == "summary":- return Response.json(summarize(self.selected(query)).model_dump(mode="json"))- if what == "index":- return Response.json(self.index.model_dump(mode="json"))- raise FileNotFoundError("/api/" + "/".join(rest))-def _js_type(path: Path) -> str:"""Vendor modules must be served as JavaScript for ``<script type=module>``."""@@ -360,11 +319,11 @@ def make_server(app: GalleryApp, host: str = DEFAULT_HOST, port: int = DEFAULT_Praise GalleryError(f"cannot bind {host}:{port}: {e}") from e-def serve(roots: list[Path] | list[str], *, host: str | None = None, host_explicit: bool = False,+def serve(roots: list[Path] | list[str], *, host: str | None = None,port: int = DEFAULT_PORT, reload: bool = False, open_browser: bool = False,title: str = "3dcode gallery", on_start: Any = None) -> None:"""Build the index and serve it until Ctrl-C."""- bind = resolve_host(host, explicit=host_explicit)+ bind = host or DEFAULT_HOSTapp = GalleryApp(roots, reload=reload, title=title)httpd = make_server(app, bind, port)url = f"http://{'127.0.0.1' if bind == '0.0.0.0' else bind}:{httpd.server_address[1]}/" # noqa: S104diff --git a/harness/codeverse3d/addons/select.py b/harness/codeverse3d/addons/select.pyindex 45e3c471..eba1fe22 100644--- a/harness/codeverse3d/addons/select.py+++ b/harness/codeverse3d/addons/select.py@@ -198,7 +198,7 @@ def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: stseen = hashlib.sha256("\n".join(sha256_file(v.path) if Path(v.path).is_file() else v.pathfor rs in renders for v in rs.views).encode()).hexdigest()stored = read_json_or_none(cache) or {}- if (stored.get("model") == model and stored.get("renders", seen) == seen # pre-2026-09-23 caches kept no fingerprint+ if (stored.get("model") == model and stored.get("renders") == seenand isinstance(stored.get("note"), dict)):return PairwiseNote.model_validate(stored["note"])try:diff --git a/harness/codeverse3d/addons/skill_targets.py b/harness/codeverse3d/addons/skill_targets.pyindex 478b5618..a44b5902 100644--- a/harness/codeverse3d/addons/skill_targets.py+++ b/harness/codeverse3d/addons/skill_targets.py@@ -38,7 +38,6 @@ from codeverse3d.skills.model import Skill#: the direction that counts as an improvementDOWN = "down"UP = "up"-DIRECTIONS = (DOWN, UP)#: where the readout gets the numberSRC_GATE = "gate_kinds" #: count findings of `kinds` in the last gated round@@ -337,18 +336,12 @@ TARGETS: tuple[Target, ...] = ()BY_SKILL: dict[str, Target] = {t.skill: t for t in TARGETS}-METRICS: frozenset[str] = frozenset(t.metric for t in TARGETS)def target_for(skill: str) -> Target | None:return BY_SKILL.get(skill)-def gate_kinds_claimed() -> frozenset[str]:- """Every registry kind some row counts — what test_targets checks is still live."""- return frozenset(k for t in TARGETS for k in t.kinds)--# ===================================================================== claims# A claim pins a number some text states to the code constant that produces it: a skill's# ``_claims/<name>.toml`` (its SKILL.md body, or a bundle file such as ``references/x.md`` viadiff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.pyindex 979f63be..16577a76 100644--- a/harness/codeverse3d/agents/backends.py+++ b/harness/codeverse3d/agents/backends.py@@ -66,10 +66,6 @@ class _CliAgent:model: strbinary: str- @property- def id(self) -> str:- return f"{self.kind}:{self.model}"-def available(self) -> tuple[bool, str]:if not exists_on_path(self.binary):return False, f"{self.cli_label} CLI not found: {self.binary!r}"@@ -108,16 +104,8 @@ CLAUDE_SETTINGS = {"skillOverrides": {"design": "off", "doctor": "off"}}def parse_claude_json(stdout: str) -> dict[str, Any] | None:- """The ``type == "result"`` envelope, else the one JSON document ``--output-format- json`` printed. A stream (a stream-json array, or the JSONL ``--output-format- stream-json`` writes) without its result event is no envelope: its last line is an- assistant turn of a session that never finished."""- env = find_json_object(stdout, lambda d: d.get("type") == "result")- if env is not None or stdout.lstrip().startswith("["):- return env- if sum(1 for line in stdout.splitlines() if line.lstrip().startswith("{")) > 1:- return None- return find_json_object(stdout, lambda d: True)+ """The ``type == "result"`` envelope of a ``claude -p`` stream, else ``None``."""+ return find_json_object(stdout, lambda d: d.get("type") == "result")class ClaudeStream:@@ -125,7 +113,7 @@ class ClaudeStream:session made, the skill index its ``init`` event reported (the list the model wasshown), each message's usage block (``messages``: the last copy per message id — what asession killed before its result event billed), the CLI's own ``api_retry`` events- (``retries``: ``(t, announced back-off s, HTTP status)``) and when every other event+ (``retries``: ``(t, announced back-off s)``) and when every other eventarrived (``progress``) — the two ``cli_common.provider_wait`` reads.Since 2026-09-22 the backend streams instead of printing one envelope: the envelope@@ -139,7 +127,7 @@ class ClaudeStream:self._at: dict[str, int] = {} # tool_use id → index in calls, for its tool_resultself.messages: dict[str, dict[str, Any]] = {}self.served = ""- self.retries: list[tuple[float, float, int]] = []+ self.retries: list[tuple[float, float]] = []self.progress: list[float] = []def feed(self, line: str) -> None:@@ -154,7 +142,7 @@ class ClaudeStream:returnif ev.get("type") == "system" and ev.get("subtype") == "api_retry":# {"attempt", "max_retries", "retry_delay_ms", "error_status": 529, "error": "overloaded"}- self.retries.append((time.time(), float(ev.get("retry_delay_ms") or 0) / 1000.0, int(ev.get("error_status") or 0)))+ self.retries.append((time.time(), float(ev.get("retry_delay_ms") or 0) / 1000.0))returnself.progress.append(time.time())if ev.get("type") == "system" and ev.get("subtype") == "init":@@ -240,7 +228,7 @@ def primary_served_model(env: dict[str, Any], model: str) -> str:return max(served, key=lambda n: float((served[n] or {}).get("costUSD") or 0.0))-def claude_end(proc: CompletedProc, env: dict[str, Any] | None, stream: ClaudeStream, text: str) -> SessionEnd:+def claude_end(proc: CompletedProc, env: dict[str, Any] | None, text: str) -> SessionEnd:"""How a ``claude -p`` process ended (``cli_common.classify_end`` with claude's evidence: its``api_retry`` events, its result envelope) — the harness session and the bench one-shot alike."""sub = str((env or {}).get("subtype", ""))@@ -317,7 +305,7 @@ class ClaudeCodeAgent(_CliAgent):turns = int((env or {}).get("num_turns") or 0)errors: list[str] = []sub = str((env or {}).get("subtype", ""))- end = claude_end(proc, env, stream, text)+ end = claude_end(proc, env, text)if proc.timed_out:errors.append(watchdog_error(proc))elif env is None or proc.rc != 0:@@ -327,7 +315,7 @@ class ClaudeCodeAgent(_CliAgent):return finish_session(s, ok=end.exit_reason == "completed", exit_reason=end.exit_reason, text=text, usage=usage,tool_calls=n_calls, turns=turns, errors=errors, transient=end.transient, quota=end.quota, stalled=end.stalled,- provider_wait_s=provider_wait([(t, b) for t, b, _ in stream.retries], ended, stream.progress),+ provider_wait_s=provider_wait(stream.retries, ended, stream.progress),rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns, effort=get_settings().agents.claude_effort,session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),model_usage=(env or {}).get("modelUsage", {}),diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.pyindex 8bd3b973..9e6ebae2 100644--- a/harness/codeverse3d/agents/cli_common.py+++ b/harness/codeverse3d/agents/cli_common.py@@ -253,9 +253,8 @@ log = logging.getLogger(__name__)def clean_env(keep: set[str] | frozenset[str] = frozenset()) -> dict[str, str]:"""``os.environ`` minus secrets (the one owner of the patterns: ``proc.scrub_secrets``) but- for the ``keep`` names (a CLI's own auth var), plus the recursion guard — a vendor CLI's env."""+ for the ``keep`` names (a CLI's own auth var) — a vendor CLI's env."""env = scrub_secrets(dict(os.environ)) | {k: v for k, v in os.environ.items() if k in keep}- env["C3D_AGENT_CONTEXT"] = "1"env["PYTHONUNBUFFERED"] = "1"return env@@ -281,7 +280,7 @@ def default_mcp_command(ws: Workspace, *, language: str = "", track: str = "", rdef mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:- """The 3dcode MCP command for this job, from the TYPED job: ``job.mcp_command`` > default.+ """The 3dcode MCP command for this job, from the TYPED job.It deliberately does NOT read the workspace's ``.mcp.json``. That file lives wherethe agent works and every CLI backend runs unsandboxed inside it, so an agent that@@ -289,15 +288,12 @@ def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:with provider credentials in the environment, and (for codex) outside the``--sandbox workspace-write`` its own shell obeys. The command is rebuilt from thejob every session instead; nothing on disk can redirect it (audit 2026-08-27)."""- if job.mcp_command:- return list(job.mcp_command)return default_mcp_command(ws, language=job.language, track=job.track, round_index=job.round)# --------------------------------------------------------------------------- session#: paths the harness owns; never attributed to an agent session even when git sees them change-#: (`.3dcv` = `.3dcode` in a workspace made before the 2026-09-21 rename, still resumable)-HARNESS_OWNED_DIRS = ("artifacts", "trajectories", "stages", "rounds", "_cand", "_assets", ".3dcode", ".3dcv", ".gemini", ".claude", ".agents", ".git")+HARNESS_OWNED_DIRS = ("artifacts", "trajectories", "stages", "rounds", "_cand", "_assets", ".3dcode", ".gemini", ".claude", ".agents", ".git")HARNESS_OWNED_FILES = frozenset({"events.jsonl", "run_state.json", "record.json", "AGENTS.md", "CLAUDE.md",".mcp.json", ".antigravityignore", ".gitignore"})#: gitignored control files git cannot revert (downstream trusts both blindly):@@ -796,7 +792,7 @@ class SessionEnd:def classify_end(proc: CompletedProc, *, ok: bool, text: str, said: Sequence[str] = (),- provider_failed: bool = False, rate_limited: bool | None = None) -> SessionEnd:+ provider_failed: bool = False) -> SessionEnd:"""THE end rule for every CLI backend (N71; D83) — each backend brings only its vendor'sevidence: ``said`` (what the CLI printed about the call that ended it) and ``provider_failed``(a typed vendor verdict: agy's ``AGY_ERROR.retryable``).@@ -817,7 +813,7 @@ def classify_end(proc: CompletedProc, *, ok: bool, text: str, said: Sequence[strif proc.timed_out:return SessionEnd("timeout", stalled=proc.killed_reason == "idle" and not text.strip())quota = is_quota_failure(*said)- limited = is_rate_limited(*said) if rate_limited is None else rate_limited+ limited = is_rate_limited(*said)return SessionEnd("budget" if quota or limited else "error",transient=not quota and (provider_failed or is_transient_failure(*said)),quota=quota, rate_limited=limited)diff --git a/harness/codeverse3d/agents/materialize.py b/harness/codeverse3d/agents/materialize.pyindex 697cb0d5..686cfd4b 100644--- a/harness/codeverse3d/agents/materialize.py+++ b/harness/codeverse3d/agents/materialize.py@@ -49,14 +49,7 @@ IGNORE_LINES = (# --------------------------------------------------------------------------- body-def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str], ws: Workspace | None = None) -> str:- if not spatial_tools:- return (- "## Spatial tools\n\n"- "No spatial tools are available in this session. Verify your work by reading the "- "code carefully and keeping every dimension explicit; the harness builds, measures "- "and renders after you finish.\n"- )+def _tool_section(agent_kind: str, mcp_command: list[str], ws: Workspace | None = None) -> str:from codeverse3d.spatial.registry import list_tools# the MCP server's track/language filter (mcp_server.build_context): this file is@@ -89,7 +82,7 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str],)-def _body(agent_kind: str, contract_md: str, spatial_tools: bool, mcp_command: list[str],+def _body(agent_kind: str, contract_md: str, mcp_command: list[str],ws: Workspace | None = None) -> str:return ("# 3dcode workspace — rules for the coding agent\n\n"@@ -108,7 +101,7 @@ def _body(agent_kind: str, contract_md: str, spatial_tools: bool, mcp_command: l"5. Keep dimensions explicit and in meters; follow the coordinate frame stated in the contract.\n""6. When you are done, reply with a SHORT summary of what you changed and what you verified. ""Do not ask questions — there is no human in the loop; make a reasonable decision and proceed.\n\n"- f"{_tool_section(agent_kind, spatial_tools, mcp_command, ws)}\n"+ f"{_tool_section(agent_kind, mcp_command, ws)}\n"f"## Language contract\n\n{contract_md.strip()}\n")@@ -144,7 +137,6 @@ def materialize_workspace(*,agent_kind: str,contract_md: str,- spatial_tools: bool,mcp_command: list[str] | None = None,) -> None:"""Write AGENTS.md / CLAUDE.md + the ignore file into ``ws``.@@ -161,7 +153,7 @@ def materialize_workspace(written for the agent to read (D107, owner 2026-10-15: no language ships a cookbook; theinterface facts are in the contract, the craft in the routed skills)."""mcp_command = list(mcp_command) if mcp_command else default_mcp_command(ws)- body = _body(agent_kind, contract_md, spatial_tools, mcp_command, ws)+ body = _body(agent_kind, contract_md, mcp_command, ws)for name in BODY_FILES:(ws.root / name).write_text(body)# No MCP server is written into the workspace: every CLI gets 3dcode from a harness-owneddiff --git a/harness/codeverse3d/agents/registry.py b/harness/codeverse3d/agents/registry.pyindex 640ab6df..60a018e7 100644--- a/harness/codeverse3d/agents/registry.py+++ b/harness/codeverse3d/agents/registry.py@@ -3,12 +3,11 @@from __future__ import annotationsfrom functools import lru_cache-from typing import Protocol, runtime_checkable+from typing import Protocolfrom codeverse3d.contracts.agent import AgentJob, AgentResult-@runtime_checkableclass CodingAgent(Protocol):"""Runs ONE headless agent session in ``job.workspace``.@@ -29,9 +28,6 @@ class CodingAgent(Protocol):kind: str # claude-code | codex | agymodel: str- @property- def id(self) -> str: ...-def run(self, job: AgentJob) -> AgentResult: ...def available(self) -> tuple[bool, str]:diff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.pyindex 3409f076..71468f6a 100644--- a/harness/codeverse3d/cli/_common.py+++ b/harness/codeverse3d/cli/_common.py@@ -252,7 +252,7 @@ def check_backends(backends: Any) -> None:from codeverse3d.models.registry import parse_model_idfrom codeverse3d.tracks.generation import is_single_shot, single_shot_model_id- for role in ("generator", "planner", "judge", "captioner"):+ for role in ("generator", "planner", "judge"):value = getattr(backends, role)try:if role != "generator":diff --git a/harness/codeverse3d/cli/doctor.py b/harness/codeverse3d/cli/doctor.pydeleted file mode 100644index 4d1250cf..00000000--- a/harness/codeverse3d/cli/doctor.py+++ /dev/null@@ -1,33 +0,0 @@-"""``3dcode doctor`` — the typer shim over :mod:`codeverse3d.doctor`."""--from __future__ import annotations--import json-from typing import Annotated--import typer--from codeverse3d.cli._common import console, doctor_table-from codeverse3d.doctor import run_doctor--doctor_app = typer.Typer(invoke_without_command=True)---@doctor_app.callback(invoke_without_command=True)-def doctor(- ctx: typer.Context,- live: Annotated[bool, typer.Option("--live", help="make one tiny Gemini call")] = False,- gpu: Annotated[bool, typer.Option("--gpu/--no-gpu", help="probe headless Chrome WebGL")] = True,- skills: Annotated[bool, typer.Option("--skills", help="also check the skill library and its discovery wiring")] = False,- as_json: Annotated[bool, typer.Option("--json")] = False,-) -> None:- """Check python deps, Blender, node/three/puppeteer, keys, CLIs and MCP."""- if ctx.invoked_subcommand:- return- rows = run_doctor(live=live, gpu=gpu, skills=skills)- if as_json:- console.print_json(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows]))- else:- console.print(doctor_table(rows))- if any(s == "FAIL" for _, s, _ in rows):- raise typer.Exit(code=1)diff --git a/harness/codeverse3d/cli/flywheel_cmd.py b/harness/codeverse3d/cli/flywheel_cmd.pyindex 425d68cc..9198adb3 100644--- a/harness/codeverse3d/cli/flywheel_cmd.py+++ b/harness/codeverse3d/cli/flywheel_cmd.py@@ -136,27 +136,3 @@ def caption_cmd(ok(f"captioned {done}, skipped {skipped} (already), failed {failed}")if failed and not done:raise typer.Exit(code=1)---@flywheel_app.command("index")-def index_cmd(- runs_dir: Annotated[Path, typer.Argument()],- out_sqlite: Annotated[Path, typer.Argument()] = Path("runs_index.sqlite"),- show: Annotated[bool, typer.Option("--summary/--no-summary")] = True,-) -> None:- """Build the SQLite index (runs / rounds / usage) and print a summary."""- from codeverse3d.addons.dataset.index import build_index, summary-- n = build_index(runs_dir, out_sqlite)- ok(f"indexed {n} runs → {out_sqlite}")- if show and n:- from rich.table import Table-- t = Table(title="summary")- for col in ("track", "language", "generator", "n", "baseline", "picked", "Δ", "cost"):- t.add_column(col)- for r in summary(out_sqlite):- t.add_row(r["track"], r["language"], r["generator"], str(r["n"]),- f"{(r['baseline_mean'] or 0):.3f}", f"{(r['picked_mean'] or 0):.3f}",- f"{(r['delta_mean'] or 0):+.3f}", f"${(r['cost_usd'] or 0):.2f}")- console.print(t)diff --git a/harness/codeverse3d/cli/inspect_cmd.py b/harness/codeverse3d/cli/inspect_cmd.pyindex ca31738b..44228880 100644--- a/harness/codeverse3d/cli/inspect_cmd.py+++ b/harness/codeverse3d/cli/inspect_cmd.py@@ -1,7 +1,7 @@"""``3dcode render`` / ``3dcode judge`` — act on one existing run.Owns the ``render`` command (the working tree, which ends at the run's last round) with-its round-label refusal and the graphics-track frame copy, and the ``judge`` re-judge that+the graphics-track frame copy, and the ``judge`` re-judge thatwrites ``artifacts/judge/rNN_cli.json`` (default: the round ``addons/select`` picks). Thesingle-run VIEW (``show``, and ``status`` = ``show --section status``) is ``layout_cmd.py``'s.Its sibling ``cli/main.py`` owns the typer app, ``make`` / ``resume`` (spec building + track@@ -27,7 +27,6 @@ from codeverse3d.contracts.spec import Spec# --------------------------------------------------------------------------- render / judgedef render(slug: str,- round_index: Annotated[int | None, typer.Option("--round")] = None,mode: Annotated[str, typer.Option("--mode", help="shaded | wire | normals | clay | silhouette")] = "shaded",@@ -52,7 +51,7 @@ def render(if spec.track is Track.GRAPHICS and (width or height): # the frames are the runtime's size: dropped silentlyraise C.CliError("--width/--height do not apply to a graphics run: its frames are rendered at the runtime's size",code=2)- idx = _render_round_or_refuse(ws, round_index)+ idx = max(ws.rendered_rounds(), default=0)out_dir = out or ws.renders_dir(idx) / ("cli" if mode == "shaded" else f"cli_{mode}")# writes into the run (a graphics render even rebuilds it): one writer per run dirwith C.mutating(ws, what=f"3dcode render {ws.root.name}", action="render"):@@ -214,26 +213,3 @@ def _render_graphics(ws, spec: Spec, out_dir: Path) -> None:},))---def _render_round_or_refuse(ws, round_index: int | None) -> int:- """Which round this render is labelled as — refusing when the label would lie.-- ``render`` renders the WORKING TREE, which ends at the last round the run wrote- (2026-09-22: nothing restores an earlier round). ``--round`` only chose the output- folder, so `3dcode render X --round 3` wrote r03-labelled images of round 4's code.- Rendering another round would need it checked out, which this command does not do —- every round's own renders are already in ``artifacts/renders/rNN/``, and- ``3dcode pick <slug> --round N`` packages any round with its GLB.- """- tree = max(ws.rendered_rounds(), default=0)- if round_index is not None and round_index != tree:- raise C.CliError(- f"cannot render round {round_index}: `render` renders the working tree, which is at "- f"round {tree}, and --round only labels the output folder. Round {round_index}'s renders "- f"are in {ws.renders_dir(round_index)}; `3dcode pick {ws.root.name} --round {round_index}` "- f"packages it.",- code=2)- return tree--diff --git a/harness/codeverse3d/cli/layout_cmd.py b/harness/codeverse3d/cli/layout_cmd.pyindex 7ccbe9c2..a9dcbae7 100644--- a/harness/codeverse3d/cli/layout_cmd.py+++ b/harness/codeverse3d/cli/layout_cmd.py@@ -151,8 +151,6 @@ def print_deliverable(ws: Workspace, record: RunRecord) -> None:console.print(kv_table("deliverable", head))if d is not None:console.print(_deliverable_table(d))- for name, why in d.skipped.items():- warn(f"not packaged: {name} — {why}")else:console.print(kv_table("artifacts (no deliverable/ yet — `3dcode pick` packages a round)",_unpackaged_artifact_rows(ws)))diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.pyindex d505f517..3fcdf113 100644--- a/harness/codeverse3d/cli/main.py+++ b/harness/codeverse3d/cli/main.py@@ -36,7 +36,6 @@ from codeverse3d.cli._common import (warn,)from codeverse3d.cli.cost_cmd import cost_app-from codeverse3d.cli.doctor import doctor_appfrom codeverse3d.cli.flywheel_cmd import flywheel_appfrom codeverse3d.cli.skills_cmd import skills_appfrom codeverse3d.config import get_settings@@ -44,6 +43,24 @@ from codeverse3d.contracts.common import TRACK_INFO, TRACK_LANGUAGES, Budget, Lafrom codeverse3d.contracts.spec import Constraints, ReferenceImage, RunOptions, Spec+# ===================================================================== doctor+def doctor(+ live: Annotated[bool, typer.Option("--live", help="make one tiny Gemini call")] = False,+ gpu: Annotated[bool, typer.Option("--gpu/--no-gpu", help="probe headless Chrome WebGL")] = True,+ as_json: Annotated[bool, typer.Option("--json")] = False,+) -> None:+ """Check python deps, Blender, node/three/puppeteer, keys, CLIs and MCP."""+ from codeverse3d.doctor import run_doctor++ rows = run_doctor(live=live, gpu=gpu)+ if as_json:+ console.print_json(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows]))+ else:+ console.print(C.doctor_table(rows))+ if any(s == "FAIL" for _, s, _ in rows):+ raise typer.Exit(code=1)++# ===================================================================== tools_cmddef tools(name: Annotated[str, typer.Argument(help="'list' or a tool name")] = "list",@@ -141,7 +158,7 @@ def serve_cmd(console.print("[dim]Ctrl-C to stop[/dim]")try:- serve(root_paths, host=host, host_explicit=host is not None, port=port, reload=reload,+ serve(root_paths, host=host, port=port, reload=reload,open_browser=open_browser, title=title, on_start=announce)except GalleryError as e:raise C.CliError(str(e)) from e@@ -174,7 +191,7 @@ app = typer.Typer(help="3dcodeverse: LLMs write raw 3D code; the harness builds, judges, refines, records.",pretty_exceptions_enable=False,)-app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / captions / index.")+app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / captions.")app.add_typer(gallery_app,name="gallery",@@ -183,10 +200,10 @@ app.add_typer(app.add_typer(cost_app, name="cost", help="Cost audit: per stage/role/model, waste, $ per run.")-app.add_typer(doctor_app, name="doctor", help="Environment checks.")app.add_typer(skills_app, name="skills", help="The skill library: list / show / validate / read-rate report.")+app.command("doctor", help="Environment checks.")(doctor)app.command("tools",help="List spatial tools or run one: `3dcode tools list` | `3dcode tools <name> --json '{...}' --workspace ws`.",@@ -241,7 +258,6 @@ def make(] = None,planner: Annotated[str | None, typer.Option()] = None,judge: Annotated[str | None, typer.Option()] = None,- captioner: Annotated[str | None, typer.Option()] = None,image: Annotated[list[Path] | None, typer.Option("--image", help="reference image(s)")] = None,variant: Annotated[str,@@ -326,9 +342,7 @@ def make(candidates = settings.default_candidatesif candidates > 1 and not TRACK_INFO[track].best_of_n: # the same rule for best-of-Nraise _no_best_of_n(track)- backends = settings.backends(- generator=generator, planner=planner, judge=judge, captioner=captioner- )+ backends = settings.backends(generator=generator, planner=planner, judge=judge)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` toodiff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.pyindex 6ed871d1..a761171c 100644--- a/harness/codeverse3d/config.py+++ b/harness/codeverse3d/config.py@@ -2,8 +2,7 @@Resolution order (later wins): built-in defaults < ``~/.config/3dcodeverse/config.yaml``< ``./3dcodeverse.yaml`` < environment variables (``C3D_*``). Secrets are never-written to run records. The names before D78 (``~/.config/codeverse/config.yaml``,-``./codeverse.yaml``, ``CV3D_*``) are still read, each under its new name.+written to run records.Gemini keys: ``GEMINI_API_KEYS`` (csv) or ``GEMINI_API_KEY`` or the owner's``~/.config/astra3d/gemini_keys.env`` file (read-only compatibility).@@ -43,8 +42,6 @@ from codeverse3d.contracts.common import Backends_LEGACY_KEYS_FILE = Path.home() / ".config" / "astra3d" / "gemini_keys.env"_USER_CONFIG = Path.home() / ".config" / "3dcodeverse" / "config.yaml"-#: the file names before D78 (2026-09-22): still read, each UNDER its new name (a new file wins per setting)-_LEGACY_USER_CONFIG = Path.home() / ".config" / "codeverse" / "config.yaml"log = logging.getLogger(__name__)@@ -343,8 +340,6 @@ class Settings(BaseSettings):settle: Flag = Field(default=True, description="scene driver: the boot-time auto-seat")camera_repair: Flag = Field(default=True, description="scene driver: move a camera out of geometry ""(zero triggers on a healthy battery; the case it exists for is fatal)")- auto_exposure: Flag = Field(default=False, description="scene driver: bounded scene-wide exposure "- "into the healthy band")post: Flag = Field(default=True, description="scene pictures: the GTAO + bloom + grade post chain")stream: Flag = Field(default=True, description="Gemini: stream replies with inter-chunk stall ""detection (a hung buffered read held the socket for the whole attempt)")@@ -457,7 +452,7 @@ def _deep_merge(base: dict, overlay: dict) -> dict:def get_settings() -> Settings:"""Build the singleton Settings (cached; call ``get_settings.cache_clear()`` in tests)."""data: dict = {}- for p in (_LEGACY_USER_CONFIG, _USER_CONFIG, Path("codeverse.yaml"), Path("3dcodeverse.yaml")):+ for p in (_USER_CONFIG, Path("3dcodeverse.yaml")):data = _deep_merge(data, _load_yaml(p))s = Settings(**data)if not s.gemini_api_keys:diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.pyindex c6bae1fb..fb67b834 100644--- a/harness/codeverse3d/contracts/agent.py+++ b/harness/codeverse3d/contracts/agent.py@@ -24,8 +24,6 @@ AgentEffort = Literal["low", "medium", "high"]class FileChange(BaseModel):path: strstatus: str # added | modified | deleted- lines_added: int = 0- lines_removed: int = 0class AgentJob(BaseModel):@@ -94,9 +92,6 @@ class AgentJob(BaseModel):"never with ``edit_only`` (a sibling's write cannot be told from an out-of-scope one, so the scope ""revert would undo the sibling's work)",)- mcp_command: list[str] | None = Field(- default=None, description="override for the 3dcode MCP server command"- )@model_validator(mode="after")def _shared_tree_scope(self) -> AgentJob:diff --git a/harness/codeverse3d/contracts/chat.py b/harness/codeverse3d/contracts/chat.pyindex 26916c15..7b7b242c 100644--- a/harness/codeverse3d/contracts/chat.py+++ b/harness/codeverse3d/contracts/chat.py@@ -17,7 +17,6 @@ class TextPart(BaseModel):class ImagePart(BaseModel):type: Literal["image"] = "image"path: str | None = None- data_b64: str | None = Nonemime: str = "image/png"label: str = ""diff --git a/harness/codeverse3d/contracts/plan.py b/harness/codeverse3d/contracts/plan.pyindex b2de9d43..607bcef6 100644--- a/harness/codeverse3d/contracts/plan.py+++ b/harness/codeverse3d/contracts/plan.py@@ -133,8 +133,6 @@ class PartPlan(BaseModel):pmin, pmax = self.bbox.min, self.bbox.maxfor c in self.children:key = to_snake(c.name)- if not key:- raise ValueError(f"part {self.name}: a sub-part has an empty name")if key == to_snake(self.name):raise ValueError(f"part {self.name}: sub-part {c.name} repeats its parent's name")if key in seen:@@ -172,13 +170,8 @@ class StaticPlan(BaseModel):for p in self.parts:if p.attach_to and to_snake(p.attach_to) not in names:raise ValueError(f"part {p.name} attaches to unknown part {p.attach_to}")- dotted: set[str] = set()for p in self.parts:for c in p.children:- key = f"{to_snake(p.name)}.{to_snake(c.name)}"- if key in dotted: # pragma: no cover — PartPlan._children_ok already rejects this- raise ValueError(f"duplicate sub-part name {p.name}.{c.name}")- dotted.add(key)if to_snake(c.name) in names:raise ValueError(f"sub-part {p.name}.{c.name} has the same name as top-level part {c.name}; ""either rename it or promote it to a top-level part")diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.pyindex b17bb920..7c0c6454 100644--- a/harness/codeverse3d/contracts/run.py+++ b/harness/codeverse3d/contracts/run.py@@ -98,7 +98,7 @@ class RunId(BaseModel):``runs/<id>`` layout and catastrophically wrong for nested batteries(compare_backends ``cells/<id>/<arm>/run``, ab_plan``arms/<arm>/cells/<id>/<slug>/run``): hundreds of distinct runs are all named- ``run``, so exports rmtree'd each other, the SQLite index tripped its PRIMARY KEY+ ``run``, so exports rmtree'd each otherand the gallery collapsed whole batteries into one entry.``battery`` labels the scan root the run was found under; ``rel`` is the run@@ -328,7 +328,6 @@ class RunDeliverable(BaseModel):entry: str = Field(default="", description="run-relative entry file of the code snapshot")files: list[DeliverableFile] = Field(default_factory=list)total_bytes: int = 0- skipped: dict[str, str] = Field(default_factory=dict, description="name → why it is not in deliverable/")generated_at: datetime | None = Nonedef by_role(self, role: str) -> list[DeliverableFile]:diff --git a/harness/codeverse3d/contracts/spec.py b/harness/codeverse3d/contracts/spec.pyindex a68cda7e..612e4b96 100644--- a/harness/codeverse3d/contracts/spec.py+++ b/harness/codeverse3d/contracts/spec.py@@ -22,7 +22,6 @@ class Constraints(BaseModel):dimensions_m: dict[str, float] | None = Field(default=None, description="e.g. {'width': 1.2, 'depth': 0.6, 'height': 0.75}")- max_triangles: int | None = Nonestyle: str = ""must_have: list[str] = Field(default_factory=list)must_not: list[str] = Field(default_factory=list)diff --git a/harness/codeverse3d/cost/context.py b/harness/codeverse3d/cost/context.pyindex e8acfdb0..6be53824 100644--- a/harness/codeverse3d/cost/context.py+++ b/harness/codeverse3d/cost/context.py@@ -221,8 +221,8 @@ class AttemptRecord:The metering layer (``instrument.MeteredChatModel``) installs a sink for thesewith :func:`attempt_recording`; the backend reports every round-trip — thewinner included — so a hedge loser's and a charged-but-invalid reply's tokens- reach the ledger instead of vanishing (audit 2026-08-27). Rows written from- these carry ``source="attempt"`` and are excluded from every total."""+ reach the ledger instead of vanishing (audit 2026-08-27). A discarded one that cost+ money becomes a ``source="extra"`` row."""attempt: int #: 1-based issue order within the logical callkey: str #: the full API key that served it; the ledger keeps only its last 4 charsdiff --git a/harness/codeverse3d/cost/instrument.py b/harness/codeverse3d/cost/instrument.pyindex 8ee8dfe5..4e085230 100644--- a/harness/codeverse3d/cost/instrument.py+++ b/harness/codeverse3d/cost/instrument.py@@ -144,12 +144,12 @@ class MeteredChatModel(_Proxy):def _record_attempt(self, request: ChatRequest, call_id: str, rec: AttemptRecord,ledger: CostLedger | None, run: str = "",ctx: CallContext | None = None, tallies: tuple[Tally, ...] | None = None) -> bool:- """One row per round-trip. A round-trip that was DISCARDED and still cost money- (a billed-but-invalid reply, a hedge loser that landed) is money nothing else- records, so it goes in as ``source="extra"`` and counts in every total; the rest- are ``source="attempt"`` forensics, excluded because the call's logical row- already carries their tokens. Returns True when it billed an ``extra``."""- extra = bool(rec.discarded and rec.usage.cost_usd)+ """A round-trip that was DISCARDED and still cost money (a billed-but-invalid reply, a+ hedge loser that landed) is money nothing else records, so it goes in as+ ``source="extra"`` and counts in every total; the others are already on the call's+ logical row. Returns True when it billed an ``extra``."""+ if not (rec.discarded and rec.usage.cost_usd):+ return Falsetry:record_call(rec.usage, run=run, label=request.label,stage=ctx.stage if ctx else None, role=ctx.role if ctx else None,@@ -158,13 +158,13 @@ class MeteredChatModel(_Proxy):model=rec.usage.model or self.model,outcome="discarded" if rec.discarded else "ok",latency_ms=rec.usage.latency_ms,- source="extra" if extra else "attempt", key=_key_suffix(rec.key),+ source="extra", key=_key_suffix(rec.key),call_id=call_id, attempt=rec.attempt, discarded=rec.discarded,ledger=ledger, tallies=tallies)except Exception as e: # pragma: no cover - accounting must never break a calllog.debug("cost: could not record attempt %s#%d: %s", request.label, rec.attempt, e)return False- return extra+ return Trueclass _RoundTrips:diff --git a/harness/codeverse3d/cost/ledger.py b/harness/codeverse3d/cost/ledger.pyindex 83f0eb22..32d79613 100644--- a/harness/codeverse3d/cost/ledger.py+++ b/harness/codeverse3d/cost/ledger.py@@ -129,12 +129,9 @@ def process_ledger_path() -> Path:"""The fallback log for calls made with no run context: one file per processunder ``<cache_dir>/cost/``. Never inside a run directory, so it can never bemistaken for a run's own ledger."""- try:- from codeverse3d.config import get_settings+ from codeverse3d.config import get_settings- base = Path(get_settings().cache_dir)- except Exception: # pragma: no cover - settings must never break accounting- base = Path.home() / ".cache" / "codeverse3d"+ base = Path(get_settings().cache_dir)stamp = time.strftime("%Y%m%d", time.localtime())return base / "cost" / f"p{os.getpid()}-{stamp}.jsonl"@@ -286,26 +283,20 @@ def record_call(**extra,)(ledger if isinstance(ledger, CostLedger) else CostLedger(ledger) if ledger else default_ledger()).append(row)- if source != "attempt": # an attempt row's tokens are already on its call's own row- book_usage(Usage(backend=row.backend, model=row.model, input_tokens=row.input_tokens,- output_tokens=row.output_tokens, cached_tokens=row.cached_tokens,- thoughts_tokens=row.thoughts_tokens, tool_calls=row.tool_calls,- cost_usd=row.cost_usd, latency_ms=row.latency_ms), tallies)+ book_usage(Usage(backend=row.backend, model=row.model, input_tokens=row.input_tokens,+ output_tokens=row.output_tokens, cached_tokens=row.cached_tokens,+ thoughts_tokens=row.thoughts_tokens, tool_calls=row.tool_calls,+ cost_usd=row.cost_usd, latency_ms=row.latency_ms), tallies)return row-def load_ledger(path: str | Path, *, include_attempts: bool = False) -> list[CallCost]:+def load_ledger(path: str | Path) -> list[CallCost]:"""Read a ledger file, or a run directory holding one (``telemetry/cost.jsonl``).Bad lines are skipped with a debug log — a truncated last line never loses therest of the file.- ``source="attempt"`` rows (one per round-trip, ``instrument.MeteredChatModel``)- are left out unless ``include_attempts=True``: their tokens are already on the- call's logical row, so every aggregate built on this reader (``summarise``, a run's- ``total_usage``, the cost audit) keeps counting each call exactly once. This is the ONLY- place that filter lives — ``summarise`` used to repeat it, which made- ``include_attempts=True`` summarise to $0. Paid-but-discarded round-trips are- ``source="extra"`` instead and always count: nothing else records them."""+ Paid-but-discarded round-trips are ``source="extra"`` rows and always count: nothing+ else records them."""p = Path(path)if p.is_dir():found = existing_ledger_path(p)@@ -319,8 +310,6 @@ def load_ledger(path: str | Path, *, include_attempts: bool = False) -> list[Calexcept Exception as e: # pragma: no cover - defensivelog.debug("cost ledger %s:%d unreadable: %s", p, i, e)continue- if not include_attempts and row.source == "attempt":- continuerows.append(row)return rows@@ -334,7 +323,7 @@ def _key(row: CallCost, dim: str) -> str:def ledger_usage(rows: Iterable[CallCost]) -> Usage:"""The money and tokens of ``rows`` as one ``Usage`` — how a run's ``total_usage`` is read- off its ledger (list price; attempt rows are already out: ``load_ledger``)."""+ off its ledger (list price)."""t = summarise(rows, dimensions=()).totalreturn Usage(input_tokens=t.input_tokens, output_tokens=t.output_tokens, cached_tokens=t.cached_tokens,thoughts_tokens=t.thoughts_tokens, tool_calls=t.tool_calls, cost_usd=t.cost_usd,diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.pyindex 92eb5073..13d97981 100644--- a/harness/codeverse3d/cost/types.py+++ b/harness/codeverse3d/cost/types.py@@ -38,7 +38,6 @@ class Stage(StrEnum):RENDER = "render"JUDGE = "judge"PAIRWISE = "pairwise"- TEXTURE = "texture" # historical: ledgers of runs that had a texture pass still carry itCAPTION = "caption"OTHER = "other"@@ -54,7 +53,6 @@ class Role(StrEnum):GENERATOR = "generator"JUDGE = "judge"CAPTIONER = "captioner"- IMAGE = "image" # historical: rows booked by the removed image modelOTHER = "other"diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.pyindex ebfd8cb6..da68596f 100644--- a/harness/codeverse3d/doctor.py+++ b/harness/codeverse3d/doctor.py@@ -1,6 +1,5 @@"""Environment checks behind ``3dcode doctor`` — python deps, Blender, node/three/-puppeteer, the GPU probe, keys, the machine-wide in-flight slots, the vendor CLIs, MCP-and the skill library wiring. Moved out of ``cli/`` 2026-08-28: only the typer+puppeteer, the GPU probe, keys, the machine-wide in-flight slots, the vendor CLIs, MCP. Moved out of ``cli/`` 2026-08-28: only the typershim is a CLI concern (tests/install imports these checks as documentation facts)."""@@ -16,7 +15,7 @@ from codeverse3d.proc import read_json_or_none, run_subprocess, version_lineRow = tuple[str, str, str]_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "fcl", "PIL", "pyarrow",- "scipy", "shapely", "networkx", "manifold3d", "matplotlib", "google.genai", "anthropic", "openai",+ "scipy", "shapely", "networkx", "matplotlib", "google.genai", "anthropic", "openai","yourdfpy", "mcp", "moderngl", "cadquery")#: modules that come from an OPTIONAL extra: missing means one track is unavailable, not a#: broken install, so they are a WARN naming the extra to install. `moderngl` and `cadquery`@@ -29,7 +28,7 @@ _PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml",#: docs/INSTALL.md §1 documents (no extras) got `python deps FAIL 14/23` — "your install#: is broken" for an install that is correct — and a remedy that named four of the five#: extras and could not clear the row. Verified on a 3.13 clean clone, 2026-08-24.-_OPTIONAL_DEPS = {"manifold3d": "mesh", "shapely": "mesh", "networkx": "mesh", "matplotlib": "mesh",+_OPTIONAL_DEPS = {"shapely": "mesh", "networkx": "mesh", "matplotlib": "mesh","yourdfpy": "urdf", "scipy": "urdf", "mcp": "mcp","moderngl": "graphics", "cadquery": "cad", "pyarrow": "flywheel"}_CLI_TIMEOUT = 25@@ -320,68 +319,7 @@ def check_mcp() -> list[Row]:return [("mcp", "WARN", f"codeverse3d.spatial.mcp_server not importable ({e})")]-def check_skills() -> list[Row]:- """The static half of the live CLI smoke: is the library there, valid, and reachable?-- A CLI upgrade that moves its skills root ships an empty index and the run still- 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,- shipped_roots,- skills_dir,- validate_bundle,- variants_table,- )- from codeverse3d.skills.materialize import SKILL_ROOTS- from codeverse3d.skills.registry import ROUTED_SKILLS-- on = get_settings().skills- rows: list[Row] = [("skills switch", "OK" if on else "WARN",- "C3D_SKILLS on (the default since 2026-09-22)" if on- else "C3D_SKILLS=0: no skill is attached to any session")]- dirs = bundle_dirs()- if not dirs:- rows.append(("skills library", "WARN", f"no bundles under {skills_dir()}"))- else:- bad = {d.name: validate_bundle(d) for d in dirs}- bad = {k: v for k, v in bad.items() if v}- rows.append(("skills library", "FAIL" if bad else "OK",- f"{len(dirs)} bundles, {len(bad)} invalid" + (f": {', '.join(bad)}" if bad else "")))- 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"))- return rows---def run_doctor(*, live: bool = False, gpu: bool = True, skills: bool = False) -> list[Row]:+def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:rows: list[Row] = []rows += check_python_deps()rows += check_blender()@@ -393,6 +331,4 @@ def run_doctor(*, live: bool = False, gpu: bool = True, skills: bool = False) ->rows += check_pool(live)rows += check_clis()rows += check_mcp()- if skills:- rows += check_skills()return rowsdiff --git a/harness/codeverse3d/judges/prompt_builder.py b/harness/codeverse3d/judges/prompt_builder.pyindex 075c17ac..2e33bc14 100644--- a/harness/codeverse3d/judges/prompt_builder.py+++ b/harness/codeverse3d/judges/prompt_builder.py@@ -680,8 +680,6 @@ def brief_section(spec: Spec) -> str:cons = []if c.dimensions_m:cons.append("dimensions_m: " + ", ".join(f"{k}={v:g}" for k, v in c.dimensions_m.items()))- if c.max_triangles:- cons.append(f"max_triangles: {c.max_triangles}")if c.style:cons.append(f"style: {c.style}")if c.must_have:diff --git a/harness/codeverse3d/judges/rubrics.py b/harness/codeverse3d/judges/rubrics.pyindex 6e0246a8..4cedba33 100644--- a/harness/codeverse3d/judges/rubrics.py+++ b/harness/codeverse3d/judges/rubrics.py@@ -167,7 +167,6 @@ class CapRule(BaseModel):class Rubric(BaseModel):name: strversion: int = 1- track_hint: str = Field(default="", description="static_object | articulated_object | scene | asset | reference")pass_threshold: float = Field(ge=0.0, le=1.0)criteria: list[Criterion] = Field(min_length=1)caps: list[CapRule] = Field(default_factory=list)@@ -196,12 +195,6 @@ class Rubric(BaseModel):def weights(self) -> dict[str, float]:return {c.id: c.weight for c in self.criteria}- def criterion(self, cid: str) -> Criterion:- for c in self.criteria:- if c.id == cid:- return c- raise KeyError(f"rubric {self.name} has no criterion {cid!r}")-def defect(self, did: str) -> DefectItem:for d in self.defects:if d.id == did:diff --git a/harness/codeverse3d/judges/rubrics/articulated.yaml b/harness/codeverse3d/judges/rubrics/articulated.yamlindex 79e42bd8..54478b61 100644--- a/harness/codeverse3d/judges/rubrics/articulated.yaml+++ b/harness/codeverse3d/judges/rubrics/articulated.yaml@@ -1,6 +1,5 @@name: articulatedversion: 1-track_hint: articulated_objectpass_threshold: 0.7description: 'Rubric for an ARTICULATED object (cabinet with doors/drawers, laptop, folding chair, robot arm, scissors...)judged on the rest-pose render rig PLUS the POSE SHEET: a harness-made grid whose rows are poses (rest, then eachdiff --git a/harness/codeverse3d/judges/rubrics/asset.yaml b/harness/codeverse3d/judges/rubrics/asset.yamlindex cd348555..40f7a91c 100644--- a/harness/codeverse3d/judges/rubrics/asset.yaml+++ b/harness/codeverse3d/judges/rubrics/asset.yaml@@ -1,6 +1,5 @@name: assetversion: 1-track_hint: assetpass_threshold: 0.70description: >Per-asset rubric used inside scenes: ONE asset (a building, a tree, a boat, a lampdiff --git a/harness/codeverse3d/judges/rubrics/reference.yaml b/harness/codeverse3d/judges/rubrics/reference.yamlindex 83fdd238..a42c5592 100644--- a/harness/codeverse3d/judges/rubrics/reference.yaml+++ b/harness/codeverse3d/judges/rubrics/reference.yaml@@ -1,6 +1,5 @@name: referenceversion: 1-track_hint: referencepass_threshold: 0.70description: >Image-conditioned rubric: the object must match one or more REFERENCE images. Thediff --git a/harness/codeverse3d/judges/rubrics/scene.yaml b/harness/codeverse3d/judges/rubrics/scene.yamlindex e6111f31..52d0d0f5 100644--- a/harness/codeverse3d/judges/rubrics/scene.yaml+++ b/harness/codeverse3d/judges/rubrics/scene.yaml@@ -1,6 +1,5 @@name: sceneversion: 2-track_hint: scenepass_threshold: 0.70description: >Rubric for a procedural 3D SCENE (a place) judged on its authored cameras plus adiff --git a/harness/codeverse3d/judges/rubrics/shader.yaml b/harness/codeverse3d/judges/rubrics/shader.yamlindex a22751a6..d88918d1 100644--- a/harness/codeverse3d/judges/rubrics/shader.yaml+++ b/harness/codeverse3d/judges/rubrics/shader.yaml@@ -1,6 +1,5 @@name: shaderversion: 2-track_hint: graphicspass_threshold: 0.70description: >Rubric for the GRAPHICS track (Shadertoy-style fragment shader or raw OpenGL program), judged ondiff --git a/harness/codeverse3d/judges/rubrics/static_object.yaml b/harness/codeverse3d/judges/rubrics/static_object.yamlindex a9c17458..e7ea9e4b 100644--- a/harness/codeverse3d/judges/rubrics/static_object.yaml+++ b/harness/codeverse3d/judges/rubrics/static_object.yaml@@ -1,6 +1,5 @@name: static_objectversion: 1-track_hint: static_objectpass_threshold: 0.72description: >Assembly-level rubric for ONE static object (furniture, tool, vehicle, appliance,diff --git a/harness/codeverse3d/judges/vlm_judge.py b/harness/codeverse3d/judges/vlm_judge.pyindex 05a46342..434e89d7 100644--- a/harness/codeverse3d/judges/vlm_judge.py+++ b/harness/codeverse3d/judges/vlm_judge.py@@ -85,7 +85,7 @@ THINKING_LEVELS: tuple[str, ...] = ("off", "low", "medium", "high")#: battery measures it. The scene rig moved 3 → 4 with scene (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.+#: dropped the low tile the contact crops are cut from.TRACK_MONTAGE_CAP: dict[str, int] = {"scene": 4, "graphics": 3}@@ -115,9 +115,6 @@ class VlmJudge:*,thinking: Literal["off", "low", "medium", "high"] | None = None,max_attempts: int = 3,- max_montages: int | None = None,- detail_crops: int | None = None,- max_px: int | None = None,chat_model: ChatModel | None = None,cache_dir: Path | None = None,label: str = "judge",@@ -139,7 +136,7 @@ class VlmJudge:"acceptance item follows the representative sample (rubrics.aggregate_samples); an odd n ""gives a true majority", self.n_samples)self.temperature = temperature- # payload size and thinking: the profile's dial (Settings.judge) unless the caller states one+ # payload size and thinking: Settings.judgejd = 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:@@ -150,19 +147,18 @@ class VlmJudge:self.thinking: str = levelself.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)- 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))- self.max_px = int(jd.max_px if max_px is None else max_px)+ self.max_montages = max(1, int(jd.montages))+ self.detail_crops = max(0, int(jd.detail_crops))+ self.max_px = int(jd.max_px)self._model = chat_modelself.cache_dir = cache_dirself.label = labeldef _montages_for(self, inp: JudgeInput) -> int:"""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."""+ the dial, D47)."""cap = TRACK_MONTAGE_CAP.get(inp.spec.track.value)- if self._montages_explicit or cap is None:+ if cap is None:return self.max_montagesreturn min(self.max_montages, cap)@@ -389,15 +385,11 @@ class ReferenceJudge(VlmJudge):rubric: str | Rubric = "reference",silhouette_fn: CompareFn | None = None,diff: bool = True,- diff_model: Any | None = None,- diff_model_id: str = "",**kwargs: Any,):super().__init__(rubric, model_id, n_samples, temperature, **kwargs)self.silhouette_fn = silhouette_fn or compare_silhouetteself.diff = diff- self._diff_model = diff_model- self.diff_model_id = diff_model_id# ------------------------------------------------------------------ hookdef context(self, inp: JudgeInput) -> JudgeContext:@@ -466,21 +458,12 @@ class ReferenceJudge(VlmJudge):measured = None if match is None else {"iou": match.iou, "aspect_ratio_err": match.aspect_ratio_err, "reliable": match.reliable,"view": match.view, "reference": Path(match.reference).name}try:- return compare(inp.spec, targets, renders, model=self._pick_diff_model(),+ return compare(inp.spec, targets, renders, model=self.model,part_names=inp.part_names, measured=measured)except Exception as e: # noqa: BLE001 — an advisory pass must never fail a verdictlog.warning("reference diff pass failed: %s", e)return None- def _pick_diff_model(self) -> Any:- """``diff_model`` > ``diff_model_id`` (a cheaper perception model) > the judge's own model."""- if self._diff_model is not None:- return self._diff_model- if self.diff_model_id:- self._diff_model = get_chat_model(self.diff_model_id)- return self._diff_model- return self.model-def diff_views(self, views: list[RenderView]) -> list[str]:"""Up to 3 shaded views for the diff, front-ish first."""picked = [v.path for v in views_by_preference(views, DIFF_VIEW_NAMES)]@@ -522,14 +505,13 @@ class LikenessJudge(VlmJudge):name = "likeness"def __init__(self, model_id: str | None = None, n_samples: int = 1, temperature: float = 0.2, *,- rubric: str | Rubric = "shader", max_refs: int = 3, **kwargs: Any):+ rubric: str | Rubric = "shader", **kwargs: Any):super().__init__(rubric, model_id, n_samples, temperature, **kwargs)- self.max_refs = max(1, int(max_refs))def context(self, inp: JudgeInput) -> JudgeContext:if self.rubric.measured_criteria():raise ValueError(f"rubric {self.rubric.name} has measured criteria; LikenessJudge measures nothing")- refs = [r for r in inp.spec.references if Path(r.path).is_file()][: self.max_refs]+ refs = [r for r in inp.spec.references if Path(r.path).is_file()][:3]images = [(f"REAL-WORLD REFERENCE {i}/{len(refs)}" + (f" — {r.note}" if r.note else ""), r.path)for i, r in enumerate(refs, 1)]return JudgeContext(extra_text=LIKENESS_NOTE if refs else "", extra_images=images)diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.pyindex b329aaab..5215043d 100644--- a/harness/codeverse3d/languages/blender/__init__.py+++ b/harness/codeverse3d/languages/blender/__init__.py@@ -22,8 +22,8 @@ from codeverse3d.languages._ast_lint import ()from codeverse3d.languages._common import run_wrapper_build, strip_blender_noise, ws_relfrom codeverse3d.languages.base import RuntimeLayout+from codeverse3d.languages.blender._pbr import family_for, pbr_forfrom codeverse3d.proc import scrub_secrets-from codeverse3d.texturing.materials import family_for, pbr_forfrom codeverse3d.workspace import Workspace# ===================================================================== lint@@ -500,7 +500,7 @@ _COLOUR_WORDS: tuple[tuple[str, tuple[float, float, float]], ...] = (def finish_for(text: str) -> tuple[tuple[float, float, float], float, float]:"""Placeholder (rgb, roughness, metallic) so the first render is not all-grey: the material- family's base hint and factors from ``texturing.materials`` (THE PBR table), else a bare+ family's base hint and factors from ``_pbr`` (THE PBR table), else a barecolour word at the Principled defaults, else neutral grey."""hit = family_for(text)pbr = pbr_for(hit.family) if hit else None@@ -719,7 +719,7 @@ def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, ground_tol_m: flo``ground_tol_m`` is the self-check's "stands on z=0" tolerance: ``conventions.GROUND_TOL_M``for an object (the contract gate's own line), looser for a scene hero, which- the scene seats anyway (`lib/place.js seat`) and whose module twin is allowed 20 mm."""+ the scene seats anyway and whose module twin is allowed 20 mm."""ws.src.mkdir(parents=True, exist_ok=True)entry = ws.src / "model.py"entry.write_text(model_file_source(plan, ground_tol_m=ground_tol_m))diff --git a/harness/codeverse3d/texturing/materials.py b/harness/codeverse3d/languages/blender/_pbr.pysimilarity index 100%rename from harness/codeverse3d/texturing/materials.pyrename to harness/codeverse3d/languages/blender/_pbr.pydiff --git a/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.py b/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.pyindex 92123ce0..271ac9c8 100644--- a/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.py+++ b/harness/codeverse3d/languages/scene_blender/starter/src/lib/vegetation.py@@ -14,7 +14,6 @@ import mathfrom collections.abc import Callable, Sequencefrom typing import Any-import bpyfrom mathutils import Vectorfrom lib.materials import material@@ -228,9 +227,3 @@ def tree_stand(collection: Any, batch: Any, positions: Sequence[Sequence[float]]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_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.pyindex 3ded21f1..b18d40d5 100644--- a/harness/codeverse3d/languages/scene_threejs/__init__.py+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py@@ -42,7 +42,6 @@ if TYPE_CHECKING:# ===================================================================== lintGATE = "lint:scene_threejs"-MAX_LINES = 800_CREATE_SCENE_RE = re.compile(r"export\s+(?:async\s+)?function\s+createScene\b|export\s+(?:const|let)\s+createScene\b|export\s*\{[^}]*\bcreateScene\b[^}]*\}")_BUILD_RE = re.compile(r"export\s+(?:async\s+)?function\s+build\b|export\s+(?:const|let)\s+build\b|export\s*\{[^}]*\bbuild\b[^}]*\}")@@ -75,7 +74,7 @@ def _is_lib(path: Path, ws: Workspace) -> bool:They ship into every workspace (D51) and are verified by the harness's ownsuite — ``tests/scene_runtime/lib/`` — not by the workspace gate, whose jobis to police the code the AGENT writes. Linting them as agent code was- three hard ERRORs (signage.js's node-only font fallback imports+ three hard ERRORs (a node-only font fallback importing``node:module`` / ``node:fs/promises`` / ``node:url``, which the browserhalf never touches) plus twelve "large file" WARNs telling the agent tosplit files it does not own. Syntax is still checked below: a library file@@ -126,7 +125,6 @@ def lint(ws: Workspace) -> GateReport:if not scene.is_file():findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, "src/scene.js is missing", target="src/scene.js",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:@@ -144,9 +142,6 @@ def lint(ws: Workspace) -> GateReport:if m:line = line_of(code, m.start())findings.append(_f(kind, sev, msg, target=f"{rel}:{line}", hint=hint))- n_lines = text.count("\n") + 1- if n_lines > MAX_LINES:- big.append(f"{rel} ({n_lines} lines)")if path == scene and not _CREATE_SCENE_RE.search(text):findings.append(_f(LintKind.LAYOUT, Severity.ERROR, "src/scene.js does not export createScene", target=rel,hint="export function createScene({ THREE, renderer, loaders }) { ... return { scene, cameras, update } }"))@@ -156,9 +151,6 @@ def lint(ws: Workspace) -> GateReport:if path.parent == ws.src / "assets" and not _BUILD_ANY_RE.search(text):findings.append(_f(LintKind.LAYOUT, Severity.WARN, "asset module exports no build<Pascal>(THREE) factory", target=rel,hint="export function buildLamp(THREE) { ... return group; }"))- for b in big:- findings.append(_f(LintKind.LAYOUT, Severity.WARN, f"large file {b} > {MAX_LINES} lines", target=b.split(" ")[0],- hint="a file over 800 lines is reported; how (or whether) to split it is yours"))return GateReport.of(GATE, findings, duration_ms=int((time.time() - t0) * 1000))@@ -543,7 +535,7 @@ def _glb_preload_js(glbs: list[str], *, target: str, on_error: str, indent: str" try {"," const gltf = await loaders.gltf.loadAsync(a.url);"," const root = gltf.scene;",- " root.animations = gltf.animations || []; // a keyframed Blender part is a clip; .clone() keeps it (lib/place.js clipPlayer)",+ " root.animations = gltf.animations || []; // a keyframed Blender part is a clip; .clone() keeps it"," root.name = a.name; // a glTF root is called 'Scene' until someone names it",# what every procedural asset sets on its meshes; GLTFLoader leaves both false, so a# hero neither cast nor received a shadow in any recorded scene (8/8 GLBs, 2026-09-07)diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.jsdeleted file mode 100644index d456f877..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/accumulation.js+++ /dev/null@@ -1,405 +0,0 @@-/**- * Accumulation: what LIES on a scene, from one rule on every surface.- *- * A scene reads as WEATHER when the same stuff is on everything at- * once — snow on the roof, the sill, the branch and the rock; sand- * banked against the windward side of every wall. One white-topped- * material is a prop, twenty materials sharing one deposit rule is a- * storm, so both patches shade from world position and world normal- * only: no UV, no per-object setup, and two objects sharing a scale- * share one weather.- *- * Both go through `patchStandard`, so lighting, shadows, fog and the- * depth chunks survive, and both CHAIN with `surface_wear`,- * `terrain_shade`, `waterside` and `aging` on one material.- *- * THE CONSTRAINT IS THAT NEITHER HAS THICKNESS. `fragmentBody` edits- * albedo and the lit micro-normal; vertex displacement would tear every- * hard-edged BoxGeometry open at its rim, because the top face's- * vertices carry a different normal from the side's and would walk- * away from them. So a layer sells its depth by what it COVERS (steep- * faces lose it, concave lees keep it), by a torn edge instead of a- * ruled one, and by the shade it drops on the material just outside- * that edge. Roughness and metalness follow the same local coverage as- * the albedo; bare faces retain the authored substrate finish.- */--import * as THREE from 'three';-import {- patchStandard, glslAxes, glslCurv, glslTriNoise,- readWind, seedVec3, toColor, unit, upVector, worldBase,-} from './shader.js';--// Both patches read these, so they are declared once, in the base.-// astraAcc*, not a neighbour's spelling: patchStandard THROWS when two-// chained patches give one function name two different bodies.-const ACC_HEAD = [- glslAxes('astraAccAxes'),- // Three world-plane projections blended by the normal: a deposit- // must break up the same way on a wall, a roof and a boulder.- glslTriNoise('astraAccNoise', 23.1, 57.7, 91.3),- // NEGATIVE curvature is the concave lee that holds what a convex- // edge sheds.- glslCurv('astraAccCurv'),-].join('\n');--// One base for both, on the world varyings every library shares; the-// vertex locals are ac* because terrain_shade, waterside, surface_wear-// and aging own astraWp, wsP, wrP and agP.-const BASE = worldBase('acc:base', 'acP', 'acN', ACC_HEAD);--// The constants differ from surface_wear's and aging's, or one seed-// would drift this library's snow along that library's blotches.-const seedOffset = (seed, salt) =>- seedVec3(seed + salt, 1.61, 8.09, 13.77, 56);--/**- * Read `wind` as the horizontal direction it blows TOWARD, length 0..1 = strength.- *- * Length rather than a second option: zero wind must mean an even fall- * with no drift axis at all, and normalizing a zero vector is NaN.- */-function windVector(value, fallback) {- if (value == null && !fallback) return new THREE.Vector3();- const w = readWind(value, fallback, 'wind');- return new THREE.Vector3(w.x, 0, w.z).clampLength(0, 1);-}--/**- * Lay snow on everything at once, by how each surface is turned.- *- * Snow is the deposit that most changes a scene, because it lands on- * every upward face in it from one rule: a roof with a white cap over- * a bare sill, a bare branch and a bare rock is a prop in a snow- * scene, and the fix is not more painting but the SAME patch on every- * material. What makes it snow rather than white paint is where it- * stops — and it stops in four ways.- *- * DEPOSIT is the cosine against `up` (the scene's own gravity, not- * world Y — a tilted asset or a listing hull snows on the faces that- * really point up), thinning as a face steepens and reaching NOTHING- * past about 58 degrees, the angle snow slides off at. That gate is- * MULTIPLICATIVE, so no amount of noise can put snow on a wall.- * SHELTER is the surface's own signed curvature: a convex edge sheds- * what a concave lee keeps, and how small a feature the fall can bury- * goes with how deep it lies. Curvature reads ZERO across a hard,- * unwelded edge (`BoxGeometry`'s corners, anything flat-shaded), so- * there the cosine carries it alone. WIND scours the face it meets and- * leaves the lee packed. And the EDGE is a threshold on a two-octave- * world field, torn by its own screen gradient, with a soft shade laid- * on the material just outside it — the only thickness a patch that- * cannot displace geometry has.- *- * `melt` gives the material back from the bottom up: the thaw line- * climbs from the plane through the world origin, which is where an- * asset's foot rests, so a wall's footing goes bare while its coping- * stays white. Passed `{ amount, at, radius }` it also eats a hole- * around one warm world point — a flue, a lamp, a vent.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` snows every mesh- * wearing it, so clone it first (and clone BEFORE patching).- * @param {object} [opts] `depth` metres of lying snow, which sets how- * far down a pitch it holds and how opaque it is (default 0.05; 0.01- * is a dusting, 0.15 buries); `color` THREE.Color or hex (default a- * neutral white below 0.78 linear — snow is the brightest albedo in a scene- * and still has to sit UNDER the tone curve's shoulder, or its own- * shading clips to one flat card); `up` THREE.Vector3 or [x, y, z], the scene's up- * (default +Y); `wind` the scene's wind (shader.js `readWind`) it blows- * TOWARD, its horizontal LENGTH 0..1 the strength (default none, an even fall);- * `melt` 0..1 how high the thaw has climbed, or- * `{ amount, at, radius }` to melt around a warm point as well- * (default 0); `seed` moves the drifts (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uSnowMelt` can thaw over a- * shot and `uSnowDepth` can deepen through a storm.- */-export function patchSnow(material, opts = {}) {- const depth = opts.depth === undefined ? 0.05 : Math.max(0, opts.depth);- const seed = opts.seed === undefined ? 1 : opts.seed;- const melt = opts.melt;- const meltAmt = unit(- typeof melt === 'number' ? melt : (melt && melt.amount) || 0);- const at = (melt && melt.at) || null;- const warm = new THREE.Vector3();- if (at) warm.fromArray(at.toArray ? at.toArray() : at);- const warmR = at- ? Math.max(1e-3, melt.radius === undefined ? 0.9 : melt.radius) : 0;- // Snow is a diffuse cover with a faint sheen, and it takes the- // material's gloss over only as far as it takes the surface over.-- patchStandard(material, BASE);- return patchStandard(material, {- name: 'acc:snow',- uniforms: {- uSnowDepth: { value: depth },- uSnowColor: { value: toColor(opts.color, 0xe0e2e3) },- uSnowUp: { value: upVector(opts.up) },- uSnowWind: { value: windVector(opts.wind, null) },- uSnowMelt: { value: meltAmt },- uSnowWarm: { value: new THREE.Vector4(warm.x, warm.y, warm.z, warmR) },- uSnowSeed: { value: seedOffset(seed, 0.7) },- },- fragmentHead: [- 'uniform float uSnowDepth;',- 'uniform vec3 uSnowColor;',- 'uniform vec3 uSnowUp;',- 'uniform vec3 uSnowWind;',- 'uniform float uSnowMelt;',- 'uniform vec4 uSnowWarm;',- 'uniform vec3 uSnowSeed;',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, 0.86, snAmt);',- metalnessBody: 'metalnessFactor *= 1.0 - snAmt;',- normalBody: [- 'normal = astraBump(-vViewPosition, normal, snAmt * snF * snFad * 0.0009);',- ].join('\n'),- fragmentBody: [- ' vec3 snN = normalize(vAstraWorldN);',- ' vec3 snUp = normalize(uSnowUp);',- // Depth in metres decides how much this fall can bury and how- // little of the material is left showing through it.- ' float snCov = clamp(uSnowDepth / 0.06, 0.0, 1.0);',- ' vec3 snW = astraAccAxes(snN);',- ' vec3 snP = vAstraWorld * mix(2.6, 1.3, snCov) + uSnowSeed;',- ' float snG = astraAccNoise(snP, snW) * 0.62',- ' + astraAccNoise(snP * 4.3, snW) * 0.38;',- // Wind combs a drift OUT along itself: the same field with its- // wind axis compressed makes every feature four times as long.- ' float snWl = clamp(length(uSnowWind), 0.0, 1.0);',- ' vec3 snWv = uSnowWind / max(length(uSnowWind), 1e-4);',- ' vec3 snQ = vAstraWorld - snWv * dot(vAstraWorld, snWv) * 0.74;',- ' snG = mix(snG, snG * 0.45',- ' + astraAccNoise(snQ * 2.6 + uSnowSeed, snW) * 0.55, snWl);',- // How far the surface faces up, gone by ~58 degrees — the angle- // snow slides off — and thinner on everything steeper than flat.- ' float snC = dot(snN, snUp);',- ' float snLay = smoothstep(0.52, 0.80, snC)',- ' * mix(0.55, 1.0, clamp(snC, 0.0, 1.0));',- // A convex edge sheds what a concave lee holds, and a deeper fall- // buries a bigger feature before it starts to shed.- ' float snCv = astraAccCurv(snN, vAstraWorld);',- ' float snR = 1.0 / max(uSnowDepth * 6.0, 0.05);',- ' float snHold = 1.0 - 0.70 * smoothstep(snR * 0.6, snR * 3.0, snCv)',- ' + 0.60 * smoothstep(snR * 0.4, snR * 2.2, -snCv);',- // Wind scours the face it meets; its LENGTH is the strength, so- // no wind is an even fall rather than a normalize() of zero.- ' float snScour = 1.0 - 0.45 * snWl',- ' * smoothstep(-0.10, 0.90, -dot(snN, snWv));',- // MULTIPLICATIVE, so a steep face keeps nothing whatever the- // field says: noise may tear an edge, never move a wall's.- ' float snD = snLay * snHold * snScour * (0.55 + 0.90 * snG);',- // The thaw climbs from the plane through the origin, where an- // asset's foot rests, and its line is ragged from the same field.- ' float snH = dot(vAstraWorld, snUp) + (snG - 0.5) * 0.8;',- ' float snLine = mix(-0.8, 5.0, uSnowMelt);',- ' float snThaw = 1.0 - smoothstep(snLine - 0.7, snLine + 0.5, snH);',- ' float snWr = max(uSnowWarm.w, 1e-3);',- ' float snWarm = (1.0 - smoothstep(snWr * 0.35, snWr,',- ' length(vAstraWorld - uSnowWarm.xyz)))',- ' * step(1e-4, uSnowWarm.w);',- ' snD -= snThaw * 1.10 + snWarm * 1.10;',- // One threshold, antialiased by its own screen gradient: a hard- // line is paint, and a torn one is something that landed.- ' float snT = mix(0.92, 0.18, snCov);',- ' float snAA = clamp(fwidth(snD), 0.0, 0.35);',- ' float snK = smoothstep(snT - 0.05 - snAA, snT + 0.12 + snAA, snD);',- // A SECOND, finer field, for the tone alone — kept out of snD so- // the edge is untouched. The deposit's own field is most of a- // metre across, and a metre of one value at arm's length is paint.- // It fades out once a pixel spans it, or the grain aliases into- // shimmer at the far end of a shot.- ' float snFad = 1.0 - smoothstep(0.04, 0.10,',- ' length(fwidth(vAstraWorld)));',- ' float snF = astraAccNoise(snP * 6.0 + 17.3, snW);',- ' float snTn = clamp(mix(snG, snG * 0.66 + snF * 0.34, snFad),',- ' 0.0, 1.0);',- // Fresh snow is nearly neutral. Wide blue/white albedo swings made- // flat ground look marbled; the scene light supplies its shadow hue.- ' vec3 snCol = mix(uSnowColor * 0.82, uSnowColor * 1.03,',- ' smoothstep(0.16, 0.86, snTn));',- ' snCol = astraHueBreak(snCol, vAstraWorld.xz, 0.22, 0.025);',- ' snCol = astraHueBreak(snCol, vAstraWorld.xz + 31.7, 1.45, 0.012);',- // A third of a code value of screen dither: a near-white ramp- // across a roof is the one place 8-bit banding is unmissable, and- // there is no post chain here to dither it for us.- ' snCol += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- // The shade just OUTSIDE the edge is the only thickness a patch- // that cannot displace geometry has. The band is a FRACTION of the- // threshold and never a fixed offset below it: past a dusting snT- // drops under 0.55, a fixed 0.55 offset puts ZERO deposit inside- // the ramp, and every bare wall and soffit in the scene picks up a- // shade it has no snow to justify (measured: a 21% darkening on- // every vertical face, with the melt hole printed through it).- ' float snLip = (1.0 - snK) * smoothstep(snT * 0.40, snT - 0.02,',- ' snD);',- ' diffuseColor.rgb *= 1.0 - 0.30 * snLip;',- // Thin snow is TRANSLUCENT — the substrate comes through it — so- // the drifts read as deep and the scoured lanes as shallow.- ' float snThin = mix(0.38, 1.0, smoothstep(0.55, 1.30, snD));',- ' snThin = mix(snThin, 1.0, snCov * 0.88);',- ' float snAmt = clamp(snK * snThin * mix(0.55, 1.0, snCov)',- ' * smoothstep(0.0, 0.004, uSnowDepth), 0.0, 1.0);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, snCol, snAmt);',- ].join('\n'),- });-}--/**- * Bank sand against everything the wind runs into.- *- * Sand is not dust: dust is a film on what faces up, and sand is a- * DRIFT — it has a windward side, a lee, a wedge profile that is- * deepest at the foot of whatever stopped it, and ripples. A scene- * reads as desert when every wall in it is banked on the same side,- * which is one wind vector shared by every material.- *- * THE DRIFT IS A WEDGE. Deposit is banked on the face that meets the- * wind and tapers to a thin tail in the lee, and it thins with height- * above the plane through the world origin — so it climbs the foot of- * a wall and lets its head go clear, which is the profile that says- * drift rather than wash. `amount` raises the whole bank: how high it- * climbs, how much it fills, how far the ripples space out.- *- * IT FILLS THE CONCAVITIES FIRST. The surface's own signed curvature- * adds where it is concave and subtracts where it is convex, so at a- * low `amount` sand shows only in the inside corners, along the joints- * and in the hollows of a rock — the way a floor sands up before its- * middle does. Curvature reads ZERO across a hard, unwelded edge, so- * there the wedge carries it alone.- *- * RIPPLES RUN ACROSS THE WIND. Their phase advances ALONG the wind- * axis, which puts every crest square to the flow the way aeolian- * ripples lie; they wander on the same field so they are not ruled- * lines, they light the crest and shade the trough, they hold a little- * more sand than the troughs do, and they are dropped once a pixel- * spans one — past that they are not ripples, they are static.- *- * @param {THREE.Material} material A built-in material, patched in- * place — a shared material from `materials.js` sands every mesh- * wearing it, so clone it first (and clone BEFORE patching).- * @param {object} [opts] `amount` how much has drifted, 0..1 (default- * 0.45; 0.1 is sand in the corners, 0.9 is a buried wall);- * `color` THREE.Color or hex (default a warm ochre at 0.42 linear, the- * luminance family a lit ground sits in — a paler one renders as cream- * under a physical sun and stops reading as sand at all); `wind`- * the scene's wind (shader.js `readWind`) it blows TOWARD, its- * horizontal LENGTH 0..1 the strength (default [1, 0, 0]); `up` THREE.Vector3 or [x, y, z], the- * scene's up (default +Y); `seed` moves the drifts (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`, so `uSandWind` can swing with a- * storm and `uSandAmt` can bury a scene over a shot.- */-export function patchSand(material, opts = {}) {- const amount = opts.amount === undefined ? 0.45 : unit(opts.amount);- const seed = opts.seed === undefined ? 1 : opts.seed;- // Sand is the mattest thing in any scene it lands in.-- patchStandard(material, BASE);- return patchStandard(material, {- name: 'acc:sand',- uniforms: {- uSandAmt: { value: amount },- uSandColor: { value: toColor(opts.color, 0xb08a55) },- uSandWind: { value: windVector(opts.wind, [1, 0, 0]) },- uSandUp: { value: upVector(opts.up) },- uSandSeed: { value: seedOffset(seed, 3.9) },- },- fragmentHead: [- 'uniform float uSandAmt;',- 'uniform vec3 uSandColor;',- 'uniform vec3 uSandWind;',- 'uniform vec3 uSandUp;',- 'uniform vec3 uSandSeed;',- ].join('\n'),- roughnessBody: 'roughnessFactor = mix(roughnessFactor, 0.94, sdAmt);',- metalnessBody: 'metalnessFactor *= 1.0 - sdAmt;',- fragmentBody: [- ' vec3 sdN = normalize(vAstraWorldN);',- ' vec3 sdUp = normalize(uSandUp);',- ' float sdWl = clamp(length(uSandWind), 0.0, 1.0);',- ' vec3 sdWv = uSandWind / max(length(uSandWind), 1e-4);',- ' vec3 sdW = astraAccAxes(sdN);',- ' vec3 sdP = vAstraWorld * 1.4 + uSandSeed;',- ' float sdG = astraAccNoise(sdP, sdW) * 0.62',- ' + astraAccNoise(sdP * 3.9, sdW) * 0.38;',- // The wedge: deepest at the foot of whatever stopped it, gone by- // the height this much sand can climb.- ' float sdTop = mix(0.35, 2.4, uSandAmt);',- ' float sdRise = 1.0 - smoothstep(0.0, sdTop,',- ' max(dot(vAstraWorld, sdUp), 0.0));',- // Banked on the face that meets the wind, a thin tail in the lee;- // with no wind at all there is no windward side to bank on.- ' float sdFace = -dot(sdN, sdWv);',- ' float sdBank = mix(0.45, mix(0.18, 1.0,',- ' smoothstep(-0.55, 0.75, sdFace)), sdWl);',- ' float sdLie = smoothstep(-0.10, 0.55, dot(sdN, sdUp));',- // Nothing banks against a soffit: a face turned under holds no- // more sand than it holds water.- ' sdBank *= smoothstep(-0.55, -0.05, dot(sdN, sdUp));',- // Concave first: a corner sands up long before the flat beside it- // does, and a convex edge is swept clean. The shed window starts- // WELL past the fill's, because sand does not scour a stone the- // way it scours a rib: at the old 0.5/2.5 window every cobble in a- // drift came out bare and black while the sand ran on around it,- // which is a deflation pavement and not the yard we asked for.- ' float sdCv = astraAccCurv(sdN, vAstraWorld);',- ' float sdR = 1.0 / max(uSandAmt * 0.6 + 0.05, 0.05);',- ' float sdFill = smoothstep(sdR * 0.35, sdR * 2.0, -sdCv);',- ' float sdShed = smoothstep(sdR * 0.9, sdR * 3.2, sdCv);',- // The wedge gates EVERY term, tops included: wind carries sand- // along the ground, so a roof four metres up gets none of it.- ' float sdLay = clamp((max(sdLie * 0.90, sdBank)',- ' + sdFill * 0.55) * sdRise',- ' - sdShed * 0.42, 0.0, 1.6);',- // Crests square to the flow: the phase runs ALONG the wind axis,- // wandering on the field so they are not ruled lines. The skew- // steepens the lee face of each crest the way a ripple's is.- ' float sdLam = mix(0.12, 0.45, uSandAmt);',- ' float sdPh = dot(vAstraWorld, sdWv) / sdLam + (sdG - 0.5) * 1.4;',- ' sdPh = sdPh * 6.2831853;',- // Gone once a pixel spans a ripple: past that it is not a ripple,- // it is static, which is the one way this reads as an effect.- ' float sdFade = 1.0 - smoothstep(0.16, 0.50,',- ' length(fwidth(vAstraWorld)) / sdLam);',- ' float sdRip = sin(sdPh + 0.55 * sin(sdPh)) * sdFade * sdWl',- ' * mix(0.25, 1.0, sdLie);',- // The crests hold a little more than the troughs, so the ripple- // is in the COVERAGE and not only in the tone.- ' float sdD = sdLay * (0.55 + 0.90 * sdG) + sdRip * 0.14;',- ' float sdT = mix(1.10, 0.20, uSandAmt);',- ' float sdAA = clamp(fwidth(sdD), 0.0, 0.35);',- ' float sdK = smoothstep(sdT - 0.05 - sdAA, sdT + 0.14 + sdAA, sdD);',- // A finer field for the TONE only, faded once a pixel spans it:- // dune sand is graded, and a decimetre of one value is paint.- ' float sdFad = 1.0 - smoothstep(0.04, 0.10,',- ' length(fwidth(vAstraWorld)));',- ' float sdF = astraAccNoise(sdP * 7.5 + 41.9, sdW);',- ' float sdTn = clamp(mix(sdG, sdG * 0.66 + sdF * 0.34, sdFad),',- ' 0.0, 1.0);',- ' vec3 sdCol = mix(uSandColor * 0.68, uSandColor * 1.10,',- ' smoothstep(0.22, 0.84, sdTn));',- // The crest is sun-bleached and warm, the trough holds the sky: a- // ripple that is one brightness is a stripe painted on flat sand.- ' sdCol *= vec3(1.0) + sdRip * vec3(0.20, 0.15, 0.06);',- // Sand is a mineral mix, not a paint chip: quartz, iron and shell- // put warm and cool metres apart, and the palette probe named a- // whole dune field "one flat hue per surface". Wider than stone- // because a dune has nothing else in it to carry variety, and at- // TWO scales because the metre-wide one alone is a flat tint on- // anything smaller than the dune it was written for.- ' sdCol = astraHueBreak(sdCol, vAstraWorld.xz, 0.28, 0.36);',- ' sdCol = astraHueBreak(sdCol, vAstraWorld.xz + 12.4, 1.70, 0.13);',- ' sdCol += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- // A FRACTION of the threshold, never a fixed offset below it — see- // snLip: past `amount` 0.5 sdT drops under 0.55 and a fixed offset- // shades every wall the drift never reached.- ' float sdLip = (1.0 - sdK) * smoothstep(sdT * 0.40, sdT - 0.02,',- ' sdD);',- ' diffuseColor.rgb *= 1.0 - 0.22 * sdLip;',- ' float sdAmt = clamp(sdK * mix(0.70, 1.0, uSandAmt)',- ' * smoothstep(0.0, 0.05, uSandAmt), 0.0, 1.0);',- ' diffuseColor.rgb = mix(diffuseColor.rgb, sdCol, sdAmt);',- ].join('\n'),- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.jsdeleted file mode 100644index cf423093..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/caustics.js+++ /dev/null@@ -1,298 +0,0 @@-/**- * Caustics: the net of light a water surface throws on what is under it.- *- * The one cue that says a floor is UNDERWATER rather than merely blue,- * and it belongs to the lit surface, not to the water — a pool floor,- * harbour steps, a boulder, a swimmer. It is a `patchStandard`, so the- * material keeps its lighting, shadows, fog and depth chunks and can- * chain with the waterline (`waterside.js`), the rock projection- * (`terrain_shade.js`) and the wear (`surface_wear.js`) it will- * normally be wearing already.- */--import * as THREE from 'three';-import { patchStandard, seedLattice, toColor, WORLD_VARYINGS, worldBody } from './shader.js';--// The world varyings terrain_shade and waterside share, so a submerged-// bank wearing a splat, a waterline and this declares ONE pair; the-// instance transform folded in, or an instanced boulder takes the-// origin's depth.-const CAU_VERTEX = worldBody('cauWp', 'cauWn');--const CAU_HEAD = [- 'uniform float uCauLevel;',- 'uniform vec3 uCauSun;',- 'uniform vec2 uCauSlide;',- 'uniform float uCauScale;',- 'uniform float uCauAmt;',- 'uniform float uCauSpeed;',- 'uniform vec3 uCauColor;',- 'uniform float uCauFade;',- 'uniform vec3 uCauAbs;',- // xyz = a LOCAL source over the water, w = 1 / its reach. w = 0 (the- // default) is the sun: parallel light, no falloff, no branch.- 'uniform vec4 uCauSrc;',- 'uniform vec2 uCauSeed;',- // A crease, not a blob: folded about its own mid-line, noise leaves a- // ridge along every contour, and the power narrows that ridge to a- // filament. The second octave kinks it; one alone draws smooth worms.- 'float astraCauWeb(vec2 p) {',- // fbm2 over two octaves tops out at 0.75, so 2.667 centres the fold.- ' float d = abs(astraFbm2(p, 2) * 2.667 - 1.0);',- ' return pow(1.0 - d, 16.0);',- '}',-].join('\n');--const CAU_BODY = [- ' float cauD = max(uCauLevel - vAstraWorld.y, 0.0);',- // The projection, incident cosine and extinction must describe the SAME- // refracted beam. Using the air direction here put low-sun caustics on- // near-vertical faces while starving the floor the bent ray actually hits.- ' vec3 cauBeam = normalize(vec3(uCauSlide.x, 1.0, uCauSlide.y));',- ' float cauPath = cauD / cauBeam.y;',- // Shade from where this fragment's light ENTERED the water: the net- // belongs to the surface overhead, so a riser takes a stretched- // slice of the floor's net instead of a pattern of its own.- ' vec2 cauP = (vAstraWorld.xz + uCauSlide * cauD) / uCauScale',- ' + uCauSeed;',- ' float cauAa = max(fwidth(cauP.x), fwidth(cauP.y));',- ' float cauT = uTime * uCauSpeed;',- // Water does not slide past itself: warping the sample point is what- // makes the net writhe where a scrolled one would crawl.- ' vec2 cauW = vec2(astraNoise2(cauP * 0.35 + cauT * 0.07),',- ' astraNoise2(cauP * 0.35 - cauT * 0.06 + 7.3));',- ' cauP += (cauW - 0.5) * 0.40;',- // And a second, finer, faster warp: without it the filaments are- // clean arcs, which is the one thing water never draws.- ' cauP += (vec2(astraNoise2(cauP * 2.2 + cauT * 0.30),',- ' astraNoise2(cauP * 2.2 - cauT * 0.27 + 3.7)) - 0.5)',- ' * 0.10;',- // Two wave trains crossing near a right angle. Each is sampled in- // its OWN frame, stretched across its travel, because a train's- // crests — and so its filaments — run across the way it runs.- ' vec2 cauU = vec2(0.86, 0.51);',- ' vec2 cauV = vec2(-0.51, 0.86);',- ' float cauA = astraCauWeb(vec2(dot(cauP, cauU) + cauT,',- ' dot(cauP, cauV) * 0.80));',- ' float cauB = astraCauWeb(vec2(dot(cauP, cauV) * 1.43 - cauT * 0.83,',- ' dot(cauP, cauU) * 1.14 + 3.1));',- // Their sum is the net; their product flares the crossings into the- // bright nodes, which travel at neither train's speed. That- // interference is the caustic — one field of it is a smear. The two- // halves are kept APART because they are not the same light: a node- // is where every wavelength converged, a filament is one fold's- // edge, and they are coloured differently below.- ' float cauFil = (cauA + cauB) * 0.5;',- ' float cauNode = cauA * cauB;',- ' float cauNet = cauFil + 4.0 * cauNode;',- // A third, slow, broad cell: open water is not uniformly lit, and- // this is where the swell has bunched the light.- ' float cauC = astraNoise2(cauP * 0.30',- ' + vec2(0.20, -0.14) * (cauT * 0.21) + 11.7);',- ' float cauSwell = 0.35 + 1.30 * cauC;',- ' cauNet *= cauSwell;',- // Once a pixel spans a cell the net can only alias into sparkle —- // but fading it to BLACK draws a line across the floor where the- // water stops being lit. It fades to the field's own mean instead,- // keeping the swell, so distance goes smooth and stays lit.- ' cauNet = mix(cauNet, 0.30 * cauSwell,',- ' smoothstep(0.25, 0.9, cauAa));',- // Two folds plus their product run to 5, and the swell carries that- // to 8: 8 x strength is far outside anything a tone map holds, so- // the brightest nodes came out of ACES as the same flat white as the- // ones a third as bright — the net lost its own structure at the top- // and took the floor's material with it. This rolls the peaks toward- // 5.5 instead, which lands a node near 3.5 units of radiance: inside- // the tone map's shoulder, and inside a bloom threshold's range.- ' cauNet = cauNet / (1.0 + 0.18 * cauNet);',- // Light needs a run to converge: nothing at the line, a focus a- // fraction of a depth down. The column it loses light IN is the- // tint below — extinction is per channel, not one number.- ' float cauK = smoothstep(0.0, uCauFade * 0.3, cauD);',- ' cauK *= max(dot(normalize(vAstraWorldN), cauBeam), 0.0);',- // No beam enters the surface from a sun below its horizon. The short- // transition also avoids a hard on/off edge at grazing incidence.- ' cauK *= smoothstep(0.0, 0.05, uCauSun.y);',- // A long shallow shelf is one smooth ramp of this term over hundreds- // of pixels, which is exactly where 8-bit output bands.- ' cauK *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.05;',- // A lamp over a pool at night lights a POOL of net, not a reservoir:- // inverse-square in units of its reach, and identically 1.0 for the- // sun, whose w is zero.- ' float cauR = length(vAstraWorld.xz - uCauSrc.xz) * uCauSrc.w;',- ' cauK /= 1.0 + cauR * cauR;',- // WATER DRINKS RED FIRST. The scalar fade this replaces dimmed the- // net evenly and left a deep floor lit the same colour as a shin-- // deep one; a per-channel Beer-Lambert is what makes shallow water- // warm and a depth go green-blue — the whole reason a pool- // photographs. The coefficients have unit luminance-weighted mean,- // preserving the initial extinction rate set by `depthFade`.- ' vec3 cauTint = uCauColor * exp(-cauPath * uCauAbs);',- // Dispersion: a lone filament is a fold seen edge-on and keeps the- // cool end, a crossing is achromatic and runs warm-white.- ' float cauNf = cauNode / (cauNode + cauFil * 0.5 + 1e-4);',- ' cauTint *= mix(vec3(0.84, 0.98, 1.10), vec3(1.08, 1.00, 0.92),',- ' cauNf);',- // And broken colour over metres, so no two bays of one pool are the- // same green — a single flat tint is the tell of a painted pattern.- ' cauTint = astraHueBreak(cauTint, cauP, 0.25, 0.22);',- // Caustics are LIGHT, so they land on the emissive term; tinted by- // the albedo, because what the eye sees is that light reflected.- ' totalEmissiveRadiance += cauTint * diffuseColor.rgb',- ' * (cauNet * cauK * uCauAmt);',-].join('\n');--/**- * Metres a sunbeam slides sideways per metre of depth, REFRACTED.- *- * Water bends the ray toward the vertical (n = 1.333), so the air- * tangent overshoots — at a low sun by more than a third, which would- * shear the net right off the wall it is supposed to be climbing.- */-function refractSlide(sun) {- const sinAir = Math.min(Math.hypot(sun.x, sun.z), 1);- const sinWater = Math.min(sinAir / 1.333, 0.999);- const tanWater = sinWater / Math.sqrt(1 - sinWater * sinWater);- return new THREE.Vector2(sun.x, sun.z).normalize()- .multiplyScalar(tanWater);-}--/**- * Per-channel extinction of the beam through the water column.- *- * Water is not a grey filter: red is gone in a couple of metres where- * blue crosses tens, which is why every photograph of a pool ramps warm- * at the step and green-blue at the drain. Red runs 0.62 of the- * caller's `depthFade` and blue 1.45 — pulled IN from the ~20:1 clear- * water really has, because the true ratio takes the net monochrome- * cyan inside three metres and a pool is not an ocean trench.- *- * Normalised to a unit luminance-weighted mean extinction rate, so- * `depthFade` sets the initial loss per metre. At greater depth the- * surviving blue/green light decays more slowly; a spectral mixture- * cannot retain one exact luminance e-fold distance at every depth.- */-function absorption(fade) {- const w = new THREE.Vector3(1 / 0.62, 1 / 1.00, 1 / 1.45);- const lum = 0.2126 * w.x + 0.7152 * w.y + 0.0722 * w.z;- return w.divideScalar(lum * Math.max(1e-3, fade));-}--/**- * A local source over the water, packed as (x, y, z, 1 / reach).- *- * The sun is parallel light and covers a bay as evenly as a puddle, so- * it is the default and its `w` is 0 — which makes the falloff term in- * the shader exactly 1.0 with no branch. A LAMP is the opposite: a- * night pool is a pool, and one bulb lighting a whole reservoir's floor- * is the tell that the net is a texture. `reach` is where the net is- * down to half.- */-function sourceReach(source, reach) {- if (!source) return new THREE.Vector4(0, 0, 0, 0);- const r = Math.max(1e-3, reach === undefined ? 8 : reach);- return new THREE.Vector4(source.x, source.y, source.z, 1 / r);-}--const seedOffset = (seed) => new THREE.Vector2(seedLattice(seed) * 0.103,- seedLattice(seed, 48271) * 0.071);--/**- * Throw a moving net of caustic light on what is under the water.- *- * Applied to the material of the surface being LIT, never to the- * water. Nothing above `level` is touched at all; below it the net- * fades IN over the first fraction of a depth — light needs a run to- * converge — and out again with the water column, which is what- * separates a lit pool from a floor with a pattern painted on it.- *- * Two things earn the look. The pattern is sampled where the sunbeam- * ENTERED the water: this fragment's world XZ slid toward the sun by- * its own depth, refracted. So the net belongs to the surface overhead- * and a step riser takes a stretched slice of the same net rather than- * a pattern of its own. Incidence and absorption use that same bent- * ray: a grazing sun still reaches the floor steeply, the beam loses- * light over its full slanted water path, and back-facing surfaces- * receive no direct caustics. A sun below the horizon contributes none.- * And it is ridged interference — two wave- * trains crossing, plus a slow third that bunches the light — so the- * bright nodes travel at neither train's speed, where one fbm at any- * speed reads as dirt sliding over the floor.- *- * The third is the COLOUR. The light reaching a fragment has crossed- * its own depth of water, and water drinks red long before blue, so the- * tint is a per-channel Beer-Lambert rather than one fade: warm at the- * step, green-blue at the drain, all from one `depthFade` (measured on- * a two-slab rig, blue/red 1.17 -> 1.41 at 2.4 m against 0.95 -> 0.92- * at 0.4 m). Over that, the crossings run warm-white — every wavelength- * converged there — against cooler filaments, and a slow broken-colour- * field keeps two bays of one pool from being the same green. And the- * whole net is rolled off before it is scaled, so a bright node lands- * near 3.5 units of radiance rather than the 30 that came out of the- * tone map as flat white with the floor's material inside it.- *- * It lifts `totalEmissiveRadiance`, tinted by `diffuseColor`, and does- * NOT change albedo: caustics are light, and albedo alone would cap- * them at the light the surface already gets, so a shaded corner or a- * soffit would take none. That needs a LIT material — MeshStandard /- * MeshPhysical, not Basic, which has no emissive term at all. Drive it- * with `tickShaders(scene, t)`; an un-advanced uTime is a frozen net.- *- * @param {THREE.Material} material A built-in lit material, patched in- * place.- * @param {object} [opts] `level` world Y of the water surface (default- * 0); `sunDir` THREE.Vector3 TOWARD the sun — the same one the key- * light uses (default 0.45, 0.75, 0.35); `scale` metres across one- * cell of the net (default 0.6); `strength` how hard the net- * burns — a node peaks near 3 x this (default 4); `speed` how fast- * the water runs (default 0.35); `color` THREE.Color or hex of the- * light ABOVE the surface, before the water tints it (default a- * warm daylight white); `depthFade` metres of beam travel in water the net survives- * in luminance — red keeps 0.62 of that and blue 1.45, which is the- * ramp from a warm step to a green-blue drain (default 3); `seed`- * moves the lattice, so two pools are not one pool twice (default 1);- * `source` a THREE.Vector3 world position when the light over the- * water is a LAMP rather than the sun, with `reach` the metres at- * which its net is half gone (default 8) — omit both for sunlight.- * @returns {THREE.Material} The same material, its uniforms live on- * `material.userData.uniforms` so `uCauLevel` can follow a tide.- */-export function patchCaustics(material, opts = {}) {- const level = opts.level === undefined ? 0 : opts.level;- const scale = opts.scale === undefined ? 0.6 : opts.scale;- const strength = opts.strength === undefined ? 4 : opts.strength;- const speed = opts.speed === undefined ? 0.35 : opts.speed;- const fade = opts.depthFade === undefined ? 3 : opts.depthFade;- const sun = (opts.sunDir ? opts.sunDir.clone()- : new THREE.Vector3(0.45, 0.75, 0.35)).normalize();- const slide = refractSlide(sun);- // The one silent failure here: no emissive term means either a raw- // ShaderMaterial (no hook at all) or a Basic (no such variable).- if (material && material.emissive === undefined) {- console.warn(- 'patchCaustics: ' + (material.name || material.type) + ' has no '- + 'emissive term — caustics are LIGHT and land on '- + 'totalEmissiveRadiance, which a MeshBasicMaterial and a raw '- + 'ShaderMaterial do not have. Patch a lit material instead.');- }- return patchStandard(material, {- name: 'caustics:net',- uniforms: {- uCauLevel: { value: level },- uCauSun: { value: sun },- uCauSlide: { value: slide },- uCauScale: { value: Math.max(1e-3, scale) },- uCauAmt: { value: Math.max(0, strength) },- uCauSpeed: { value: speed },- uCauColor: { value: toColor(opts.color, 0xfff2e2) },- uCauFade: { value: Math.max(1e-3, fade) },- uCauAbs: { value: absorption(fade) },- uCauSrc: { value: sourceReach(opts.source, opts.reach) },- uCauSeed: { value: seedOffset(opts.seed) },- },- vertexHead: WORLD_VARYINGS,- vertexBody: CAU_VERTEX,- fragmentHead: [WORLD_VARYINGS, CAU_HEAD].join('\n'),- fragmentBody: CAU_BODY,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.jsindex 67c3966a..0a2dee72 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/cloth.js@@ -28,8 +28,6 @@* Which sibling do you want?* `grass.js` — ankle-high ground cover, clumped, per-blade phase; the* ground itself needs covering.- * `smalllife.js` makeReeds — waterline stand, rooted on a bed, the- * bend BREAKING at the surface.* `flowers.js` — colour above the grass, nodding heads.* here — a crop: chest-high, sown in DRILL ROWS, one shared wave.*@@ -654,7 +652,7 @@ const BANNER_FRAGMENT = [* stalk is a bare stem with a heavy EAR that bends further than the* stem does; and the wave is made visible by the pale flank a laid-* over ear turns to the light, not by the bend alone. For ankle-high- * ground cover use `grass.js`; at a waterline use `makeReeds`.+ * ground cover use `grass.js`.** @param {object} [opts]* `extent` metres of the square field's side (default 30, centred ondiff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.jsindex 276e29b6..3a1ecd15 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/dapple.js@@ -7,7 +7,7 @@* ground under a tree is a flat tone with a shadow blob on it.** It goes on the material of the surface BEING LIT, not on the canopy,- * for the same reason `patchCaustics` does — the pattern belongs to the+ * because the pattern belongs to the* leaves overhead, which the floor knows nothing about. So the caller* states where the canopy is and how dense it is.*@@ -53,8 +53,7 @@ const FLECK_LOW = new THREE.Color(0xffc287);* cloudy blur that reads as fog on the floor instead. It lifts the* light rather than the albedo — a sunfleck on a shaded floor is often* the only direct light there is, and lifting albedo alone would cap it- * at the ambient the floor already receives, exactly the choice- * `windows.js` and `caustics.js` document.+ * at the ambient the floor already receives.** Three things make a fleck read as SUNLIGHT rather than as a pale* texture, and all three are geometry the caller already stated:diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.jsdeleted file mode 100644index 5106d061..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/figure.js+++ /dev/null@@ -1,575 +0,0 @@-/**- * A human, with real proportions and joints that pose — the guessed- * arithmetic (seat heights, gait, tapers) ships as functions because- * prose never landed. Standard 7.5-head figure, FEET AT y=0, facing- * -Z, so `seat()` and `alignAlong()` from place.js work unchanged.- * `walk()` owns the gait contract: pass the route's `speed` and the- * feet match the ground covered by construction.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import * as MAT from './materials.js';--/**- * A tapered limb segment hanging down -Y from its pivot. The taper is- * most of what makes a silhouette read as a person at 30 metres.- *- * @param {number} len Segment length in metres.- * @param {number} r0 Radius at the pivot end.- * @param {number} r1 Radius at the free end.- * @param {THREE.Material} mat- * @param {string} name- * @returns {THREE.Mesh} Positioned so its top sits at the pivot.- */-function seg(len, r0, r1, mat, name) {- const g = new THREE.CylinderGeometry(r1, r0, len, 8, 1, false);- g.translate(0, -len / 2, 0);- const m = new THREE.Mesh(g, mat);- m.name = name;- m.castShadow = true;- // A ball cap at the pivot: a flat-capped cylinder opens a visible- // wedge at every bent knee and elbow (worst on seated crowds at- // close cameras). ~30 tris buys articulation at any bend angle.- const cap = new THREE.Mesh(new THREE.SphereGeometry(r0, 6, 5), mat);- cap.castShadow = true;- m.add(cap);- return m;-}--/** An empty pivot at a local point, named so poses can find it. */-function pivot(name, x, y, z) {- const o = new THREE.Object3D();- o.name = name;- o.position.set(x, y, z);- return o;-}--// A ladder of complexions, warm through olive to deep, with the HUE-// moving as well as the value (a crowd graded only in lightness reads-// as one person under five lamps). Every entry stays inside the-// non-emissive albedo window: the brightest channel here is 0xcc, and-// the old code's real bug was handing MAT.skin `color: undefined`,-// which `Object.assign` copied OVER the default — every face in every-// scene rendered at albedo 1.0, i.e. a blown white ball.-const SKIN_TONES = [0xcca07d, 0xc08e63, 0xa2764c, 0x8a6446, 0x805334,- 0x5b3c2a];--// One shared eye material for the whole scene: low roughness so the-// environment puts a single specular dot on each eye, which is the-// entire difference between a face and a ball at a close camera.-let _eyeMat = null;-function eyeMaterial() {- if (!_eyeMat) {- // Dark, but not below the albedo floor the rest of the figure keeps:- // a pupil at linear 0.013 is a hole, and the specular dot is what- // sells an eye anyway.- _eyeMat = new THREE.MeshStandardMaterial(- { color: 0x352a20, roughness: 0.22, metalness: 0 });- }- return _eyeMat;-}--/** Never let a colour fall to a light-swallowing void (dark hair, dark- * shoes): floor its LINEAR lightness, keeping hue and saturation. */-function floorValue(hex, minL) {- const c = new THREE.Color(hex);- const hsl = c.getHSL({ h: 0, s: 0, l: 0 });- if (hsl.l < minL) c.setHSL(hsl.h, hsl.s, minL);- return c;-}--/**- * Build an articulated human.- *- * @param {object} [opts]- * `height` metres (default 1.72), `build` 0.8 slight to 1.25 heavy- * (default 1), `fem` 0..1 slides the shoulder:hip width ratio from- * the measured male 1.4 to the female 1.2 biacromial:biiliac mean —- * two scalars that turn one generator into a mixed crowd, `rand`- * seeded PRNG used for the small per-person variation that keeps a- * crowd from looking cloned, `skin`, `top`, `bottom`, `hair` hex- * colours (`skin` unset picks a complexion off SKIN_TONES from the- * same draw that sets the material variant — so a crowd is mixed- * without multiplying the material cache), `face` false to drop the- * eyes and nose on figures that will never be seen close, `name`.- * @returns {THREE.Group} Feet at y=0, facing -Z, with `userData.forward`- * `'-Z'`, `userData.height`, and `userData.joints` naming every pivot- * (`waist`, `neck`, `hipL/R`, `kneeL/R`, `ankleL/R`, `shoulderL/R`,- * `elbowL/R`).- */-export function figure(opts = {}) {- const rand = opts.rand || (() => 0.5);- const h = (opts.height || 1.72) * (0.96 + rand() * 0.08);- const b = opts.build || (0.9 + rand() * 0.25);- const fem = opts.fem === undefined ? 0 : opts.fem;-- // ONE draw picks both the complexion and the material variant, so the- // skin cache stays at one material per variant bucket however many- // tones the ladder holds — a crowd costs no more textures than before.- const skinV = rand();- // Quantised to the SAME 9 buckets materials.js quantises `variant`- // into, so the tone is a function of the bucket and the pair stays- // 1:1 — a ladder of six tones still costs nine skin materials, not- // the thirteen two independent partitions would produce.- const skinQ = Math.round(skinV * 8) / 8;- const skinCol = opts.skin === undefined- ? SKIN_TONES[Math.min(SKIN_TONES.length - 1,- Math.floor(skinQ * SKIN_TONES.length))]- : opts.skin;- // Hue break, not just value break: real skin is pink at the knuckles- // and olive in the shadow, and a flat albedo is what makes a figure- // read as a mannequin however good the silhouette is.- const skin = MAT.skin({ color: skinCol, variant: skinV,- contrast: 0.13, hueBreak: 0.15, scale: 26, roughness: 0.58 });- const top = MAT.fabric({ color: opts.top === undefined ? 0x44506b- : opts.top, variant: rand(), contrast: 0.30, hueBreak: 0.15,- scale: 46 });- const bottom = MAT.fabric({ color: opts.bottom === undefined ? 0x2f3440- : opts.bottom, variant: rand(), contrast: 0.26, hueBreak: 0.12,- scale: 34 });- // Leather, not the painted-wood grain the first port put on a shoe;- // the value is floored off black so a shoe is a dark object in the- // scene's light rather than a hole in the frame.- // No roughness map and a high roughness on purpose: the noise- // roughnessMap dips to a near-mirror in places, and on the UPWARD- // face of a shoe that is a full sky reflection — measured as a- // blown white (159,152,139) toe cap on a 0x3a albedo.- const shoe = MAT.fabric({ color: 0x3a332c, roughness: 0.78, scale: 55,- contrast: 0.18, hueBreak: 0.08, bump: 0.004,- extra: { roughnessMap: null } });-- const root = new THREE.Group();- root.name = opts.name || 'Figure';-- const hipY = 0.53 * h;- const shoulderY = 0.82 * h;- const shoulderX = (0.115 - 0.018 * fem) * h * b;- const hipX = 0.052 * h;- const thigh = 0.25 * h;- const shin = 0.24 * h;- const upper = 0.19 * h;- const fore = 0.145 * h; // canon 0.146h: the wrist lands at the crotch-- // Torso hangs off a waist pivot so a figure can lean or slump. A- // lathe, not a cylinder: the S-curve is the strongest silhouette cue- // and the neck ramp kills the coat-hanger read of a flat-topped torso.- const waist = pivot('waist', 0, hipY, 0);- const prof = [- [0.088 * (1 + 0.12 * fem) * b, 0], // hip- [0.070 * (1 - 0.08 * fem) * b, 0.07], // waist- [0.105 * (1 - 0.08 * fem) * b, 0.19], // chest- [0.095 * (1 - 0.10 * fem), 0.27], // shoulder- [0.032, 0.29], // trapezius ramp to neck- ];- const chest = new THREE.Mesh(- // 12 radial segments, not 10: at a close camera the 10-segment- // lathe threw a hard vertical facet crease down the chest, and- // the extra two rings cost 8 quads on the whole body.- new THREE.LatheGeometry(- prof.map((q) => new THREE.Vector2(q[0] * h, q[1] * h)), 12),- top);- chest.geometry.scale(1, 1, 0.62); // people are not cylinders in plan- chest.name = 'torso';- chest.castShadow = true;- waist.add(chest);-- // Pelvis: below the hip line nothing existed, so a seated figure- // showed a see-through crotch the moment the thighs went horizontal.- const pelvis = new THREE.Mesh(- new THREE.SphereGeometry(0.095 * h * b * (1 + 0.10 * fem), 8, 6),- bottom);- pelvis.scale.set(1, 0.6, 0.62);- pelvis.position.y = -0.02 * h;- pelvis.name = 'pelvis';- pelvis.castShadow = true;- waist.add(pelvis);-- const neck = pivot('neck', 0, shoulderY - hipY + 0.02 * h, 0);- const R = h / 15.5;- const head = new THREE.Mesh(- new THREE.SphereGeometry(R, 14, 12), skin);- head.geometry.scale(0.86, 1, 0.92);- head.position.y = R + 0.03 * h;- head.name = 'head';- head.castShadow = true;- neck.add(new THREE.Mesh(- new THREE.CylinderGeometry(0.028 * h, 0.032 * h, 0.07 * h, 8), skin));- neck.add(head);- // A face, at ~150 triangles. Without it the head is a ball, and a- // ball is what makes a close figure read as a shop dummy however- // good the gait is: the eye finds a face or it finds a mannequin.- // `face: false` for crowds that stay past ~15 m, where these are- // sub-pixel anyway.- if (opts.face !== false) {- for (const s of [-1, 1]) {- const eye = new THREE.Mesh(- new THREE.SphereGeometry(0.155 * R, 5, 4), eyeMaterial());- eye.name = 'eye' + (s < 0 ? 'L' : 'R');- // Flattened: an eye is an aperture three times wider than it is- // tall, and a round ball of one reads as an insect.- eye.scale.set(1, 0.58, 1);- eye.position.set(s * 0.32 * R, -0.02 * R, -0.80 * R);- head.add(eye);- }- // The nose is the whole profile: a head in silhouette against the- // sky is otherwise a circle from every angle.- const nose = new THREE.Mesh(- new THREE.SphereGeometry(0.20 * R, 5, 4), skin);- nose.scale.set(0.62, 1.05, 0.85);- nose.position.set(0, -0.18 * R, -0.90 * R);- head.add(nose);- }- if (opts.hair !== undefined) {- const hair = new THREE.Mesh(- // A CAP, not a helmet: 0.62pi reached below the eye line and- // swallowed the whole face (measured — the render showed a- // dark ball with a nose). 0.53pi stops at the temple, and the- // 0.19 rad tilt drops the rim at the back and lifts it off the- // brow at the front, which is what a hairline is.- new THREE.SphereGeometry(R * 1.06, 12, 10,- 0, Math.PI * 2, 0, Math.PI * 0.53),- // Roughness 0.62, not 0.85: hair is the one thing on a person- // that carries a broad specular band, and the flat 0.85 felt- // cap was reading as a helmet. The value floor keeps very dark- // hair a dark BROWN object instead of a hole in the frame.- MAT.fabric({ color: floorValue(opts.hair, 0.035), variant: 0.5,- roughness: 0.62, scale: 70, contrast: 0.35, hueBreak: 0.10,- bump: 0.004 }));- hair.position.copy(head.position);- hair.position.z += 0.03 * R;- hair.position.y -= 0.02 * R;- hair.rotation.x = 0.19;- hair.scale.set(0.90, 1.0, 0.99);- hair.castShadow = true;- neck.add(hair);- }- waist.add(neck);-- const joints = { waist, neck };- for (const s of [-1, 1]) {- const tag = s < 0 ? 'L' : 'R';- const sh = pivot('shoulder' + tag, s * shoulderX,- shoulderY - hipY - 0.03 * h, 0);- sh.add(seg(upper, 0.042 * h * b, 0.033 * h, top, 'upperArm' + tag));- const el = pivot('elbow' + tag, 0, -upper, 0);- el.add(seg(fore, 0.033 * h, 0.024 * h, skin, 'forearm' + tag));- const hand = new THREE.Mesh(- new THREE.SphereGeometry(0.028 * h, 8, 6), skin);- hand.scale.set(0.8, 1.25, 0.55);- hand.position.y = -fore - 0.015 * h;- hand.name = 'hand' + tag;- el.add(hand);- sh.add(el);- waist.add(sh);- joints['shoulder' + tag] = sh;- joints['elbow' + tag] = el;-- const hip = pivot('hip' + tag, s * hipX, 0, 0);- hip.add(seg(thigh, 0.062 * h * b, 0.048 * h, bottom, 'thigh' + tag));- const kn = pivot('knee' + tag, 0, -thigh, 0);- kn.add(seg(shin, 0.046 * h, 0.032 * h, bottom, 'shin' + tag));- // An ankle pivot: heel strike and toe-off are the only two moments- // the eye reads as ground contact, and a foot welded to the shin- // can express neither — that is the flat-footed shuffle.- const ak = pivot('ankle' + tag, 0, -shin, 0);- // A shoe, not a brick. The box was 12 triangles but presented one- // large FLAT horizontal facet, and a horizontal facet in an open- // sky is the brightest thing in the frame: measured sRGB 159 on a- // 0x3a albedo, i.e. a white plate stuck to a black shoe, on every- // figure in the render. A domed upper spreads that same light over- // a curve, which is what a shoe actually does — 56 triangles, and- // 6.4% of its area horizontal against the box's 27.2%. Rounded- // toe, short heel, sole clamped FLAT so the feet-at-y=0 arithmetic- // every placer depends on is unchanged.- const fg = new THREE.SphereGeometry(1, 7, 4);- const fp = fg.attributes.position;- for (let i = 0; i < fp.count; i++) {- const z = fp.getZ(i);- fp.setXYZ(i,- fp.getX(i) * 0.030 * h,- Math.max(fp.getY(i) * 0.021 * h, -0.014 * h),- z * (z < 0 ? 0.085 : 0.058) * h); // -Z is forward: a toe- }- fg.computeVertexNormals();- const foot = new THREE.Mesh(fg, shoe);- foot.position.set(0, -0.026 * h, -0.030 * h);- foot.name = 'foot' + tag;- foot.castShadow = true;- ak.add(foot);- kn.add(ak);- hip.add(kn);- waist.add(hip);- joints['hip' + tag] = hip;- joints['knee' + tag] = kn;- joints['ankle' + tag] = ak;- }-- // Perfectly vertical limbs are the strongest mannequin tell: every- // figure carries its own resting offsets, and `neutral()` restores- // THESE, not zeros, so poses stack on a body that already stands.- root.userData.rest = {- shoulderL: [0, 0, -0.10], shoulderR: [0, 0, 0.10],- elbowL: [0.10, 0, 0], elbowR: [0.10, 0, 0],- hipL: [0, 0, -0.03], hipR: [0, 0, 0.03],- waist: [0, (rand() - 0.5) * 0.10, 0],- neck: [0, (rand() - 0.5) * 0.30, 0],- };- root.add(waist);- root.userData.forward = '-Z';- root.userData.height = h;- root.userData.joints = joints;- root.userData.hipHeight = hipY;- const sole = root.getObjectByName('footL');- root.userData.gaitDimensions = { thigh, shin,- sole: Array.from({ length: sole.geometry.attributes.position.count }, (_, i) => [- sole.geometry.attributes.position.getY(i) + sole.position.y,- sole.geometry.attributes.position.getZ(i) + sole.position.z,- ]) };- root.userData.update = root.userData.tick = () => {};- // MAT and eyeMaterial cache their materials across figures. Only the- // geometry belongs to this figure; attached held objects stay caller-owned.- attachDisposal(root, snapshotResources(root, { materials: false }));- return neutral(root);-}--/** Reset every joint to this figure's resting stance (not rigid zeros). */-function neutral(fig) {- const rest = fig.userData.rest || {};- for (const [name, j] of Object.entries(fig.userData.joints)) {- const r = rest[name] || [0, 0, 0];- j.rotation.set(r[0], r[1], r[2]);- }- fig.userData.joints.waist.position.set(0, fig.userData.hipHeight, 0);- fig.getObjectByName('torso').rotation.set(0, 0, 0);- return fig;-}--/**- * Sit a figure on something, with its pelvis ON the seat: the seat- * height determines the pose (thighs horizontal, shins to the floor,- * torso leant onto the backrest) rather than the author guessing a y.- *- * @param {THREE.Group} fig From `figure()`.- * @param {THREE.Object3D|number} seatTo A chair/bench/stool (its bbox top- * is measured) or a seat height in metres.- * @param {object} [opts] `lean` radians (default 0.12), `spread` radians- * of knee splay (default 0.06).- * @returns {THREE.Group} fig- */-export function sit(fig, seatTo, opts = {}) {- // POSE WHATEVER IS ACTUALLY THE FIGURE: composers pass wrapper- // Groups with the figure() output nested inside. Descend to the- // first node with userData.joints; if there is none, say so.- const posed = fig && fig.userData && fig.userData.joints- ? fig- : (() => {- let hit = null;- if (fig && fig.traverse) {- fig.traverse((o) => {- if (!hit && o.userData && o.userData.joints) hit = o;- });- }- return hit;- })();- if (!posed) {- throw new Error(- 'sit(): "' + ((fig && fig.name) || 'this object') + '" was not '- + 'built by figure(), and neither is anything inside it — there '- + 'are no joints to pose. Build the person with figure() from '- + './lib/figure.js, or seat the object with seat() from '- + './lib/place.js instead.');- }- fig = posed;- const j = neutral(fig).userData.joints;- let seatY;- if (typeof seatTo === 'number') {- seatY = seatTo;- } else {- seatTo.updateMatrixWorld(true);- seatY = new THREE.Box3().setFromObject(seatTo).max.y;- }- const lean = opts.lean === undefined ? 0.12 : opts.lean;- const spread = opts.spread === undefined ? 0.06 : opts.spread;-- // Solve the thigh angle from the seat height: on a low stool the- // knees ride ABOVE the hips because the shins must reach the floor.- // `u` lands the feet at y=0, clamped so a bar stool can't fold double.- const h = fig.userData.height;- const drop = 0.24 * h + 0.0335 * h; // shin + ankle + sole- const u = Math.asin(Math.max(-0.35, Math.min(0.35,- (drop - seatY) / (0.25 * h))));- j.waist.rotation.x = -lean; // back onto the backrest- for (const s of ['L', 'R']) {- const sgn = s === 'L' ? -1 : 1;- // `+ lean` cancels the torso's tilt, so the femur angle is set by- // the seat and not by how far back the person is reclining.- j['hip' + s].rotation.x = Math.PI / 2 + u + lean;- j['hip' + s].rotation.z = sgn * spread;- j['knee' + s].rotation.x = -(Math.PI / 2 + u); // shin vertical- j['shoulder' + s].rotation.x = 0.35; // forearms toward the table- // Positive x flexes the forearm FORWARD (measured on the rig; the- // old -0.8 bent every seated elbow backward, behind the chair).- j['elbow' + s].rotation.x = 0.8;- }- // Pelvis exactly on the seat; the legs then reach the floor on their own.- fig.position.y = seatY - fig.userData.hipHeight;- return fig;-}--/**- * Pose a figure mid-stride. Call per frame with the animation clock.- * Anti-moonwalk contract: pass `speed` — the SAME m/s the route uses —- * and cadence + stride are derived so stepLength x cadence === speed- * by construction; a time-only gait reads as "sliding sideways".- *- * @param {THREE.Group} fig From `figure()`.- * @param {number} t Seconds (give each walker its own `phase`, or a- * crowd marches in lockstep).- * @param {object} [opts] `speed` metres per second — pass the route's- * speed and the stride is sized to cover it exactly; `phase`- * per-person offset in stride cycles; or the manual knobs `stride`- * radians of hip swing (default 0.42) and `rate` strides per second- * (default 0.95, about 114 steps/min).- * @returns {THREE.Group} fig- */-export function walk(fig, t, opts = {}) {- const j = fig.userData.joints;- const h = fig.userData.height;- const L = fig.userData.hipHeight; // hip pivot to sole: the leg- if (!Number.isFinite(t)) throw new RangeError('walk: time must be finite');- let a, cyc, speed;- if (opts.speed !== undefined) {- if (!Number.isFinite(opts.speed) || opts.speed < 0)- throw new RangeError('walk: speed must be finite and nonnegative');- if (opts.speed === 0) {- neutral(fig);- fig.userData.gait = { phase: 0, speed: 0, stance: [true, true] };- return fig;- }- const v = opts.speed;- const wr = 0.0065 * (h / 1.72); // walk ratio, m per (step/min)- const cadence = Math.min(145, Math.max(70, Math.sqrt(60 * v / wr)));- // At an unusually high requested route speed, shorten the cycle instead- // of silently clamping foot travel and allowing the planted foot to slide.- const reach = fig.userData.gaitDimensions.thigh + fig.userData.gaitDimensions.shin;- cyc = Math.max(cadence / 120, v * .55 / (2 * reach * .68));- // stepLen = v / (2 * cyc), so stepLen x cadence === v exactly,- // even where the cadence clamps; a = asin(stepLen / (2 * L)).- a = Math.asin(Math.min(0.98, v / (4 * cyc * L)));- speed = v;- } else {- a = opts.stride === undefined ? 0.42 : opts.stride;- cyc = opts.rate === undefined ? 0.95 : opts.rate;- speed = 4 * L * Math.sin(a) * cyc;- }- const cycle = t * cyc + (opts.phase || 0);- const p = cycle * Math.PI * 2;- const sw = Math.sin(p);- const dimensions = fig.userData.gaitDimensions;- const thigh = dimensions.thigh, shin = dimensions.shin;- const stanceFraction = 0.55;- const halfStroke = Math.min((thigh + shin) * .68,- speed * stanceFraction / (2 * Math.max(cyc, 1e-5)));- const smooth = (x) => { x = THREE.MathUtils.clamp(x, 0, 1); return x * x * (3 - 2 * x); };- const feet = [0, .5].map((offset) => {- const phase = THREE.MathUtils.euclideanModulo(cycle - .25 + offset, 1);- const stance = phase < stanceFraction;- let z, lift = 0, pitch;- if (stance) {- // A planted foot travels BACKWARD in the figure frame at precisely the- // route speed. With root motion along -Z, it stays on one ground point.- z = halfStroke * (2 * phase / stanceFraction - 1);- pitch = .20 * (1 - smooth(phase / .10))- - .35 * smooth((phase - .40) / .15);- } else {- const q = (phase - stanceFraction) / (1 - stanceFraction);- // Cubic return with matching endpoint velocity: the foot does not snap- // from the moving stance arc to a zero-velocity swing arc.- const slope = 2 * halfStroke / stanceFraction * (1 - stanceFraction);- z = halfStroke * (4 * q ** 3 - 6 * q * q + 1)- + slope * (2 * q ** 3 - 3 * q * q + q);- lift = h * .065 * Math.sin(Math.PI * q) ** 2;- pitch = -.35 + .55 * smooth(q);- }- const c = Math.cos(pitch), s = Math.sin(pitch);- let soleY = Infinity;- for (const [y, pointZ] of dimensions.sole) soleY = Math.min(soleY, y * c - pointZ * s);- return { phase, stance, z: z + .03 * h, y: lift - soleY, pitch };- });- let pelvisY = L - .004 * h - .038 * h * sw * sw;- const reach = (thigh + shin) * .999;- for (const foot of feet) {- pelvisY = Math.min(pelvisY, foot.y + Math.sqrt(Math.max(.01, reach * reach - foot.z * foot.z)));- }- for (let i = 0; i < 2; i++) {- const side = i === 0 ? 'L' : 'R', foot = feet[i];- const y = foot.y - pelvisY, z = foot.z;- const cosine = THREE.MathUtils.clamp((y * y + z * z - thigh * thigh - shin * shin)- / (2 * thigh * shin), -1, 1);- const knee = -Math.acos(cosine);- const hip = Math.atan2(-z, -y) - Math.atan2(shin * Math.sin(knee), thigh + shin * Math.cos(knee));- j['hip' + side].rotation.set(hip, 0, 0);- j['knee' + side].rotation.set(knee, 0, 0);- j['ankle' + side].rotation.set(foot.pitch - hip - knee, 0, 0);- }- // Arms counter-swing the legs, and the elbow flexes hardest when its- // arm is forward — a straight pumping stick reads as a mannequin.- j.shoulderL.rotation.x = -sw * a * 0.7;- j.shoulderR.rotation.x = sw * a * 0.7;- j.elbowL.rotation.x = 0.35 + 0.3 * Math.max(0, -sw);- j.elbowR.rotation.x = 0.35 + 0.3 * Math.max(0, sw);- // Keep the leg frame stable while the torso twists above it. Rotating the- // waist parent would rotate planted feet away from their ground contacts.- j.waist.rotation.set(0, 0, 0);- fig.getObjectByName('torso').rotation.y = sw * .06;- // Pelvis dips twice per stride and lowers enough to keep each target- // within leg reach. Route motion remains on fig.position.- j.waist.position.set(0, pelvisY, 0);- fig.userData.gait = { phase: THREE.MathUtils.euclideanModulo(cycle, 1),- speed, stance: feet.map((foot) => foot.stance) };- return fig;-}--/**- * Raise both forearms to hold something at chest height (a tray, a box).- *- * @param {THREE.Group} fig- * @param {THREE.Object3D} [held] Optional object parented between the- * hands, so it tracks the pose instead of floating near it.- * @returns {THREE.Group} fig- */-export function carry(fig, held) {- const j = fig.userData.joints;- for (const s of ['L', 'R']) {- j['shoulder' + s].rotation.x = 0.5;- // +0.6 puts the hands ON the held object's rim (the old -1.3 bent- // the elbows backward, hands behind the body).- j['elbow' + s].rotation.x = 0.6;- j['shoulder' + s].rotation.z = (s === 'L' ? 1 : -1) * 0.12;- }- if (held) {- // MEASURE the hands, do not guess. The held object is parented to- // the WAIST pivot, which already sits at hipHeight — so the old- // `0.52 * h` (a figure-root height) put the tray a clear 0.85 m- // above the hands, i.e. balanced on top of the head. Reading the- // posed hands back also means the offset survives any later change- // to the shoulder/elbow angles above.- const j2 = fig.userData.joints;- fig.updateMatrixWorld(true);- const mid = new THREE.Vector3();- const p = new THREE.Vector3();- for (const s of ['L', 'R']) {- const hand = j2['elbow' + s].getObjectByName('hand' + s);- if (hand) mid.add(hand.getWorldPosition(p));- }- mid.multiplyScalar(0.5);- j2.waist.worldToLocal(mid);- const h = fig.userData.height;- held.position.copy(mid);- held.position.y += 0.035 * h; // it RESTS on the hands- held.position.z -= 0.020 * h; // ... just past the fingertips- j2.waist.add(held);- }- return fig;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.jsindex ad17f6e1..084eea70 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/finish.js@@ -11,7 +11,7 @@* one decision that separates them from a pale repaint. At* `<color_fragment>`, where both run, a patch may either tint ALBEDO* — capped at the light already landing on the surface — or ADD light,- * the choice `windows.js` documents for a lit room. A lantern at dusk+ * the choice made here. A lantern at dusk* and an oil sheen on a shaded cobble are both brighter than their own* front lighting, so neither can be albedo.*/diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.jsdeleted file mode 100644index 04d3c908..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js+++ /dev/null@@ -1,451 +0,0 @@-/**- * A bounded shared fire/soot field for fuel beds, large fires and authored- * structural-fire scenes. This is prescribed transport, not combustion or- * structural simulation. Legacy makeFire/makeCandle remain in fire.js.- *- * makeFireField({emitters:[{position:[0,0,0],radius:.3,height:1,strength:1}],- * seed:7, wind:[.15,0], quality:'balanced', intensity:1,- * smoke:{height:3,density:.65,albedo:0x514942},- * embers:{count:48,size:[.0015,.006],lifetime:[2,4],riseSpeed:1.2},- * lighting:{count:2,intensity:12}, occluders:[], depthResolution:512})- *- * Positions/dimensions are local metres; wind is local metres/second. All- * emitters share one ray integration. A baked source atlas makes runtime- * density cost independent of emitter count. Source layout and wind are baked at- * construction; rebuild the field to change them. Nonuniform object transforms- * are supported; optical depth uses world metres. update(t) takes absolute seconds;- * sampleField(x,y,z,t) mirrors the GPU's flame/soot/temperature field.- *- * Optional occluders are BORROWED Object3D roots. An isolated depth-proxy scene- * terminates rays at those opaque meshes, including alpha cuts, instances and- * customDepthMaterial deformation. Hidden ancestors are respected. Original- * callbacks/parents/materials are never changed. Skinned meshes and morphed- * InstancedMesh occluders are unsupported;- * custom vertex deformation requires a matching customDepthMaterial. Glass and- * other transparent volumes are not depth-resolved. One depth-aware fire field- * per scene is recommended; each visible view adds a pass over its occluders.- * Logarithmic depth is not supported by the optional depth-termination path.- * No global renderer hooks or recursively captured reflective materials.- */-import * as THREE from 'three';-import { bakeFbm3, dataTexture3D, mulberry32, sampleGrid3 } from './noise.js';-import { intOption, makeShaderMaterial, keepOutOfDepthPasses, makeLightProbe, option, readWind, vector, withRendererState } from './shader.js';-import { snapshotResources, attachDisposal } from './lifecycle.js';--const TIERS = {- low: { resolution: 48, steps: 48, lightSteps: 3 },- balanced: { resolution: 64, steps: 80, lightSteps: 5 },- high: { resolution: 80, steps: 128, lightSteps: 7 },-};-const NOISE_RESOLUTION = 48;-const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));-const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };-const fract = x => x - Math.floor(x);-function noiseTexture(seed) {- const { values } = bakeFbm3(mulberry32(seed), NOISE_RESOLUTION, [4, 8, 16], 4);- return dataTexture3D(Uint8Array.from(values, v => Math.round(clamp(v) * 255)), NOISE_RESOLUTION, true);-}-function sourceAtlas(emitters, box, resolution, smokeHeight, wind, rise, seed) {- const extent = box.getSize(new THREE.Vector3()), data = new Uint8Array(resolution ** 3 * 4);- const random = mulberry32(seed ^ 0x7139), phases = emitters.map(() => random()); let at = 0;- for (let z = 0; z < resolution; z++) for (let y = 0; y < resolution; y++) for (let x = 0; x < resolution; x++) {- const px = box.min.x + (x + .5) / resolution * extent.x;- const py = box.min.y + (y + .5) / resolution * extent.y;- const pz = box.min.z + (z + .5) / resolution * extent.z;- let flame = 0, progress = 0, soot = 0, phase = 0, strongest = 0;- for (let i = 0; i < emitters.length; i++) {- const e = emitters[i], h = py - e.position[1];- if (h <= 0 || e.strength === 0) continue;- const age = h / rise, dx = px - e.position[0] - wind[0] * age;- const dz = pz - e.position[2] - wind[1] * age;- const distance = Math.hypot(dx, dz), f = h / e.height;- if (f < 1.65) {- const profile = Math.pow(Math.max(0, 1 - f / 1.05), .72) * .94 - Math.max(0,f-1.05)*2;- const potential = clamp(.5 + (profile - distance / e.radius) * .57 + Math.log2(Math.max(.01,e.strength))*.075);- if (potential > flame) { flame = potential; progress = f; phase = phases[i]; }- }- const s = h / smokeHeight;- if (s < 1) {- const radius = e.radius * .70 + h * .23;- const plume = Math.pow(clamp(1 - distance / radius), .65)- * smooth(.025, .16, s) * (1 - smooth(.70, 1, s)) * Math.exp(-s * 1.4) * e.strength;- soot += plume * .55;- if (plume > strongest && flame === 0) { strongest = plume; phase = phases[i]; }- }- }- data[at++] = Math.round(flame * 255); data[at++] = Math.round(clamp(progress) * 255);- data[at++] = Math.round(clamp(soot) * 255); data[at++] = Math.round(phase * 255);- }- return dataTexture3D(data, resolution, false);-}--const FIELD = /* glsl */`-precision highp sampler3D;-uniform float uTime;-uniform sampler3D uSourceAtlas, uFieldNoise;-uniform sampler2D uOpaqueDepth;-uniform vec3 uBoxMin, uBoxSize, uFlameBoxMin, uFlameBoxSize, uSunLocal, uSunColor, uAmbient, uSootAlbedo;-uniform vec4 uViewport, uFireLights[4];-uniform vec3 uFireLightColor;-uniform mat4 uViewToLocal, uInverseProjection, uLocalToClip;-uniform mat3 uLocalToWorld;-uniform float uCoarseScale, uWarp, uRise, uTurbulence, uIntensity;-uniform float uFlameExtinction, uSootExtinction, uUseOpaqueDepth;-uniform int uFireLightCount;-varying vec3 vFieldLocal;-vec4 fireAtlas(vec3 p) {- vec3 uv=(p-uBoxMin)/uBoxSize;- if(any(lessThan(uv,vec3(0.0)))||any(greaterThan(uv,vec3(1.0))))return vec4(0.0);- return texture(uSourceAtlas,uv);-}-vec3 fireFieldSample(vec3 p) {- vec4 initial=fireAtlas(p);- vec3 flow=p*vec3(.32,.13,.32)/uCoarseScale-vec3(0.0,uTime*uRise*.13/uCoarseScale,0.0);- vec3 coarse=texture(uFieldNoise,flow+initial.a*.31).rgb;- float anchor=smoothstep(0.0,.22,initial.g);- vec3 warped=p+(coarse-.5)*uWarp*vec3(1.0,.38,1.0)*anchor*uTurbulence;- vec4 field=fireAtlas(warped);- float fine=texture(uFieldNoise,p*vec3(2.6,.75,2.6)-vec3(0.0,uTime*uRise*.75,0.0)+.197).g;- float surface=field.r-.5+((coarse.g-.5)*(.35+field.g*.8)+(fine-.5)*.30)*uTurbulence;- float flame=smoothstep(-.025,.075,surface)*(1.0-smoothstep(.035,.22,surface)*.97)- *smoothstep(0.0,.055,field.g)*(1.0-smoothstep(.90,1.0,field.g));- flame*=smoothstep(.21+field.g*.20,.42+field.g*.23,coarse.r*.65+fine*.35);- float smoke=field.b*pow(clamp(.68+(coarse.r-.5)*2.4+(fine-.5)*.55,0.0,1.6),1.3);- float temperature=clamp(.18+flame*.57+coarse.b*.15-field.g*.18,0.0,1.0);- return vec3(flame,smoke,temperature);-}-// Light samples use only the precomputed soot scaffold, not every emitter.-float fireSootCoarse(vec3 p) {- vec4 a=fireAtlas(p);- float n=texture(uFieldNoise,p*vec3(.32,.13,.32)/uCoarseScale-vec3(0.0,uTime*uRise*.13/uCoarseScale,0.0)+a.a*.31).r;- return a.b*pow(clamp(.68+(n-.5)*2.4,0.0,1.6),1.3);-}-vec2 fireBox(vec3 origin,vec3 direction){return astraRayBox(origin,direction,uBoxMin,uBoxMin+uBoxSize);}-vec3 fireRadiance(float heat) {- vec3 c=mix(vec3(1.8,.06,.002),vec3(4.0,.75,.04),smoothstep(.15,.58,heat));- return mix(c,vec3(6.0,2.8,.65),smoothstep(.55,.96,heat))*.72;-}-float fireSunTransmission(vec3 p,float jitter) {- float end=max(0.0,fireBox(p,uSunLocal).y),sum=0.0;- for(int j=0;j<FIELD_LIGHT_STEPS;j++) {- float a=float(j)/float(FIELD_LIGHT_STEPS),b=float(j+1)/float(FIELD_LIGHT_STEPS);- float start=a*a*end,stop=b*b*end;- sum+=fireSootCoarse(p+uSunLocal*mix(start,stop,jitter))*(stop-start);- }- return exp(-sum*uSootExtinction*length(uLocalToWorld*uSunLocal));-}-`;--function fieldMaterial(uniforms, tier) {- return makeShaderMaterial({name:'SharedFireSootVolume',fog:true,- transparent:true,depthWrite:false,side:THREE.BackSide,uniforms,- defines:{FIELD_STEPS:tier.steps,FIELD_LIGHT_STEPS:tier.lightSteps},- varyings:'varying vec3 vFieldLocal;',vertexMain:'vFieldLocal=position;',fragmentHead:FIELD,- fragmentMain:/* glsl */`- vec2 uv=(gl_FragCoord.xy-uViewport.xy)/uViewport.zw;- vec4 nearView=uInverseProjection*vec4(uv*2.0-1.0,-1.0,1.0);- vec4 farView=uInverseProjection*vec4(uv*2.0-1.0,1.0,1.0);- vec3 origin=(uViewToLocal*vec4(nearView.xyz/nearView.w,1.0)).xyz;- vec3 farPoint=(uViewToLocal*vec4(farView.xyz/farView.w,1.0)).xyz;- vec3 ray=normalize(farPoint-origin);- vec2 range=fireBox(origin,ray);float enter=max(0.0,range.x),leave=range.y;- if(uUseOpaqueDepth>.5) {- float depth=texture2D(uOpaqueDepth,uv).r;- if(depth<.999999) {- vec4 viewPoint=uInverseProjection*vec4(uv*2.0-1.0,depth*2.0-1.0,1.0);- vec3 localPoint=(uViewToLocal*vec4(viewPoint.xyz/viewPoint.w,1.0)).xyz;- leave=min(leave,dot(localPoint-origin,ray));- }- }- if(leave<=enter||uIntensity<=0.0)discard;- float metric=length(uLocalToWorld*ray);- vec2 hot=astraRayBox(origin,ray,uFlameBoxMin,uFlameBoxMin+uFlameBoxSize);- hot=vec2(max(enter,hot.x),min(leave,hot.y));- int pre=0,post=0;- if(hot.y>hot.x){- if(hot.x>enter)pre=int(float(FIELD_STEPS)*.12);- if(hot.y<leave)post=int(float(FIELD_STEPS)*.12);- }else hot=vec2(enter,leave);- int mainCount=FIELD_STEPS-pre-post;- float jitter=fract(sin(dot(gl_FragCoord.xy,vec2(12.9898,78.233)))*43758.5453);- vec3 radiance=vec3(0.0),first=origin+ray*leave;float transmittance=1.0;bool hit=false;- for(int i=0;i<FIELD_STEPS;i++) {- float start=hot.x,stop=hot.y,offset=float(i-pre),count=float(mainCount);- if(i<pre){start=enter;stop=hot.x;offset=float(i);count=float(pre);}- else if(i>=pre+mainCount){start=hot.y;stop=leave;offset=float(i-pre-mainCount);count=float(post);}- float ds=(stop-start)/max(count,1.0);- vec3 p=origin+ray*(start+(offset+jitter)*ds);- vec3 field=fireFieldSample(p);- float flame=field.x*uFlameExtinction,soot=field.y*uSootExtinction,total=flame+soot;- if(total<.0001)continue;- float alpha=1.0-exp(-total*ds*metric);- if(!hit&&alpha>.0005){first=p;hit=true;}- vec3 incoming=uAmbient;- if(soot>.001) {- incoming+=uSunColor*fireSunTransmission(p,jitter);- for(int j=0;j<4;j++) {- if(j>=uFireLightCount)break;- vec3 delta=uLocalToWorld*(p-uFireLights[j].xyz);- incoming+=uFireLightColor*uFireLights[j].w/(dot(delta,delta)+.09);- }- }- vec3 source=(fireRadiance(field.z)*flame*uIntensity+incoming*uSootAlbedo*soot)/max(total,.0001);- radiance+=transmittance*alpha*source;transmittance*=1.0-alpha;- if(transmittance<.008)break;- }- float alpha=1.0-transmittance;if(alpha<.005)discard;- #ifndef USE_LOGDEPTHBUF- gl_FragDepth=astraClipDepth(uLocalToClip,first);- #endif- gl_FragColor=vec4(radiance/max(alpha,.001),alpha);- `});-}--function visibleInTree(object) {- for(let o=object;o;o=o.parent)if(!o.visible)return false;- return true;-}--/** Isolated borrowed-geometry proxies: no original render callbacks can recurse. */-function depthCapture(roots, resolution) {- const scene=new THREE.Scene(),proxies=new Map(),materials=new Map(),ownedInstances=new Set();- let target=null,captures=0,disposed=false;- const invisible=new THREE.MeshDepthMaterial();invisible.visible=false;- function depthMaterial(material, source) {- if(!material?.visible||material.transparent||material.transmission>0)return invisible;- if(source.customDepthMaterial)return source.customDepthMaterial;- let depth=materials.get(material);- if(!depth){depth=new THREE.MeshDepthMaterial();materials.set(material,depth);}- const changed=depth.map!==material.map||depth.alphaMap!==material.alphaMap- ||depth.alphaTest!==material.alphaTest||depth.side!==material.side- ||depth.displacementMap!==material.displacementMap||depth.userData.sourceVersion!==material.version;- depth.map=material.map;depth.alphaMap=material.alphaMap;depth.alphaTest=material.alphaTest;depth.opacity=material.opacity;- depth.side=material.side;depth.displacementMap=material.displacementMap;- depth.displacementScale=material.displacementScale;depth.displacementBias=material.displacementBias;- depth.wireframe=material.wireframe;depth.vertexColors=material.vertexColors;depth.alphaHash=material.alphaHash;- depth.clippingPlanes=material.clippingPlanes;depth.clipIntersection=material.clipIntersection;- depth.userData.sourceVersion=material.version;if(changed)depth.needsUpdate=true;- return depth;- }- function sync() {- const seen=new Set();- for(const root of roots)root.traverse(source=>{- if(!source.isMesh||seen.has(source)||!visibleInTree(source))return;- seen.add(source);- if(source.isSkinnedMesh||source.isInstancedMesh&&source.morphTexture)throw new TypeError('makeFireField: skinned or morphed-instance depth occluders are unsupported');- if(source.userData?.astraNoOverride)return;- const material=Array.isArray(source.material)?source.material.map(m=>depthMaterial(m,source))- :depthMaterial(source.material,source);- let proxy=proxies.get(source);- if(!proxy){- proxy=source.isInstancedMesh?new THREE.InstancedMesh(source.geometry,material,source.instanceMatrix.count)- :new THREE.Mesh(source.geometry,material);- if(proxy.isInstancedMesh)ownedInstances.add(proxy);- proxy.matrixAutoUpdate=false;proxy.frustumCulled=false;proxy.name='FireDepthProxy';- proxies.set(source,proxy);scene.add(proxy);- }- source.updateWorldMatrix(true,false);proxy.geometry=source.geometry;proxy.material=material;- proxy.layers.mask=source.layers.mask;- proxy.matrix.copy(source.matrixWorld);proxy.matrixWorld.copy(source.matrixWorld);- if(source.morphTargetInfluences)proxy.morphTargetInfluences=source.morphTargetInfluences.slice();- if(proxy.isInstancedMesh){- if(proxy.instanceMatrix.count<source.instanceMatrix.count){- proxy.dispose();proxy.instanceMatrix=new THREE.InstancedBufferAttribute(new Float32Array(source.instanceMatrix.array.length),16);- }- proxy.instanceMatrix.array.set(source.instanceMatrix.array);proxy.instanceMatrix.needsUpdate=true;- proxy.count=Math.min(source.count,source.instanceMatrix.count);- }- });- // A source removed, hidden or turned into a skip since the last capture- // loses its proxy, so the proxy scene never outgrows the live occluders.- proxies.forEach((proxy,source)=>{- if(seen.has(source)&&!source.userData?.astraNoOverride)return;- scene.remove(proxy);proxies.delete(source);- if(ownedInstances.delete(proxy))proxy.dispose();- });- }- return {- capture(renderer,camera,viewport){- if(disposed)throw new Error('Disposed fire depth capture');- sync();- const scale=resolution/Math.max(viewport.z,viewport.w);- const width=Math.max(1,Math.round(viewport.z*scale)),height=Math.max(1,Math.round(viewport.w*scale));- if(!target){- target=new THREE.WebGLRenderTarget(width,height,{minFilter:THREE.NearestFilter,magFilter:THREE.NearestFilter});- target.depthTexture=new THREE.DepthTexture(width,height,THREE.UnsignedIntType);- target.depthTexture.minFilter=target.depthTexture.magFilter=THREE.NearestFilter;- }else if(target.width!==width||target.height!==height)target.setSize(width,height);- withRendererState(renderer,()=>{- renderer.xr.enabled=false;renderer.shadowMap.autoUpdate=false;renderer.toneMapping=THREE.NoToneMapping;- renderer.setRenderTarget(target);renderer.setScissorTest(false);renderer.setClearColor(0xffffff,1);- renderer.clear(true,true,true);renderer.render(scene,camera);- });- captures++;return target.depthTexture;- },- get captures(){return captures;},- get target(){return target;},- get proxies(){return proxies.size;},- dispose(){if(disposed)return;disposed=true;target?.dispose();- materials.forEach(m=>m.dispose());invisible.dispose();ownedInstances.forEach(m=>m.dispose());- proxies.clear();materials.clear();ownedInstances.clear();scene.clear();},- };-}--export function makeFireField(opts = {}) {- const input=opts.emitters??[{position:[0,0,0],radius:.3,height:1,strength:1}];- if(!Array.isArray(input)||input.length<1||input.length>16)throw new RangeError('makeFireField: needs1–16 emitters');- const emitters=input.map((e,i)=>({position:vector(e.position, [0,0,0], 3, `makeFireField: emitter${i} position`),- radius:option(e.radius, .3, 'makeFireField: emitter radius', .025, 8),height:option(e.height, 1, 'makeFireField: emitter height', .08, 25),- strength:option(e.strength, 1, 'makeFireField: emitter strength', 0, 4)}));- const activeEmitters=emitters.filter(e=>e.strength>0);- const sources=activeEmitters.length?activeEmitters:[emitters[0]];- const seed=option(opts.seed, 7, 'makeFireField: seed');- const quality=opts.quality??'balanced';if(!Object.hasOwn(TIERS,quality))throw new RangeError('makeFireField: invalid quality');- const tier=TIERS[quality],w=readWind(opts.wind,[.12,0],'makeFireField wind'),wind=[w.x,w.z];- if(wind.some(v=>Math.abs(v)>8))throw new RangeError('makeFireField: wind exceeds8m/s');- const intensity=option(opts.intensity, 1, 'makeFireField: intensity', 0, 8),turbulence=option(opts.turbulence, 1, 'makeFireField: turbulence', 0, 2);- const radius=sources.reduce((s,e)=>s+e.radius,0)/sources.length;- const height=Math.max(...sources.map(e=>e.height)),rise=option(opts.riseSpeed, .75+Math.sqrt(height)*.75, 'makeFireField: riseSpeed', .1, 12);- const smoke=opts.smoke===false?{density:0}:opts.smoke??{};- const smokeHeight=option(smoke.height, height*3, 'makeFireField: smoke height', Math.max(.1,height), 80);- const smokeDensity=option(smoke.density, .65, 'makeFireField: smoke density', 0, 5);- const warp=Math.max(.025,Math.sqrt(radius)*.25),box=new THREE.Box3();- for(const e of sources){- const top=smokeDensity>0?Math.max(e.height*1.1,smokeHeight):e.height*1.1;- const spread=smokeDensity>0?e.radius*.7+smokeHeight*.23:e.radius*1.4;- const reach=Math.max(e.radius*(1.35+.85*turbulence),spread)+warp*1.5*turbulence;- box.expandByPoint(new THREE.Vector3(e.position[0]-reach+Math.min(0,wind[0]*top/rise),e.position[1],e.position[2]-reach+Math.min(0,wind[1]*top/rise)));- box.expandByPoint(new THREE.Vector3(e.position[0]+reach+Math.max(0,wind[0]*top/rise),e.position[1]+top+warp*.3,e.position[2]+reach+Math.max(0,wind[1]*top/rise)));- }- const flameBox=new THREE.Box3();- for(const e of sources){const top=e.height*1.12,reach=e.radius*(1.35+.85*turbulence)+warp*1.5*turbulence;- flameBox.expandByPoint(new THREE.Vector3(e.position[0]-reach+Math.min(0,wind[0]*top/rise),e.position[1],e.position[2]-reach+Math.min(0,wind[1]*top/rise)));- flameBox.expandByPoint(new THREE.Vector3(e.position[0]+reach+Math.max(0,wind[0]*top/rise),e.position[1]+top+warp*.3,e.position[2]+reach+Math.max(0,wind[1]*top/rise)));- }- const size=box.getSize(new THREE.Vector3());- if(Math.max(size.x,size.y,size.z)>120)throw new RangeError('makeFireField: emitter field exceeds120m');- const noise=noiseTexture(seed),atlas=sourceAtlas(emitters,box,tier.resolution,smokeHeight,wind,rise,seed);- const emptyDepth=new THREE.DataTexture(new Uint8Array([255,255,255,255]),1,1);emptyDepth.needsUpdate=true;- const roots=opts.occluders??[];- if(!Array.isArray(roots)||roots.some(o=>!o?.isObject3D))throw new TypeError('makeFireField: occluders must be Object3D roots');- const depthResolution=intOption(opts.depthResolution, 512, 'makeFireField: depthResolution', 64, 2048);- const depth=roots.length?depthCapture(roots.slice(),depthResolution):null;- const lighting=opts.lighting===false?{count:0}:opts.lighting??{};- const requestedLights=intOption(lighting.count, Math.min(2,activeEmitters.length), 'makeFireField: light count', 0, 4);- const lightCount=Math.min(requestedLights,activeEmitters.length);- const lightIntensity=option(lighting.intensity, 12*radius/.3, 'makeFireField: light intensity', 0, 20000);- const uniforms={- uTime:{value:0},uSourceAtlas:{value:atlas},uFieldNoise:{value:noise},uOpaqueDepth:{value:emptyDepth},- uBoxMin:{value:box.min.clone()},uBoxSize:{value:size.clone()},- uFlameBoxMin:{value:flameBox.min.clone()},uFlameBoxSize:{value:flameBox.getSize(new THREE.Vector3())},uViewport:{value:new THREE.Vector4(0,0,1,1)},- uViewToLocal:{value:new THREE.Matrix4()},uInverseProjection:{value:new THREE.Matrix4()},- uLocalToClip:{value:new THREE.Matrix4()},uLocalToWorld:{value:new THREE.Matrix3()},- uSunLocal:{value:new THREE.Vector3(0,1,0)},uSunColor:{value:new THREE.Color(0)},uAmbient:{value:new THREE.Color(.03,.03,.04)},- uSootAlbedo:{value:new THREE.Color(smoke.albedo??0x514942)},uCoarseScale:{value:Math.max(.3,Math.sqrt(radius)*.7)},- uWarp:{value:warp},uRise:{value:rise},uTurbulence:{value:turbulence},uIntensity:{value:intensity},- uFlameExtinction:{value:1.3/Math.sqrt(radius)},uSootExtinction:{value:smokeDensity},uUseOpaqueDepth:{value:0},- uFireLightCount:{value:lightCount},uFireLights:{value:Array.from({length:4},()=>new THREE.Vector4())},- uFireLightColor:{value:new THREE.Color(0xff973d)},- };- const group=new THREE.Group();group.name=opts.name??'FireField';- const geometry=new THREE.BoxGeometry(size.x,size.y,size.z);geometry.translate(...box.getCenter(new THREE.Vector3()).toArray());- const material=fieldMaterial(uniforms,tier);material.userData.bloom=true;- const volume=new THREE.Mesh(geometry,material);volume.name='SharedFlameSootVolume';volume.renderOrder=2;volume.visible=activeEmitters.length>0;- keepOutOfDepthPasses(volume);group.add(volume);- const inverse=new THREE.Matrix4(),readLights=makeLightProbe();- const guard=volume.onBeforeRender;- volume.onBeforeRender=function(renderer,scene,camera,geo,mat,...rest){- guard.call(this,renderer,scene,camera,geo,mat,...rest);- if(mat!==material||scene.overrideMaterial)return;- inverse.copy(volume.matrixWorld).invert();- uniforms.uInverseProjection.value.copy(camera.projectionMatrixInverse);- uniforms.uViewToLocal.value.multiplyMatrices(inverse,camera.matrixWorld);- uniforms.uLocalToClip.value.copy(camera.projectionMatrix).multiply(camera.matrixWorldInverse).multiply(volume.matrixWorld);- uniforms.uLocalToWorld.value.setFromMatrix4(volume.matrixWorld);- renderer.getCurrentViewport(uniforms.uViewport.value);- const lights=readLights(scene);uniforms.uSunColor.value.setRGB(0,0,0);- if(lights.sun){uniforms.uSunLocal.value.copy(lights.sunDirection).transformDirection(inverse);- uniforms.uSunColor.value.copy(lights.sun.color).multiplyScalar(lights.sun.intensity*.20);}- uniforms.uAmbient.value.copy(lights.ambient).add(lights.sky).multiplyScalar(.15);- if(scene.environment)uniforms.uAmbient.value.addScalar(.035);- if(depth){- if(renderer.capabilities.logarithmicDepthBuffer)throw new Error('makeFireField: occluder depth requires non-logarithmic depth');- uniforms.uOpaqueDepth.value=depth.capture(renderer,camera,uniforms.uViewport.value);- uniforms.uUseOpaqueDepth.value=1;- }- };- const lights=[];- const ranked=activeEmitters.map((e,i)=>({e,i,weight:e.radius*e.radius*e.strength})).sort((a,b)=>b.weight-a.weight);- for(let i=0;i<lightCount;i++){- const e=ranked[Math.floor(i*ranked.length/lightCount)].e;- const light=new THREE.PointLight(0xff973d,lightIntensity,0,2);light.name=`FireFieldLight_${i}`;- light.position.fromArray(e.position);light.position.y+=e.height*.24;light.userData.sourceStrength=e.strength;group.add(light);lights.push(light);- }- const emberOptions=opts.embers===false?{count:0}:opts.embers??{};- const requestedEmbers=intOption(emberOptions.count, 48, 'makeFireField: ember count', 0, 512);- const count=activeEmitters.length?requestedEmbers:0;- const emberSize=vector(emberOptions.size, [.0015,.006], 2, 'makeFireField: ember size');- const lifetime=vector(emberOptions.lifetime, [2,4], 2, 'makeFireField: ember lifetime');- if(emberSize[0]<=0||emberSize[1]<emberSize[0]||emberSize[1]>.12||lifetime[0]<=0||lifetime[1]<lifetime[0]||lifetime[1]>30)throw new RangeError('makeFireField: invalid ember size/lifetime');- const emberRise=option(emberOptions.riseSpeed, rise, 'makeFireField: ember rise speed', .1, 20);- const random=mulberry32(seed^0x1837),particles=Array.from({length:count},()=>{- const total=activeEmitters.reduce((sum,e)=>sum+e.radius*e.radius*e.strength,0);- let pick=random()*total,emitter=activeEmitters[activeEmitters.length-1];- for(const candidate of activeEmitters){pick-=candidate.radius*candidate.radius*candidate.strength;if(pick<=0){emitter=candidate;break;}}- return {emitter,phase:random(),life:THREE.MathUtils.lerp(...lifetime,random()),angle:random()*Math.PI*2,- offset:random()*.7,size:THREE.MathUtils.lerp(...emberSize,random())};- });- const dummy=new THREE.Object3D(),emberColor=new THREE.Color();let embers=null;- if(count){embers=new THREE.InstancedMesh(new THREE.SphereGeometry(1,5,3),new THREE.MeshBasicMaterial(),count);- embers.name='FieldEmbers';embers.frustumCulled=false;embers.instanceMatrix.setUsage(THREE.DynamicDrawUsage);group.add(embers);}- // `out` lets update() reuse one record instead of allocating per ember.- function sampleEmber(index,t,out={position:new THREE.Vector3()}){- if(!count)return null;const p=particles[clamp(index|0,0,count-1)],a=fract(t/p.life+p.phase),age=a*p.life;- const e=p.emitter,swirl=Math.sin(age*2.1+p.angle)*.07*age;- out.position.set(e.position[0]+Math.cos(p.angle)*e.radius*p.offset+wind[0]*age+swirl,- e.position[1]+.08+emberRise*age,e.position[2]+Math.sin(p.angle)*e.radius*p.offset+wind[1]*age+Math.cos(age*1.7+p.angle)*.07*age);- out.size=p.size*Math.pow(Math.sin(a*Math.PI),.6);out.age=a;return out;- }- const ember={position:new THREE.Vector3()};- let disposed=false;- group.userData.update=group.userData.tick=(t=0)=>{- if(disposed)return;option(t, 0, 'makeFireField: time', -1e9, 1e9);material.uniforms.uTime.value=t;- lights.forEach((light,i)=>{const flicker=.83+.10*Math.sin(t*(3.1+i*.47)+seed+i*2)+.07*Math.sin(t*7.3+seed*.7+i);- light.intensity=lightIntensity*flicker*intensity*light.userData.sourceStrength;- uniforms.uFireLights.value[i].set(light.position.x,light.position.y,light.position.z,light.intensity*.10);});- if(embers){embers.visible=intensity>0;for(let i=0;i<count;i++){- const p=sampleEmber(i,t,ember);dummy.position.copy(p.position);dummy.scale.set(p.size,p.size*2.5,p.size);dummy.updateMatrix();- embers.setMatrixAt(i,dummy.matrix);emberColor.setRGB(5*(1-p.age*.82),.6*(1-p.age),.01).multiplyScalar(intensity);embers.setColorAt(i,emberColor);- }embers.instanceMatrix.needsUpdate=true;embers.instanceColor.needsUpdate=true;}- };- const atlasRead=p=>[0,1,2,3].map(c=>{- const uv=p.map((v,i)=>(v-box.min.getComponent(i))/size.getComponent(i));- return uv.some(v=>v<0||v>1)?0:sampleGrid3(atlas.image.data,tier.resolution,...uv.map(v=>v*tier.resolution-.5),4,c,false)/255;- });- const noiseRead=(p,c)=>sampleGrid3(noise.image.data,NOISE_RESOLUTION,...p.map(v=>v*NOISE_RESOLUTION-.5),4,c)/255;- group.userData.sampleField=(x,y,z,t=material.uniforms.uTime.value)=>{- if(![x,y,z,t].every(Number.isFinite))throw new RangeError('makeFireField: sample requires finite coordinates/time');- const p=[x,y,z],initial=atlasRead(p),coarseScale=uniforms.uCoarseScale.value;- const flow=p.map((v,i)=>v*(i===1?.13:.32)/coarseScale-(i===1?t*rise*.13/coarseScale:0)+initial[3]*.31);- const coarse=[0,1,2].map(c=>noiseRead(flow,c)),anchor=smooth(0,.22,initial[1]);- const warped=p.map((v,i)=>v+(coarse[i]-.5)*warp*(i===1?.38:1)*anchor*turbulence),field=atlasRead(warped);- const fine=noiseRead(p.map((v,i)=>v*(i===1?.75:2.6)-(i===1?t*rise*.75:0)+.197),1);- const surface=field[0]-.5+((coarse[1]-.5)*(.35+field[1]*.8)+(fine-.5)*.30)*turbulence;- const flame=smooth(-.025,.075,surface)*(1-smooth(.035,.22,surface)*.97)*smooth(0,.055,field[1])*(1-smooth(.90,1,field[1]))- *smooth(.21+field[1]*.20,.42+field[1]*.23,coarse[0]*.65+fine*.35);- const soot=field[2]*Math.pow(clamp(.68+(coarse[0]-.5)*2.4+(fine-.5)*.55,0,1.6),1.3);- return {flame,soot,temperature:clamp(.18+flame*.57+coarse[2]*.15-field[1]*.18)};- };- const bounds=box.clone();- if(count)for(const e of sources){const age=lifetime[1],travel=.07*age+emberSize[1]*3;- bounds.expandByPoint(new THREE.Vector3(e.position[0]-e.radius*.7+Math.min(0,wind[0]*age)-travel,e.position[1],e.position[2]-e.radius*.7+Math.min(0,wind[1]*age)-travel));- bounds.expandByPoint(new THREE.Vector3(e.position[0]+e.radius*.7+Math.max(0,wind[0]*age)+travel,e.position[1]+.08+emberRise*age+travel,e.position[2]+e.radius*.7+Math.max(0,wind[1]*age)+travel));}- group.userData.bounds=bounds;group.userData.sampleEmber=sampleEmber;- group.userData.emitters=emitters.map(e=>({...e,position:e.position.slice()}));group.userData.quality=quality;- group.userData.cost={emitters:emitters.length,steps:tier.steps,lightSteps:tier.lightSteps,- textureBytes:atlas.image.data.byteLength+noise.image.data.byteLength,depthPass:!!depth};- group.userData.depthCapture=depth;- const owned=snapshotResources(group);[atlas,noise,emptyDepth,...lights].forEach(r=>owned.add(r));- if(depth)owned.add(depth);owned.add({dispose(){disposed=true;}});- attachDisposal(group,owned);group.userData.update(0);return group;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.jsindex 1d711a24..9a4f4bd8 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/grass.js@@ -162,7 +162,7 @@ function clumpField(seed, extent) {/*** Place the blades on a fully jittered grid, thinned by the clumps.*- * Full-cell jitter, not scatterGrid's 0.35: from directly above, a+ * Full-cell jitter, not a 0.35 fraction: from directly above, a* partly jittered lattice still shows its rows, which is the "grid of* dots" this library exists to avoid.*/diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.jsdeleted file mode 100644index 4de69c74..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/ice.js+++ /dev/null@@ -1,448 +0,0 @@-/** Fractured freshwater ice in metres.- *- * Each seeded floe is a closed, bevelled solid. Open fissures are geometry,- * not dark lines on a transparent plane. Three's physical transmission reads- * the opaque scene behind the volume; attenuation follows its local thickness.- * Frost changes transmission and roughness together. Trapped air is instanced- * inside the volume and therefore shifts relative to its surface with the view.- */-import * as THREE from 'three';-import { fbm2, mulberry32 } from './noise.js';-import { patchStandard } from './shader.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';--const clamp = (x, a, b) => Math.max(a, Math.min(b, x));-const smooth = (a, b, value) => {- const t = clamp((value - a) / (b - a), 0, 1);- return t * t * (3 - 2 * t);-};--// Clip a convex XZ polygon by nx*x + nz*z <= limit.-function clip(polygon, nx, nz, limit) {- const result = [];- for (let i = 0; i < polygon.length; i++) {- const a = polygon[i], b = polygon[(i + 1) % polygon.length];- const da = nx * a[0] + nz * a[1] - limit;- const db = nx * b[0] + nz * b[1] - limit;- if (da <= 1e-10) result.push(a);- if ((da < 0 && db > 0) || (da > 0 && db < 0)) {- const t = da / (da - db);- result.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);- }- }- return result.filter((p, i) => {- const q = result[(i + result.length - 1) % result.length];- return !q || Math.hypot(p[0] - q[0], p[1] - q[1]) > 1e-8;- });-}--function inset(polygon, distance) {- const xs=polygon.map(p=>p[0]),zs=polygon.map(p=>p[1]);- const x0=Math.min(...xs),x1=Math.max(...xs),z0=Math.min(...zs),z1=Math.max(...zs);- let out = [[x0,z0],[x1,z0],[x1,z1],[x0,z1]];- for (let i = 0; i < polygon.length && out.length > 2; i++) {- const a = polygon[i], b = polygon[(i + 1) % polygon.length];- const length = Math.hypot(b[0] - a[0], b[1] - a[1]);- const nx = (b[1] - a[1]) / length, nz = -(b[0] - a[0]) / length;- out = clip(out, nx, nz, nx * a[0] + nz * a[1] - distance);- }- return out;-}--function distanceToEdge(polygon, point) {- let distance = Infinity;- for (let i = 0; i < polygon.length; i++) {- const a = polygon[i], b = polygon[(i + 1) % polygon.length];- const dx = b[0] - a[0], dz = b[1] - a[1];- distance = Math.min(distance,- (dx * (point[1] - a[1]) - dz * (point[0] - a[0])) / Math.hypot(dx, dz));- }- return distance;-}--function opticalTexture(width, depth, thicknessAt, maximumThickness, frost, seed, cracks) {- const resolution = 512, data = new Uint8Array(resolution * resolution * 4);- for (let z = 0; z < resolution; z++) for (let x = 0; x < resolution; x++) {- const px = ((x + 0.5) / resolution - 0.5) * width;- const pz = ((z + 0.5) / resolution - 0.5) * depth;- const field = fbm2(px * 1.8, pz * 1.8, { seed: seed + 101, octaves: 3 });- const grain = fbm2(px * 24, pz * 24, { seed: seed + 303, octaves: 2 });- const cover = smooth(0.32 - frost * 0.62, 0.53 - frost * 0.62,- field + grain * 0.28) * Math.min(1, frost * 3);- const i = (z * resolution + x) * 4;- data[i] = Math.round((1 - cover * 0.96) * 255);- data[i + 1] = Math.round(clamp(thicknessAt(px, pz) / maximumThickness, 0, 1) * 255);- data[i + 2] = Math.round(clamp(0.5 + grain, 0, 1) * 255);- data[i + 3] = 0;- }- // Rasterize a sparse branching stress network in the same metric domain- // as the volume. Coverage stores subtexel line width, then mipmaps filter- // it further. These arrested hairlines terminate inside a solid floe.- for (const [a, b] of cracks) {- const ax=(a[0]/width+.5)*resolution, ay=(a[1]/depth+.5)*resolution;- const bx=(b[0]/width+.5)*resolution, by=(b[1]/depth+.5)*resolution;- const dx=bx-ax,dy=by-ay,length2=dx*dx+dy*dy;- const steps=Math.max(1,Math.ceil(Math.sqrt(length2)*1.5));- const coverage=Math.min(1,0.0025*resolution/Math.sqrt(width*depth));- for(let i=0;i<=steps;i++) {- const x=ax+dx*i/steps,y=ay+dy*i/steps;- for(let oy=-1;oy<=1;oy++)for(let ox=-1;ox<=1;ox++) {- const px=Math.floor(x)+ox,py=Math.floor(y)+oy;- if(px<0||py<0||px>=resolution||py>=resolution)continue;- const t=clamp(((px+.5-ax)*dx+(py+.5-ay)*dy)/Math.max(length2,1e-9),0,1);- const distance=Math.hypot(px+.5-ax-t*dx,py+.5-ay-t*dy);- const index=(py*resolution+px)*4+3;- data[index]=Math.max(data[index],Math.round(Math.max(0,1-distance)*coverage*255));- }- }- }- const texture = new THREE.DataTexture(data, resolution, resolution);- texture.colorSpace = THREE.NoColorSpace;- texture.magFilter = THREE.LinearFilter;- texture.minFilter = THREE.LinearMipmapLinearFilter;- texture.generateMipmaps = true;- texture.anisotropy = 8;- texture.needsUpdate = true;- return texture;-}--function iceMaterial(opts, optical, maximumThickness) {- const material = new THREE.MeshPhysicalMaterial({- color: opts.color ?? 0xc9e7ed,- roughness: clamp(opts.roughness ?? 0.075, 0.015, 1),- metalness: 0, ior: 1.31,- transmission: clamp(opts.transmission ?? 0.98, 0, 1),- transmissionMap: optical,- thickness: maximumThickness,- attenuationColor: new THREE.Color(opts.attenuationColor ?? 0x80c8d5),- attenuationDistance: Math.max(0.02, opts.attenuationDistance ?? 1.8),- envMapIntensity: opts.envMapIntensity ?? 1,- });- material.name = 'FracturedFreshwaterIce';- patchStandard(material, {- name: 'ice:volume',- uniforms: {- uIceOptical: { value: optical },- uIceSeed: { value: (opts.seed ?? 47) % 997 },- uIceFrost: { value: clamp(opts.frost ?? 0.35, 0, 1) },- },- vertexHead: 'attribute float aIceEdge, aIcePath, aIceChip;\nvarying vec3 vIceLocal;\nvarying vec3 vIceFace;\nvarying vec2 vIceUV;\nvarying float vIceEdge, vIcePath, vIceChip;',- vertexBody: 'vIceLocal = position; vIceFace = normal; vIceUV = uv; vIceEdge = aIceEdge; vIcePath = aIcePath; vIceChip = aIceChip;',- fragmentHead: `- uniform sampler2D uIceOptical;- uniform float uIceSeed, uIceFrost;- varying vec3 vIceLocal, vIceFace;- varying vec2 vIceUV;- varying float vIceEdge, vIcePath, vIceChip;- `,- fragmentBody: `- vec4 iceOptical = texture2D(uIceOptical, vIceUV);- float iceTop = smoothstep(0.3, 0.9, normalize(vIceFace).y);- float iceFrost = clamp((1.0 - iceOptical.r) / 0.96, 0.0, 1.0) * iceTop;- float iceEdge = 1.0 - smoothstep(0.006, 0.04, vIceEdge);- float iceRime = iceEdge * iceTop * uIceFrost * 0.28;- float iceCover = max(max(iceFrost, iceRime), vIceChip * 0.72);- float iceFaceFade = 1.0 - smoothstep(0.35, 1.2, length(fwidth(vIceLocal)) * 110.0);- float iceFaceGrain = mix(0.5, astraNoise2(vec2(vIceLocal.x + vIceLocal.z,- vIceLocal.y * 0.85) * 110.0), iceFaceFade);- float iceFracture = (1.0 - abs(normalize(vIceFace).y)) * 0.24;- float iceHairline = iceOptical.a * iceTop;- iceCover = max(iceCover, iceHairline * 0.85);- diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.77, 0.84, 0.85), iceCover);- // Fine etched surface relief vanishes before it becomes a pixel grid.- vec2 iceP = mix(vec2(vIceLocal.x + vIceLocal.z, vIceLocal.y * 0.85),- vIceLocal.xz, iceTop) * 65.0 + uIceSeed;- float iceFineFade = 1.0 - smoothstep(0.25, 1.0, length(fwidth(iceP)));- float iceFine = astraNoise2(iceP) * iceFineFade;- float iceHeight = iceCover * (0.0005 + iceFine * 0.0008)- + iceFine * 0.000025 + iceFracture * iceFaceGrain * 0.000015;- `,- roughnessBody: 'roughnessFactor = mix(roughnessFactor + iceFracture, 0.86, iceCover);',- normalBody: 'normal = astraBump(-vViewPosition, normal, iceHeight);',- transmissionBody: `- material.thickness = max(0.001, vIcePath);- material.transmission = transmission * (1.0 - iceCover * 0.96) * (1.0 - iceFracture);- `,- });- return material;-}--/**- * A Group with a closed volume mesh and optional instanced trapped air.- * size number/[width,depth] (default [8,6]), thickness metres (.28),- * outline optional convex [[x,z],...] polygon inside size, crackDensity- * sites per square metre (.65; a very large sheet gets coarser floes), gap metres- * (.018), frost/bubbles/chipping 0..1 (.35/.45/.4), heave metres (0), seed (47),- * color/attenuationColor, attenuationDistance metres (1.8), roughness (.075).- *- * Nominal top is local y=0, bottom near -thickness; heave lifts and tilts- * individual floes. sampleHeight(x,z) returns the actual LOCAL upper triangle- * height, or null in an open fissure/outside the sheet. update(t,dt) is a- * static no-op; dispose() releases only construction-owned resources.- *- * Optical path is estimated from local thickness on the top and bottom,- * and floe width on fracture faces. It is not an exact volume exit trace.- * Physical transmission sees opaque scene objects. Transparent water and- * other transmissive volumes are not recursively ray traced by this renderer.- * A lakebed or opaque water backing supplies that view. Ice does not cast- * opaque shadows by default (castShadow:true explicitly opts in).- */-export function makeFracturedIce(opts = {}) {- for (const key of ['gap', 'frost', 'bubbles', 'chipping', 'heave', 'seed', 'roughness',- 'transmission', 'attenuationDistance', 'envMapIntensity'])- if (opts[key] != null && !Number.isFinite(opts[key]))- throw new RangeError(`ice ${key} must be finite`);- let outline = null;- if (opts.outline !== undefined) {- if (!Array.isArray(opts.outline) || opts.outline.length < 3 || opts.outline.length > 128- || !opts.outline.every(p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite)))- throw new RangeError('ice outline must contain 3..128 finite [x,z] points');- outline = opts.outline.map(p => [...p]);- const turns = outline.map((a, i) => {- const b = outline[(i + 1) % outline.length], c = outline[(i + 2) % outline.length];- return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);- });- if (!turns.every(t => t > 1e-10) && !turns.every(t => t < -1e-10))- throw new RangeError('ice outline must be strictly convex and ordered around its boundary');- if (turns[0] < 0) outline.reverse();- if (outline.some((a, i) => {- const b = outline[(i + 1) % outline.length];- return outline.some(p => (b[0] - a[0]) * (p[1] - a[1])- - (b[1] - a[1]) * (p[0] - a[0]) < -1e-10);- })) throw new RangeError('ice outline must not intersect itself');- }- const size = Array.isArray(opts.size) ? opts.size : opts.size !== undefined- ? [opts.size, opts.size] : outline- ? [2 * Math.max(...outline.map(p => Math.abs(p[0]))), 2 * Math.max(...outline.map(p => Math.abs(p[1])))]- : [8, 6];- if (size.length !== 2 || !size.every(value => Number.isFinite(value) && value > 0))- throw new RangeError('ice size must contain positive finite metres');- const [width, depth] = size;- if (outline?.some(p => Math.abs(p[0]) > width / 2 || Math.abs(p[1]) > depth / 2))- throw new RangeError('ice outline must lie inside the requested size');- const thickness = opts.thickness ?? 0.28;- if (!Number.isFinite(thickness) || thickness <= 0) throw new RangeError('ice thickness must be positive finite metres');- const seed = opts.seed ?? 47, rand = mulberry32(seed);- const density = opts.crackDensity ?? 0.65;- if (!Number.isFinite(density) || density < 0) throw new RangeError('ice crackDensity must be finite and nonnegative');- const count = clamp(Math.round(width * depth * density), 1, 180);- const gap = clamp(opts.gap ?? 0.018, 0,- Math.min(Math.min(width, depth) * 0.08, Math.sqrt(width * depth / count) * 0.2));- const frost = clamp(opts.frost ?? 0.35, 0, 1), heave = Math.max(0, opts.heave ?? 0);- const chipping = clamp(opts.chipping ?? 0.4, 0, 1);- const thicknessAt = (x, z) => thickness * (0.9- + fbm2(x * 0.72, z * 0.72, { seed: seed + 711, octaves: 3 }) * 0.5);- const maximumThickness = thickness * 1.3;- const sites = [];- // Stratification keeps the cells distributed without regular crack lines.- const columns = Math.max(1, Math.round(Math.sqrt(count * width / depth)));- const rows = Math.ceil(count / columns);- for (let i = 0; i < count; i++) sites.push([- ((i % columns + 0.12 + rand() * 0.76) / columns - 0.5) * width,- ((Math.floor(i / columns) + 0.12 + rand() * 0.76) / rows - 0.5) * depth,- ]);- // Some pressure fractures split an existing large plate. Keeping both- // broad floes and small chips avoids a uniformly sized paving pattern.- const cellScale = Math.sqrt(width * depth / count);- for (let i = 3; i < sites.length; i += 4) {- const anchor = sites[i - 2], angle = rand() * Math.PI * 2;- sites[i] = [clamp(anchor[0] + Math.cos(angle) * cellScale * 0.25, -width * 0.49, width * 0.49),- clamp(anchor[1] + Math.sin(angle) * cellScale * 0.25, -depth * 0.49, depth * 0.49)];- }- const boundaryCenter=outline ? outline.reduce((sum,p)=>[sum[0]+p[0]/outline.length,- sum[1]+p[1]/outline.length],[0,0]) : [0,0];- // One deformation for every shared point. Sampling an inset cell first,- // or scaling this by its radius, lets neighboring boundaries cross.- const deform=(x,z)=>{- const margin=Math.max(0,outline?distanceToEdge(outline,[x,z])- :Math.min(width/2-Math.abs(x),depth/2-Math.abs(z)));- const strength=Math.min(1,margin/.08)*Math.min(1,cellScale/.25);- const warpX=fbm2(x*2.2,z*2.2,{seed:seed+907,octaves:3})*.13- +fbm2(x*17,z*17,{seed:seed+813,octaves:2})*.014;- const warpZ=fbm2(x*2.2,z*2.2,{seed:seed+1009,octaves:3})*.13- +fbm2(x*17,z*17,{seed:seed+1213,octaves:2})*.014;- const chip=(1-Math.min(1,margin/.035))*(.002+Math.abs(warpX+warpZ)*.8)- *Math.min(1,cellScale/.25);- const length=Math.max(1e-9,Math.hypot(boundaryCenter[0]-x,boundaryCenter[1]-z));- return [x+warpX*strength+(boundaryCenter[0]-x)/length*chip,- z+warpZ*strength+(boundaryCenter[1]-z)/length*chip];- };- const position = [], uv = [], edge = [], path = [], chips = [], topTriangles = [], cells = [], cracks = [];- let opticalWidth = thickness, triangleChip = 0;- const vertex = (p, e, vertical) => {- position.push(...p); uv.push(p[0] / width + 0.5, p[2] / depth + 0.5); edge.push(e);- path.push(THREE.MathUtils.lerp(opticalWidth, thicknessAt(p[0], p[2]), vertical));- chips.push(triangleChip);- };- const triangle = (a, b, c, ea, eb, ec, top = false) => {- const normal = new THREE.Vector3().subVectors(new THREE.Vector3(...b), new THREE.Vector3(...a))- .cross(new THREE.Vector3().subVectors(new THREE.Vector3(...c), new THREE.Vector3(...a))).normalize();- const vertical = Math.abs(normal.y);- vertex(a, ea, vertical); vertex(b, eb, vertical); vertex(c, ec, vertical);- if (top) topTriangles.push([a, b, c]);- };- for (const [id, site] of sites.entries()) {- let polygon = outline || [[-width / 2, -depth / 2], [width / 2, -depth / 2],- [width / 2, depth / 2], [-width / 2, depth / 2]];- for (const other of sites) if (other !== site) {- const nx = other[0] - site[0], nz = other[1] - site[1];- polygon = clip(polygon, nx, nz,- (other[0] * other[0] + other[1] * other[1] - site[0] * site[0] - site[1] * site[1]) * 0.5);- }- const cellGap=gap*(0.38+rand()*.25);- if (polygon.length < 3) continue;- const center = polygon.reduce((sum, p) => [sum[0] + p[0] / polygon.length,- sum[1] + p[1] / polygon.length], [0, 0]);- let radius = distanceToEdge(polygon, center);- // A shared domain warp makes neighboring fracture sides interlock.- // Independent edge noise would overlap floes or widen cracks randomly.- const corners = polygon.map(p => [...p]), jagged = [];- for (let i = 0; i < polygon.length; i++) {- const a = polygon[i], b = polygon[(i + 1) % polygon.length];- const steps = clamp(Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 0.065), 1, 48);- for (let j = 0; j < steps; j++) {- const x = a[0] + (b[0] - a[0]) * j / steps;- const z = a[1] + (b[1] - a[1]) * j / steps;- jagged.push(deform(x,z));- }- }- polygon = jagged;- // A point in every inward half-plane is in the polygon's visibility- // kernel. Shrinking toward it therefore stays inside the shared cell,- // even when a fracture boundary is concave. Tiny degenerate chips vanish.- const kernel=inset(polygon,0);- if(kernel.length<3)continue;- center[0]=kernel.reduce((sum,p)=>sum+p[0]/kernel.length,0);- center[1]=kernel.reduce((sum,p)=>sum+p[1]/kernel.length,0);- radius=distanceToEdge(polygon,center);- if(radius<1e-7)continue;- const shrink=Math.min(.45,cellGap/radius);- polygon=polygon.map(p=>[THREE.MathUtils.lerp(p[0],center[0],shrink),- THREE.MathUtils.lerp(p[1],center[1],shrink)]);- radius*=1-shrink;- opticalWidth = Math.max(thickness, radius * 1.7);- const bevel = Math.min(thickness * (0.015 + chipping * 0.10),- 0.003 + chipping * 0.025, radius * 0.055);- const lift = (rand() - 0.3) * heave;- const tiltX = (rand() - 0.5) * heave / Math.max(radius, 0.1) * 0.32;- const tiltZ = (rand() - 0.5) * heave / Math.max(radius, 0.1) * 0.32;- const topAt = p => lift + (p[0] - center[0]) * tiltX + (p[1] - center[1]) * tiltZ;- // Radial bevel retains a one-to-one ring topology even at acute corners.- const cuts=polygon.map(p=>.35+Math.abs(fbm2(p[0]*9,p[1]*9,{seed:seed+337,octaves:2}))*2.4);- const inner = polygon.map((p,i) => [p[0] + (center[0] - p[0]) * bevel * cuts[i] / radius,- p[1] + (center[1] - p[1]) * bevel * cuts[i] / radius]);- const top = inner.map(p => [p[0], topAt(p), p[1]]);- const rim = polygon.map((p,i) => [p[0], topAt(p) - bevel * cuts[i], p[1]]);- // Fracture planes widen and undercut at different depths. Every ring- // moves inward from the shared footprint, so neighboring solids fit.- const insetPoint=(p,i,amount)=>{- const move=Math.min(radius*.08,thickness*amount)*cuts[i];- return [p[0]+(center[0]-p[0])*move/radius,p[1]+(center[1]-p[1])*move/radius];- };- const mid = polygon.map((p,i)=>{const q=insetPoint(p,i,.09);- return [q[0],topAt(q)-thicknessAt(...q)*(.38+cuts[i]*.09),q[1]];});- const bottom = polygon.map((p,i)=>{const q=insetPoint(p,i,.04);- return [q[0],topAt(q)-thicknessAt(...q),q[1]];});- const ct = [center[0], topAt(center), center[1]];- const cb = [center[0], topAt(center) - thicknessAt(...center), center[1]];- for (let i = 0; i < polygon.length; i++) {- const j = (i + 1) % polygon.length;- triangleChip=0;- triangle(ct, top[j], top[i], radius, bevel, bevel, true);- triangle(cb, bottom[i], bottom[j], radius, 0, 0);- triangleChip=clamp(((cuts[i]+cuts[j])*.5-.65)*2.5,0,1)*chipping;- triangle(top[i], top[j], rim[j], bevel, bevel, 0, true);- triangle(top[i], rim[j], rim[i], bevel, 0, 0, true);- triangleChip*=.25;- triangle(rim[i], rim[j], mid[j], 0, 0, 0);- triangle(rim[i], mid[j], mid[i], 0, 0, 0);- triangleChip*=.3;- triangle(mid[i], mid[j], bottom[j], 0, 0, 0);- triangle(mid[i], bottom[j], bottom[i], 0, 0, 0);- }- cells.push({ id, polygon, center, topAt, radius });- for(let branch=0;branch<2;branch++) {- const start=corners[Math.floor(rand()*corners.length)];- const bend=[THREE.MathUtils.lerp(start[0],center[0],.45+rand()*.2),- THREE.MathUtils.lerp(start[1],center[1],.45+rand()*.2)];- const end=[THREE.MathUtils.lerp(start[0],center[0],.78+rand()*.13),- THREE.MathUtils.lerp(start[1],center[1],.78+rand()*.13)];- cracks.push([start,bend],[bend,end]);- const fork=corners[(corners.indexOf(start)+1)%corners.length];- cracks.push([bend,[THREE.MathUtils.lerp(bend[0],fork[0],.25),- THREE.MathUtils.lerp(bend[1],fork[1],.25)]]);- }- }- const geometry = new THREE.BufferGeometry();- geometry.setAttribute('position', new THREE.Float32BufferAttribute(position, 3));- geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));- geometry.setAttribute('aIceEdge', new THREE.Float32BufferAttribute(edge, 1));- geometry.setAttribute('aIcePath', new THREE.Float32BufferAttribute(path, 1));- geometry.setAttribute('aIceChip', new THREE.Float32BufferAttribute(chips, 1));- geometry.computeVertexNormals(); geometry.computeBoundingBox(); geometry.computeBoundingSphere();- const optical = opticalTexture(width, depth, thicknessAt, maximumThickness, frost, seed, cracks);- const volume = new THREE.Mesh(geometry, iceMaterial(opts, optical, maximumThickness));- volume.name = 'IceVolume'; volume.castShadow = opts.castShadow === true; volume.receiveShadow = true;- const group = new THREE.Group(); group.name = opts.name ?? 'FracturedIce';- group.userData.placement = volume.userData.placement = 'free';- group.add(volume);-- // Flattened gas lenses occur in columns where bubbles rose before the- // water froze. Their depth is real geometry, not dots on the top texture.- const bubbles = clamp(opts.bubbles ?? 0.45, 0, 1);- const bubbleCount = clamp(Math.round(width * depth * bubbles * 11), 0, 4000);- if (bubbleCount && cells.length) {- const bubbleGeometry = new THREE.SphereGeometry(1, 12, 6);- const bubbleMaterial = new THREE.MeshStandardMaterial({ color: 0x758f93, roughness: 0.35 });- const air = new THREE.InstancedMesh(bubbleGeometry, bubbleMaterial, bubbleCount);- air.name = 'TrappedAir'; const dummy = new THREE.Object3D();- let cluster = null, remaining = 0;- for (let i = 0; i < bubbleCount; i++) {- if (remaining === 0) {- const cell = cells[Math.floor(rand() * cells.length)];- const direction = rand() * Math.PI * 2, spread = Math.sqrt(rand()) * cell.radius * 0.55;- cluster = { cell, x: cell.center[0] + Math.cos(direction) * spread,- z: cell.center[1] + Math.sin(direction) * spread,- size: 0.004 + Math.pow(rand(), 3) * 0.026 };- remaining = 1 + Math.floor(rand() * 5);- }- const { cell } = cluster;- const drift = Math.min(0.05, cell.radius * 0.12);- const x = cluster.x + (rand() - 0.5) * drift, z = cluster.z + (rand() - 0.5) * drift;- const radius = Math.min(thickness * 0.085, cell.radius * 0.06,- cluster.size * (0.45 + rand() * 0.95));- const localDepth = thicknessAt(x, z);- dummy.position.set(x, cell.topAt([x, z]) - localDepth * (0.16 + rand() * 0.68), z);- dummy.scale.set(radius, radius * (0.10 + rand() * 0.18), radius * (0.7 + rand() * 0.5));- dummy.rotation.set((rand() - 0.5) * 0.18, rand() * Math.PI, (rand() - 0.5) * 0.18);- dummy.updateMatrix(); air.setMatrixAt(i, dummy.matrix);- remaining--;- }- air.instanceMatrix.needsUpdate = true; air.computeBoundingSphere();- air.userData.placement = 'free'; group.add(air);- }- // Float32 coordinates are exactly what the GPU and raycaster see.- for (const face of topTriangles) for (const point of face)- for (let i = 0; i < 3; i++) point[i] = Math.fround(point[i]);- group.userData.sampleHeight = (x, z) => {- let result = null;- for (const [a, b, c] of topTriangles) {- const denominator = (b[2] - c[2]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[2] - c[2]);- if (Math.abs(denominator) < 1e-12) continue;- const wa = ((b[2] - c[2]) * (x - c[0]) + (c[0] - b[0]) * (z - c[2])) / denominator;- const wb = ((c[2] - a[2]) * (x - c[0]) + (a[0] - c[0]) * (z - c[2])) / denominator;- const wc = 1 - wa - wb;- if (Math.min(wa, wb, wc) >= -1e-7) {- const y = wa * a[1] + wb * b[1] + wc * c[1];- result = result === null ? y : Math.max(result, y);- }- }- return result;- };- group.userData.floeCount = cells.length;- group.userData.floeOutlines = cells.map(cell => cell.polygon.map(point => [...point]));- group.userData.seed = seed;- group.userData.update = () => {};- const owned = snapshotResources(group); owned.add(optical);- return attachDisposal(group, owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.jsdeleted file mode 100644index 9bab0b05..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/instancing.js+++ /dev/null@@ -1,434 +0,0 @@-/**- * Place one asset hundreds of times for the cost of building it once.- * Hand-instancing is fiddly enough that no delivered scene ever did- * it, so the capability ships as a function.- */--import * as THREE from 'three';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';-import { snapshotResources, attachDisposal } from './lifecycle.js';--/** A baked mirror changes triangle orientation as well as vertex positions. */-function reverseWinding(geometry) {- if (!geometry.index) {- geometry.setIndex(Array.from({length:geometry.attributes.position.count}, (_, i) => i));- }- const index = geometry.index;- for (let i = 0; i + 2 < index.count; i += 3) {- const b = index.getX(i + 1);- index.setX(i + 1, index.getX(i + 2));- index.setX(i + 2, b);- }- index.needsUpdate = true;- return geometry;-}--/**- * Build one prototype and stamp it across many transforms.- *- * The prototype is built ONCE. Every mesh inside it becomes one- * InstancedMesh sharing that mesh's geometry and material, so a 200-copy- * placement costs the prototype's triangles once on the CPU side and one- * draw call per (geometry, material) pair.- *- * A mesh carrying an ARRAY of materials is split along its geometry- * groups first, so a box whose door face is a second material keeps it:- * merging by `material[0]` alone painted every face with the first one.- *- * @param {(opts: object) => THREE.Object3D} build The asset's exported- * build function.- * @param {Array<{position?: number[]|THREE.Vector3, rotationY?: number,- * scale?: number|number[], color?: number[]|THREE.Color|number|string}>}- * placements One entry per copy. `rotationY` is radians; `scale` is- * uniform when a number. `color` MULTIPLIES that copy's albedo — no- * `vertexColors` needed, three defines `USE_INSTANCING_COLOR` off the- * instance buffer alone. Give it as a LINEAR `[r, g, b]` (what- * `scatterGrid` emits) or a `THREE.Color`; a hex or a CSS string is- * read as sRGB, so `0x808080` is not "half" but a quarter — the trap- * that turns a tint into a dimmer.- * @param {object} [opts] `buildOpts` is passed to `build` for the- * prototype; `name` names the returned group.- * @returns {THREE.Group} A group of InstancedMeshes, positioned in world- * space by the placements. Empty group when there are no placements.- * Mirrored placements use a second batch with baked reversed winding;- * every instance matrix then has positive determinant, as Three requires.- * userData.dispose() releases copied geometry and instance buffers, while- * prototype materials/textures remain borrowed. Later children are unowned.- */-export function instanceAsset(build, placements, opts = {}) {- const group = new THREE.Group();- group.name = opts.name || 'InstancedAsset';- if (!placements || placements.length === 0) return attachDisposal(group, []);-- const proto = build(opts.buildOpts || {});- proto.updateWorldMatrix(true, true);-- // Collect meshes with transforms RELATIVE to the prototype root,- // then MERGE by material — unmerged, a 1418-mesh asset would cost- // 1418 draw calls per placement batch; merged, one per material.- const buckets = new Map();- const inv = new THREE.Matrix4().copy(proto.matrixWorld).invert();- proto.traverseVisible((n) => {- if (!n.isMesh || n.isInstancedMesh || !n.geometry) return;- const mats = Array.isArray(n.material) ? n.material : [n.material];- if (!mats[0]) return;- const xf = new THREE.Matrix4().copy(inv).multiply(n.matrixWorld);- for (const { material, geometry } of splitByMaterial(n.geometry, mats)) {- const g = geometry;- g.applyMatrix4(xf);- if (xf.determinant() < 0) reverseWinding(g);- // Merging needs identical attribute sets; drop the extras.- for (const name of Object.keys(g.attributes)) {- // `color` stays: a vertexColors material with no color- // attribute renders BLACK, and mergeStatic() returns one.- if (!['position', 'normal', 'uv', 'color'].includes(name)) {- g.deleteAttribute(name);- }- }- if (!g.attributes.normal) g.computeVertexNormals();- if (!g.attributes.uv) {- const n2 = g.attributes.position.count;- g.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(n2 * 2), 2));- }- if (!buckets.has(material.uuid)) {- buckets.set(material.uuid, { material, geos: [] });- }- buckets.get(material.uuid).geos.push(g);- }- });- const parts = [];- for (const { material, geos } of buckets.values()) {- for (const geometry of mergeBucket(geos)) {- parts.push({ geometry, material, local: new THREE.Matrix4() });- }- }- if (!parts.length) return attachDisposal(group, []);-- const world = placements.map((p) => {- const pos = p.position instanceof THREE.Vector3- ? p.position- : new THREE.Vector3(...(p.position || [0, 0, 0]));- const s = Array.isArray(p.scale)- ? new THREE.Vector3(...p.scale)- : new THREE.Vector3(1, 1, 1).multiplyScalar(- typeof p.scale === 'number' ? p.scale : 1);- const matrix = new THREE.Matrix4().compose(- pos,- new THREE.Quaternion().setFromEuler(- new THREE.Euler(0, p.rotationY || 0, 0)),- s);- if (!matrix.elements.every(Number.isFinite) || Math.abs(matrix.determinant()) < 1e-12) {- throw new RangeError('instanceAsset: placements need finite transforms and nonzero scale');- }- return matrix;- });-- const m = new THREE.Matrix4();- const tint = new THREE.Color();- const reflection = new THREE.Matrix4().makeScale(-1, 1, 1);- const batches = [[], []];- for (let i = 0; i < world.length; i++) batches[world[i].determinant() < 0 ? 1 : 0].push(i);- for (const part of parts) {- for (let mirrored = 0; mirrored < batches.length; mirrored++) {- const indices = batches[mirrored];- if (!indices.length) continue;- const geometry = mirrored- ? reverseWinding(part.geometry.clone().applyMatrix4(reflection)) : part.geometry;- const mesh = new THREE.InstancedMesh(- geometry, part.material, indices.length);- mesh.castShadow = true;- mesh.receiveShadow = true;- let tinted = false;- for (let i = 0; i < indices.length; i++) {- const sourceIndex = indices[i];- m.copy(world[sourceIndex]).multiply(part.local);- if (mirrored) m.multiply(reflection);- mesh.setMatrixAt(i, m);- const c = placements[sourceIndex].color;- if (c !== undefined && c !== null) {- // An array is LINEAR — the space the multiply happens in, and the- // only way to say "1.06 of the albedo". set() reads a hex or a- // string as sRGB.- if (Array.isArray(c)) tint.setRGB(c[0], c[1], c[2]);- else tint.set(c);- mesh.setColorAt(i, tint);- tinted = true;- }- }- mesh.instanceMatrix.needsUpdate = true;- if (tinted && mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- mesh.frustumCulled = false; // one bbox for the whole spread- mesh.userData.placementIndices = Int32Array.from(indices);- group.add(mesh);- }- }- return attachDisposal(group, snapshotResources(group, {materials:false}));-}--/**- * One geometry per material the mesh actually draws with.- *- * A multi-material mesh draws its groups with different materials; taking- * `material[0]` for the whole geometry paints the door, the glass and the- * roof with the wall's material and the copy loses every second colour it- * had. Each group becomes its own geometry, de-indexed so it carries only- * the vertices it uses.- * @private- */-function splitByMaterial(geo, mats) {- const groups = geo.groups || [];- if (mats.length < 2 || groups.length === 0) {- return [{ material: mats[0], geometry: geo.clone() }];- }- const out = [];- const idx = geo.index;- const total = idx ? idx.count : geo.attributes.position.count;- for (const gr of groups) {- const start = Math.max(0, gr.start | 0);- const count = Math.min(gr.count === Infinity ? total : gr.count | 0,- total - start);- const material = mats[gr.materialIndex || 0] || mats[0];- if (count <= 0 || !material) continue;- let piece;- if (idx) {- piece = geo.clone();- piece.clearGroups();- piece.setIndex(Array.from(idx.array.slice(start, start + count)));- piece = piece.toNonIndexed(); // drops the vertices this group misses- } else {- piece = new THREE.BufferGeometry();- for (const name of Object.keys(geo.attributes)) {- const a = geo.attributes[name];- piece.setAttribute(name, new THREE.BufferAttribute(- a.array.slice(start * a.itemSize, (start + count) * a.itemSize),- a.itemSize, a.normalized));- }- }- out.push({ material, geometry: piece });- }- return out.length ? out : [{ material: mats[0], geometry: geo.clone() }];-}--/**- * Merge one material's geometries into as few draws as possible.- *- * `mergeGeometries` returns NULL — silently — when the inputs disagree on- * their attribute set or on being indexed, and the old code dropped that- * bucket: the asset rendered with a part MISSING and nothing said so.- * Harmonise what can be harmonised (a white `color` for the geometries- * that lack one, de-index the mixed case) and fall back to separate draws- * rather than to a hole.- * @private- */-function mergeBucket(geos) {- if (geos.length <= 1) return geos;- let list = geos;- if (list.some((g) => g.index) && list.some((g) => !g.index)) {- list = list.map((g) => (g.index ? g.toNonIndexed() : g));- }- if (list.some((g) => g.attributes.color)) {- for (const g of list) {- if (g.attributes.color) continue;- const n = g.attributes.position.count;- g.setAttribute('color',- new THREE.BufferAttribute(new Float32Array(n * 3).fill(1), 3));- }- }- const merged = mergeGeometries(list, false);- return merged ? [merged] : list;-}--/**- * Fill a rectangle with placements on a jittered grid.- *- * A perfect lattice reads as wallpaper and an unconstrained random- * scatter clumps and overlaps; a jittered grid is the middle that reads- * as a city block or an orchard. Deterministic: pass your seeded PRNG.- *- * Every copy also gets its OWN albedo. One prototype means one colour,- * and a field of thirty identical greens or thirty identical roof reds- * is the flat "high repetition of identical towers" read however much- * the silhouettes vary — no orchard has two leaves the same hue. `tint`- * is a per-copy LINEAR multiplier averaging 0.96, so the field keeps the- * albedo the asset was authored with and mostly gains SPREAD: pass a- * number to scale the default strength, `{ chroma, value }` to set the- * hue swing and the light/dark swing apart, or `false` for the old flat- * field (a copy that must match a stated brand colour exactly).- *- * @param {object} area `{x, z, w, d}` — centre and extents in metres.- * @param {number} spacing Nominal metres between copies.- * @param {() => number} rand Seeded PRNG returning [0, 1).- * @param {object} [opts] `jitter` (0-1, default 0.35) fraction of- * spacing to offset by; `yaw` true (default) for random Y rotation,- * false for none, or a NUMBER of radians to snap to — `Math.PI / 2`- * is the built fabric that faces its street instead of spinning- * freely, with `yawJitter` (default 0.035 rad) of hand-placed slop- * on top; `scaleVar` (default 0.12) uniform scale spread;- * `heightVar`/`widthVar` (default 0) per-instance NON-uniform- * stretch — a city fabric wants heightVar 0.4-0.7 so the block is- * not one model repeated; `clearance` metres of centre-to-centre- * room every copy is given (jitter plus scaleVar routinely lands two- * copies inside each other, and two coincident roofs z-fight);- * `tint` per-copy albedo variation (see below); `height` a- * function (x, z) => y for the ground under each copy; `skip` a- * predicate (x, z) => boolean to leave gaps (streets, water, parks).- * @returns {Array<object>} Placements for `instanceAsset`.- */-export function scatterGrid(area, spacing, rand, opts = {}) {- if (!Number.isFinite(spacing) || spacing <= 0 ||- ![area.x, area.z, area.w, area.d].every(Number.isFinite) || area.w < 0 || area.d < 0) {- throw new RangeError('scatterGrid: spacing must be positive and area finite with nonnegative size');- }- if (area.w === 0 || area.d === 0) return [];- const jitter = opts.jitter ?? 0.35;- const scaleVar = opts.scaleVar ?? 0.12;- // Per-instance SHAPE variation, not just yaw: cheap repetition is- // not density. heightVar/widthVar stretch each copy independently,- // free through the per-instance matrix.- const heightVar = opts.heightVar ?? 0;- const widthVar = opts.widthVar ?? 0;- const tint = tintAmount(opts.tint);- const clearance = Math.max(0, opts.clearance ?? 0);- const yawStep = typeof opts.yaw === 'number' ? Math.abs(opts.yaw) : 0;- const yawSlots = yawStep > 0- ? Math.max(1, Math.round((Math.PI * 2) / yawStep)) : 0;- const yawSlop = opts.yawJitter ?? 0.035;- const kept = clearance > 0 ? new Map() : null;- const out = [];- const nx = Math.max(1, Math.round(area.w / spacing));- const nz = Math.max(1, Math.round(area.d / spacing));- for (let ix = 0; ix < nx; ix++) {- for (let iz = 0; iz < nz; iz++) {- const x = area.x - area.w / 2 + (ix + 0.5) * (area.w / nx)- + (rand() - 0.5) * spacing * jitter;- const z = area.z - area.d / 2 + (iz + 0.5) * (area.d / nz)- + (rand() - 0.5) * spacing * jitter;- if (opts.skip && opts.skip(x, z)) continue;- if (kept && crowded(kept, x, z, clearance)) continue;- const base = 1 + (rand() - 0.5) * 2 * scaleVar;- const scale = (heightVar || widthVar)- ? [base * (1 + (rand() - 0.5) * 2 * widthVar),- base * (1 + (rand() - 0.5) * 2 * heightVar),- base * (1 + (rand() - 0.5) * 2 * widthVar)]- : base;- let rotationY = 0;- if (opts.yaw !== false) {- rotationY = yawSlots- ? Math.floor(rand() * yawSlots) * yawStep- + (rand() - 0.5) * 2 * yawSlop- : rand() * Math.PI * 2;- }- const p = {- position: [x, opts.height ? opts.height(x, z) : 0, z],- rotationY,- scale,- };- if (tint) p.color = tintOf(rand, tint);- out.push(p);- if (kept) remember(kept, x, z, clearance);- }- }- return out;-}--// Default per-copy albedo spread, set against the crown measurement the-// canopy work landed on — 9.4 degrees of hue across one tree, where a-// photograph carries 25-45. Measured over 400 copies of the showcase-// assets, this pair gives a 5-95 hue spread of 5.3 deg on the terracotta-// roof, 13.8 on the leaf green and 28.6 on the near-neutral plaster-// (whose hue is the least stable and moves furthest for the least-// perceived change), with a 5-95 lightness spread of 0.072 / 0.058 /-// 0.114. The roof moves least in HUE because terracotta already sits on-// the warm axis the swing runs along — there it spends itself on-// saturation and value instead, which is what a batch of tiles does.-// Half of this measured 2.7 / 6.9 / 12.3 and the widest pixel gap-// between a tinted field and a flat one was 10/255: real, and invisible.-const TINT = { chroma: 0.22, value: 0.22 };--// The value swing is wider DOWNWARD (x0.6 up, x1.2 down). A copy that-// has stood in weather is darker than the reference far more often than-// brighter, and the up-swing has a ceiling the down-swing does not: an-// albedo authored near the top of the 0.02-0.8 band has no room to be-// multiplied, and a surface pushed past it has no shading left in it.-const VALUE_UP = 0.6, VALUE_DOWN = 1.2;--// How much of the chroma swing goes ACROSS the warm-cool axis (the-// green-magenta one). Well under half: see tintOf.-const ACROSS = 0.45;--/** Normalise the `tint` option to amounts, or null for none. @private */-function tintAmount(spec) {- if (spec === false || spec === 0 || spec === null) return null;- if (spec === undefined || spec === true) return TINT;- if (typeof spec === 'number') {- return { chroma: TINT.chroma * spec, value: TINT.value * spec };- }- return { chroma: spec.chroma ?? TINT.chroma, value: spec.value ?? TINT.value };-}--/**- * One copy's albedo multiplier, in LINEAR space and centred on white.- *- * The hue part is an offset in the plane PERPENDICULAR to the grey axis- * — the only directions that change hue without changing brightness —- * drawn over an ELLIPSE, not a disc: 1.0 along warm-cool (red up, blue- * down) and 0.45 across it. A disc spreads a near-neutral copy in any- * direction at all, and a violet wall beside an olive one reads as a- * bug; the same spread laid on the temperature axis reads as different- * limewash under the same sun, which is what the eye expects of a row of- * houses. `value` then scales the whole triple, so the field is moved- * APART rather than lifted or dimmed (its mean lands at 0.96 of the- * authored albedo, the weathering skew).- *- * It is a MULTIPLIER and not a hue rotation on purpose: a rotation about- * the grey axis drives the small channels of a near-primary negative and- * the clamp then forks one swing into two lobes — the failure the flower- * field was measured splitting into an amber half and a magenta half. A- * positive multiplier cannot leave the hue's own quadrant.- * @private- */-function tintOf(rand, amt) {- const a = rand() * Math.PI * 2;- const m = amt.chroma * Math.sqrt(rand());- const r = (rand() - 0.5) * 2;- const v = 1 + amt.value * r * (r < 0 ? VALUE_DOWN : VALUE_UP);- const warm = Math.cos(a) * m, cast = Math.sin(a) * m * ACROSS;- // A guard, not a shaper: the defaults' corner is 1.31 and 1600 copies- // measured a widest channel of 1.29.- const clamp = (c) => Math.min(1.35, Math.max(0.5, c));- return [- clamp(v * (1 + 0.70711 * warm - 0.40825 * cast)),- clamp(v * (1 + 0.81650 * cast)),- clamp(v * (1 - 0.70711 * warm - 0.40825 * cast)),- ];-}--// Kept centres in a hash grid of `clearance`-sized cells: the 3x3-// neighbourhood holds every copy close enough to matter, so the test-// stays O(1) per candidate instead of O(n) against the whole field.-const cellKey = (i, j) => `${i},${j}`;--/** @private */-function crowded(kept, x, z, cell) {- const i = Math.floor(x / cell), j = Math.floor(z / cell);- const r2 = cell * cell;- for (let di = -1; di <= 1; di++) {- for (let dj = -1; dj <= 1; dj++) {- const a = kept.get(cellKey(i + di, j + dj));- if (!a) continue;- for (let n = 0; n < a.length; n += 2) {- const dx = a[n] - x, dz = a[n + 1] - z;- if (dx * dx + dz * dz < r2) return true;- }- }- }- return false;-}--/** @private */-function remember(kept, x, z, cell) {- const k = cellKey(Math.floor(x / cell), Math.floor(z / cell));- const a = kept.get(k);- if (a) a.push(x, z);- else kept.set(k, [x, z]);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.jsindex d264c054..c777afbd 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/neon.js@@ -14,9 +14,7 @@* (0 an unlit street, 1 open daylight): from 0.35 up it stops adding* and paints a pale, normal-blended tube instead, so the 0.5 a composer* picks when handed "0 to 1" is the mode that cannot clip.- *- * Composes with `windows.js` (the rooms behind the facade this spills- * onto).+*/import { attachDisposal, snapshotResources } from './lifecycle.js';@@ -486,7 +484,7 @@ const SPILL_BODY = [* dark frame a night city is and clipping over a bright one, which is* what `ambient` is for. It is a `patchStandard`, so it needs a LIT* material (MeshStandard/MeshPhysical, not Basic), and it chains- * happily with `patchWindowInteriors` and `patchMicroBreakup`.+ * happily with `patchMicroBreakup`.** The one constraint it cannot solve: nothing is occluded. Light* reaches the far side of a wall as readily as the near one, so keepdiff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.jsindex ff7ced75..39cc936c 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/noise.js@@ -33,7 +33,7 @@ export function mulberry32(seed) {/*** The 16807 (Park-Miller) stream the older effects were tuned on —- * celestial, godrays, veils, watermist, submerged and+ * celestial, godrays, veils, watermist and* `instanceVariation`. Kept because moving them to `mulberry32` would* move every star, shaft and drop they place; new code takes that.*diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.jsdeleted file mode 100644index 4275aa54..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/place.js+++ /dev/null@@ -1,690 +0,0 @@-/**- * Placement, derived instead of typed — hand-typed yaws and y's are- * what produce ungrounded geometry, backwards vehicles and- * back-to-front seating, so the arithmetic lives here as functions.- * Every function MUTATES and returns the object, so calls chain; the- * camera builders (`shot`, `establishingShot`) instead return a ready- * CAMERAS entry, and `route()` returns a stateless pose function.- */--import * as THREE from 'three';-import { sunVector } from './shader.js';--const _ray = new THREE.Raycaster();-const _down = new THREE.Vector3(0, -1, 0);-const _box = new THREE.Box3();-const _v = new THREE.Vector3();-const _t = new THREE.Vector3();-const DEG = Math.PI / 180;--/** Raycaster does not check Object3D.visible or invisible ancestors. */-function visibleInTree(object) {- for (let p = object; p; p = p.parent) if (!p.visible) return false;- return true;-}--/** A world position must be converted before writing a child's local slot. */-function positionInWorld(object, position) {- if (object.parent) {- object.parent.updateWorldMatrix(true, false);- object.position.copy(object.parent.worldToLocal(position.clone()));- } else object.position.copy(position);- object.updateWorldMatrix(false, true);-}--/** Unit vector for a `forward` string as reported by assets_api.json. */-function fwdVec(forward) {- switch (forward) {- case '+X': return new THREE.Vector3(1, 0, 0);- case '-X': return new THREE.Vector3(-1, 0, 0);- case '+Z': return new THREE.Vector3(0, 0, 1);- default: return new THREE.Vector3(0, 0, -1); // '-Z', the three.js default- }-}--/**- * Every surface y over (x, z), highest first — one down-ray from `top`.- * `intersectObjects` already sorts by distance, and the ray points- * down, so the array comes back descending.- */-function columnAt(x, z, targets, top, far, ignore) {- _ray.set(_v.set(x, top, z), _down);- _ray.far = far;- const ys = [];- for (const h of _ray.intersectObjects(targets, true)) {- if (!visibleInTree(h.object)) continue;- if (ignore && (h.object === ignore || ignore.getObjectById(h.object.id))) {- continue;- }- ys.push(h.point.y);- }- return ys;-}--/**- * Which of those surfaces a body at height `y` actually rests on: the- * TOPMOST one at or below it — what is UNDER it, a quay beating the- * seabed — and only when nothing is under it the LOWEST one above (an- * object authored at y = 0 on a hillside is still lifted onto the hill).- *- * The split is the fix for a measured teleport: the down-ray starts far- * overhead, so its nearest hit is a ROOF, and anything with something- * over it flew up onto that roof — a crate under a 3 m arch seated at- * y 3.62, and an interior camera handed its room group (which is what- * the catalog tells composers to pass) shipped at eye 4.60 in a room- * whose ceiling tops out at 3.00 (2026-09-01 port probe).- */-function restingY(ys, y) {- for (const v of ys) if (v <= y + 1e-4) return v;- return ys.length ? ys[ys.length - 1] : null;-}--/**- * Drop an object until it rests on whatever is under it.- * Casts down from base corners AND centre: per ray the surface UNDER- * the base wins (a quay beats the seabed), across rays the LOWEST wins- * (a wide object on a slope buries its uphill side instead of hovering- * on the high corner), then sinks `bite` metres so no seam shows.- *- * @param {THREE.Object3D} obj Already positioned in x/z.- * @param {THREE.Object3D|THREE.Object3D[]} surfaces Ground, terrain,- * decks, roofs — anything that can be stood on.- * @param {object} [opts] `bite` metres to sink so no seam shows- * (default 0.03, inside the placement gate's contact tolerance — the- * gate measures contact, not this number), `maxDrop` how far down to- * look (default 500).- * @returns {THREE.Object3D} obj, or obj unchanged when nothing is below.- */-export function seat(obj, surfaces, opts = {}) {- const targets = Array.isArray(surfaces) ? surfaces : [surfaces];- const bite = opts.bite === undefined ? 0.03 : opts.bite;- obj.updateWorldMatrix(true, true);- // The SURFACE's world matrix has to be current too: a ground group- // built and moved in the same tick still carries its old matrix, so- // every raycast hits the old height and the whole scene seats to it- // (measured 1.53 m under a quay, 2026-08-04 drawbridge repair).- for (const t of targets) if (t) t.updateWorldMatrix(true, true);- _box.setFromObject(obj);- if (_box.isEmpty()) return obj;- const y0 = _box.min.y;- const xs = [_box.min.x, _box.max.x, (_box.min.x + _box.max.x) / 2];- const zs = [_box.min.z, _box.max.z, (_box.min.z + _box.max.z) / 2];- const drop = opts.maxDrop ?? 500;- if (!Number.isFinite(drop) || drop < 0 || !Number.isFinite(bite)) {- throw new RangeError('seat: maxDrop must be finite and nonnegative, bite finite');- }- if (drop === 0) return obj;- let best = null;- for (const x of xs) {- for (const z of zs) {- const y = restingY(- columnAt(x, z, targets, y0 + drop * 0.5, drop, obj), y0);- if (y !== null && (best === null || y < best)) best = y;- }- }- if (best === null) return obj;- const position = obj.getWorldPosition(new THREE.Vector3());- position.y += best - y0 - bite;- positionInWorld(obj, position);- return obj;-}--/** Coerce a `surfaces` argument to an array, `undefined` to []. */-function surfaceList(surfaces) {- if (surfaces === undefined || surfaces === null) return [];- return Array.isArray(surfaces) ? surfaces : [surfaces];-}--/**- * Lift a point so it clears the FLOOR under it — the surface- * `restingY()` picks, not whatever is highest in the column: handed a- * room group (which is exactly what the catalog tells composers to- * pass indoors) the old rule lifted the eye 1.6 m above the CEILING- * and the shot shipped from on top of the roof.- * Only ever lifts (an intentionally aerial camera is left where it- * is), and never through a low ceiling: in a room too short for the- * clearance the eye stops 0.25 m under it instead of leaving.- */-function liftAbove(pos, targets, clearance) {- if (!targets.length) return pos;- for (const t of targets) if (t) t.updateWorldMatrix(true, true);- const ys = columnAt(pos.x, pos.z, targets, pos.y + 1000, 4000);- const floorY = restingY(ys, pos.y);- if (floorY === null) return pos;- let want = Math.max(pos.y, floorY + clearance);- let ceiling = null; // lowest surface above the floor- for (const v of ys) if (v > floorY + 0.05) ceiling = v;- if (ceiling !== null && want > ceiling - 0.25) {- want = Math.max(floorY + 0.3, ceiling - 0.25);- }- pos.y = want;- return pos;-}--/**- * How far the view from `pos` to `look` gets before something is in- * the way — ONE definition of "blocked" for both camera builders.- *- * @returns {{dir: THREE.Vector3, dist: number, hit: number}} `dir` unit- * eye-to-subject, `dist` their separation, `hit` distance to the- * first surface in between (Infinity when the view is clear).- */-function probeView(pos, look, targets) {- const dir = new THREE.Vector3().subVectors(look, pos);- const dist = dir.length();- if (dist < 1e-6 || !targets.length) return { dir, dist, hit: Infinity };- dir.multiplyScalar(1 / dist);- _ray.set(pos, dir);- _ray.far = dist;- const hits = _ray.intersectObjects(targets, true).filter((h) => visibleInTree(h.object));- return { dir, dist, hit: hits.length ? hits[0].distance : Infinity };-}--/** Nothing may fill the frame from closer than this. */-function clearNeeded(dist) {- return Math.max(2, dist * 0.05);-}--/**- * Build a CAMERAS entry whose geometry is verified, not guessed.- * What is measured (the frame gate's `camera_underground` and "camera- * blocked" findings): the eye is above the surface under it and- * nothing fills the frame from closer than max(2 m, 5% of target- * distance). Two checks: (1) a down-ray over `surfaces` lifts the eye- * to at least 1.6 m (a standing eye) above the floor it finds — only- * ever lifts, so a deliberately low or aerial eye stays where it is- * put; (2) a ray toward `lookAt` that hits something closer than the- * clearance slides the camera back and up until the frame clears.- *- * @param {string} name Camera name for the CAMERAS array.- * @param {THREE.Vector3|number[]} position Requested eye point.- * @param {THREE.Vector3|number[]} lookAt What the shot is of.- * @param {number} [fov] Vertical field of view (default 55).- * @param {THREE.Object3D|THREE.Object3D[]} [surfaces] Ground, terrain,- * decks, walls — everything the camera must clear.- * @returns {{name: string, position: number[], lookAt: number[],- * fov: number}} A ready CAMERAS entry.- */-export function shot(name, position, lookAt, fov, surfaces) {- const pos = position instanceof THREE.Vector3- ? position.clone() : new THREE.Vector3(...position);- const look = lookAt instanceof THREE.Vector3- ? lookAt.clone() : new THREE.Vector3(...lookAt);- const targets = surfaceList(surfaces);- liftAbove(pos, targets, 1.6);- for (let i = 0; i < 12 && targets.length; i++) {- const v = probeView(pos, look, targets);- if (v.dist < 1e-6) break;- const clear = clearNeeded(v.dist);- if (v.hit >= clear) break;- pos.addScaledVector(v.dir, -(clear - v.hit + 0.25));- pos.y += 0.5;- liftAbove(pos, targets, 1.6);- }- // INDOORS THERE IS NOWHERE TO RETREAT TO: backing away from a screen- // walks into the wall behind, and the shot ships from inside the- // screen. If the view is still blocked, step FORWARD past the- // blocker instead — what a person holding the camera would do.- if (targets.length) {- const v = probeView(pos, look, targets);- if (v.dist > 1e-6 && v.hit < clearNeeded(v.dist)- && v.hit < v.dist * 0.6) {- pos.addScaledVector(v.dir, v.hit + 0.35);- liftAbove(pos, targets, 1.6);- }- }- return {- name,- position: [pos.x, pos.y, pos.z],- lookAt: [look.x, look.y, look.z],- fov: fov === undefined ? 55 : fov,- };-}--// Measured: a low-sun mie lobe within ~90 deg of the view direction-// washed the frame — 55 deg still bleached a third of it, 25 deg blew-// the whole image, 120 deg rendered clean (theme-park run). The-// requirement is only that the judged frame stays in the luminance band.-const SUN_CLEAR_DEG = 90;--/**- * Push a camera azimuth out of the sun's glare lobe — opt-in: it acts- * only when `sunAzDeg` is given. Omit it for a deliberate contre-jour- * composition and handle the exposure another way. A camera at azimuth- * A LOOKS toward A, so the sun at S is in frame when |A - S| is small.- *- * @param {number} azDeg Requested camera azimuth in degrees.- * @param {number} [sunAzDeg] Sun azimuth, same convention; when absent- * the request passes through untouched.- * @returns {number} The nearest azimuth at least 90 deg off the sun.- */-export function awayFromSun(azDeg, sunAzDeg) {- if (typeof sunAzDeg !== 'number' || !isFinite(sunAzDeg)) return azDeg;- const wrap = (d) => ((d % 360) + 540) % 360 - 180;- const off = wrap(azDeg - sunAzDeg);- if (Math.abs(off) >= SUN_CLEAR_DEG) return azDeg;- // Nearest legal side, so the requested composition moves as little as- // it can rather than jumping to the anti-sun default.- const side = off === 0 ? 1 : Math.sign(off);- return sunAzDeg + side * SUN_CLEAR_DEG;-}--/**- * One establishing composition (optional): a hero object whole,- * centred, filling `coverage` of the frame — derived instead of- * eyeballed: project the 8 world-bbox corners, dolly until the widest- * NDC extent hits `coverage`, seat the eye with the same down-ray as- * `shot()`, and — when something stands between the eye and the hero —- * slide along the fit sphere (up first, then around) until the hero is- * actually visible. What is measured for ANY establishing camera: the- * brief's subject is visible and unblocked in the judged frame (frame- * gate "camera blocked") and the eye is above the surface under it- * (`camera_underground`). A street receding, a view through a doorway- * or a low wide are establishing shots too — compose those with- * `shot()` or by hand.- *- * @param {string} name Camera name for the CAMERAS array.- * @param {THREE.Object3D} heroObj The subject to fit whole.- * @param {object} [opts] the defaults of this composition: `azDeg`- * view azimuth (default 35), `elDeg` elevation (default 22), `fov`- * (default 45), `coverage` how much of the frame the hero spans,- * 0.5-0.9 (default 0.7), `surfaces` to keep the eye at least `eyeMin`- * m above the ground (default 1.6, a standing eye), `sunAzDeg` to- * have the azimuth pushed clear of the sun's glare lobe.- * @returns {{name: string, position: number[], lookAt: number[],- * fov: number}} A ready CAMERAS entry.- */-export function establishingShot(name, heroObj, opts = {}) {- // `azDeg` is where the EYE stands; it looks back at the centre, so- // the view direction is azDeg + 180 and that is what must clear the- // sun. Correcting the eye azimuth directly would aim it AT the glare.- const azDeg = awayFromSun(- (opts.azDeg === undefined ? 35 : opts.azDeg) + 180,- opts.sunAzDeg) - 180;- const elDeg = opts.elDeg === undefined ? 22 : opts.elDeg;- const fov = opts.fov === undefined ? 45 : opts.fov;- const coverage = opts.coverage === undefined ? 0.7 : opts.coverage;- const eyeMin = opts.eyeMin === undefined ? 1.6 : opts.eyeMin;- const targets = surfaceList(opts.surfaces);- heroObj.updateWorldMatrix(true, true);- _box.setFromObject(heroObj);- if (_box.isEmpty()) {- return { name, position: [10, 6, 10], lookAt: [0, 0, 0], fov };- }- const center = _box.getCenter(new THREE.Vector3());- const radius = Math.max(- _box.getSize(new THREE.Vector3()).length() / 2, 0.25);- const corners = [];- for (const cx of [_box.min.x, _box.max.x])- for (const cy of [_box.min.y, _box.max.y])- for (const cz of [_box.min.z, _box.max.z])- corners.push(new THREE.Vector3(cx, cy, cz));- // 16:9 is the harness's render aspect (800x450 / 1280x720).- const camera = new THREE.PerspectiveCamera(fov, 16 / 9, 0.1, 1e6);- /** The dolly distance that puts the widest bbox extent on `coverage`. */- const fit = (dirVec) => {- let d = radius / Math.sin((fov / 2) * DEG);- for (let it = 0; it < 5; it++) {- camera.position.copy(center).addScaledVector(dirVec, d);- camera.lookAt(center);- camera.updateMatrixWorld(true);- let maxExt = 1e-6;- for (const c of corners) {- _v.copy(c).project(camera);- maxExt = Math.max(maxExt, Math.abs(_v.x), Math.abs(_v.y));- }- d = d * (maxExt / coverage);- }- return d;- };- // MOVE ON THE FIT SPHERE, NEVER BACKWARDS. `shot()` retreats from a- // blocker, which is right for a street camera and wrong here: backing- // away shrinks the hero the establishing shot exists to show. Look- // OVER the obstacle first (raise the elevation — what a person with a- // camera does), then step around it (swing the azimuth), re-fitting at- // every candidate so the framing survives the move. Measured before- // this: a hero behind a 9 m ridge shipped a frame filled by ridge at- // 1.19 m of an 8.92 m shot — the "one wall fills the frame" failure- // the module was written to end (2026-09-01 port probe).- const arcs = [[0, 0], [0, 9], [0, 19], [0, 31], [24, 6], [-24, 6],- [24, 20], [-24, 20], [48, 10], [-48, 10], [0, 46]];- let pos = null;- let bestGap = -1;- for (const [dAz, dEl] of arcs) {- const a = dAz === 0 ? azDeg- : awayFromSun(azDeg + dAz + 180, opts.sunAzDeg) - 180;- const dir = sunVector(a, Math.min(70, elDeg + dEl));- const p = center.clone().addScaledVector(dir, fit(dir));- liftAbove(p, targets, eyeMin);- const v = probeView(p, center, targets);- if (v.hit >= clearNeeded(v.dist)) { pos = p; break; }- // Nothing clears: keep whichever candidate sees furthest into the- // scene, so the shot degrades toward the most open direction.- if (v.hit > bestGap) { bestGap = v.hit; pos = p; }- }- return {- name,- position: [pos.x, pos.y, pos.z],- lookAt: [center.x, center.y, center.z],- fov,- };-}--/**- * Turn an object so its own forward axis points at a target.- *- * @param {THREE.Object3D} obj- * @param {THREE.Vector3|number[]} target World point to face.- * @param {string} [forward] The asset's forward as reported by- * assets_api.json ('+X' | '-X' | '+Z' | '-Z'); defaults to '-Z'.- * @returns {THREE.Object3D} obj- */-export function faceToward(obj, target, forward) {- const p = target instanceof THREE.Vector3- ? target : new THREE.Vector3(...target);- _t.subVectors(p, obj.getWorldPosition(new THREE.Vector3()));- _t.y = 0;- if (_t.lengthSq() < 1e-9) return obj;- return alignAlong(obj, _t, forward);-}--/**- * Turn an object so its forward axis runs along a direction — pass a- * route tangent, not a guessed angle (backwards vehicles came from- * guessed yaws).- *- * @param {THREE.Object3D} obj- * @param {THREE.Vector3|number[]} dir WORLD direction of travel (y ignored).- * @param {string} [forward] Asset forward from assets_api.json.- * @returns {THREE.Object3D} obj- */-export function alignAlong(obj, dir, forward) {- const d = dir instanceof THREE.Vector3- ? dir.clone() : new THREE.Vector3(...dir);- d.y = 0;- if (d.lengthSq() < 1e-9) return obj;- d.normalize();- const f = fwdVec(forward);- if (obj.parent) {- obj.parent.updateWorldMatrix(true, false);- const inverse = obj.parent.matrixWorld.clone().invert();- d.transformDirection(inverse);- // Map the world horizontal heading and up into the parent's axes. With- // a scaled parent, subtracting its Euler yaw is not a valid conversion.- const up = new THREE.Vector3(0, 1, 0).transformDirection(inverse);- const basis = new THREE.Matrix4().lookAt(new THREE.Vector3(), d, up);- obj.quaternion.setFromRotationMatrix(basis).multiply(- new THREE.Quaternion().setFromUnitVectors(f, new THREE.Vector3(0, 0, -1)));- return obj;- }- // Yaw that takes the asset's own forward onto d.- obj.rotation.y = Math.atan2(d.x, d.z) - Math.atan2(f.x, f.z);- return obj;-}--/**- * Sample a route as a closed or open path and walk objects along it.- *- * Returns positions AND tangents, so callers cannot place a vehicle- * without also having the direction it should face.- *- * A closed path divides into n equal arcs (the last sample is one arc- * short of the start, which is where it belongs). An OPEN path spans- * end to end — n samples, n-1 gaps: dividing by n instead left the row- * a whole gap short of its own last waypoint (6 posts over a 12 m quay- * stopped at x = 10, and the missing post is visible in the frame).- *- * @param {number[][]} points Control points [[x,y,z], ...].- * @param {number} n How many samples.- * @param {object} [opts] `closed` (default true).- * @returns {Array<{position: THREE.Vector3, tangent: THREE.Vector3}>}- */-export function alongPath(points, n, opts = {}) {- const closed = opts.closed !== false;- const curve = new THREE.CatmullRomCurve3(- points.map((p) => new THREE.Vector3(...p)), closed);- const out = [];- const span = closed ? n : Math.max(1, n - 1);- for (let i = 0; i < n; i++) {- const t = i / span;- out.push({- position: curve.getPointAt(t),- tangent: curve.getTangentAt(t).setY(0).normalize(),- });- }- return out;-}--/**- * A teleport-free, dt-free path mover — `alongPath()`'s animated twin.- * The pose is a pure function of absolute `t`: no internal state, no- * `+=` drift, a closed loop wraps continuously by construction, and- * an open path ping-pongs instead of the modulo jump to its start.- *- * @param {number[][]|THREE.Vector3[]} points Control points.- * @param {object} [opts] `closed` (default true; false ping-pongs),- * `speed` metres per second (default 1), `forward` the asset's- * forward from assets_api.json, `wheels` array of `{node, radius}`- * rotated by arcDistance/radius so wheels roll exactly the ground- * they cover, `lane` signed metres of sideways offset (positive =- * left of travel; a ping-pong return leg flips sides, so a two-way- * path keeps its directions apart), `phase` 0..1 head start along- * the path. `lane`/`phase` are pure per-walker constants — several- * walkers may share one path without ever meeting, and `crowdOn()`- * does that assignment arithmetic for a whole crowd. `avoid` the- * scene (or an array of roots): the path is re-projected clear of- * furniture-scale solids at build time — pass it whenever a route- * crosses furnished space; `clearance` kept margin in metres- * (default 0.45).- * @returns {{length: number, curve: THREE.CatmullRomCurve3,- * poseAt: function}} `poseAt(t, obj, over)` places, orients and- * rolls `obj` at absolute time `t` and returns it; without `obj` it- * returns `{position, tangent, u}`. `over` is an optional per-call- * `{lane, phase}` override — how `crowdOn()` walks many figures on- * one shared curve.- */-/**- * Collect furniture-scale obstacle boxes under `avoid` — the SAME- * filter the renderer's mover-through-solid instrument uses, so what- * the path avoids and what the instrument flags stay one definition.- * Buildings are not obstacles (a covered lane sits INSIDE its bbox).- */-function obstacleBoxes(avoid) {- const solids = [];- const roots = Array.isArray(avoid) ? avoid : [avoid];- for (const root of roots) {- if (!root || !root.traverse) continue;- if (root.updateWorldMatrix) root.updateWorldMatrix(true, true);- root.traverse((o) => {- if (!o.isMesh || !visibleInTree(o) || solids.length >= 3000) return;- const nm = (o.name || (o.parent && o.parent.name) || '');- if (/ground|floor|terrain|road|path|water|sky|dome|wall|roof|ceiling/i- .test(nm)) return;- const b = new THREE.Box3().setFromObject(o);- if (b.isEmpty()) return;- const sx = b.max.x - b.min.x;- const sy = b.max.y - b.min.y;- const sz = b.max.z - b.min.z;- // Height alone is not architecture: fountains/columns/statues- // are tall AND collide — the footprint caps below are what- // separate an obstacle from a building.- if (sy < 0.3 || sy > 14) return;- if (Math.max(sx, sz) > 12 || sx * sz > 40) return;- if (Math.min(sx, sz) < 0.05) return;- solids.push(b);- });- }- return solids;-}--/** Push a point out of every expanded box via the cheapest face. */-function pushClear(p, solids, clearance) {- for (let iter = 0; iter < 3; iter++) {- let moved = false;- for (const b of solids) {- if (p.x < b.min.x - clearance || p.x > b.max.x + clearance ||- p.z < b.min.z - clearance || p.z > b.max.z + clearance) {- continue;- }- if (b.min.y > p.y + 1.2 || b.max.y < p.y - 1.2) continue;- const dxMin = p.x - (b.min.x - clearance);- const dxMax = (b.max.x + clearance) - p.x;- const dzMin = p.z - (b.min.z - clearance);- const dzMax = (b.max.z + clearance) - p.z;- const m = Math.min(dxMin, dxMax, dzMin, dzMax);- if (m === dxMin) p.x = b.min.x - clearance;- else if (m === dxMax) p.x = b.max.x + clearance;- else if (m === dzMin) p.z = b.min.z - clearance;- else p.z = b.max.z + clearance;- moved = true;- }- if (!moved) break;- }- return p;-}--/**- * Densify a path to ~0.75 m samples and push every blocked sample- * clear, so a leg that CROSSES a stall mid-segment reroutes around- * it — waypoint-only checks miss exactly that case.- */-function clearPath(pts, solids, clearance, closed) {- if (!solids.length || pts.length < 2) return pts;- const out = [];- const last = closed ? pts.length : pts.length - 1;- for (let i = 0; i < last; i++) {- const A = pts[i];- const B = pts[(i + 1) % pts.length];- const steps = Math.max(1, Math.ceil(A.distanceTo(B) / 0.75));- for (let k = 0; k < steps; k++) {- out.push(pushClear(A.clone().lerp(B, k / steps), solids, clearance));- }- }- if (!closed) out.push(pushClear(pts[pts.length - 1].clone(),- solids, clearance));- return out;-}--export function route(points, opts = {}) {- const closed = opts.closed !== false;- const speed = opts.speed === undefined ? 1 : opts.speed;- const lane0 = opts.lane === undefined ? 0 : opts.lane;- const phase0 = opts.phase === undefined ? 0 : opts.phase;- const wheels = opts.wheels || [];- let pts = points.map((p) => (p instanceof THREE.Vector3- ? p.clone() : new THREE.Vector3(...p)));- // `avoid: scene` makes furniture-clearance CONSTRUCTIVE: the path- // is re-projected off solids at build time, so a walker cannot- // stride through a stall whatever coordinates were authored.- if (opts.avoid) {- pts = clearPath(pts, obstacleBoxes(opts.avoid),- opts.clearance === undefined ? 0.45 : opts.clearance,- closed);- }- const curve = new THREE.CatmullRomCurve3(pts, closed);- const length = curve.getLength();- const poseAt = (t, obj, over) => {- const lane = over && over.lane !== undefined ? over.lane : lane0;- const phase = over && over.phase !== undefined ? over.phase : phase0;- const s = t * speed + phase * length;- let u = 0;- let dirSign = 1;- if (length > 1e-9) {- if (closed) {- u = ((s / length) % 1 + 1) % 1;- } else {- // Ping-pong: out along the path, back along the path — never- // the open-path modulo jump from the end to the start.- const p = ((s / length) % 2 + 2) % 2;- if (p <= 1) {- u = p;- } else {- u = 2 - p;- dirSign = -1;- }- }- }- const position = curve.getPointAt(u);- const tangent = curve.getTangentAt(u).multiplyScalar(dirSign);- if (lane) {- // Sideways offset in the horizontal plane, positive = left of- // travel; built from the dirSign-flipped tangent so a ping-pong- // path returns on its other side (two-way traffic self-separates).- const h = Math.hypot(tangent.x, tangent.z);- if (h > 1e-9) {- position.x += lane * (tangent.z / h);- position.z += lane * (-tangent.x / h);- }- }- if (!obj) return { position, tangent, u };- positionInWorld(obj, position);- alignAlong(obj, tangent, opts.forward);- // Roll from the arc distance actually COVERED, which on a ping-pong- // return leg decreases: `s` only ever grows, so a cart driving back- // along an open path spun its wheels forward while reversing- // (measured -0.4 m of travel against +0.8 rad of wheel, 2026-09-01).- // A closed loop keeps `s` — u wraps, and wrapping u would snap the- // wheel by length/radius once a lap.- const rolled = closed ? s : u * length;- for (const w of wheels) {- w.node.rotation.x = rolled / w.radius;- }- return obj;- };- return { length, curve, poseAt };-}--/**- * Give every figure on a shared route its own lane and phase, so a- * crowd can never bunch into one body. The guarantee is arithmetic,- * not a solver: one shared speed + equal phase slots keep the- * arc-length gap >= `spacing` forever (golden-ratio jitter is bounded- * by 80% of the slot slack, so it breaks the parade look without- * touching the bound); overflow opens parallel lanes at `laneStep`.- *- * @param {{length: number, poseAt: function}} routeObj From `route()`- * — one shared speed per route is what makes the gap permanent (two- * speeds on one path collide within seconds).- * @param {THREE.Object3D[]} figures The walkers, one entry each.- * @param {object} [opts] `spacing` minimum along-path gap in metres- * (default 2 — walker body plus clear air), `laneStep` sideways gap- * between overflow lanes (default 0.7 — shoulder width + margin).- * @returns {{assignments: Array<{lane: number, phase: number}>,- * tick: function}} `tick(t)` poses every figure at absolute time- * `t` (pure — call it from the scene's `tick`); `assignments` is- * the per-figure `{lane, phase}` in `figures` order, overriding the- * route's own `lane`/`phase` opts.- */-export function crowdOn(routeObj, figures, opts = {}) {- const spacing = opts.spacing === undefined ? 2 : opts.spacing;- const laneStep = opts.laneStep === undefined ? 0.7 : opts.laneStep;- const n = figures.length;- const cap = Math.max(1, Math.floor(routeObj.length / spacing));- const lanes = Math.max(1, Math.ceil(n / cap));- const per = Math.ceil(n / lanes);- const assignments = [];- for (let i = 0; i < n; i++) {- const k = Math.floor(i / per); // lane index- const j = i - k * per; // slot within the lane- const m = Math.min(per, n - k * per); // walkers in this lane- const slot = 1 / m;- const spacingU = Math.min(spacing / routeObj.length, slot);- // Jitter spends at most 80% of the slack, so the consecutive gap- // slot - 2*jit stays >= spacingU: the bound survives the jitter.- const jit = 0.4 * (slot - spacingU);- const eps = (((j * 0.618034) % 1) - 0.5) * 2 * jit;- assignments.push({- lane: (k - (lanes - 1) / 2) * laneStep,- phase: k * (slot / lanes) + j * slot + eps,- });- }- return {- assignments,- tick(t) {- for (let i = 0; i < n; i++) {- routeObj.poseAt(t, figures[i], assignments[i]);- }- return figures;- },- };-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.jsdeleted file mode 100644index 4c16fa33..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rain.js+++ /dev/null@@ -1,953 +0,0 @@-/**- * Rain: falling streaks, impact splashes on the surfaces the rain- * actually hits, a wet-material conversion and a rippling puddle.- * DOM-free (DataTexture only), seeded through mulberry32, no RTT and- * no post pass. Delivery frames are STILLS, so every effect must read- * FROZEN: streaks are drawn long, splash phases are spread across the- * field so all radii show at once, and puddle ripples displace real- * geometry. Drive each factory with `obj.userData.update(t)`. Rainfall uses- * local coordinates and supports transformed parents. Surface-baked splashes- * store world-space impact positions and belong at the scene root.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32, fbm2, noiseDataTexture } from './noise.js';-import { instancedQuad, intOption, makeShaderMaterial, keepOutOfDepthPasses, option, positive, readWind, vector } from './shader.js';--const _UP = new THREE.Vector3(0, 1, 0);--/**- * The scene's own air, read where every shader here already has it: the- * fog uniforms three refreshes each frame. Water is colourless — streak,- * ring and crown all show you the sky — so a hardcoded tint puts- * steel-blue rain in a golden dusk. `rainAirHue` takes the air's HUE at- * the caller's own luminance; `rainAirLit` its brightness, on a fourth- * root (a night scene is ~140x darker in linear light, and a plain- * multiply would delete the effect rather than dim it). `fogColor`- * exists only under USE_FOG: no fog, no change.- */-const _AIR_GLSL = [- 'vec3 rainAirHue(vec3 c, float k) {',- '#ifdef USE_FOG',- ' float l = max(dot(fogColor, vec3(0.2126, 0.7152, 0.0722)), 1e-4);',- ' return mix(c, c * (fogColor / l), k);',- '#else',- ' return c;',- '#endif',- '}',- 'float rainAirLit(float dim) {',- '#ifdef USE_FOG',- ' float a = max(dot(fogColor, vec3(0.2126, 0.7152, 0.0722)), 0.0);',- ' return mix(dim, 1.0, clamp(pow(a, 0.25), 0.0, 1.0));',- '#else',- ' return 1.0;',- '#endif',- '}',-].join('\n');--/** Raycaster includes invisible meshes and children of hidden groups. */-function visibleHit(hit) {- for (let object = hit.object; object; object = object.parent) {- if (!object.visible) return false;- }- const material = Array.isArray(hit.object.material)- ? hit.object.material[hit.face?.materialIndex ?? 0] : hit.object.material;- return material?.visible !== false;-}--/**- * Falling rain as ONE instanced mesh of camera-facing streaks.- *- * Each instance is a quad stretched along the fall vector and rolled- * to face the camera, which is what makes rain legible in a still: a- * frozen drop is a point, a frozen STREAK is rain. The field wraps- * modulo a box that follows the camera, so any authored or orbit- * camera sits inside the weather without the scene knowing where it is.- *- * @param {object} [opts]- * `seed` (default 5) mulberry32 seed;- * `count` (default 7000) streaks — one draw call regardless. The- * box is small on purpose: density where the camera is, not a- * thin sprinkle across a stadium;- * `radius` (default 16) half-extent in X/Z of the wrap box in- * metres — streaks fade out over its last 45%;- * `height` (default 18) its Y extent;- * `speed` (default 14) fall speed in m/s (drives lean and drift);- * `length` (default 0.6) streak length in metres — this is the- * "exposure", the single strongest still-frame knob;- * `width` (default 0.014) streak width in metres;- * `wind` (default [1.4, 0]) horizontal drift [x, z] in m/s, which- * also tilts the streaks off vertical;- * `color` (default 0xdbe6f2) streak tint at the HEAD of the streak;- * `rimColor` (default 0x0b111a) the tail tint — that dark trail is- * the only thing that prints rain on a sky the tone map has already- * pushed to 0.94;- * `air` (default 0.55) how far both tints follow the scene's fog hue- * (0 keeps `color` exactly): a golden dusk gets golden rain;- * `opacity` (default 0.42) peak alpha before distance fade;- * `follow` (default true) wrap the box around the camera; false pins- * it to `center`;- * `center` (default [0, height / 2, 0]) box centre when not following;- * `groundY` optional local ground cutoff;- * `surfaces` optional borrowed meshes/groups which shelter the rain;- * `heightAt(x,z)` optional local terrain-height callback, null means no hit;- * `shelterResolution` 8..64 (32), square height atlas samples;- * `shelterUpdateDistance` local camera travel before rebuilding (radius*.2).- * Shelter uses vertical height-field occlusion: no undercuts, sideways entry- * under overhangs or moving-surface dynamics. Resolution limits thin roofs and- * edge precision. Each rebuild casts at most resolution squared rays, with- * cost also depending on source geometry. Atlas bounds cover the rain box plus- * movement padding. Call userData.refreshShelter() after moving/editing/hiding- * source surfaces; the next render rebuilds. Camera travel and effect transforms- * refresh automatically. Source meshes/materials remain caller-owned.- * @returns {THREE.Mesh} Mesh named 'Rainfall', transparent and- * non-shadowing, with `userData.update(t)` advancing the fall.- */-export function makeRain(opts = {}) {- const seed = option(opts.seed, 5, 'makeRain: seed');- const count = intOption(opts.count, 7000, 'makeRain: count', 0, 1000000);- const radius = positive(opts.radius, 16, 'makeRain: radius');- const height = positive(opts.height, 18, 'makeRain: height');- const speed = positive(opts.speed, 14, 'makeRain: speed');- const length = positive(opts.length, 0.6, 'makeRain: length');- const width = positive(opts.width, 0.014, 'makeRain: width');- const w = readWind(opts.wind, [1.4, 0], 'makeRain wind'), wind = [w.x, w.z];- const opacity = option(opts.opacity, 0.42, 'makeRain: opacity', 0, 1);- const follow = opts.follow === false ? 0 : 1;- const center = vector(opts.center, [0, height * 0.5, 0], 3, 'makeRain: center');- const surfaces = opts.surfaces ?? [];- if (!Array.isArray(surfaces) || surfaces.some((surface) => !surface?.isObject3D)) {- throw new RangeError('makeRain: surfaces must be an array of Object3D');- }- if (opts.heightAt != null && typeof opts.heightAt !== 'function') {- throw new RangeError('makeRain: heightAt must be a function');- }- const shelterResolution = intOption(opts.shelterResolution, 32, 'makeRain: shelterResolution', 8, 64);- const shelterUpdateDistance = positive(opts.shelterUpdateDistance, Math.max(.5, radius * .20),- 'makeRain: shelterUpdateDistance');- const groundY = option(opts.groundY, -1e8, 'makeRain: groundY');- const rand = mulberry32(seed);- const inst = instancedQuad(count);- const off = new Float32Array(count * 3);- const ext = new Float32Array(count * 3);- for (let i = 0; i < count; i++) {- off[i * 3] = (rand() - 0.5) * 2 * radius;- off[i * 3 + 1] = rand() * height;- off[i * 3 + 2] = (rand() - 0.5) * 2 * radius;- ext[i * 3] = 0.55 + rand() * 0.6; // length scale- ext[i * 3 + 1] = 0.45 + rand() * 0.55; // brightness- // Hue jitter: a field of one tint is a hatch pattern.- ext[i * 3 + 2] = rand();- }- inst.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));- inst.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ext, 3));-- const mat = makeShaderMaterial({- name: 'Rainfall',- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- uniforms: {- // Declared and bound EXPLICITLY here and in both splash shaders:- // shader.js injects both, but glsl_audit.mjs reads the MODULE's- // source, and uTime undeclared there is two hard ERRORS in the- // scene build's preflight — every scene importing this file.- uTime: { value: 0 },- uCameraLocal: { value: new THREE.Vector3() },- uShelterMap: { value: null },- uShelterRect: { value: new THREE.Vector4() },- uHasShelter: { value: 0 },- uGroundY: { value: groundY },- uVel: { value: new THREE.Vector3(wind[0], -speed, wind[1]) },- uBox: { value: new THREE.Vector3(radius * 2, height, radius * 2) },- uCenter: { value: new THREE.Vector3(...center) },- uFollow: { value: follow },- uLen: { value: length },- uWidth: { value: width },- uFar: { value: radius },- uColor: {- value: new THREE.Color(- opts.color === undefined ? 0xdbe6f2 : opts.color),- },- uRim: {- value: new THREE.Color(- opts.rimColor === undefined ? 0x0b111a : opts.rimColor),- },- uAir: { value: opts.air === undefined ? 0.55 : opts.air },- uOpacity: { value: opacity },- },- varyings: 'varying vec2 vUv; varying float vFade; varying float vJit;',- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 iOff; attribute vec3 iExtra;',- 'uniform float uTime;',- 'uniform vec3 uVel; uniform vec3 uBox; uniform vec3 uCameraLocal;',- 'uniform vec3 uCenter; uniform float uFollow;',- 'uniform float uLen; uniform float uWidth; uniform float uFar;',- 'uniform sampler2D uShelterMap; uniform vec4 uShelterRect;',- 'uniform float uHasShelter; uniform float uGroundY;',- ].join('\n'),- vertexMain: [- ' vUv = uv; vJit = iExtra.z;',- ' vec3 anchor = mix(uCenter, uCameraLocal, uFollow);',- // Wrap the whole field into a box centred on the anchor: rain is- // everywhere the camera is, for a fixed instance budget.- ' vec3 p = mod(iOff + uVel * uTime - anchor + uBox * 0.5, uBox)',- ' - uBox * 0.5 + anchor;',- ' vec3 axis = normalize(uVel);',- ' vec3 toCam = p - uCameraLocal;',- ' float dist = length(toCam);',- ' vec3 side = cross(axis, toCam / max(dist, 1e-4));',- ' float sl = length(side);',- ' side = sl > 1e-4 ? side / sl : vec3(1.0, 0.0, 0.0);',- ' transformed = p + axis * (aCorner.y * uLen * iExtra.x)',- ' + side * (aCorner.x * uWidth);',- ' vFade = iExtra.y * smoothstep(1.0, 6.0, dist)',- ' * (1.0 - smoothstep(uFar * 0.55, uFar, dist));',- ' vec3 head = p + axis * (.5 * uLen * iExtra.x);',- ' float roof = uGroundY;',- ' if (uHasShelter > .5) {',- ' vec2 shelterUv = (head.xz - uShelterRect.xy) / uShelterRect.zw;',- ' if (all(greaterThanEqual(shelterUv, vec2(0.0))) &&',- ' all(lessThanEqual(shelterUv, vec2(1.0))))',- ' roof = max(roof, texture2D(uShelterMap, shelterUv).r);',- ' }',- ' vFade *= step(roof + .015, head.y);',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uColor; uniform vec3 uRim;',- 'uniform float uOpacity; uniform float uAir;',- _AIR_GLSL,- ].join('\n'),- fragmentMain: [- ' float core = smoothstep(0.0, 0.55,',- ' 1.0 - abs(vUv.x - 0.5) * 2.0);',- // v = 1 is the leading end (the axis points down): brightest- // there, tapered at both tips so the quad never reads as a bar.- ' float ends = smoothstep(0.0, 0.28, vUv.y)',- ' * (1.0 - smoothstep(0.70, 1.0, vUv.y));',- // HEAD BRIGHT, TAIL DARK — along the LENGTH: a streak is ~2 px- // wide, so a split across its width averages back to one tone in- // a single pixel. The head prints on anything dark, the tail is- // all that prints on a 0.94 sky (3/255 pale, 5-86 dark).- ' vec3 tint = uColor * mix(vec3(0.90, 0.97, 1.12),',- ' vec3(1.10, 1.00, 0.88), vJit);',- ' vec3 c = mix(rainAirHue(uRim, uAir), rainAirHue(tint, uAir),',- ' smoothstep(0.20, 0.92, vUv.y));',- ' float a = core * ends * (0.62 + 0.38 * vUv.y)',- ' * vFade * uOpacity;',- // A 0.6 m ramp bands into flat segments on a clean sky; dither.- ' a *= 0.97 + 0.06 * astraHash21(gl_FragCoord.xy);',- ' if (a < 0.004) discard;',- ' gl_FragColor = vec4(c, a);',- ].join('\n'),- });-- const mesh = new THREE.Mesh(inst, mat);- mesh.name = 'Rainfall';- mesh.frustumCulled = false; // positions live in the shader- mesh.renderOrder = 4; // in front of splashes and puddles- keepOutOfDepthPasses(mesh);- const beforeRender = mesh.onBeforeRender;- const shelter = makeShelterAtlas(mesh, {- surfaces, heightAt: opts.heightAt, groundY, resolution: shelterResolution,- distance: shelterUpdateDistance, radius, height, center, follow,- });- const inverse = new THREE.Matrix4();- mesh.onBeforeRender = (...args) => {- beforeRender.apply(mesh, args);- const camera = args[2];- inverse.copy(mesh.matrixWorld).invert();- camera.getWorldPosition(mat.uniforms.uCameraLocal.value).applyMatrix4(inverse);- shelter?.update(mat.uniforms.uCameraLocal.value, inverse);- };- mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };- const owned = snapshotResources(mesh);- if (shelter) owned.add(shelter.texture);- return attachDisposal(mesh, owned);-}---/** A bounded vertical height atlas; source surfaces remain caller-owned. */-function makeShelterAtlas(mesh, cfg) {- if (!cfg.surfaces.length && !cfg.heightAt) return null;- const n = cfg.resolution;- const data = new Float32Array(n * n).fill(cfg.groundY);- const texture = new THREE.DataTexture(data, n, n, THREE.RedFormat, THREE.FloatType);- texture.minFilter = texture.magFilter = THREE.NearestFilter;- texture.generateMipmaps = false;- texture.needsUpdate = true;- const uniforms = mesh.material.uniforms;- uniforms.uShelterMap.value = texture;- const rect = uniforms.uShelterRect.value;- const lastMatrix = new THREE.Matrix4();- const anchor = new THREE.Vector2(Infinity, Infinity);- const ray = new THREE.Raycaster();- const point = new THREE.Vector3(), hitLocal = new THREE.Vector3();- const box = new THREE.Box3(), corner = new THREE.Vector3();- const direction = new THREE.Vector3();- let dirty = true;- const info = { resolution: n, rebuilds: 0, raysPerRebuild: n * n, texelSize: 0 };- mesh.userData.shelter = info;- mesh.userData.refreshShelter = () => { dirty = true; };- mesh.userData.sampleShelterHeight = (x, z) => {- if (!Number.isFinite(x) || !Number.isFinite(z)) throw new RangeError('Rainfall.sampleShelterHeight: finite coordinates required');- if (!info.rebuilds || x < rect.x || x > rect.x + rect.z || z < rect.y || z > rect.y + rect.w) return null;- const ix = Math.min(n - 1, Math.floor((x - rect.x) / rect.z * n));- const iz = Math.min(n - 1, Math.floor((z - rect.y) / rect.w * n));- const value = data[iz * n + ix];- return value <= -1e7 ? null : value;- };- return {- texture,- update(cameraLocal, inverse) {- const x = cfg.follow ? cameraLocal.x : cfg.center[0];- const z = cfg.follow ? cameraLocal.z : cfg.center[2];- if (!dirty && Math.hypot(x - anchor.x, z - anchor.y) < cfg.distance && lastMatrix.equals(mesh.matrixWorld)) return;- const extent = 2 * (cfg.radius + cfg.distance + .5);- const texel = extent / n;- // Keep the lattice in fixed local coordinates while the atlas follows.- const cx = Math.round(x / texel) * texel, cz = Math.round(z / texel) * texel;- rect.set(cx - extent * .5, cz - extent * .5, extent, extent);- let top = Math.max(cfg.center[1], cameraLocal.y) + cfg.height;- for (const surface of cfg.surfaces) {- surface.updateWorldMatrix(true, true);- box.setFromObject(surface);- if (box.isEmpty()) continue;- for (let mask = 0; mask < 8; mask++) {- corner.set(mask & 1 ? box.max.x : box.min.x,- mask & 2 ? box.max.y : box.min.y, mask & 4 ? box.max.z : box.min.z)- .applyMatrix4(inverse);- top = Math.max(top, corner.y + 1);- }- }- direction.set(0, -1, 0).transformDirection(mesh.matrixWorld);- ray.ray.direction.copy(direction);- for (let row = 0; row < n; row++) for (let col = 0; col < n; col++) {- const px = rect.x + (col + .5) * texel, pz = rect.y + (row + .5) * texel;- let height = cfg.groundY;- if (cfg.heightAt) {- const sample = cfg.heightAt(px, pz);- if (sample != null && !Number.isFinite(sample)) throw new RangeError('Rainfall.heightAt must return a finite height or null');- if (sample != null) height = Math.max(height, sample);- }- if (cfg.surfaces.length) {- point.set(px, top, pz).applyMatrix4(mesh.matrixWorld);- ray.ray.origin.copy(point);- for (const hit of ray.intersectObjects(cfg.surfaces, true)) {- if (!visibleHit(hit)) continue;- hitLocal.copy(hit.point).applyMatrix4(inverse);- height = Math.max(height, hitLocal.y);- break;- }- }- data[row * n + col] = height;- }- texture.needsUpdate = true;- uniforms.uHasShelter.value = 1;- anchor.set(x, z);- lastMatrix.copy(mesh.matrixWorld);- dirty = false;- info.rebuilds++;- info.texelSize = texel;- info.bounds = [rect.x, rect.y, rect.x + extent, rect.y + extent];- },- };-}--/**- * Bake the splash crown alpha map — a starburst of thin rays rising- * from the bottom-centre impact point, with droplets at their tips.- *- * @param {number} [size] Cell width and height in px (default 64).- * @param {number} [variants] Grid side of an ATLAS of DIFFERENT crowns- * (default 1 — one crown, the whole texture). 2 bakes a 2x2 sheet of- * four, each with its own ray count, angles and rim shape;- * `makeSplashes` picks one per impact, which is what stops a field of- * 500 splashes reading as one stamp repeated 500 times. Every cell is- * transparent at its own border, so mips do not bleed across cells.- * @returns {THREE.DataTexture} White RGB, crowns in alpha,- * `size * variants` square.- */-export function splashTexture(size = 64, variants = 1) {- const n = Math.max(1, Math.round(variants));- const W = size * n;- const data = new Uint8Array(W * W * 4);- for (let cell = 0; cell < n * n; cell++) {- const rand = mulberry32(31 + cell * 977);- const rays = [];- // 6..9 rays: the count is half of what makes two crowns look unlike.- const nRays = 6 + Math.floor(rand() * 4);- for (let k = 0; k < nRays; k++) {- const a = Math.PI * (0.2 + 0.6 * (k + rand() * 0.6) / nRays);- rays.push([Math.cos(a), Math.sin(a), 0.34 + rand() * 0.32]);- }- const rw = 0.30 + rand() * 0.09; // rim half-width- const rh = 0.16 + rand() * 0.06; // rim height- const cx0 = (cell % n) * size;- const cy0 = Math.floor(cell / n) * size;- for (let y = 0; y < size; y++) {- for (let x = 0; x < size; x++) {- const px = (x / size - 0.5) * 2;- const py = y / size;- // The crown itself: an elliptical rim of water thrown up around- // the impact. Without it the rays read as a firework, not a- // drop.- const e = Math.hypot(px / rw, py / rh);- let a = 0.85 * Math.exp(-((e - 1) ** 2) / 0.05)- * Math.min(1, py / 0.03);- for (const [dx, dy, len] of rays) {- const t = px * dx + py * dy;- if (t <= 0 || t >= len) continue;- const d = Math.abs(px * dy - py * dx);- const w = 0.032 * (1 - 0.5 * t / len);- const ray = 0.85 * Math.exp(-(d * d) / (w * w)) * (1 - t / len);- const tip = 0.8 * Math.exp(- -((px - dx * len) ** 2 + (py - dy * len) ** 2) / 0.0009);- a = Math.max(a, ray + tip);- }- // The whole crown rises OUT of the surface, rays included: only- // the rim faded in at the contact line, so the bottom pixel row- // held alpha 34 under the impact — a hard stub, and on an atlas- // a mip-level leak into the cell below.- const i = ((cy0 + y) * W + cx0 + x) * 4;- data[i] = data[i + 1] = data[i + 2] = 255;- data[i + 3] = Math.round(- 255 * Math.max(0, Math.min(1, a * Math.min(1, py / 0.05))));- }- }- }- const tex = new THREE.DataTexture(data, W, W, THREE.RGBAFormat);- // DataTexture defaults to NearestFilter with no mipmaps; a 64px crown- // seen 20 m away then stair-steps into a cluster of hard blocks.- tex.minFilter = THREE.LinearMipmapLinearFilter;- tex.magFilter = THREE.LinearFilter;- tex.generateMipmaps = true;- tex.anisotropy = 8;- tex.needsUpdate = true;- return tex;-}--/**- * Sample impact points: raycast straight down onto real surfaces and- * fall back to the ground plane where nothing is in the way.- *- * @param {object} opts Same surface/area options as `makeSplashes`.- * @param {() => number} rand Seeded PRNG.- * @returns {Array<{p: THREE.Vector3, n: THREE.Vector3}>} World-space- * points already lifted off their surface, with world normals.- */-function _impactPoints(opts, rand) {- // A number is truthy, so `area: 12` used to read x/w as- // undefined and every impact landed at NaN — 520 of 780- // offsets non-finite, with 260 instances still drawn.- const area = typeof opts.area === 'number'- ? { x: 0, z: 0, w: opts.area, d: opts.area }- : (opts.area || { x: 0, z: 0, w: 40, d: 40 });- const y = opts.y === undefined ? 0 : opts.y;- const ground = opts.ground !== false;- const surfaces = opts.surfaces || [];- const count = opts.count === undefined ? 260 : opts.count;- const lift = opts.lift === undefined ? 0.012 : opts.lift;- const bias = opts.surfaceBias === undefined ? 0.5 : opts.surfaceBias;- const minNy = Math.cos(THREE.MathUtils.degToRad(- opts.maxSlopeDeg === undefined ? 65 : opts.maxSlopeDeg));-- const box = new THREE.Box3();- for (const s of surfaces) {- s.updateWorldMatrix(true, true);- box.expandByObject(s);- }- const hasBox = surfaces.length > 0 && !box.isEmpty();- const top = hasBox ? Math.max(box.max.y, y) + 1 : y + 1;-- const ray = new THREE.Raycaster(- new THREE.Vector3(), new THREE.Vector3(0, -1, 0));- const nm = new THREE.Matrix3();- const surfaceMatrix = new THREE.Matrix4();- const out = [];- // Rejections (steep faces, undersides) re-sample; the budget stops a- // scene whose only "surface" is a wall from looping forever.- const attempts = Math.max(1, count) * 8;- for (let a = 0; a < attempts && out.length < count; a++) {- let x, z;- // Aim a share of the samples INSIDE the surfaces' footprint, or a- // car in a 40 m plaza collects three drops and reads as dry.- if (hasBox && rand() < bias) {- x = box.min.x + rand() * (box.max.x - box.min.x);- z = box.min.z + rand() * (box.max.z - box.min.z);- } else {- x = area.x + (rand() - 0.5) * area.w;- z = area.z + (rand() - 0.5) * area.d;- }- let hit = null;- if (surfaces.length) {- ray.ray.origin.set(x, top, z);- for (const h of ray.intersectObjects(surfaces, true)) {- if (h.face && visibleHit(h)) { hit = h; break; }- }- }- if (hit) {- // InstancedMesh raycasts return geometry-local face normals. Include- // the individual transform before the object's world normal matrix,- // or tilted instances splash flat and steep ones evade maxSlopeDeg.- if (hit.instanceId !== undefined) {- hit.object.getMatrixAt(hit.instanceId, surfaceMatrix);- surfaceMatrix.premultiply(hit.object.matrixWorld);- } else surfaceMatrix.copy(hit.object.matrixWorld);- nm.getNormalMatrix(surfaceMatrix);- const n = hit.face.normal.clone().applyMatrix3(nm).normalize();- if (n.y < minNy) continue;- out.push({ p: hit.point.clone().addScaledVector(n, lift), n });- } else if (ground) {- out.push({ p: new THREE.Vector3(x, y + lift, z), n: _UP.clone() });- }- }- return out;-}--/**- * Splashes where the rain lands: an expanding ring flat on each- * surface plus a crown of spray standing up off it.- *- * Pass `surfaces` and the impacts are RAYCAST onto them, so drops land- * on the car roof, the bonnet and the umbrella at their real heights- * and tilts; everything the rays miss falls through to the `y` ground- * plane. Per-instance phases are spread over the whole cycle, so one- * frozen frame shows rings at every radius — that is what reads as- * continuous rainfall rather than one synchronized pulse.- *- * @param {object} [opts]- * `seed` (default 11) mulberry32 seed;- * `count` (default 260) impacts;- * `surfaces` (default none) meshes/groups to raycast onto;- * `surfaceBias` (default 0.5) share of samples aimed inside the- * surfaces' footprint instead of `area`;- * `area` (default `{x: 0, z: 0, w: 40, d: 40}`) ground sampling rect;- * `y` (default 0) ground plane height;- * `ground` (default true) let misses land on that plane;- * `maxSlopeDeg` (default 65) reject faces tilted past this — rain- * does not splash on walls or undersides;- * `size` (default 0.26) ring diameter in metres at full expansion;- * `rate` (default 2.2) splash cycles per second;- * `color` (default 0xe6eef7) ring and crown tint — thrown water is- * colourless, so it takes the scene's fog hue and dims with it;- * `air` (default 0.6) how far the tint follows that hue;- * `dim` (default 0.4) what it keeps in a black scene, on a fourth- * root — half, not 1/140th (it had white-hot crowns before);- * `variants` (default 2) grid side of the crown atlas (4 crowns),- * mirrored per instance for 8 apparent stamps;- * `opacity` (default 0.6) peak ring alpha;- * `crowns` (default true) add the upright spray billboards;- * `crownScale` (default 1) multiplies crown size relative to `size`;- * `lift` (default 0.012) metres pushed along the normal (z-fighting).- * @returns {THREE.Group} Group named 'RainSplashes' holding- * 'SplashRings' (+ 'SplashCrowns'), world-space — add it at the- * scene ROOT — with `userData.update(t)` driving both.- */-export function makeSplashes(opts = {}) {- const rand = mulberry32(opts.seed === undefined ? 11 : opts.seed);- const size = opts.size === undefined ? 0.26 : opts.size;- const rate = opts.rate === undefined ? 2.2 : opts.rate;- const opacity = opts.opacity === undefined ? 0.6 : opts.opacity;- const color = new THREE.Color(- opts.color === undefined ? 0xe6eef7 : opts.color);- const group = new THREE.Group();- group.name = 'RainSplashes';-- const pts = _impactPoints(opts, rand);- if (!pts.length) {- group.userData.update = () => {};- return attachDisposal(group, snapshotResources(group));- }-- const n = pts.length;- const variants = Math.max(1, Math.round(- opts.variants === undefined ? 2 : opts.variants));- const off = new Float32Array(n * 3);- const nrm = new Float32Array(n * 3);- const tan = new Float32Array(n * 3);- const ext = new Float32Array(n * 4);- const t = new THREE.Vector3();- pts.forEach((q, i) => {- off[i * 3] = q.p.x; off[i * 3 + 1] = q.p.y; off[i * 3 + 2] = q.p.z;- nrm[i * 3] = q.n.x; nrm[i * 3 + 1] = q.n.y; nrm[i * 3 + 2] = q.n.z;- t.set(0, 0, 1).cross(q.n);- if (t.lengthSq() < 1e-8) t.set(1, 0, 0);- t.normalize();- tan[i * 3] = t.x; tan[i * 3 + 1] = t.y; tan[i * 3 + 2] = t.z;- ext[i * 4] = size * (0.65 + rand() * 0.7);- ext[i * 4 + 1] = rand(); // phase: spread so a still shows all radii- // Hue and the crown's mirror flip; the cell is drawn separately so- // the two never correlate into a pattern.- ext[i * 4 + 2] = rand();- ext[i * 4 + 3] = Math.floor(rand() * variants * variants);- });- const attrs = (geom) => {- geom.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));- geom.setAttribute('iNrm', new THREE.InstancedBufferAttribute(nrm, 3));- geom.setAttribute('iTan', new THREE.InstancedBufferAttribute(tan, 3));- geom.setAttribute('iExtra',- new THREE.InstancedBufferAttribute(ext, 4));- return geom;- };- const air = opts.air === undefined ? 0.6 : opts.air;- const dim = opts.dim === undefined ? 0.4 : opts.dim;-- const ringMat = makeShaderMaterial({- name: 'SplashRings',- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- uniforms: {- uTime: { value: 0 }, // see makeRain: the audit reads this file- uRate: { value: rate },- uColor: { value: color },- uOpacity: { value: opacity },- uAir: { value: air },- uDim: { value: dim },- },- varyings: [- 'varying vec2 vUv; varying float vPhase; varying float vJit;',- ].join('\n'),- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 iOff; attribute vec3 iNrm; attribute vec3 iTan;',- 'attribute vec4 iExtra;',- ].join('\n'),- vertexMain: [- ' vUv = uv; vPhase = iExtra.y; vJit = iExtra.z;',- ' vec3 b = cross(iNrm, iTan);',- ' transformed = iOff + iTan * (aCorner.x * iExtra.x)',- ' + b * (aCorner.y * iExtra.x);',- ].join('\n'),- fragmentHead: [- 'uniform float uTime; uniform float uRate;',- 'uniform vec3 uColor; uniform float uOpacity;',- 'uniform float uAir; uniform float uDim;',- _AIR_GLSL,- ].join('\n'),- fragmentMain: [- ' float r = length(vUv * 2.0 - 1.0);',- ' if (r > 1.0) discard;',- ' float k = fract(vPhase + uTime * uRate);',- // Two crests, the trailing one fainter: one lone circle reads as- // a decal, a pair reads as a wave leaving the impact.- ' float w = 0.09 + 0.15 * k;',- ' float f = (r - k) / w;',- ' float g = (r - k * 0.55) / (w * 0.8);',- ' float a = (exp(-f * f) + 0.45 * exp(-g * g))',- ' * (1.0 - k) * (1.0 - smoothstep(0.72, 1.0, r))',- ' * uOpacity;',- // Two gaussians on flat road band; a fraction of a step hides it.- ' a *= 0.96 + 0.08 * astraHash21(gl_FragCoord.xy);',- ' if (a < 0.004) discard;',- // A sheet of water lifting off the ground shows you the sky.- ' vec3 c = rainAirHue(uColor, uAir) * rainAirLit(uDim)',- ' * (0.88 + 0.24 * vJit);',- ' gl_FragColor = vec4(c, a);',- ].join('\n'),- });- const rings = new THREE.Mesh(attrs(instancedQuad(n)), ringMat);- rings.name = 'SplashRings';- rings.frustumCulled = false;- rings.renderOrder = 2;- group.add(rings);-- let crownMat = null;- if (opts.crowns !== false) {- crownMat = makeShaderMaterial({- name: 'SplashCrowns',- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- uniforms: {- uTime: { value: 0 }, // see makeRain- uRate: { value: rate },- uColor: { value: color },- uScale: {- value: (opts.crownScale === undefined ? 1 : opts.crownScale)- * 0.7,- },- uAtlas: { value: variants },- uAir: { value: air },- uDim: { value: dim },- map: { value: splashTexture(64, variants) },- },- varyings: [- 'varying vec2 vUv; varying float vK;',- 'varying float vJit; varying float vCell;',- ].join('\n'),- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 iOff; attribute vec3 iNrm;',- 'attribute vec4 iExtra;',- 'uniform float uTime; uniform float uRate; uniform float uScale;',- ].join('\n'),- vertexMain: [- ' vUv = uv; vJit = iExtra.z; vCell = iExtra.w;',- ' float k = fract(iExtra.y + uTime * uRate);',- ' vK = k;',- // Crowns pop fast and settle: sqrt growth, so a frozen frame- // catches most of them already open rather than as specks.- ' float s = iExtra.x * uScale * (0.3 + 0.9 * sqrt(k));',- ' vec3 up = iNrm;',- ' vec3 view = normalize(iOff - cameraPosition);',- ' vec3 right = cross(up, view);',- ' float rl = length(right);',- ' right = rl > 1e-4 ? right / rl : vec3(1.0, 0.0, 0.0);',- ' transformed = iOff + right * (aCorner.x * s)',- ' + up * ((aCorner.y + 0.5) * s);',- ].join('\n'),- fragmentHead: [- 'uniform sampler2D map; uniform vec3 uColor;',- 'uniform float uAtlas; uniform float uAir; uniform float uDim;',- _AIR_GLSL,- ].join('\n'),- fragmentMain: [- // ONE stamp repeated 500 times is the tell of an instanced- // field, and a crown is a shape the eye knows. Mirror per- // instance, then pick an atlas crown: 4 x 2 handednesses.- ' vec2 cuv = vec2(mix(vUv.x, 1.0 - vUv.x, step(0.5, vJit)),',- ' vUv.y);',- ' float cell = floor(vCell + 0.5);',- ' vec2 g = vec2(mod(cell, uAtlas), floor(cell / uAtlas));',- ' float a = texture2D(map, (cuv + g) / uAtlas).a',- ' * pow(1.0 - vK, 1.6) * smoothstep(0.0, 0.06, vK);',- ' if (a < 0.01) discard;',- // Spray is water in the air: the sky's hue, the sky's light —- // left white it was the brightest thing in a night frame.- ' vec3 c = rainAirHue(uColor, uAir) * rainAirLit(uDim)',- ' * (0.86 + 0.28 * fract(vJit * 7.3));',- ' gl_FragColor = vec4(c, a);',- ].join('\n'),- });- const crowns = new THREE.Mesh(attrs(instancedQuad(n)), crownMat);- crowns.name = 'SplashCrowns';- crowns.frustumCulled = false;- crowns.renderOrder = 3;- group.add(crowns);- }-- group.userData.update = (t2) => {- ringMat.uniforms.uTime.value = t2;- if (crownMat) crownMat.uniforms.uTime.value = t2;- };- const owned = snapshotResources(group);- if (crownMat) owned.add(crownMat.uniforms.map.value);- return attachDisposal(keepOutOfDepthPasses(group), owned);-}--/**- * Wet a material (or every material under an object) IN PLACE: darker- * albedo, near-mirror roughness, stronger environment reflection.- *- * That triple is what "it has been raining" looks like — a wet surface- * absorbs more light AND reflects the sky harder at once, so darkening- * alone just reads as a repaint. Mutates in place like- * `materials.weather()`, so a material SHARED with dry objects wets- * them too — clone first when that matters.- *- * @param {THREE.Material|THREE.Object3D} target Material, or an object- * whose meshes' materials are all wetted (each one once).- * @param {number} [amount] 0..1 soak, default 0.7.- * @param {object} [opts] `minRoughness` (default 0.1) the wettest a- * surface may get; `darken` (default 0.45) peak albedo loss;- * `envGain` (default 0.6) peak envMapIntensity boost — three scales- * the DIFFUSE irradiance with it too, so a big gain LIGHTS the object- * up: at 1.2 the wet car roof measured 0.613 against a 0.568 dry- * control and read as white plastic. Keep `(1 - darken) * (1 +- * envGain)` under 1; `roughFactor` (default 0.25) share of its own- * roughness a surface keeps — a soaked brick is a damp sheen, and one- * flat floor made brick, dirt and paint identical; `floor` (default- * 0.02) darkest albedo a soak may leave, in linear light (a wet tyre- * sat at 0.0006 of a night frame: a hole, not a surface).- * @returns {THREE.Material|THREE.Object3D} The same target.- */-export function wetten(target, amount = 0.7, opts = {}) {- const k = Math.max(0, Math.min(1, amount));- const minRough = opts.minRoughness === undefined ? 0.1- : opts.minRoughness;- const darken = opts.darken === undefined ? 0.45 : opts.darken;- const envGain = opts.envGain === undefined ? 0.6 : opts.envGain;- const roughFactor = opts.roughFactor === undefined ? 0.25- : opts.roughFactor;- const floor = opts.floor === undefined ? 0.02 : opts.floor;-- const wetOne = (mat) => {- if (!mat) return;- if (mat.color) {- mat.color.multiplyScalar(1 - darken * k);- // A film makes a colour READ deeper, not just darker: it kills- // the diffuse haze washing the pigment out. A scalar multiply- // alone is a neutral-density filter.- mat.color.offsetHSL(0, 0.06 * k, 0);- const m = Math.max(mat.color.r, mat.color.g, mat.color.b);- if (m > 1e-6 && m < floor) mat.color.multiplyScalar(floor / m);- }- if (typeof mat.roughness === 'number') {- const wet = Math.max(minRough, mat.roughness * roughFactor);- mat.roughness = mat.roughness + (wet - mat.roughness) * k;- }- if (typeof mat.envMapIntensity === 'number') {- mat.envMapIntensity *= 1 + envGain * k;- }- // Water fills the micro-relief it is sitting in.- if (typeof mat.bumpScale === 'number') mat.bumpScale *= 1 - 0.6 * k;- if (mat.isMeshPhysicalMaterial) {- mat.clearcoat = Math.max(mat.clearcoat || 0, k);- mat.clearcoatRoughness = Math.min(- mat.clearcoatRoughness === undefined ? 1 : mat.clearcoatRoughness,- 0.04 + 0.1 * (1 - k));- }- mat.needsUpdate = true;- };-- if (target && target.isMaterial) {- wetOne(target);- return target;- }- if (target && target.isObject3D) {- const seen = new Set();- target.traverse((o) => {- if (!o.isMesh || !o.material) return;- for (const m of (Array.isArray(o.material) ? o.material- : [o.material])) {- if (m && !seen.has(m.uuid)) { seen.add(m.uuid); wetOne(m); }- }- });- }- return target;-}--/**- * Standing water with rain ripples — concentric wavefronts spreading- * from drops that keep landing in new places.- *- * The ripples are REAL vertex displacement, not a normal map, so the- * scene's own lights and environment carry them; a still frame catches- * several rings mid-expansion because the drops are phase-staggered.- * Crest vertices are also brightened through vertex colours — and- * TINTED with them, cool on the crests that tip toward the sky, warm in- * the troughs that show the bed — so the rings stay legible under flat- * overcast light and the pool never reads as one flat hue.- *- * @param {number} w Puddle width (X) in metres.- * @param {number} d Puddle depth (Z) in metres.- * @param {object} [opts]- * `seed` (default 3) mulberry32 seed;- * `segments` (default: derived as 4 samples per wavelength, 24-96)- * grid resolution per axis — a ripple the mesh cannot resolve- * flattens into an invisible one, so raise `wavelength` rather- * than the cap on a large pool;- * `drops` (default 8) simultaneous ripple sources;- * `amplitude` (default 0.006) crest height in metres;- * `wavelength` (default 0.3) metres between crests;- * `speed` (default 0.7) wavefront speed in m/s;- * `life` (default 2.6) seconds a ripple lives before its drop- * relands elsewhere;- * `color` (default 0x121820) water tint (dark: depth IS the darkness);- * `roughness` (default 0.07) low so the sky reflects;- * `mask` (default true) fade the rectangle out with a seeded fBm- * alpha so the puddle has an organic shoreline.- * @returns {THREE.Mesh} Mesh named 'Puddle' lying at y = 0 (position it- * just above the road), with `userData.update(t)` driving the ripples;- * already stepped to t = 0, so it is never flat.- */-export function makePuddle(w, d, opts = {}) {- const seed = opts.seed === undefined ? 3 : opts.seed;- const drops = opts.drops === undefined ? 8 : opts.drops;- const amp = opts.amplitude === undefined ? 0.006 : opts.amplitude;- const lambda = opts.wavelength === undefined ? 0.3 : opts.wavelength;- // Four samples per wavelength or the rings alias flat; capped- // because every vertex is re-evaluated on the CPU each update.- const seg = opts.segments === undefined- ? Math.max(24, Math.min(96, Math.round(Math.max(w, d) * 4 / lambda)))- : opts.segments;- const speed = opts.speed === undefined ? 0.7 : opts.speed;- const life = opts.life === undefined ? 2.6 : opts.life;-- const geom = new THREE.PlaneGeometry(w, d, seg, seg);- geom.rotateX(-Math.PI / 2);- const pos = geom.attributes.position;- const col = new Float32Array(pos.count * 3).fill(1);- geom.setAttribute('color', new THREE.BufferAttribute(col, 3));-- const mat = new THREE.MeshStandardMaterial({- color: opts.color === undefined ? 0x121820 : opts.color,- roughness: opts.roughness === undefined ? 0.07 : opts.roughness,- metalness: 0, // water is a dielectric; metalness makes dirty chrome- vertexColors: true,- envMapIntensity: 1.6,- });- if (opts.mask !== false) {- mat.transparent = true;- mat.alphaMap = noiseDataTexture(128, (u, v) => {- const r = Math.hypot(u - 0.5, v - 0.5) * 2;- const k = 1 - r + 0.42 * fbm2(u * 3.4, v * 3.4, { seed });- return Math.max(0, Math.min(1, (k - 0.18) * 3.2));- });- }-- // Each source relands every `life` seconds; the cycle index seeds- // where, so the puddle is not eight fixed drip points forever.- const offs = [];- const rand = mulberry32(seed);- for (let i = 0; i < drops; i++) offs.push(rand());- const cache = offs.map(() => ({ cyc: NaN, x: 0, z: 0, r: 0, fade: 0 }));- const sigma = lambda * 1.1;- const k2 = (Math.PI * 2) / lambda;-- const update = (t) => {- for (let i = 0; i < drops; i++) {- const phase = t / life + offs[i];- const cyc = Math.floor(phase);- const c = cache[i];- if (c.cyc !== cyc) {- const r = mulberry32((seed + i * 7919 + cyc * 104729) | 0);- c.cyc = cyc;- c.x = (r() - 0.5) * w;- c.z = (r() - 0.5) * d;- }- c.r = (phase - cyc) * life * speed; // wavefront radius- c.fade = 1 - (phase - cyc);- }- for (let vi = 0; vi < pos.count; vi++) {- const x = pos.getX(vi), z = pos.getZ(vi);- // Wind chop: rain-struck water is never glassy between drops.- let h = amp * 0.22 * Math.sin(x * 11.3 + t * 3.1) *- Math.sin(z * 9.7 - t * 2.6);- for (let i = 0; i < drops; i++) {- const c = cache[i];- const dist = Math.hypot(x - c.x, z - c.z);- const f = dist - c.r;- if (f > 3 * sigma || f < -3 * sigma) continue;- h += amp * Math.cos(f * k2) * Math.exp(-(f * f) / (2 * sigma * sigma))- * c.fade / (1 + dist * 1.4);- }- pos.setY(vi, h);- // Crest and trough are not the same water: a crest tips toward- // the sky it mirrors and goes cool, a trough shows the warm bed.- // One achromatic multiply left the pool on a single flat hue.- const s = amp > 0 ? h / amp : 0;- const b = Math.max(0.72, Math.min(1.35, 1 + s * 0.14));- const w = Math.max(0, Math.min(1, 0.5 + 0.5 * s));- col[vi * 3] = b * (1.06 - 0.12 * w);- col[vi * 3 + 1] = b * (1.005 - 0.01 * w);- col[vi * 3 + 2] = b * (0.94 + 0.12 * w);- }- pos.needsUpdate = true;- geom.attributes.color.needsUpdate = true;- geom.computeVertexNormals();- };-- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Puddle';- mesh.receiveShadow = true;- mesh.userData.update = update;- update(0);- const owned = snapshotResources(mesh);- if (mat.alphaMap) owned.add(mat.alphaMap);- return attachDisposal(mesh, owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.jsindex c58d2ed5..84a3f4ef 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/rock.js@@ -307,7 +307,7 @@ export function makeRock(opts = {}) {/** Seeded scatter; heightAt(x,z) is local to the returned group. Each rock owns* its geometry and material; cap count for close foreground dressing, use- * instancing.js for distant repetitions of a few shared prototypes.+ * InstancedMesh for distant repetitions of a few shared prototypes.*/export function makeRockField(opts = {}) {const rand = mulberry32(option(opts.seed, 31, 'makeRockField: seed')), group = new THREE.Group();diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.jsindex 956e53bb..53c5a103 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/shader.js@@ -234,7 +234,7 @@ export function seedVec3(s, a, b, c, k) {/*** The library's ONE azimuth/elevation -> direction rule: azimuth in degrees* from +X toward +Z (0 = +X, 90 = +Z), elevation in degrees above the- * horizon. sunRig, makeSky, the moon, establishingShot's eye and every+ * horizon. sunRig, makeSky, the moon and every* default sun use it, so an angle means the same thing to all of them.*/export function sunVector(azDeg, elDeg) {@@ -699,7 +699,7 @@ export function makeShaderMaterial(opts = {}) {if (!vs.includes(LOG_V)) vs = intoMainEnd(vs, LOG_V);// Raw sources opt out the same way: the trap does not care who// wrote the shader, and neither does the checker.- if (!fog && !/(3dcode|astra3d): no-fog/.test(fs)) {+ if (!fog && !/3dcode: no-fog/.test(fs)) {fs = '// 3dcode: no-fog\n' + fs;}if (!fs.includes(LOG_PARS_F)) fs = '#include <common>\n' + LOG_PARS_F + '\n' + fs;@@ -1145,37 +1145,6 @@ export function composeRoughness(material, key, factor, floor = 0.04) {return material.roughness;}-/** The roughness the material was AUTHORED with, before any cover. */-export function baseRoughness(material) {- const store = material.userData.astraRoughness;- return store ? store.base : material.roughness;-}--/**- * A roughening factor one patch cannot push past fully rough.- *- * Roughness only means anything up to 1, and the material may start- * near it.- */-export function matteFactor(material, add) {- const base = baseRoughness(material);- return base > 0 ? Math.min(1 + add, 1 / base) : 1;-}--/**- * Move the material's gloss toward a cover's, never past it.- *- * Roughness is per MATERIAL here, so a cover can only say how much of- * the surface is no longer the material: `blend` 0 leaves it alone, 1- * hands the whole material to the cover's own roughness.- */-export function towardRoughness(material, target, blend) {- const base = baseRoughness(material);- if (!(base > 0)) return 1;- return 1 + (target / base - 1) * unit(blend);-}--/*** Drive every astra shader under `root` from one call in `update`.*diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.jsdeleted file mode 100644index 8ec7a590..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/signage.js+++ /dev/null@@ -1,301 +0,0 @@-/**- * Readable lettering: real extruded glyphs from the fonts the npm- * three package already ships — no new deps, no import-map edits.- * The load path is DUAL-RUNTIME and both halves are load-bearing:- * headless Chrome fetches over HTTP, plain node (census / assets_api)- * reads the same file off disk. `makeText` is async: await ONCE at- * module top level, `.clone()` per copy inside `build()`.- *- * Font path, ported 2026-09-01 — BOTH halves were broken on this host,- * because both assumed a `node_modules` next to the app:- * · browser — the workspace is served at `/` and three at- * `/__runtime/node_modules/`, so `../../node_modules/...` 404d and- * the module only survived by falling through to its CDN pin: it- * did not work offline, and the harness counts every 404 as a- * console error (2 per render, run marked not-ok).- * · node — a workspace / test probe has no parent `node_modules` at- * all, so `createRequire().resolve('three/examples/fonts/…')` threw- * MODULE_NOT_FOUND and every census-side makeText died.- * Both now ask `import.meta.resolve` where `three` itself came from —- * the page's import map in Chrome, the module resolver (our- * `resolve_three.mjs` hook included) in node — and the old guesses are- * kept as later candidates for the reference app's own layout.- *- * Grading, same pass: extruded letters lit only by sky + environment —- * the normal case, since a sign faces the viewer and the sun rarely- * does — used to read as a flat pale cutout. The glyphs now carry a- * paint-variance vertex colour (mottle + weathering + darker extrusion- * walls + a bright bevel rim), so the depth reads without a key light,- * they cast shadows by default, and an emissive sign carries its own- * practical so it LIGHTS the board it is bolted to instead of sitting- * on it as a decal.- */--import * as THREE from 'three';-import { attachDisposal } from './lifecycle.js';-import { FontLoader } from 'three/addons/loaders/FontLoader.js';-import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';--const FONT_FILES = {- regular: 'helvetiker_regular.typeface.json',- bold: 'helvetiker_bold.typeface.json',-};--// The reference kept a CDN pin here as a last resort. It is deleted:-// this contract forbids the network outright, the run is offline, and-// the only thing it ever did on this host was mask the `../../node_modules`-// 404 that `import.meta.resolve` (above) now resolves properly.-const IS_NODE = typeof process !== 'undefined' &&- !!(process.versions && process.versions.node);--const _fontCache = new Map();--/** Font URLs to try, best first — ONE list for both runtimes.- * `import.meta.resolve` answers from the page's import map in Chrome and- * from the module resolver (our `resolve_three.mjs` hook included) in- * node, so "wherever three itself came from" is the same question in- * both, and this module has already proved three resolves: it imports- * it at the top. Everything after those two entries is a guess kept- * for other layouts. */-function _fontUrls(file) {- const urls = [];- const add = (u) => { if (u && urls.indexOf(u) === -1) urls.push(u); };- const resolve = (typeof import.meta.resolve === 'function')- ? import.meta.resolve : null;- if (resolve) {- try {- // examples/jsm/loaders/FontLoader.js -> examples/fonts/- add(new URL('../../fonts/' + file,- resolve('three/addons/loaders/FontLoader.js')).href);- } catch (_e) { /* no such entry — try the next form */ }- try {- // build/three.module.js -> examples/fonts/- add(new URL('../examples/fonts/' + file, resolve('three')).href);- } catch (_e) { /* ditto */ }- }- // a node_modules sibling of src/ (the reference app's own layout)- add(new URL('../../node_modules/three/examples/fonts/' + file,- import.meta.url).href);- return urls;-}--async function _loadFontJson(file) {- const tried = [];- const urls = _fontUrls(file);- if (IS_NODE) {- // an app whose node_modules is a PARENT of this file resolves the- // font through the three exports map; a bare workspace (our runs,- // the test probes) does not, and falls back to the URL list.- try {- const { createRequire } = await import('node:module');- urls.push(createRequire(import.meta.url)- .resolve('three/examples/fonts/' + file));- } catch (_e) { /* no parent node_modules */ }- }- for (const url of urls) {- try {- if (IS_NODE && !/^https?:/.test(url)) {- const { readFile } = await import('node:fs/promises');- const { fileURLToPath } = await import('node:url');- const p = url.startsWith('file:') ? fileURLToPath(url) : url;- return JSON.parse(await readFile(p, 'utf-8'));- }- const r = await fetch(url);- if (!r.ok) throw new Error('HTTP ' + r.status);- return await r.json();- } catch (e) {- tried.push(url + ': ' + ((e && e.message) || e));- }- }- throw new Error('font load failed: ' + file + ' [' + tried.join(' | ') + ']');-}--/**- * Load a shipped helvetiker font, cached per variant.- *- * @param {object} [opts] `bold` (default false) picks the bold face.- * @returns {Promise<object>} A parsed `Font` for TextGeometry.- */-export function loadHelvetiker(opts = {}) {- const file = FONT_FILES[opts.bold ? 'bold' : 'regular'];- let p = _fontCache.get(file);- if (!p) {- p = _loadFontJson(file).then((json) => new FontLoader().parse(json));- _fontCache.set(file, p);- }- return p;-}--/**- * Paint variance as a vertex colour, in place. Deterministic (a pure- * function of position + normal), so a re-render of the same string is- * byte-identical. Three parts, all measured on this pipeline against- * a sign lit by sky + environment only:- * · mottle — two sine octaves in glyph-relative units; paint, print- * and enamel are never one flat value, and the variance is what- * stops a big letter from reading as a screen-space cutout- * · weathering — the bottom of a letter is dirtier than its top- * · form — the extrusion WALLS go down to 0.80 (they see far less- * sky than the face) while the BEVEL rim, which does catch it,- * goes up to +10 %. Both are read off |n.z|, so this needs no- * material groups and survives any bevel setting.- */-const MOTTLE = 0.070; // paint value swing, +/- (peak |m| is ~1.02)-const MOTTLE_HUE = 0.034; // warm/cool swing riding the same signal-// Everything below is NORMALISED to a ceiling of exactly 1.0, so a vertex-// colour can only ever DARKEN: `color` stays the true albedo (the brief's-// 0.02-0.8 linear band is a ceiling, and a rim that multiplied it by 1.14-// would have quietly broken it).-const FORM_PEAK = 1 + 0.10;-const MOTTLE_PEAK = (1 + MOTTLE * 1.02) * (1 + MOTTLE_HUE * 1.02);--function _paintVariance(geo, size, amount) {- const pos = geo.attributes.position;- const nrm = geo.attributes.normal;- if (!pos || !nrm) return;- const n = pos.count;- const col = new Float32Array(n * 3);- const s = 1 / Math.max(size, 1e-4);- for (let i = 0; i < n; i++) {- const x = pos.array[i * 3] * s;- const y = pos.array[i * 3 + 1] * s;- const nz = Math.abs(nrm.array[i * 3 + 2]);-- // mottle in [-1, 1]-ish, hue-signed: warm where the paint is thick- const m = 0.46 * Math.sin(x * 2.7 + 0.9) +- 0.26 * Math.sin(x * 7.3 + y * 3.1 + 2.1) +- 0.30 * Math.sin(y * 4.6 - 1.3);- // grime in the first 0.35 of cap height- const grime = 1 - 0.06 * Math.max(0, 1 - Math.max(0, y) / 0.35);- // form: walls dark, bevel rim the brightest thing on the glyph- const wall = 1 - Math.min(1, nz * 1.6);- const rim = 4 * nz * (1 - nz);- const form = (1 - 0.22 * wall + 0.10 * rim) / FORM_PEAK;-- const v = (1 + MOTTLE * m) * grime * form / MOTTLE_PEAK;- const hue = MOTTLE_HUE * m;- // `amount` lerps the whole thing back towards flat white- col[i * 3] = 1 + amount * (v * (1 + hue) - 1);- col[i * 3 + 1] = 1 + amount * (v - 1);- col[i * 3 + 2] = 1 + amount * (v * (1 - hue) - 1);- }- geo.setAttribute('color', new THREE.BufferAttribute(col, 3));-}--/**- * Build one line of real extruded 3D text: centered on X/Z, BASELINE- * at y = 0, facing +Z (`userData.size` carries the measured bbox).- *- * @param {string} str One line of text (no newlines — stack meshes for- * multiple lines).- * @param {object} [opts] `size` glyph height in metres (default 1);- * `depth` extrusion depth (default 0.15 * size); `bold` (default- * false); `bevel` (default true — softened edges, razor edges read- * as CG, and the bevel rim is where a sky-lit letter gets its- * catchlight); `curveSegments` (default 8); `color` (default- * 0xe7e3da — a paint white: 0xffffff-class albedo bakes a letter to- * a flat blown slab under ACES at exposure 1.0), `roughness`- * (default 0.45), `metalness` (default 0.1); `variation` 0..1- * (default 1) scales the baked paint mottle / wall shading, 0 drops- * the vertex colours entirely (a `material` you pass in reads them- * only if it sets `vertexColors`); `emissive` + `emissiveIntensity`- * (default 1.6 when emissive is set — the post chain's bloom only- * adds a soft halo, so 1.5-4 is the whole usable range and 20 is a- * white blob) make a neon / backlit sign; `light` the practical an- * emissive sign throws on its own board — `false` to drop it (do- * that for a facade carrying dozens of signs: this is one real- * PointLight per line), a number to set its candela directly. The- * default is derived — `1.8 * emissiveIntensity * inked area` —- * measured on a 0.42 m OPEN sign 0.4 m off its board: at night the- * board just above it went from r 0.174 / warmth +0.023 to r 0.265 /- * warmth +0.108, and by day the sun still owns the frame;- * `shadow: false` opts out of- * cast/receive shadows (on by default — the glyph shadow on the- * board is what says "extruded", not "decal"); `material` replaces- * the built material entirely; `font` supplies a pre-loaded Font and- * skips loading.- * @returns {Promise<THREE.Mesh>} Mesh named `SignText`; the practical,- * when there is one, is `mesh.userData.light`.- */-export async function makeText(str, opts = {}) {- const font = opts.font || await loadHelvetiker({ bold: !!opts.bold });- const size = opts.size === undefined ? 1 : opts.size;- const depth = opts.depth === undefined ? 0.15 * size : opts.depth;- const bevel = opts.bevel === undefined ? true : !!opts.bevel;-- const geo = new TextGeometry(String(str), {- font: font,- size: size,- depth: depth,- curveSegments:- opts.curveSegments === undefined ? 8 : opts.curveSegments,- bevelEnabled: bevel,- // A wider, rounder bevel than the reference's razor lip: this ring- // is the only part of a front-facing letter that sees the sky, and- // it carries the catchlight. `bevelSize` is in-plane, so it grows- // the glyph box — 0.015 is the most that keeps a size-1 line inside- // the 1.1 m the placement contract is measured against.- bevelThickness: 0.024 * size,- bevelSize: 0.015 * size,- bevelSegments: 3,- });- geo.computeBoundingBox();- const bb = geo.boundingBox;- geo.translate(- -0.5 * (bb.min.x + bb.max.x), 0, -0.5 * (bb.min.z + bb.max.z));-- const variation = opts.variation === undefined- ? 1 : Math.max(0, Math.min(1, opts.variation));- if (variation > 0) _paintVariance(geo, size, variation);-- let mat = opts.material;- if (!mat) {- mat = new THREE.MeshStandardMaterial({- color: opts.color === undefined ? 0xe7e3da : opts.color,- roughness: opts.roughness === undefined ? 0.45 : opts.roughness,- metalness: opts.metalness === undefined ? 0.1 : opts.metalness,- vertexColors: variation > 0,- });- if (opts.emissive !== undefined) {- mat.emissive = new THREE.Color(opts.emissive);- mat.emissiveIntensity = opts.emissiveIntensity === undefined- ? 1.6 : opts.emissiveIntensity;- }- }-- const mesh = new THREE.Mesh(geo, mat);- mesh.name = 'SignText';- const w = bb.max.x - bb.min.x;- const h = bb.max.y - bb.min.y;- const d = bb.max.z - bb.min.z;- mesh.userData.size = { w: w, h: h, d: d };- // Lettering is MOUNTED — on a board, a facade, a plinth — so the- // host's settle pass (runtime_js/lib/host_placement.mjs) must never- // drop it onto the terrain the way it seats a floating crate.- mesh.userData.placement = 'free';- if (opts.shadow === undefined || opts.shadow) {- mesh.castShadow = true;- mesh.receiveShadow = true;- }-- // A neon / backlit sign that lights nothing is a decal. Derive the- // candela from what the letters actually emit: radiance x inked area- // (~28 % of the bbox for a line of caps) x a lambertian-ish gain.- const emi = mat.emissive;- const emiI = mat.emissiveIntensity === undefined ? 1 : mat.emissiveIntensity;- const lit = !!emi && (emi.r + emi.g + emi.b) > 0.01 && emiI > 0;- if (lit && opts.light !== false) {- const area = Math.max(0.02, 0.28 * w * h);- const cd = typeof opts.light === 'number'- ? opts.light : 1.8 * emiI * area;- const light = new THREE.PointLight(emi.clone(), cd, 0, 2);- light.name = 'SignGlow';- // just off the letter faces, at the optical centre of the line- light.position.set(0, 0.5 * h, 0.5 * d + 0.55 * size);- light.castShadow = false;- mesh.add(light);- mesh.userData.light = light;- }- attachDisposal(mesh, opts.material ? [geo] : [geo, mat]);- return mesh;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.jsdeleted file mode 100644index c2cb9b00..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/smalllife.js+++ /dev/null@@ -1,830 +0,0 @@-/**- * The small live things: a swarm in the air, a stand of reeds in the- * water. Both are motion a still scene is missing, and both are ONE- * draw call whose every moving part lives in the vertex shader.- *- * Insects are the small-and-many case of flock.js. A midge is two- * pixels, so nothing here is modelled: one seed per instance drives the- * whole path and the silhouette is drawn in the fragment. What tells- * the three kinds apart is how they MOVE — a midge jitters inside a- * knot that drifts, a butterfly wanders and settles, a firefly drifts- * and blinks — so the kind is a motion law, not a mesh.- *- * Reeds are the waterline case of grass.js: rooted on the bed, leaning- * into the SAME streaky gust field the grass above water rides (hand- * both libraries one `wind` and the meadow and the shallows move- * together). The submerged part bends less, slower and rounder because- * water damps it, and that break in the bend AT the waterline is what- * says "standing in water" rather than "standing on a blue floor".- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';--import { mulberry32 } from './noise.js';-// One reader, so a scene's meadow, its reeds and its trees-// cannot drift apart on the same `wind` option.-import { WIND_GUST_GLSL, windOf } from './grass.js';-import {- glslLocalDir, instancedQuad, makeShaderMaterial, patchStandard, readVec3,- shadowLike, tickShaders, unit,-} from './shader.js';--const _TAU = Math.PI * 2;-// Dense longitudinal rows resolve curved stems and the rounded seed head.-const _REED_LEVELS = [- ...Array.from({length:17},(_,i)=>i*.75/16),- .78,.80,.81,.818,.835,.86,.885,.905,.922,.93,.95,1,-];-const _REED_ROWS = _REED_LEVELS.length - 1;-// Water damps what stands in it: the submerged stem takes this much of-// the surface bend, on the slower of the two sway rates below.-const _SUB_DAMP = 0.28;-const _SWAY_RATE = new THREE.Vector2(1.6, 0.45);--/**- * One row per insect kind. These numbers ARE the difference between the- * three animals: `wander`/`rise` are fractions of the stated volume,- * `rate` is the wander's rad/s, `beat` the wingbeat (or the firefly's- * blink), `drift` how far the whole swarm's centre travels.- */-const _KINDS = {- midge: {- id: 0, wander: 0.07, rise: 0.12, rate: 5.2, beat: 44,- drift: 0.42, driftRate: 0.28, aspect: 0.52, hue: 0.5,- size: 0.022, color: 0x241d16,- },- butterfly: {- id: 1, wander: 0.58, rise: 0.40, rate: 0.62, beat: 24,- drift: 0, driftRate: 0, aspect: 0.88, hue: 0.26,- size: 0.085, color: 0xd8791c,- },- firefly: {- id: 2, wander: 0.20, rise: 0.15, rate: 0.30, beat: 1.15,- drift: 0, driftRate: 0, aspect: 1, hue: 0.18,- size: 0.055, color: 0xc8ff7a,- },-};--// A swarm is unlit geometry, so refresh its light approximation every update.-// This follows animated lights and is independent of update-call history.-// A billboard has no normal, so a direct light contributes its average-// over the facings that see it; a point or spot light is somewhere else-// in the scene and this cannot know how far, so it lands as a small-// ambient rather than as nothing.-const _DIRECT = 0.55;-const _LOCAL = 0.06;-const _INV_PI = 1 / Math.PI;-const _lightAcc = new THREE.Color();--/**- * What the scene's own lights put on an unlit billboard.- *- * Without it an insect is its own hex whatever the hour: measured on this- * showcase's night rig, the midge's hardcoded grey wing blur (0.5) came- * back BRIGHTER than the moonlit sky behind it — a knot of white dust- * over the water — and orange butterflies glowed like embers at midnight.- * One traverse, and it lands on 1.0 under the library's own day rig, so a- * daylight swarm keeps exactly the look it had.- *- * @returns {boolean} true if a lit Scene was found and `out` was filled.- */-function sceneLight(obj, out) {- let root = obj;- while (root.parent) root = root.parent;- if (!root.isScene) return false;- _lightAcc.setRGB(0, 0, 0);- let n = 0;- root.traverse((o) => {- if (!o.isLight) return;- n++;- if (o.visible === false || !(o.intensity > 0)) return;- const w = (o.isHemisphereLight || o.isAmbientLight) ? 1- : (o.isDirectionalLight ? _DIRECT : _LOCAL);- // A hemisphere light is its two halves averaged; every other kind- // averages its own colour with itself.- const c = o.color, g = o.groundColor || o.color, k = 0.5 * o.intensity * w;- _lightAcc.r += (c.r + g.r) * k;- _lightAcc.g += (c.g + g.g) * k;- _lightAcc.b += (c.b + g.b) * k;- });- if (!n) return false;- // Irradiance to reflected radiance, and a ceiling: a rig with a dozen- // lamps in it is not a reason for a midge to become one.- out.setRGB(Math.min(_lightAcc.r * _INV_PI, 2.5),- Math.min(_lightAcc.g * _INV_PI, 2.5),- Math.min(_lightAcc.b * _INV_PI, 2.5));- return true;-}--/**- * A swarm of insects, animated entirely from a per-instance seed.- *- * Buys the midges over a pond at dusk, the butterflies over a meadow,- * the fireflies after dark — at one draw call and one float per frame,- * so the count can be what a real swarm is. Drive it from your- * `update` — `insects.userData.update(t)` — or nothing moves.- *- * The constraint: every insect, quad and all, stays inside the volume- * this advertises (`center` +- (`extent`, `height`/2, `extent`)), which- * is the bounding box it states and the sphere three culls it by.- *- * @param {object} [opts]- * `count` individuals (default 140); `kind` 'midge' (default, a tight- * jittery knot around a slowly moving centre), 'butterfly' (a wide- * wander that settles briefly, wings folding as they beat) or- * 'firefly' (a slow drift plus a pulse of light);- * `extent` horizontal radius in metres of the volume it fills- * (default 4); `height` that volume's full height in metres (default- * 2); `center` its centre ([x,y,z] or Vector3, default- * [0, height/2, 0] — the swarm's floor on y = 0); `size` body span in- * metres (default 0.022 midge / 0.085 butterfly / 0.055 firefly);- * `color` body or glow colour; `seed` PRNG seed (default 11); `name`- * group name.- * @returns {THREE.Group} Named `Insects`, holding ONE instanced mesh,- * with `userData.update(t)` advancing the only thing that changes.- */-export function makeInsects(opts = {}) {- const kind = _KINDS[opts.kind] || _KINDS.midge;- const count = Math.max(1, opts.count === undefined ? 140 : opts.count);- const extent = opts.extent === undefined ? 4 : opts.extent;- const height = opts.height === undefined ? 2 : opts.height;- const size = opts.size === undefined ? kind.size : opts.size;- const seed = opts.seed === undefined ? 11 : opts.seed;- const color = new THREE.Color(- opts.color === undefined ? kind.color : opts.color);- const center = readVec3(opts.center, 0, height * 0.5, 0);- const half = new THREE.Vector3(extent, height * 0.5, extent);- const amp = new THREE.Vector3(- kind.wander * extent, kind.rise * height * 0.5, kind.wander * extent);- const drift = new THREE.Vector3(- kind.drift * extent, kind.drift * height * 0.25, kind.drift * extent);-- const field = swarmField(count, kind, center, half, amp, drift, size, seed);- const box = new THREE.Box3(- center.clone().sub(half), center.clone().add(half));- const geom = instancedQuad(count, 1, 1,- center.length() + half.length());- geom.setAttribute('iPos', new THREE.InstancedBufferAttribute(field.pos, 3));- geom.setAttribute('iAmp', new THREE.InstancedBufferAttribute(field.amp, 3));- geom.setAttribute('iSeed', new THREE.InstancedBufferAttribute(field.seed, 4));- geom.boundingBox = box;- geom.boundingSphere = box.getBoundingSphere(new THREE.Sphere());-- const mat = insectMaterial(kind, size, drift, color);- const mesh = new THREE.Mesh(geom, mat);- mesh.name = kind.id === 0 ? 'Midges'- : (kind.id === 1 ? 'Butterflies' : 'Fireflies');- mesh.renderOrder = 3;- const g = new THREE.Group();- g.name = opts.name || 'Insects';- g.add(mesh);- // The swarm reads the rig it was added to, from the first tick on; a- // caller who never adds it to a scene keeps the neutral 1.0 it was- // built with, which is what an asset preview wants.- g.userData.update = g.userData.tick = (t) => {- sceneLight(g, mat.uniforms.uLight.value);- tickShaders(g, t);- };- return attachDisposal(g, snapshotResources(g));-}--/**- * Where each insect lives and how far it strays from there.- *- * The base position is drawn from the volume MINUS its own wander, the- * swarm drift and the quad's own span, so containment is a property of- * the numbers rather than a hope about the shader.- */-function swarmField(count, kind, center, half, amp, drift, size, seed) {- const rand = mulberry32(seed);- const room = new THREE.Vector3(- Math.max(half.x - amp.x - drift.x - size * 2, 0),- Math.max(half.y - amp.y - drift.y - size * 2, 0),- Math.max(half.z - amp.z - drift.z - size * 2, 0));- const pos = new Float32Array(count * 3);- const am = new Float32Array(count * 3);- const sd = new Float32Array(count * 4);- for (let i = 0; i < count; i++) {- const a = rand() * _TAU;- // A midge swarm is a knot with a dense middle; the other two hold- // territory, so they spread evenly over the ground they cover.- const r = kind.id === 0 ? Math.pow(rand(), 1.6) : Math.sqrt(rand());- const v = kind.id === 2 ? Math.pow(rand(), 1.7) * 2 - 1- : (kind.id === 0 ? rand() + rand() - 1 : rand() * 2 - 1);- pos[i * 3] = center.x + Math.cos(a) * r * room.x;- pos[i * 3 + 1] = center.y + v * room.y;- pos[i * 3 + 2] = center.z + Math.sin(a) * r * room.z;- am[i * 3] = amp.x * (0.45 + 0.55 * rand());- am[i * 3 + 1] = amp.y * (0.45 + 0.55 * rand());- am[i * 3 + 2] = amp.z * (0.45 + 0.55 * rand());- sd[i * 4] = rand() * _TAU;- sd[i * 4 + 1] = 0.75 + 0.5 * rand();- sd[i * 4 + 2] = 0.7 + 0.5 * rand();- sd[i * 4 + 3] = (rand() - 0.5) * kind.hue;- }- return { pos, amp: am, seed: sd };-}--/** The one material: path, beat, blink and silhouette, all in GLSL. */-function insectMaterial(kind, size, drift, color) {- return makeShaderMaterial({- name: 'Insects',- uniforms: {- // Bound here though the wrapper supplies it: this harness's GLSL- // audit (runtime_js/lib/glsl_audit.mjs) reads THIS file, not the- // string the wrapper assembles, and reported two hard ERRORs- // against every shader here that reads uTime.- uTime: { value: 0 },- uKind: { value: kind.id },- uRate: { value: kind.rate },- uBeat: { value: kind.beat },- uSize: { value: size },- uAspect: { value: kind.aspect },- uDrift: { value: drift.clone() },- uDriftRate: { value: kind.driftRate },- uColor: { value: color },- uLight: { value: new THREE.Color(1, 1, 1) },- },- varyings: 'varying vec2 vUv; varying vec4 vSeed; varying float vBeat;'- + ' varying float vNear;',- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 iPos;',- 'attribute vec3 iAmp;',- 'attribute vec4 iSeed;',- 'uniform float uTime; uniform float uKind; uniform float uRate;',- 'uniform float uBeat; uniform float uSize; uniform float uAspect;',- 'uniform vec3 uDrift; uniform float uDriftRate;',- // Every component stays within +-1, which is what keeps a swarm- // inside the volume its bounding box claims.- 'vec3 lifeOsc(float t, vec4 sd) {',- ' float p = sd.x, r = uRate * sd.y;',- ' if (uKind < 0.5) {',- ' return vec3(',- ' (sin(t * r + p) + 0.5 * sin(t * r * 2.7 + p * 1.7)) / 1.5,',- ' (sin(t * r * 1.3 + p * 2.1) + 0.5 * sin(t * r * 3.1 + p))',- ' / 1.5,',- ' (cos(t * r * 0.9 + p * 1.3) + 0.5 * cos(t * r * 2.3',- ' + p * 2.7)) / 1.5);',- ' }',- // A butterfly settles: warped time whose rate falls to almost- // nothing once a cycle, which is the pause on a flower.- ' if (uKind < 1.5) {',- ' float w = t * r + p;',- ' float u = w + 0.95 * sin(w);',- ' return vec3(sin(u), 0.85 * sin(u * 0.5 + p),',- ' cos(u * 0.77 + p * 0.5));',- ' }',- ' return vec3(sin(t * r + p), sin(t * r * 0.61 + p * 1.7),',- ' cos(t * r * 0.43 + p * 2.3));',- '}',- // The knot itself wanders; without it a midge swarm hangs in the- // air like a fixed cloud of dust.- 'vec3 lifeDrift(float t) {',- ' float d = t * uDriftRate;',- ' return uDrift * vec3(sin(d), sin(d * 0.73 + 1.1), cos(d * 0.61));',- '}',- 'vec3 lifeAt(float t, vec3 b, vec3 a, vec4 sd) {',- ' return b + a * lifeOsc(t, sd) + lifeDrift(t);',- '}',- ].join('\n'),- vertexMain: [- ' vUv = uv;',- ' vSeed = iSeed;',- ' vec3 c = lifeAt(uTime, iPos, iAmp, iSeed);',- ' vec3 vel = lifeAt(uTime + 0.08, iPos, iAmp, iSeed) - c;',- // Own phase per individual: a swarm beating or blinking in step- // reads as one object flickering, not as many animals.- ' float beat = uTime * uBeat * iSeed.y + astraStagger(iSeed.x);',- ' vBeat = beat;',- ' vec3 camR = vec3(modelViewMatrix[0][0], modelViewMatrix[1][0],',- ' modelViewMatrix[2][0]);',- ' vec3 camU = vec3(modelViewMatrix[0][1], modelViewMatrix[1][1],',- ' modelViewMatrix[2][1]);',- ' vec3 fwd = length(vel) > 1e-7 ? normalize(vel)',- ' : vec3(1.0, 0.0, 0.0);',- // A midge is smeared ALONG its flight, a butterfly spans ACROSS- // it; either axis is used as PROJECTED, so a bug flying at the- // camera loses its span instead of sliding sideways.- ' vec3 side = cross(fwd, vec3(0.0, 1.0, 0.0)) + vec3(1e-5, 0.0, 0.0);',- ' vec3 ax = uKind < 0.5 ? fwd : normalize(side);',- ' vec2 e = vec2(dot(ax, camR), dot(ax, camU));',- ' float el = length(e);',- ' vec2 ex = el > 1e-4 ? e / el : vec2(1.0, 0.0);',- ' vec2 ey = vec2(-ex.y, ex.x);',- ' float fold = uKind > 0.5 && uKind < 1.5',- ' ? 0.24 + 0.76 * abs(cos(beat)) : 1.0;',- // A glow has no axis to foreshorten; the other two do, and an- // ellipse where a lamp belongs reads as a smear.- ' float span = uKind < 1.5 ? clamp(el, 0.3, 1.0) : 1.0;',- ' float sz = uSize * iSeed.z;',- ' vec2 q = ex * (aCorner.x * 2.0 * sz * fold * span)',- ' + ey * (aCorner.y * 2.0 * sz * uAspect);',- ' transformed = c + camR * q.x + camU * q.y;',- // A swarm is a VOLUME, and a camera placed inside one gets an- // insect at arm's length: measured on a delivered meadow, a- // 17 cm butterfly 1 m from the lens filled a quarter of a 40 deg- // frame and the judge scored the scene's whole scale down for- // it. No lens focuses at 30 cm either, so the ones that close- // fade out instead of becoming the subject.- ' vec3 cW = (modelMatrix * vec4(c, 1.0)).xyz;',- ' vNear = smoothstep(0.35, 1.8, distance(cameraPosition, cW));',- ].join('\n'),- fragmentHead: 'uniform vec3 uColor; uniform float uKind;'- + ' uniform vec3 uLight;',- fragmentMain: [- ' vec2 q = vUv * 2.0 - 1.0;',- // Hue AND value per individual: a swarm of one exact colour is- // the "primitives" look at any scale.- ' vec3 col = astraHueShift(uColor, vSeed.w)',- ' * (0.78 + 0.44 * fract(vSeed.x * 1.7));',- ' float a;',- ' if (uKind < 0.5) {',- // A hard little body inside a faint disc of wing blur: the blur- // is the whole difference between an insect and a speck of dirt.- ' float body = 1.0 - smoothstep(0.34, 0.72,',- ' length(q * vec2(0.62, 1.5)));',- ' float blur = 1.0 - smoothstep(0.2, 1.0,',- ' length(q * vec2(0.8, 1.15)));',- ' a = clamp(body + blur * 0.32 * (0.7 + 0.3 * sin(vBeat)),',- ' 0.0, 1.0);',- // The blur is LIGHTER than the body — wings scatter light, and a- // dark halo would only fatten the speck — but it is the BODY's- // own colour scattered, not a grey card: a fixed 0.5 grey is an- // albedo brighter than a moonlit sky, and it turned every night- // swarm into a knot of white dust.- ' vec3 haze = min(col * 3.4 + 0.015, vec3(0.55));',- ' col = mix(haze, col, body) * uLight;',- ' } else if (uKind < 1.5) {',- // A forewing tilted outward-forward with a hindwing tucked under- // it — two OVERLAPPING lobes, because two circles read as a bug.- ' float ax = abs(q.x);',- ' vec2 fp = vec2(ax - 0.42, q.y - 0.26);',- ' fp = vec2(fp.x * 0.93 + fp.y * 0.37, fp.y * 0.93 - fp.x * 0.37)',- ' / vec2(0.6, 0.32);',- ' float df = pow(pow(abs(fp.x), 2.4) + pow(abs(fp.y), 2.4), 0.417);',- ' float dh = length(vec2(ax - 0.26, q.y + 0.28) / vec2(0.3, 0.25));',- ' float aaf = max(fwidth(df), 0.03);',- ' float aah = max(fwidth(dh), 0.03);',- ' float wing = max(1.0 - smoothstep(1.0 - aaf, 1.0 + aaf, df),',- ' 1.0 - smoothstep(1.0 - aah, 1.0 + aah, dh));',- ' float body = (1.0 - smoothstep(0.04, 0.075, ax))',- ' * (1.0 - smoothstep(0.34, 0.46, abs(q.y)));',- // Two hairs and a club: the one detail that says butterfly- // instead of moth-shaped blob, and it costs four lines.- ' float an = abs(ax - (q.y - 0.36) * 0.5);',- ' float ant = (1.0 - smoothstep(0.012, 0.032, an))',- ' * step(0.36, q.y) * (1.0 - smoothstep(0.6, 0.72, q.y));',- ' a = clamp(wing + body + ant * 0.9, 0.0, 1.0);',- ' col = mix(col, col * 0.26, smoothstep(0.62, 1.0, min(df, dh)));',- ' col = mix(col, vec3(0.15, 0.11, 0.07), max(body, ant));',- // One wing catches the light as the pair opens.- ' col *= (0.72 + 0.42 * abs(cos(vBeat))) * uLight;',- ' } else {',- // Mostly dark, briefly a lamp: the blink is the firefly.- ' float d = length(q);',- ' float pulse = pow(max(sin(vBeat), 0.0), 9.0);',- // TWO lobes: one gaussian at this size is a speck the eye reads- // as a dead pixel, and a lamp has a core AND a falloff.- ' a = (0.74 * exp(-d * d * 9.0) + 0.32 * exp(-d * d * 1.5))',- ' * (0.04 + 0.96 * pulse);',- // The lantern is EMITTED, so it keeps its own hue whatever the- // rig is doing, and it peaks at 2.6 rather than at white: pushed- // to 1.0 the core clipped to a white dot that read as dust, while- // 2.6 rolls through the ACES shoulder as a hot core with a- // COLOURED skirt. `color` is that LANTERN — taken as the body- // albedo too, 0xc8ff7a is a near-white green, and every firefly- // in daylight was a chartreuse dot, flashing or not.- ' vec3 body = mix(vec3(dot(col, vec3(0.3333))), col, 0.4) * 0.2;',- ' vec3 lamp = col / max(max(col.r, max(col.g, col.b)), 1e-3);',- ' vec3 hot = mix(lamp, vec3(1.0, 0.97, 0.86), 0.42) * 2.6;',- // A lantern is only SEEN when it beats what is behind it: at noon- // the same flash is a beetle, and at full strength it landed on- // the day frame as a white speck that read as a dirty lens.- ' float dim = 1.0 - clamp(dot(uLight, vec3(0.5)), 0.0, 1.0);',- ' float lit = clamp(pulse * (0.4 + 0.6 * (1.0 - smoothstep(0.0, 0.5, d)))',- ' * (0.25 + 0.75 * dim), 0.0, 1.0);',- ' col = mix(body * uLight, hot, lit);',- ' }',- ' a *= vNear;',- ' if (a < 0.01) discard;',- ' gl_FragColor = vec4(col, a);',- ].join('\n'),- // Ordinary blending, even for the firefly: added light clips a- // bright frame (godrays.js measured 12.8% of one blown past 0.97),- // and `additive: true` also loses the fog chunk the gate looks for.- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- });-}--/**- * Reeds, rushes and kelp standing in water.- *- * Buys the one thing a plant on a shoreline has to prove: that it is- * IN the water, not on it. The stems are rooted on the bed (`heightAt`,- * the caller's ground truth), they thin out where the water gets too- * deep to stand in, and the bend breaks at the waterline — full,- * gusting sway above it; a slow, round, lagging fraction of it below,- * because water damps what it holds.- *- * Deterministic in `seed`, one draw call at any count, and every- * moving part in the vertex shader. Drive it from your zone's `update` —- * `reeds.userData.update(t)` — or the wind never blows.- *- * @param {object} [opts]- * `extent` metres of the square patch's side (default 12, centred on- * the group's origin); `density` stems per square metre (default 6;- * `maxStems` caps it, default 20000); `height` stem height in metres- * (default 1.8, varied per stem); `waterY` world y of the water- * surface (default 0.35); `heightAt` (x, z) => y, the caller's BED- * height (default flat y = 0); `color` the green of a live stem;- * `wind` grass.js's option, in either spelling — a strength- * multiplier or `{dir, strength, speed}` — so one wind moves a- * scene's grass and its reeds together; `dryColor` last year's dead- * straw, mixed in per stem; `waterColor` what a drowned stem loses- * its colour INTO (pass the water's own tint, or a stand in a green- * pond fades toward a blue-green that is not there); `shadows` cast- * stem and leaf shadows through matching depth/distance passes (default false, see- * `stemMesh`); `underwaterDistortion` enables a small approximate image distortion- * (default false; leave off with a refracting water surface); `seed` seed (default 11); `name` group name.- * @returns {THREE.Group} Named `Reeds`, holding ONE instanced mesh- * `Stems`, with `userData.update(t)` driving the wind.- */-export function makeReeds(opts = {}) {- const extent = opts.extent === undefined ? 12 : opts.extent;- const density = opts.density === undefined ? 6 : opts.density;- const height = opts.height === undefined ? 1.8 : opts.height;- const waterY = opts.waterY === undefined ? 0.35 : opts.waterY;- const seed = opts.seed === undefined ? 11 : opts.seed;- const maxStems = opts.maxStems === undefined ? 20000 : opts.maxStems;- const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;- const wind = windOf(opts.wind);- // Albedos, not screen colours: a scene sun runs at 5-6, so a hex that- // already looks like a sunlit reed tone-maps to pale card.- const color = new THREE.Color(- opts.color === undefined ? 0x5c6f30 : opts.color);- // Last year's stems are still standing, bleached: one green is a- // stand nobody has stood in front of.- const dry = new THREE.Color(- opts.dryColor === undefined ? 0x8f7a44 : opts.dryColor);- const deep = new THREE.Color(- opts.waterColor === undefined ? 0x24382c : opts.waterColor);-- const field = reedField(- extent, density, height, waterY, ground, wind, seed, maxStems);- const g = new THREE.Group();- g.name = opts.name || 'Reeds';- g.add(stemMesh(field, extent, waterY, { color, dry, deep }, wind,- opts.shadows === true, opts.underwaterDistortion === true));- g.userData.update = g.userData.tick = (t) => tickShaders(g, t);- return attachDisposal(g, snapshotResources(g));-}--/**- * Plant the stand, and let the water decide where it grows.- *- * Reeds fringe a shoreline: none on the dry bank above the line, fewer- * where it is deeper than they are tall. That rule needs the bed and- * the waterline together, which is why placement is on the CPU.- */-function reedField(extent, density, height, waterY, ground, wind, seed,- maxStems) {- const want = Math.max(- 1, Math.min(Math.round(density * extent * extent), maxStems));- const cells = Math.max(1, Math.round(Math.sqrt(want)));- const step = extent / cells;- const rand = mulberry32(seed);- const pos = [], shape = [], bend = [], vary = [];- let n = 0, maxH = 0, low = Infinity, high = -Infinity;- for (let iz = 0; iz < cells && n < maxStems; iz++) {- for (let ix = 0; ix < cells && n < maxStems; ix++) {- const x = -extent / 2 + (ix + rand()) * step;- const z = -extent / 2 + (iz + rand()) * step;- const bed = ground ? ground(x, z) : 0;- const depth = waterY - bed;- const h = height * (0.6 + 0.7 * rand());- const dry = unit(1 + depth / 0.3);- const deep = 1 - 0.6 * unit((depth - h * 0.7) / h);- if (rand() > dry * deep) continue;- // Radians of tip bend at a full gust: a taller stem is a longer- // lever, and each one carries its own stiffness.- const stiff = (0.7 + 0.6 * rand()) * (0.6 + 0.55 * h / height);- const head = rand() < 0.45 && depth < h * 0.85- ? 0.010 + 0.006 * rand() : 0;- pos.push(x, bed, z);- shape.push(h, 0.004 + 0.003 * rand(), unit(depth / h), head);- bend.push(wind.amp * stiff, wind.amp * stiff * _SUB_DAMP,- rand() * _TAU, 0.04 + 0.14 * rand());- // phase, hue, tone, dryness — dead stems a MINORITY, since a- // linear roll would bleach half the stand.- vary.push(rand() * _TAU, (rand() - 0.5) * 0.5, rand(),- Math.pow(rand(), 2.4));- maxH = Math.max(maxH, h);- low = Math.min(low, bed);- high = Math.max(high, bed + h);- n++;- }- }- return { n, pos, shape, bend, vary, maxH,- low: n ? low : 0, high: n ? high : 0 };-}--/**- * The stem lattice: ONE instanced strip with `position` pinned at 0.- *- * GTAOPass redraws with an override material that ignores this vertex- * shader, so a real stem left in `position` would stack every copy at- * the world origin and burn a black slab there.- */-function reedLattice(count) {- const corners=[], normals=[], uvs=[], parts=[], indices=[];- for(let part=0;part<5;part++) {- const rows=part===0 ? _REED_ROWS : 10;- const start=corners.length/3;- for(let j=0;j<=rows;j++)for(let side=0;side<3;side++) {- const u=part===0?_REED_LEVELS[j]:j/rows;- corners.push(side*.5-.5,u,0); normals.push(0,0,1);- uvs.push(side*.5,j/rows);parts.push(part);- }- for(let j=0;j<rows;j++)for(let side=0;side<2;side++) {- const a=start+j*3+side;indices.push(a,a+1,a+3,a+1,a+4,a+3);- }- }- const g=new THREE.InstancedBufferGeometry();g.setIndex(indices);- g.setAttribute('position',new THREE.Float32BufferAttribute(new Float32Array(corners.length),3));- g.setAttribute('aCorner',new THREE.Float32BufferAttribute(corners,3));- g.setAttribute('aPart',new THREE.Float32BufferAttribute(parts,1));- g.setAttribute('normal',new THREE.Float32BufferAttribute(normals,3));- g.setAttribute('uv',new THREE.Float32BufferAttribute(uvs,2));- g.instanceCount=count;return g;-}--/**- * One mesh, one draw call: every stem lives in the vertex shader.- *- * `shadows` is OPT-IN, exactly as grass.js's blades are, and for a- * measured reason: a stem is 4-10 mm across and this rig sizes its- * shadow map at ~0.05 m/texel, so a stem shadow cannot be narrower than- * ten stems. A stand of 3 000 painted 4.16% of the showcase bank with- * hard navy dashes at luminance 0.180 against mud at 0.375, each twenty- * times the area of the thing casting it. The depth material is still- * built when asked — a caller with a tight bound, or kelp with fat- * blades, can have it.- */-function stemMesh(field, extent, waterY, palette, wind, shadows, distortion) {- const color = palette.color;- const geom = reedLattice(field.n);- const inst = (name, arr, size) => geom.setAttribute(- name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));- inst('iPos', field.pos, 3);- inst('iShape', field.shape, 4);- inst('iBend', field.bend, 4);- inst('iVar', field.vary, 4);- // position is zero, so the derived bounds would be a point at the- // origin: state the box the bent stand really occupies.- const reach = extent / 2 + field.maxH * 1.15 + 0.05;- geom.boundingBox = new THREE.Box3(- new THREE.Vector3(-reach, field.low, -reach),- new THREE.Vector3(reach, field.high + field.maxH * .24, reach));- geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());-- const mat = new THREE.MeshStandardMaterial({- color: 0xffffff, roughness: 0.68, metalness: 0,- side: THREE.DoubleSide, name: 'ReedStem',- });- patchStandard(mat, {- name: 'reed:stem',- uniforms: {- uTime: { value: 0 },- uReedColor: { value: color.clone() },- uReedDry: { value: palette.dry.clone() },- uReedHead: { value: new THREE.Color(0x6b4526) },- uReedDeep: { value: palette.deep.clone() },- uReedWind: { value: wind.dir.clone() },- uReedSpeed: { value: wind.speed },- uReedRate: { value: _SWAY_RATE.clone() },- uReedWater: { value: waterY },- uReedDistort: { value: distortion ? .012 : 0 },- },- vertexHead: STEM_HEAD,- vertexBody: STEM_VERTEX,- fragmentHead: [- 'uniform vec3 uReedColor;',- 'uniform vec3 uReedDry;',- 'uniform vec3 uReedHead;',- 'uniform vec3 uReedDeep;',- 'varying vec4 vReed;',- 'varying vec4 vReedVar;',- 'varying vec2 vReedW;',- 'varying float vReedPart;',- ].join('\n'),- fragmentBody: STEM_FRAGMENT,- });-- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Stems';- mesh.frustumCulled = false;- mesh.receiveShadow = true;- mesh.castShadow = false;- // The default depth material never runs this vertex shader, so the- // shadow pass needs the same displacement or a stand casts nothing.- if (shadows) shadowLike(mesh, 'reed:stemDepth', STEM_HEAD, STEM_VERTEX);- return mesh;-}--const STEM_HEAD = [- // See the insect material's uTime note. On ONE line with the next- // uniform because that audit only reads quoted strings of 40- // characters or more.- 'uniform float uTime; uniform vec2 uReedWind;',- 'uniform float uReedSpeed;',- 'uniform vec2 uReedRate;',- 'uniform float uReedWater;',- 'uniform float uReedDistort;',- 'attribute float aPart;',- 'attribute vec3 aCorner;',- 'attribute vec3 iPos;',- 'attribute vec4 iShape;',- 'attribute vec4 iBend;',- 'attribute vec4 iVar;',- 'varying vec4 vReed;',- 'varying vec4 vReedVar;',- 'varying vec2 vReedW;',- 'varying float vReedPart;',- glslLocalDir('reedLocalDir'), WIND_GUST_GLSL,-].join('\n');--const STEM_VERTEX = [- ' vec3 rdRoot = iPos;',- ' float rdV = aPart < 0.5 ? aCorner.y : 0.15 + aPart * 0.115;',- ' vReedPart = aPart;',- ' float rdH = max(iShape.x, 1e-3);',- // Gusts are streaks running downwind — the same field grass.js rides,- // so a scene's meadow and its shallows lean together.- ' vec3 rdRootWorld = (modelMatrix * vec4(rdRoot, 1.0)).xyz;',- ' vec2 rdW = reedLocalDir(vec3(uReedWind.x, 0.0, uReedWind.y)).xz;',- ' rdW /= max(length(rdW), 1e-5);',- ' float rdT = uTime * uReedSpeed;',- ' float rdGust = astraWindGust(rdRootWorld, uReedWind, rdT, vec2(0.055, 0.21));',- ' float rdPh = astraWindPhase(rdRootWorld, iVar.x);',- ' float rdSway = (sin(rdT * uReedRate.x + rdPh)',- ' + 0.35 * sin(rdT * uReedRate.x * 1.8 + rdPh * 1.7)) / 1.35;',- // Under water: one slow sine, no harmonic, and late — the surface has- // already turned before what it holds does.- ' float rdSubSway = sin(rdT * uReedRate.y + rdPh - 1.05);',- ' float rdPush = (0.25 + 1.25 * rdGust) * (0.62 + 0.38 * rdSway);',- ' float rdSubPush = (0.45 + 0.75 * rdGust) * (0.62 + 0.38 * rdSubSway);',- // Droop and push ADD as vectors, so a still stand leans every which- // way and a gust turns all of it downwind at once.- ' vec2 rdLean = vec2(cos(iBend.z), sin(iBend.z)) * iBend.w;',- ' vec2 rdAbove = rdLean + rdW * (iBend.x * rdPush);',- ' vec2 rdBelow = rdLean * 0.6 + rdW * (iBend.y * rdSubPush);',- ' vec2 rdF = length(rdAbove) > 1e-5 ? normalize(rdAbove)',- ' : vec2(1.0, 0.0);',- ' float rdKa = max(min(length(rdAbove), 1.3), 1e-3);',- ' float rdKb = max(min(length(rdBelow), 1.3), 1e-3);',- // Two circular arcs of the stem's own length, meeting at the- // waterline: the break in curvature IS the cue.- ' float rdVw = clamp(iShape.z, 0.0, 1.0);',- ' float rdA1 = rdKb * min(rdV, rdVw);',- ' float rdU = rdH * (1.0 - cos(rdA1)) / rdKb;',- ' float rdY = rdH * sin(rdA1) / rdKb;',- ' float rdA2 = rdA1 + rdKa * max(rdV - rdVw, 0.0);',- ' rdU += rdH * (cos(rdA1) - cos(rdA2)) / rdKa;',- ' rdY += rdH * (sin(rdA2) - sin(rdA1)) / rdKa;',- ' vec3 rdSpine = rdRoot + vec3(rdF.x * rdU, rdY, rdF.y * rdU);',- ' vec3 rdTan = vec3(rdF.x * sin(rdA2), cos(rdA2), rdF.y * sin(rdA2));',- // Seen THROUGH moving water a submerged stem wavers, and the step at- // the line is the break refraction really puts there.- ' float rdWet = step(rdV, rdVw);',- ' rdSpine.xz += vec2(-rdF.y, rdF.x) * (uReedDistort * rdV * rdWet',- ' * sin(rdT * 0.9 + rdPh + rdV * 7.0));',- ' float rdT2 = (rdV - 0.87) / 0.06;',- ' float rdCap = max(abs(rdT2) - 0.68, 0.0) / 0.32;',- ' float rdHead = aPart < 0.5 ? iShape.w * sqrt(max(1.0 - rdCap * rdCap, 0.0)) : 0.0;',- ' float rdWid = iShape.y * (0.55 + 0.45 * sqrt(max(1.0 - rdV, 0.0)))',- ' + rdHead;',- // A stem is round, so its strip faces the eye from every angle- // instead of collapsing to a line like a flat blade.- ' vec3 rdWp = (modelMatrix * vec4(rdSpine, 1.0)).xyz;',- ' vec3 rdView = normalize(reedLocalDir(cameraPosition - rdWp));',- ' vec3 rdC = cross(rdTan, rdView);',- ' float rdCl = length(rdC);',- ' vec3 rdSide = rdCl > 1e-4 ? rdC / rdCl : vec3(1.0, 0.0, 0.0);',- ' float rdX = aCorner.x * 2.0;',- ' transformed = rdSpine + rdSide * (rdX * rdWid);',- ' vec3 rdLeafNormal = vec3(0.0, 1.0, 0.0);',- ' if (aPart > 0.5) {',- ' float lu = aCorner.y;',- ' float la = iBend.z + aPart * 2.39996;',- ' vec3 ld = normalize(vec3(cos(la), 0.0, sin(la)));',- ' vec3 ls = vec3(-ld.z, 0.0, ld.x);',- ' float ll = rdH * (0.30 + 0.12 * fract(iVar.x + aPart * 0.37));',- ' float lp = pow(max(sin(3.14159 * lu), 0.0), 0.65);',- ' float lw = rdH * (0.009 + 0.006 * iVar.z) * lp;',- ' float lrise = ll * (0.62 * sin(3.14159 * lu * 0.7) - 0.20 * lu * lu);',- ' float ldY = ll * (0.62 * 3.14159 * 0.7 * cos(3.14159 * lu * 0.7) - 0.40 * lu);',- ' float lflutter = iBend.x * 0.035 * sin(rdT * 3.0 + iVar.x + aPart);',- ' transformed = rdSpine + ld * (ll * lu) + vec3(0.0, lrise, 0.0)',- ' + ls * (rdX * lw) + vec3(0.0, -abs(rdX) * lw * 0.20 + lflutter * lu * lu, 0.0);',- ' vec3 ltangent = ld * ll + vec3(0.0, ldY + 2.0 * lflutter * lu, 0.0);',- ' rdLeafNormal = normalize(cross(ls - vec3(0.0, sign(rdX) * 0.20, 0.0), ltangent));',- ' rdWp = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ' }',- ' vReed = vec4(rdV, rdHead / max(iShape.w, 1e-4),',- ' rdWp.y - uReedWater, rdX);',- ' vReedVar = vec4(iVar.y, iVar.z, iVar.w, rdVw);',- // The metre-scale colour field is read at the ROOT: a stem is a few- // pixels wide, so a field sampled up its length streaks it instead of- // patching the stand.- ' vReedW = rdRoot.xz;',- '#ifndef FLAT_SHADED',- // The normal of a cylinder, not of a card: without it a stand of- // stems shades as a field of flat ribbons.- ' vec3 rdFace = normalize(cross(rdSide, rdTan));',- ' vNormal = normalize(normalMatrix * normalize(',- ' rdFace * sqrt(max(1.0 - rdX * rdX, 0.04)) + rdSide * rdX));',- ' if (aPart > 0.5) vNormal = normalize(normalMatrix * rdLeafNormal);',- '#endif',-].join('\n');--const STEM_FRAGMENT = [- // THREE scales of colour, because a stand read at one is a green- // fence: last year's bleached stems through this year's live ones,- // each stem's own hue and value, and the metre-scale field the meadow- // rides too (grass.js's astraHueBreak, so a stand and the field it- // fringes agree at the shoreline).- ' vec3 rdCol = mix(uReedColor, uReedDry, vReedVar.z);',- ' rdCol = astraHueShift(rdCol, vReedVar.x);',- ' rdCol = astraHueBreak(rdCol, vReedW, 0.5, 0.34);',- ' rdCol *= 0.82 + 0.36 * vReedVar.y;',- // A stand is DEEP: the foot of a stem sits in the shade of its- // neighbours, and that gradient is most of what reads as a stand.- // A POWER, not a smoothstep — a smoothstep is already back at 0.9 by- // mid-stem, which is where most of the stand's pixels are.- ' float rdDepth = pow(clamp(vReed.x, 0.0, 1.0), 1.3);',- ' if (vReedPart > 0.5) rdDepth = pow(clamp(vReed.x + 0.3, 0.0, 1.0), 0.7);',- ' rdCol *= 0.46 + 0.54 * rdDepth;',- ' rdCol = mix(rdCol, rdCol * vec3(1.5, 1.35, 0.75),',- ' vReedVar.y * smoothstep(0.45, 1.0, vReed.x));',- ' rdCol *= 0.93 + 0.14 * astraNoise2(vec2(vReed.x * 60.0,',- ' vReedVar.y * 30.0));',- // The seed head is velvet, not plastic: its own hue and value per- // stem, and a fine grain across it, or three thousand identical- // chocolate cigars stand over the water.- ' vec3 rdHeadCol = astraHueShift(uReedHead, vReedVar.x * 0.7)',- ' * (0.76 + 0.34 * vReedVar.z);',- ' rdHeadCol *= 0.9 + 0.2 * astraNoise2(vec2(vReed.w * 9.0,',- ' vReed.x * 150.0));',- ' float rdIsHead = smoothstep(0.15, 0.6, vReed.y);',- ' rdCol = mix(rdCol, rdHeadCol, rdIsHead);',- ' if (vReedPart > 0.5) rdCol *= 1.18 - 0.12 * exp(-abs(vReed.w) * 18.0);',- // THE WATERLINE, the whole cue: a dark wet skin the water has- // climbed, a bright meniscus where the surface grabs the stem, and- // below it a stem losing its colour into the water EXPONENTIALLY —- // light does not fall off linearly through water, and the old linear- // ramp to 0.55 m left a fringe stand with no underwater at all.- ' float rdSubm = 1.0 - exp(min(vReed.z, 0.0) * 3.6);',- ' rdCol *= 1.0 - 0.42 * (1.0 - smoothstep(0.0, 0.085, vReed.z));',- ' rdCol = mix(rdCol, uReedDeep, rdSubm * 0.85);',- // The meniscus reads the water it stands in, not a fixed white.- ' rdCol += (uReedDeep + vec3(0.1, 0.11, 0.1)) * 0.55',- ' * (1.0 - smoothstep(0.0, 0.02, abs(vReed.z)));',- // TRANSLUCENCY. A reed is a wet green straw: backlit, a good part of- // what reaches the eye came THROUGH it, and that is the difference- // between a stand and a picket fence. Albedo cannot say it (the lit- // side is the far one), so it goes in as emitted radiance read off- // the scene's OWN key light — direction and colour both, so a moon- // drives it as happily as a sun. Sap is yellower than the stem, and- // a negative turn about the grey axis is that way.- '#if NUM_DIR_LIGHTS > 0',- '#ifndef FLAT_SHADED',- ' vec3 rdN = normalize(vNormal);',- ' vec3 rdEye = normalize(vViewPosition);',- ' vec3 rdL = directionalLights[0].direction;',- ' float rdThru = clamp(-dot(rdN, rdL) * sign(dot(rdN, rdEye)),',- ' 0.0, 1.0);',- ' float rdBeam = pow(clamp(dot(rdEye, -rdL) * 0.5 + 0.5, 0.0, 1.0),',- ' 3.0);',- // A SEED HEAD IS NOT A LEAF: packed felt where the stem is a straw,- // and left in the term it lit up as a brick-red ember on every stem- // in the stand. Dead straw barely passes light either, and a drowned- // stem passes it only as far as the water allows.- ' vec3 rdSap = astraHueShift(rdCol, -0.20) * 1.7;',- ' if (vReedPart > 0.5) rdBeam = 0.45 + 0.55 * rdBeam;',- ' float rdVisibility = 1.0;',- ' #if defined(USE_SHADOWMAP) && NUM_DIR_LIGHT_SHADOWS > 0',- ' rdVisibility = getShadow(directionalShadowMap[0], directionalLightShadows[0].shadowMapSize,',- ' directionalLightShadows[0].shadowIntensity, directionalLightShadows[0].shadowBias,',- ' directionalLightShadows[0].shadowRadius, vDirectionalShadowCoord[0]);',- ' #endif',- ' totalEmissiveRadiance += directionalLights[0].color * rdSap * rdVisibility',- ' * (0.44 * rdThru * rdBeam * rdDepth * (1.0 - 0.86 * rdIsHead)',- ' * (1.0 - 0.7 * vReedVar.z) * (1.0 - rdSubm));',- '#endif',- '#endif',- ' diffuseColor.rgb = rdCol;',-].join('\n');diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.jsdeleted file mode 100644index cdf7919f..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/stream.js+++ /dev/null@@ -1,713 +0,0 @@-/**- * Clear, flowing stream along a graded Catmull-Rom path (metres, local Y up).- * Curved tessellated surface, geometric travelling ripples, obstacle wakes,- * advected foam, bed gravel and submerged stones. Uses standard PBR lighting,- * environment reflection, scene shadows and fog. Deterministic at absolute time.- * This is a kinematic shallow stream, not a Navier-Stokes solver: stones generate- * authored wake fields; water does not collide with arbitrary scene geometry.- * Refracts the opaque scene through a depth-varying water column using Three's- * physical transmission pass. Transparent objects are not in that pass; this- * remains a screen-space approximation. Reflections use the environment map,- * or an optional mean-grade planar capture of the scene's banks.- */-import * as THREE from 'three';-import { Reflector } from 'three/addons/objects/Reflector.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32 } from './noise.js';-import { GLSL_UTIL, option, planarCapture } from './shader.js';--// IcosahedronGeometry duplicates triangle vertices. Preserve rounded cobble-// shading after deformation by averaging normals at coincident positions.-function smoothCobbleNormals(geometry) {- geometry.computeVertexNormals();- const p = geometry.attributes.position;- const n = geometry.attributes.normal;- const sums = new Map();- const keyAt = (i) =>- [p.getX(i), p.getY(i), p.getZ(i)].map((v) => Math.round(v * 1e5)).join(',');- for (let i = 0; i < p.count; i++) {- const key = keyAt(i);- const sum = sums.get(key) ?? new THREE.Vector3();- sum.add(new THREE.Vector3().fromBufferAttribute(n, i));- sums.set(key, sum);- }- for (let i = 0; i < p.count; i++) {- const sum = sums.get(keyAt(i)).clone().normalize();- n.setXYZ(i, sum.x, sum.y, sum.z);- }-}--// the library's one GLSL value noise (astraHash21 / astraNoise2)-const noiseGLSL = GLSL_UTIL;--/**- * @param {object} [opts]- * points [[x,y,z],...] upstream to downstream (non-increasing control heights);- * width=3, widthVariation=0 [0,.3] (irregular bank widths), depth=.45, speed=1.1 m/s, roughness=.5 [0,1] (riffle activity);- * segments=180, widthSegments=20, stoneCount=220, seed=42;- * obstacles [{u:0..1,lateral:-1..1,radius:.3}] generate stone + trailing wake;- * bed=true, waterColor=0x80b6a6, attenuationDistance=3 metres, bedColor=0x554a35;- * caustics=.45 [0,1] modulates direct bed light from the ripple curvature.- * endFade=0 metres; positive values smoothly flatten ripples at both ends- * over that distance, allowing an exact join to a still surface or weir lip.- * reflectionSize=0 disables optional bank reflection; use 256..2048 to enable- * one mean-grade planar capture. Do not combine it with another scene reflector.- * waterColor controls absorption over attenuationDistance, not surface paint.- * Result Group .userData.update(t,dt), sample(u,lateral=0,t), dispose().- * sample returns {position, tangent, normal, depth, speed} in LOCAL coordinates.- * speed/depth are constant along the path; no tributaries/overturning falls.- */-export function makeStream(opts = {}) {- const width = option(opts.width, 3, 'makeStream: width', 0.1, 100),- depth = option(opts.depth, 0.45, 'makeStream: depth', 0.03, 10);- const widthVariation = option(opts.widthVariation, 0, 'makeStream: widthVariation', 0, 0.3);- const speed = option(opts.speed, 1.1, 'makeStream: speed', 0, 15),- activity = option(opts.roughness, 0.5, 'makeStream: roughness', 0, 1);- const segments = Math.round(option(opts.segments, 180, 'makeStream: segments', 16, 512));- const acrossSegments = Math.round(option(opts.widthSegments, 20, 'makeStream: widthSegments', 4, 96));- const count = Math.round(option(opts.stoneCount, 220, 'makeStream: stoneCount', 0, 12000));- const attenuationDistance = option(opts.attenuationDistance, 3, 'makeStream: attenuationDistance', 0.01, 10000);- const caustics = option(opts.caustics, 0.45, 'makeStream: caustics', 0, 1);- const reflectionSize = option(opts.reflectionSize, 0, 'makeStream: reflectionSize', 0, 2048);- if (reflectionSize !== 0 && (!Number.isInteger(reflectionSize) || reflectionSize < 256))- throw new RangeError('makeStream: reflectionSize must be 0 or an integer from 256 to 2048');- const seed = option(opts.seed, 42, 'makeStream: seed'),- rng = mulberry32(seed);- const points = opts.points ?? [- [-2, 0.8, -12],- [1, 0.55, -5],- [-1, 0.2, 3],- [2, 0, 12],- ];- if (- !Array.isArray(points) ||- points.length < 2 ||- points.some((p) => !Array.isArray(p) || p.length !== 3 || !p.every(Number.isFinite))- )- throw new RangeError(- 'makeStream: points must contain at least two finite [x,y,z] coordinates'- );- for (let i = 1; i < points.length; i++) {- if (points[i][1] > points[i - 1][1] + 1e-6)- throw new RangeError(- 'makeStream: points must run upstream to downstream (non-increasing y)'- );- if (Math.hypot(points[i][0] - points[i - 1][0], points[i][2] - points[i - 1][2]) < 0.001)- throw new RangeError('makeStream: adjacent points need distinct XZ positions');- }- const path = new THREE.CatmullRomCurve3(- points.map((p) => new THREE.Vector3(p[0], 0, p[2])),- false,- 'centripetal'- );- path.arcLengthDivisions = Math.max(400, segments * 3);- path.updateArcLengths();- const length = path.getLength();- const endFade = option(opts.endFade, 0, 'makeStream: endFade', 0, length * .5);- // A spatial Catmull-Rom spline can overshoot perfectly valid flat-to-sloped- // control heights and make water run uphill. Use it only for the XZ course;- // harmonic Hermite slopes preserve each monotone height interval exactly.- const heights = points.map((p) => p[1]);- const deltas = heights.slice(1).map((y, i) => y - heights[i]);- const slopes = heights.map((_, i) => {- if (i === 0) return deltas[0];- if (i === heights.length - 1) return deltas.at(-1);- const a = deltas[i - 1],- b = deltas[i];- return a * b > 0 ? (2 * a * b) / (a + b) : 0;- });- function gradedPoint(u) {- const t = path.getUtoTmapping(u);- const segment = Math.min(points.length - 2, Math.floor(t * (points.length - 1)));- const f = t * (points.length - 1) - segment;- const f2 = f * f,- f3 = f2 * f;- const point = path.getPoint(t);- point.y =- (2 * f3 - 3 * f2 + 1) * heights[segment] +- (f3 - 2 * f2 + f) * slopes[segment] +- (-2 * f3 + 3 * f2) * heights[segment + 1] +- (f3 - f2) * slopes[segment + 1];- return point;- }- const obstacles = opts.obstacles ?? [- { u: 0.25, lateral: -0.35, radius: width * 0.1 },- { u: 0.52, lateral: 0.42, radius: width * 0.13 },- { u: 0.78, lateral: -0.12, radius: width * 0.09 },- ];- if (!Array.isArray(obstacles) || obstacles.length > 24)- throw new RangeError('makeStream: at most 24 obstacles');- const stones = obstacles.map((o, i) => ({- u: option(o.u, undefined, `makeStream: obstacles[${i}].u`, 0, 1),- lateral: option(o.lateral, 0, `makeStream: obstacles[${i}].lateral`, -0.95, 0.95),- radius: option(o.radius, width * 0.1, `makeStream: obstacles[${i}].radius`, 0.002, width * 0.45),- }));- const phase = rng() * 6.28;- const waveRng = mulberry32(seed ^ 0x57a4f319);- const rippleBands = Array.from({ length: 11 }, (_, i) => {- const wavelength = .28 * 9 ** (i / 10) * (.85 + waveRng() * .3);- const angle = (waveRng() - .5) * 2.6;- const k = 2 * Math.PI / wavelength;- return { ks: k * Math.cos(angle), kl: k * Math.sin(angle),- amplitude: .0064 * wavelength ** .9, phase: waveRng() * Math.PI * 2,- drift: .92 + waveRng() * .16 };- });- const widthAt = (u) =>- width *- (1 +- widthVariation *- (Math.sin(u * 13.38 + phase) * 0.65 + Math.sin(u * 35.81 + phase * 0.7) * 0.35));- const unconstrainedDisplacement =- rippleBands.reduce((sum, wave) => sum + wave.amplitude, 0) * (0.3 + activity) +- stones.reduce((sum, o) => sum + o.radius * 0.105 * activity, 0);- // Keep supported very shallow channels above their bed, including the- // narrower optical column at the bank. This also bounds grazing normals.- const heightScale = Math.min(1, depth * .38 / Math.max(1e-6, unconstrainedDisplacement));- const displacementBound = unconstrainedDisplacement * heightScale;- const bedRelief = Math.min(.018, depth * .12);- const group = new THREE.Group();- group.name = opts.name ?? 'Stream';- group.userData.placement = 'free';- const uniforms = {- streamTime: { value: 0 },- streamSpeed: { value: speed },- streamWidth: { value: width },- streamActivity: { value: activity },- streamPhase: { value: phase },- streamLength: { value: length },- streamWidthVariation: { value: widthVariation },- streamHeightScale: { value: heightScale },- streamEndFade: { value: endFade },- };- const wakeCode = stones- .map(- (o) => `{- float ds=s-${(o.u * length).toFixed(7)}, dl=l-(${(o.lateral * widthAt(o.u) * 0.5).toFixed(7)});- float radius=${o.radius.toFixed(7)};- float gate=smoothstep(-radius*.6,radius*.7,ds)*exp(-max(ds,0.0)/(radius*6.0));- float envelope=exp(-pow(dl/(radius*.8+max(ds,0.0)*.21),2.0));- h+=gate*envelope*sin(ds*10.0-streamTime*streamSpeed*8.0+abs(dl)*4.0)*radius*.105*streamActivity;- }`- )- .join('\n');- const rippleCode = rippleBands.map((wave) =>- `h+=${wave.amplitude.toFixed(8)}*sin((s-streamTime*streamSpeed*${wave.drift.toFixed(7)})*${wave.ks.toFixed(7)}+l*${wave.kl.toFixed(7)}+${wave.phase.toFixed(7)});`- ).join('\n');- const heightGLSL = /* glsl */ `- uniform float streamTime;- uniform float streamSpeed;- uniform float streamWidth;- uniform float streamActivity;- uniform float streamPhase;- uniform float streamLength;- uniform float streamWidthVariation;- uniform float streamHeightScale;- uniform float streamEndFade;- float streamLocalWidth(float s){float u=s/streamLength;return streamWidth*(1.0+streamWidthVariation*(sin(u*13.38+streamPhase)*.65+sin(u*35.81+streamPhase*.7)*.35));}- float streamHeight(float s,float l){- float bank=1.0-pow(clamp(abs(l)/(streamLocalWidth(s)*.5),0.0,1.0),6.0);- float h=0.0;- ${rippleCode}- float riffle=.58+.42*pow(.5+.5*sin(s*.83+l*1.4+streamPhase),2.0);- h*=riffle*(.3+streamActivity);- ${wakeCode}- float endEnvelope=streamEndFade>0.0- ? smoothstep(0.0,streamEndFade,s)*smoothstep(0.0,streamEndFade,streamLength-s):1.0;- return h*bank*streamHeightScale*endEnvelope;- }- `;- // A bounded, vertical-light focusing approximation, evaluated on the same- // moving height field. It modulates only shadowed DIRECT diffuse light, never- // emits white lines in shade. This is not a photon/caustic transport solver.- const causticGLSL = /* glsl */ `- float streamCaustic(vec2 p,float waterDepth){- float e=.07,h=streamHeight(p.x,p.y);- float xx=(streamHeight(p.x+e,p.y)+streamHeight(p.x-e,p.y)-2.0*h)/(e*e);- float yy=(streamHeight(p.x,p.y+e)+streamHeight(p.x,p.y-e)-2.0*h)/(e*e);- float xy=(streamHeight(p.x+e,p.y+e)-streamHeight(p.x+e,p.y-e)-streamHeight(p.x-e,p.y+e)+streamHeight(p.x-e,p.y-e))/(4.0*e*e);- float d=waterDepth*.2498;- float determinant=(1.0+d*xx)*(1.0+d*yy)-d*d*xy*xy;- float focused=clamp(.94/max(.38,abs(determinant)),.68,2.4);- float footprint=max(length(dFdx(p)),length(dFdy(p)));- return mix(1.0,focused,${caustics.toFixed(7)}*(1.0-smoothstep(.045,.18,footprint)));- }- `;- function pathDerivative(u) {- const before = Math.max(0, u - 0.00001),- after = Math.min(1, u + 0.00001);- // s is horizontal path arc length, not the graded 3D curve's arc length.- // Preserve the derivative's magnitude: normalizing it changes ripple slopes.- return gradedPoint(after).sub(gradedPoint(before)).divideScalar((after - before) * length);- }- function frame(u) {- const position = gradedPoint(u),- longitudinal = pathDerivative(u),- tangent = longitudinal.clone().normalize(),- across = new THREE.Vector3(tangent.z, 0, -tangent.x).normalize();- const before = Math.max(0, u - 0.00001),- after = Math.min(1, u + 0.00001),- db = pathDerivative(before), da = pathDerivative(after),- acrossDerivative = new THREE.Vector3(da.z, 0, -da.x).normalize()- .sub(new THREE.Vector3(db.z, 0, -db.x).normalize())- .divideScalar((after - before) * length);- return { position, tangent, across, longitudinal, acrossDerivative };- }- // A bank further from the centreline than the bend's radius folds the- // ribbon back over itself (downward-facing water and bed). Refuse it.- const reach = opts.bed === false ? 0.5 : 0.625;- for (let i = 0; i <= segments; i++) {- const u = i / segments, radius = 1 / Math.max(1e-9, frame(u).acrossDerivative.length());- if (radius <= widthAt(u) * reach)- throw new RangeError(`makeStream: the path bends tighter (radius ${radius.toFixed(2)} m at u=${u.toFixed(3)}) `- + `than the ${opts.bed === false ? 'water' : 'bed'} half-width ${(widthAt(u) * reach).toFixed(2)} m; `- + 'narrow the stream or widen the bend');- }- function height(s, l, t) {- const bank = 1 - Math.pow(Math.min(1, Math.abs(l) / (widthAt(s / length) * 0.5)), 6);- let h = 0;- for (const wave of rippleBands)- h += wave.amplitude * Math.sin((s - t * speed * wave.drift) * wave.ks + l * wave.kl + wave.phase);- const riffle = .58 + .42 * (.5 + .5 * Math.sin(s * .83 + l * 1.4 + phase)) ** 2;- h *= riffle * (.3 + activity);- for (const o of stones) {- const ds = s - o.u * length,- dl = l - o.lateral * widthAt(o.u) * 0.5,- r = o.radius;- let g = Math.max(0, Math.min(1, (ds + r * 0.6) / (r * 1.3)));- g = g * g * (3 - 2 * g) * Math.exp(-Math.max(ds, 0) / (r * 6));- const envelope = Math.exp(-Math.pow(dl / (r * 0.8 + Math.max(ds, 0) * 0.21), 2));- h +=- g *- envelope *- Math.sin(ds * 10 - t * speed * 8 + Math.abs(dl) * 4) *- r *- 0.105 *- activity;- }- const endEnvelope = endFade > 0- ? THREE.MathUtils.smoothstep(s, 0, endFade) * THREE.MathUtils.smoothstep(length-s, 0, endFade) : 1;- return h * bank * heightScale * endEnvelope;- }- function makeRibbon(bed = false) {- const positions = [],- uv = [],- flows = [],- longitudinals = [],- acrosses = [],- indices = [];- for (let i = 0; i <= segments; i++) {- const u = i / segments,- f = frame(u);- for (let j = 0; j <= acrossSegments; j++) {- const lateral = (j / acrossSegments) * 2 - 1,- l = lateral * widthAt(u) * 0.5 * (bed ? 1.25 : 1);- const p = f.position.clone().addScaledVector(f.across, l);- if (bed)- p.y -= depth * (1 - 0.55 * (l / (widthAt(u) * .5)) ** 2) + bedRelief * Math.sin(i * 0.61 + j * 1.23);- positions.push(p.x, p.y, p.z);- uv.push(j / acrossSegments, u);- flows.push(u * length, l);- // Partial derivative of C(s) + l*A(s), holding lateral metres l fixed.- // Width variation adds a multiple of the across derivative, which drops- // out of their cross product, so this basis also covers tapered banks.- const longitudinal = f.longitudinal.clone().addScaledVector(f.acrossDerivative, l);- longitudinals.push(longitudinal.x, longitudinal.y, longitudinal.z);- acrosses.push(f.across.x, f.across.y, f.across.z);- if (i < segments && j < acrossSegments) {- const a = i * (acrossSegments + 1) + j,- b = a + acrossSegments + 1;- indices.push(a, b, a + 1, b, b + 1, a + 1);- }- }- }- const g = new THREE.BufferGeometry();- g.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));- g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));- g.setAttribute('streamFlow', new THREE.Float32BufferAttribute(flows, 2));- g.setAttribute('streamLongitudinal', new THREE.Float32BufferAttribute(longitudinals, 3));- g.setAttribute('streamAcross', new THREE.Float32BufferAttribute(acrosses, 3));- g.setIndex(indices);- g.computeVertexNormals();- g.computeBoundingBox();- g.computeBoundingSphere();- g.boundingBox.expandByScalar(displacementBound);- g.boundingSphere.radius += displacementBound;- return g;- }- const material = new THREE.MeshPhysicalMaterial({- name: 'ClearStreamWater',- color: 0xffffff,- roughness: 0.04,- metalness: 0,- ior: 1.333,- clearcoat: 0,- transmission: 1,- thickness: depth,- attenuationColor: opts.waterColor ?? 0x80b6a6,- attenuationDistance,- opacity: 1,- depthWrite: true,- side: THREE.FrontSide,- envMapIntensity: 1,- });- const foamCode = stones- .map(- (o) => `{- float ds=vStreamFlow.x-${(o.u * length).toFixed(7)},dl=vStreamFlow.y-(${(o.lateral * widthAt(o.u) * 0.5).toFixed(7)}), r=${o.radius.toFixed(7)};- float downstream=smoothstep(-r*.4,r*.4,ds)*exp(-max(ds,0.0)/(r*3.8));- float wakeWidth=r*.7+max(ds,0.0)*.22;- float wakes=exp(-pow((abs(dl)-wakeWidth*.7)/(r*.3+max(ds,0.0)*.08),2.0));- wakeFoam+=downstream*wakes;- }`- )- .join('\n');- material.onBeforeCompile = (shader) => {- Object.assign(shader.uniforms, uniforms);- shader.vertexShader = shader.vertexShader- .replace(- '#include <common>',- `#include <common>\nattribute vec2 streamFlow; attribute vec3 streamLongitudinal; attribute vec3 streamAcross; varying vec2 vStreamFlow; varying vec3 vStreamPosition; varying vec3 vStreamLongitudinal; varying vec3 vStreamAcross;\n${heightGLSL}`- )- .replace(- '#include <beginnormal_vertex>',- /* glsl */ `- float hs=(streamHeight(streamFlow.x+.015,streamFlow.y)-streamHeight(streamFlow.x-.015,streamFlow.y))/.03;- float hl=(streamHeight(streamFlow.x,streamFlow.y+.015)-streamHeight(streamFlow.x,streamFlow.y-.015))/.03;- vec3 objectNormal=normalize(cross(streamLongitudinal+vec3(0,hs,0),streamAcross+vec3(0,hl,0)));- #ifdef USE_TANGENT- vec3 objectTangent=vec3(tangent.xyz);- #endif- `- )- .replace(- '#include <begin_vertex>',- `vec3 transformed=position; transformed.y+=streamHeight(streamFlow.x,streamFlow.y); vStreamFlow=streamFlow;vStreamPosition=transformed;vStreamLongitudinal=streamLongitudinal;vStreamAcross=streamAcross;`- );- shader.fragmentShader = shader.fragmentShader- .replace(- '#include <common>',- `#include <common>\nuniform mat3 normalMatrix; varying vec2 vStreamFlow; varying vec3 vStreamPosition; varying vec3 vStreamLongitudinal; varying vec3 vStreamAcross;\n${heightGLSL}\n#define ASTRA_FRAG\n${noiseGLSL}`- )- .replace(- '#include <color_fragment>',- /* glsl */ `- #include <color_fragment>- vec2 advect=vec2(vStreamFlow.x-streamTime*streamSpeed,vStreamFlow.y);- float cellular=astraNoise2(advect*vec2(4.5,15.0));- float fine=astraNoise2(advect*vec2(12.0,29.0));- float wakeFoam=0.0;- ${foamCode}- float foam=clamp(wakeFoam*smoothstep(.52,.80,cellular*.7+fine*.3)*.52*streamActivity,0.0,.72);- float bank=pow(clamp(abs(vStreamFlow.y)/(streamLocalWidth(vStreamFlow.x)*.5),0.0,1.0),8.0);- foam=max(foam,bank*smoothstep(.76,.94,cellular)*.055*streamActivity);- diffuseColor.rgb=mix(diffuseColor.rgb,vec3(.74,.78,.72),foam);- // The refracted path reaches the graded bed rather than a flat sheet of- // constant thickness. Absorption belongs to the volume, not its surface.- float opticalDepth=${depth.toFixed(7)}*(1.0-.55*pow(vStreamFlow.y/(streamLocalWidth(vStreamFlow.x)*.5),2.0));- `- )- .replace(- '#include <normal_fragment_maps>',- `#include <normal_fragment_maps>- // Evaluate resolved slopes per fragment, not by interpolating sparse- // vertex normals. Screen-footprint averaging removes distant sparkle.- float flowFootprint=max(length(dFdx(vStreamFlow)),length(dFdy(vStreamFlow)));- float slopeStep=max(.015,flowFootprint*.6);- float streamHs=(streamHeight(vStreamFlow.x+slopeStep,vStreamFlow.y)-streamHeight(vStreamFlow.x-slopeStep,vStreamFlow.y))/(2.0*slopeStep);- float streamHl=(streamHeight(vStreamFlow.x,vStreamFlow.y+slopeStep)-streamHeight(vStreamFlow.x,vStreamFlow.y-slopeStep))/(2.0*slopeStep);- normal=normalize(normalMatrix*cross(vStreamLongitudinal+vec3(0,streamHs,0),vStreamAcross+vec3(0,streamHl,0)));- float microFilter=1.0-smoothstep(.035,.14,flowFootprint);- float streamMicro=(astraNoise2(advect*vec2(8.0,12.0))*.0012+astraNoise2(advect*vec2(19.0,24.0))*.0003)*microFilter;- normal=astraBump(-vViewPosition,normal,streamMicro);- `- )- .replace(- '#include <roughnessmap_fragment>',- `#include <roughnessmap_fragment>\nroughnessFactor=mix(roughnessFactor,.67,foam);`- )- .replace(- '#include <transmission_pars_fragment>',- THREE.ShaderChunk.transmission_pars_fragment.replaceAll(- 'refractionCoords /= 2.0;', `refractionCoords /= 2.0;- // Offscreen refraction has no valid source texel. Blend sampled- // radiance at the border, never interpolate UV coordinates: a UV- // blend folds the image and stretches pebbles into vertical bands.- vec4 surfaceNdc=projMatrix*viewMatrix*vec4(position,1.0);- vec2 streamSurfaceUv=surfaceNdc.xy/surfaceNdc.w*.5+.5;- vec2 border=min(refractionCoords,1.0-refractionCoords);- float streamInFrame=smoothstep(0.0,.06,min(border.x,border.y));- `- ).replace('transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );',- `transmittedLight = mix(getTransmissionSample(streamSurfaceUv,roughness,ior),- getTransmissionSample(clamp(refractionCoords,vec2(0.0),vec2(1.0)),roughness,ior),streamInFrame);`)- .replace('vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );',- `vec4 transmissionSample = mix(getTransmissionSample(streamSurfaceUv,roughness,iors[i]),- getTransmissionSample(clamp(refractionCoords,vec2(0.0),vec2(1.0)),roughness,iors[i]),streamInFrame);`)- .replace('return normalize( refractionVector ) * thickness * modelScale;',- // Our thickness below is the solved WORLD ray distance. Scaling a- // world direction componentwise would bend it under rotated scale.- 'return normalize( refractionVector ) * thickness;')- )- .replace(- '#include <transmission_fragment>',- THREE.ShaderChunk.transmission_fragment- .replace('material.transmission = transmission;', 'material.transmission = transmission * (1.0 - foam);')- .replace('material.thickness = thickness;', `- vec3 streamWorldNormal=inverseTransformDirection(normal,viewMatrix);- vec3 streamRay=refract(-normalize(cameraPosition-vWorldPosition),streamWorldNormal,1.0/ior);- vec3 streamLocalRay=inverse(mat3(modelMatrix))*streamRay;- vec3 streamBedNormal=normalize(cross(vStreamLongitudinal,vStreamAcross));- float streamBedDistance=(opticalDepth+streamHeight(vStreamFlow.x,vStreamFlow.y))*streamBedNormal.y;- material.thickness=max(0.0,streamBedDistance)/max(1e-8,abs(dot(streamLocalRay,streamBedNormal)));- `)- );- if (reflectionSize) {- shader.fragmentShader = shader.fragmentShader- .replace('#include <common>', '#include <common>\nuniform sampler2D streamReflection;uniform mat4 streamReflectionMatrix;')- .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>- vec4 reflectionCoord=streamReflectionMatrix*vec4(vStreamPosition,1.0);- vec2 reflectionUv=reflectionCoord.xy/reflectionCoord.w;- vec3 viewFlat=normalize(normalMatrix*vec3(0.0,1.0,0.0));- reflectionUv+=(normal.xy-viewFlat.xy)*.025;- vec2 reflectionEdge=min(reflectionUv,1.0-reflectionUv);- float reflectionWeight=smoothstep(0.0,.04,min(reflectionEdge.x,reflectionEdge.y))*(1.0-foam);- float reflectionLod=clamp(log2(max(1.0,length(fwidth(reflectionUv))*${reflectionSize.toFixed(1)})),0.0,6.0);- vec3 bankReflection=textureLod(streamReflection,clamp(reflectionUv,vec2(.001),vec2(.999)),reflectionLod).rgb;- vec3 reflectionF=EnvironmentBRDF(normal,geometryViewDir,material.specularColorBlended,material.specularF90,material.roughness);- reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,bankReflection*reflectionF,reflectionWeight);- `);- }- };- material.customProgramCacheKey = () =>- `stream-v4-${seed}-${width}-${widthVariation}-${depth}-${length}-${reflectionSize}-${JSON.stringify(stones)}`;- const surface = new THREE.Mesh(makeRibbon(), material);- surface.name = 'StreamSurface';- surface.receiveShadow = true;- surface.renderOrder = 2;- group.add(surface);- let reflection = null;- if (reflectionSize) {- // The helper never enters the scene graph. Only its clipped virtual camera- // and owned render target are used, so it cannot add a visible water slab.- reflection = new Reflector(new THREE.PlaneGeometry(1, 1), {- textureWidth: reflectionSize, textureHeight: reflectionSize, multisample: 0,- });- const first = frame(0).position, last = frame(1).position;- const direction = last.clone().sub(first);- const grade = direction.y / Math.max(.001, direction.x ** 2 + direction.z ** 2);- const gradeNormal = new THREE.Vector3(-direction.x * grade, 1, -direction.z * grade).normalize();- reflection.position.copy(frame(.5).position);- reflection.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), gradeNormal);- reflection.updateMatrix();- const target = reflection.getRenderTarget();- target.texture.generateMipmaps = true;- target.texture.minFilter = THREE.LinearMipmapLinearFilter;- uniforms.streamReflection = { value: target.texture };- uniforms.streamReflectionMatrix = { value: new THREE.Matrix4() };- // The helper Reflector is placed on the group's (possibly affine) mean- // grade; its texture matrix is mapped back onto the surface's positions.- planarCapture(surface, (renderer, scene, camera, toRigid) => {- reflection.onBeforeRender(renderer, scene, camera);- uniforms.streamReflectionMatrix.value- .copy(reflection.material.uniforms.textureMatrix.value).multiply(toRigid);- }, { mirror: reflection, frame: group, normal: gradeNormal, point: reflection.position,- skip: () => disposed });- }- if (opts.bed !== false) {- const bedMaterial = new THREE.MeshStandardMaterial({- color: opts.bedColor ?? 0x554a35,- roughness: 0.9,- });- bedMaterial.onBeforeCompile = (shader) => {- Object.assign(shader.uniforms, uniforms);- shader.vertexShader = shader.vertexShader- .replace('#include <common>', '#include <common>\nattribute vec2 streamFlow; varying vec2 vBedFlow; varying vec3 vGravelPosition;')- .replace(- '#include <begin_vertex>',- '#include <begin_vertex>\nvGravelPosition=position;vBedFlow=streamFlow;'- );- shader.fragmentShader = shader.fragmentShader- .replace(- '#include <common>',- `#include <common>\nvarying vec3 vGravelPosition;varying vec2 vBedFlow;\n${noiseGLSL}\n${heightGLSL}\n${causticGLSL}`- )- .replace(- '#include <color_fragment>',- /* glsl */ `- #include <color_fragment>- vec2 gp=vGravelPosition.xz*26.0;- vec2 cell=floor(gp), frac=fract(gp);- float d1=5.0,d2=5.0,stoneTone=.0;- for(int x=-1;x<=1;x++)for(int y=-1;y<=1;y++){- vec2 offset=vec2(float(x),float(y));- vec2 jitter=vec2(astraHash21(cell+offset),astraHash21(cell+offset+53.2));- float dist=length(offset+jitter-frac);- if(dist<d1){d2=d1;d1=dist;stoneTone=astraHash21(cell+offset+19.1);}else if(dist<d2)d2=dist;- }- float filterWidth=max(length(dFdx(gp)),length(dFdy(gp)));- float seam=smoothstep(.015,.10,d2-d1);- float gravelDetail=mix(.68,.86+stoneTone*.4,seam);- diffuseColor.rgb*=mix(gravelDetail,.91,smoothstep(.45,1.6,filterWidth));- diffuseColor.rgb=mix(diffuseColor.rgb,diffuseColor.rgb*vec3(.66,.77,.75),.2);- `- )- .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>- float waterDepth=${depth.toFixed(7)}*(1.0-.55*pow(vBedFlow.y/(streamLocalWidth(vBedFlow.x)*.5),2.0));- reflectedLight.directDiffuse*=streamCaustic(vBedFlow,max(0.0,waterDepth));- `);- };- bedMaterial.customProgramCacheKey = () => `stream-bed-v2-${material.customProgramCacheKey()}-${caustics}`;- const bed = new THREE.Mesh(makeRibbon(true), bedMaterial);- bed.name = 'StreamBed';- bed.receiveShadow = true;- group.add(bed);- // One geometry/material/draw call for gravel, actual silhouettes under water.- if (count > 0) {- const stoneGeo = new THREE.IcosahedronGeometry(1, 2);- const sp = stoneGeo.attributes.position;- for (let i = 0; i < sp.count; i++) {- const x = sp.getX(i),- y = sp.getY(i),- z = sp.getZ(i),- r = 1 + 0.13 * Math.sin(x * 4.7 + y * 3.1) * Math.cos(z * 5.3 - x * 2.3);- sp.setXYZ(i, x * r, y * r, z * r);- }- smoothCobbleNormals(stoneGeo);- const stoneMaterial = new THREE.MeshStandardMaterial({- color: 0xc5bfae,- roughness: 0.72,- });- const pebbleFlows = new Float32Array(count * 3);- const pebbleFrames = new Float32Array(count * 2);- stoneMaterial.onBeforeCompile = (shader) => {- Object.assign(shader.uniforms, uniforms);- shader.vertexShader = shader.vertexShader- .replace('#include <common>', '#include <common>\nattribute vec3 pebbleFlow;attribute vec2 pebbleFrame;varying vec3 vPebbleFlow;varying vec3 vPebblePoint;')- .replace('#include <project_vertex>', `- vec3 stoneOffset=(instanceMatrix*vec4(transformed,0.0)).xyz;- vPebbleFlow=pebbleFlow+vec3(dot(stoneOffset.xz,pebbleFrame),dot(stoneOffset.xz,vec2(pebbleFrame.y,-pebbleFrame.x)), -stoneOffset.y);- vPebblePoint=(instanceMatrix*vec4(transformed,1.0)).xyz;- #include <project_vertex>- `);- shader.fragmentShader = shader.fragmentShader- .replace('#include <common>', `#include <common>\nvarying vec3 vPebbleFlow;varying vec3 vPebblePoint;\n${noiseGLSL}\n${heightGLSL}\n${causticGLSL}`)- .replace('#include <color_fragment>', `#include <color_fragment>- float mineral=astraNoise2(vPebblePoint.xz*43.0+vPebblePoint.y*29.0);- float grain=astraNoise2(vPebblePoint.xz*167.0+vPebblePoint.y*97.0);- float filterWidth=max(length(dFdx(vPebblePoint)),length(dFdy(vPebblePoint)));- diffuseColor.rgb*=mix(.70+mineral*.55+grain*.25,1.1,smoothstep(.008,.04,filterWidth));- `)- .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>\nreflectedLight.directDiffuse*=streamCaustic(vPebbleFlow.xy,max(0.0,vPebbleFlow.z));`);- };- stoneMaterial.customProgramCacheKey = () => `stream-cobble-v2-${material.customProgramCacheKey()}-${caustics}`;- const pebbles = new THREE.InstancedMesh(stoneGeo, stoneMaterial, count);- pebbles.name = 'SubmergedPebbles';- pebbles.receiveShadow = true;- const temp = new THREE.Object3D(),- color = new THREE.Color();- for (let i = 0; i < count; i++) {- const u = 0.01 + rng() * 0.98,- lateral = (rng() * 2 - 1) * 0.91,- f = frame(u),- r = 0.035 + rng() ** 1.6 * 0.13;- temp.position.copy(f.position).addScaledVector(f.across, lateral * widthAt(u) * 0.5);- temp.position.y -= depth * (1 - 0.55 * lateral * lateral) - r * 0.2;- temp.scale.set(- r * (0.8 + rng() * 0.6),- r * (0.45 + rng() * 0.4),- r * (1 + rng() * 0.65)- );- temp.rotation.set((rng() - .5) * .32, rng() * 6.28, (rng() - .5) * .32);- temp.updateMatrix();- pebbles.setMatrixAt(i, temp.matrix);- pebbleFlows.set([u * length, lateral * widthAt(u) * .5, depth * (1 - .55 * lateral * lateral)], i * 3);- pebbleFrames.set([f.tangent.x, f.tangent.z], i * 2);- color.setHSL(0.065 + rng() * 0.07, 0.08 + rng() * 0.22, 0.07 + rng() * 0.16);- pebbles.setColorAt(i, color);- }- pebbles.instanceMatrix.needsUpdate = true;- pebbles.instanceColor.needsUpdate = true;- stoneGeo.setAttribute('pebbleFlow', new THREE.InstancedBufferAttribute(pebbleFlows, 3));- stoneGeo.setAttribute('pebbleFrame', new THREE.InstancedBufferAttribute(pebbleFrames, 2));- group.add(pebbles);- }- }- // Wake-generating cobbles are actual obstacles, not white decals in empty water.- for (let i = 0; i < stones.length; i++) {- const o = stones[i],- f = frame(o.u),- geo = new THREE.IcosahedronGeometry(o.radius, 2),- attr = geo.attributes.position;- for (let j = 0; j < attr.count; j++) {- const v = new THREE.Vector3().fromBufferAttribute(attr, j);- const k = 1 + 0.075 * Math.sin(v.x * 19 + v.z * 13) * Math.cos(v.y * 23);- v.multiplyScalar(k);- attr.setXYZ(j, v.x, v.y, v.z);- }- smoothCobbleNormals(geo);- const mat = new THREE.MeshStandardMaterial({- color: new THREE.Color().setHSL(0.105, 0.1, 0.065 + rng() * 0.045),- roughness: 0.47,- });- const rock = new THREE.Mesh(geo, mat);- rock.name = `StreamObstacle_${i}`;- rock.position.copy(f.position).addScaledVector(f.across, o.lateral * widthAt(o.u) * 0.5);- rock.position.y -= o.radius * 0.32;- rock.scale.set(1, 0.72, 1.15);- rock.rotation.y = rng() * 6.28;- rock.castShadow = rock.receiveShadow = true;- group.add(rock);- }- let time = 0,- disposed = false;- group.userData.update = (t) => {- if (!Number.isFinite(t)) throw new RangeError('makeStream: time must be finite');- time = t;- uniforms.streamTime.value = t;- };- group.userData.sample = (u, lateral = 0, t = time) => {- if (- !Number.isFinite(u) ||- u < 0 ||- u > 1 ||- !Number.isFinite(lateral) ||- Math.abs(lateral) > 1 ||- !Number.isFinite(t)- )- throw new RangeError(- 'makeStream: sample requires u in [0,1], lateral in [-1,1], finite time'- );- const f = frame(u),- s = u * length,- l = lateral * widthAt(u) * 0.5;- f.position.addScaledVector(f.across, l);- f.position.y += height(s, l, t);- const hs = (height(s + 0.015, l, t) - height(s - 0.015, l, t)) / 0.03,- hl = (height(s, l + 0.015, t) - height(s, l - 0.015, t)) / 0.03;- const normal = f.longitudinal- .clone()- .addScaledVector(f.acrossDerivative, l)- .add(new THREE.Vector3(0, hs, 0))- .cross(f.across.clone().add(new THREE.Vector3(0, hl, 0)))- .normalize();- return {- position: f.position,- tangent: f.tangent,- normal,- depth: depth * (1 - 0.55 * lateral * lateral),- speed,- width: widthAt(u),- };- };- // The helper Reflector never enters the graph: its geometry, material and- // render target are owned explicitly.- const owned = snapshotResources(group);- if (reflection) owned.add(reflection.geometry).add(reflection);- owned.add({ dispose() { disposed = true; } });- attachDisposal(group, owned);- group.userData.surface = surface;- group.userData.length = length;- group.userData.description =- 'Graded kinematic stream with geometric ripples, cobble wakes and depth-dependent opaque-scene refraction; no arbitrary fluid collisions';- return group;-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.jsdeleted file mode 100644index 3a7fb90b..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/submerged.js+++ /dev/null@@ -1,616 +0,0 @@-/**- * Submerged: the water column over what is under it, the rings rain- * leaves on open water, and a sheet of thin ice over either.- *- * A waterline alone leaves a sunk rock as a rock with a line across- * it. What says UNDER is the column: contrast falls, the colour walks- * toward the water's own, and red goes first — over DEPTH and over the- * distance the eye looks through, so a deep floor far off is further- * gone than the same floor underfoot.- *- * The two patches go through `patchStandard`, so each material keeps- * its lighting, shadows, fog and depth chunks and they CHAIN with the- * waterline (`waterside.js`), the caustic net (`caustics.js`) and the- * rock projection (`terrain_shade.js`) the same surface already wears.- * `makeRainRings` is the open-water half of `rain.js`, whose splashes- * are for hard ground.- *- * NOT a reflective surface: the reflection is `water.js`'s RTT plane.- * Everything here shades what is under that plane or lies on it.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { lehmer } from './noise.js';-import {- composeRoughness, makeShaderMaterial, instancedQuad, keepOutOfDepthPasses,- seedLattice, toColor, unit, withBase, worldBase,-} from './shader.js';--// Water absorbs red an order of magnitude faster than blue, and that-// spectrum IS the effect. Pure water is 1 : 0.21 : 0.054; lifted a-// little so a 3 m pool does not go pure cyan.-const EXT_RATIO = new THREE.Vector3(1.0, 0.26, 0.10);--// Above the surface it lies on: clears z-fighting with a coplanar-// water plane, and stays inside the 2 cm an asset's base is allowed.-const LIFT = 0.012;--// One base for both patches, on the world varyings caustics and-// waterside share, so a submerged bank wearing a waterline, a net and-// this declares ONE pair.-const BASE = worldBase('submerged:base', 'subWp', 'subWn');--const seedOffset = (seed) => new THREE.Vector2(seedLattice(seed) * 0.091,- seedLattice(seed, 48271) * 0.067);--/**- * Per-channel extinction: a scalar on water's spectrum, or three- * coefficients given outright (THREE.Vector3 or [r, g, b], per metre).- */-function extinctionVec(value) {- const channels = value?.isVector3 ? value.toArray() : Array.isArray(value) ? value : null;- if (channels) {- if (channels.length !== 3 || !channels.every(k => Number.isFinite(k) && k >= 0)) {- throw new RangeError('patchUnderwater: extinction requires three finite nonnegative coefficients');- }- return new THREE.Vector3(...channels);- }- const k = value === undefined ? 0.35 : value;- if (!Number.isFinite(k) || k < 0) {- throw new RangeError('patchUnderwater: extinction must be finite and nonnegative');- }- return EXT_RATIO.clone().multiplyScalar(k);-}--const UNDER_HEAD = [- 'uniform float uSubLevel;',- 'uniform vec3 uSubExt;',- 'uniform vec3 uSubColor;',- 'uniform float uSubMurk;',- 'uniform float uSubLight;',- 'uniform vec2 uSubSeed;',-].join('\n');--const UNDER_BODY = [- ' float subD = max(uSubLevel - vAstraWorld.y, 0.0);',- // The eye ray counts only where it runs UNDER the surface: this- // fragment's share of the climb to the camera, which is 0 at the- // line however far away the camera is.- ' float subRise = max(cameraPosition.y - vAstraWorld.y, 1e-4);',- ' float subWet = clamp(subD / subRise, 0.0, 1.0);',- ' float subView = length(cameraPosition - vAstraWorld) * subWet;',- // Silt drifts. A uniform column is glass, and a still one is a- // stain, so the path length rides a slow seeded field.- ' vec2 subQ = vAstraWorld.xz * 0.13 + uSubSeed',- ' + vec2(uTime * 0.011, uTime * -0.008);',- ' float subS = uSubMurk * (astraFbm2(subQ, 3) - 0.44);',- ' float subMk = 1.0 + subS;',- // Turbidity is not a dimmer, it is a HUE. Silt scatters green and- // drinks blue, so the cloudy reaches of one pool run green where the- // clear ones run blue — and ONE flat teal over a whole basin is the- // tell of a tint rather than a column. The swings are bounded: murk- // caps at 1 and the field at -0.44, so no coefficient can go- // negative and amplify with depth.- ' vec3 subK = uSubExt',- ' * vec3(1.0, 1.0 - 0.30 * subS, 1.0 + 1.60 * subS);',- ' vec3 subT = exp(-subK * ((subD + subView) * subMk));',- // Beer-Lambert down and back out: what the surface returns is- // absorbed along both legs, and red is gone first.- ' diffuseColor.rgb *= subT;',- // The column scatters into the ray exactly what the ray lost, lit- // by the blue that got this deep — so contrast dies into the- // water's own colour rather than into black. (Filtering the veil per- // CHANNEL here is the more literal physics and was measured to be- // worse: the red of a green-blue water colour is already near zero- // in linear, so the deep end clipped to one channel and came out a- // flat, hyper-saturated cyan — mean saturation 0.930 -> 0.941 with- // no visible gain.)- // ...and by how much light there is to scatter at all. The veil is- // LIGHT, and no fragment hook can see the scene's lamps — the head- // is injected above <lights_pars_begin> — so a column left at the- // daylight number glows the same green through a night scene, which- // is the one thing a still of a night pool never shows.- ' vec3 subVeil = uSubColor * uSubLight * (1.0 - subT)',- ' * exp(-uSubExt.b * subD);',- // The same silt that swung the path swings the COLOUR: a turbid- // reach scatters green where a clear one runs blue, so one pool is- // never one teal. This is where the murk becomes visible — inside- // the exponent it only moves an already-saturated exponential.- ' subVeil = astraHueBreak(subVeil, subQ, 1.0, 0.30 + 0.9 * uSubMurk);',- // A basin is a hundred-pixel ramp of a smooth exponential, which is- // exactly where 8-bit output lays down contour bands (measured: the- // longest constant run across the deep water fell from 31 px to 7).- ' subVeil *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.07;',- ' totalEmissiveRadiance += subVeil;',-].join('\n');--/**- * Sink a surface into a water column: contrast out, water colour in.- *- * Nothing above `level` is touched — the depth is clamped at the line- * and the eye ray's underwater share goes to zero there too, so the- * transmittance is exactly 1 and the veil exactly 0 above it, with no- * step at the line. Below it the loss runs on the TOTAL path: the- * depth the light fell through plus the underwater length of the ray- * back to the camera. That second leg is what makes the far end of a- * pool floor read as further away rather than merely darker, and it is- * why a bank photographs bluer across a bay than at your feet.- *- * Extinction is per channel, which is the whole point: red is gone in- * a couple of metres where blue runs for tens, so the albedo walks to- * the water's colour red-first while the veil the column scatters back- * fills in what was lost. Contrast between two neighbouring albedos- * falls by exactly the transmittance, because both take the same veil.- *- * Turbidity is a HUE, not a second dimmer. The silt field that swings- * the path length also swings the SPECTRUM — silt scatters green and- * drinks blue — and it swings the veil's own colour with it, so the- * cloudy reaches of one pool run green where the clear ones run blue.- * One flat teal over a whole basin is the tell of a tint rather than a- * column, and it costs one field that was already being sampled. The- * veil then carries a per-pixel dither, because a basin is a hundred- * pixels of a smooth exponential and that is where 8-bit output lays- * contours (measured here: the longest constant run across the deep- * water fell from 31 px to 7).- *- * WITH `caustics.js`: they are two halves of one surface and belong on- * the same material at the same `level`. `patchCaustics` ADDS its net- * to `totalEmissiveRadiance` tinted by `diffuseColor`; this MULTIPLIES- * `diffuseColor` by the transmittance and adds the column's veil to- * that same term. Patches run in CALL ORDER, so call this one FIRST- * and the net is tinted by the already-extinguished albedo instead of- * burning white over water that has eaten every other red in frame.- * The net's own `depthFade` is its extinction: keep it near- * `1 / extinction` or the net will outlive the floor it lands on. Both- * share `vAstraWorld`/`vAstraWorldN` by name, so the pair costs one.- *- * `level` is a world plane, so EVERYTHING under it is under water,- * including the dry outside of a pool wall and the far side of a dam.- * Give those their own material, exactly as `caustics.js` needs.- *- * Needs a LIT material — MeshStandard / MeshPhysical: the veil lands- * on the emissive term, which MeshBasicMaterial does not have. Drive- * it with `tickShaders(scene, t)`; an un-advanced uTime freezes the- * silt, which is a stain rather than a column.- *- * AT NIGHT, set `light`. The veil is scattered LIGHT and it lands on- * the emissive term, so nothing in the scene dims it: a column left at- * the daylight number glows the same green under a night sky, which is- * the one thing a photograph of a night pool never shows (measured- * here: the night basin's water sat at mean luminance 0.42 against a- * 0.25 frame until this was turned down). No fragment hook can read- * the scene's lamps — patchStandard injects its head ABOVE- * `<lights_pars_begin>` — so this is the one number that has to be- * told rather than found.- *- * @param {THREE.Material} material A built-in lit material, patched in- * place.- * @param {object} [opts] `level` world Y of the water surface (default- * 0); `color` THREE.Color or hex the water goes toward (default a- * green-blue); `extinction` per-metre loss — a scalar on water's own- * spectrum (default 0.35) or a THREE.Vector3 / [r, g, b] of- * finite nonnegative coefficients outright; `murk` how far drifting silt swings the- * path length AND its colour, 0..1 (default 0.5); `light` how much- * light there is for the column to scatter, 1 = open daylight- * (default 1; 0.15..0.3 under a night sky, more under a lamp);- * `seed` moves that silt, so two pools are not one pool twice- * (default 1).- * @returns {THREE.Material} The same material, its uniforms live on- * `material.userData.uniforms` so `uSubLevel` can follow a tide.- */-export function patchUnderwater(material, opts = {}) {- const level = opts.level === undefined ? 0 : opts.level;- const murk = opts.murk === undefined ? 0.5 : opts.murk;- // The one silent failure here: no emissive term means either a raw- // ShaderMaterial (no hook at all) or a Basic (no such variable).- if (material && material.emissive === undefined) {- console.warn(- 'patchUnderwater: ' + (material.name || material.type) + ' has '- + 'no emissive term — the column scatters LIGHT back into the '- + 'ray and that lands on totalEmissiveRadiance, which a '- + 'MeshBasicMaterial and a raw ShaderMaterial do not have. '- + 'Patch a lit material instead.');- }- return withBase(material, BASE, {- name: 'submerged:underwater',- uniforms: {- uSubLevel: { value: level },- uSubExt: { value: extinctionVec(opts.extinction) },- uSubColor: { value: toColor(opts.color, 0x1a5b63) },- uSubMurk: { value: unit(murk) },- // A negative here would subtract light and punch black holes in- // the water; there is no upper clamp because a lit pool is a- // real case.- uSubLight: {- value: Math.max(0, opts.light === undefined ? 1 : opts.light),- },- uSubSeed: { value: seedOffset(opts.seed) },- },- fragmentHead: UNDER_HEAD,- fragmentBody: UNDER_BODY,- });-}--const RING_VERTEX_HEAD = [- 'attribute vec3 aCorner;',- 'attribute vec3 iOff;',- 'attribute vec3 iExtra;',- 'uniform float uRingRate;',- 'uniform float uRingSize;',- 'uniform float uRingJit;',-].join('\n');--const RING_VERTEX = [- ' vUv = uv;',- ' float rgP = iExtra.x + uTime * uRingRate;',- ' float rgCyc = floor(rgP);',- ' vAge = fract(rgP);',- // Each cycle the drop lands somewhere new: a ring that re-forms on- // the same spot forever is a sprinkler, not rain.- ' vec2 rgJ = vec2(astraHash21(vec2(iExtra.z, rgCyc)),',- ' astraHash21(vec2(rgCyc, iExtra.z + 7.1))) - 0.5;',- // Every impact catches its own patch of sky: one crest colour over a- // whole field of rings is the tell of a sheet of decals.- ' vRgT = astraHash21(vec2(iExtra.z + 2.7, rgCyc)) - 0.5;',- ' vec3 rgC = iOff + vec3(rgJ.x, 0.0, rgJ.y) * uRingJit;',- // The quad lies FLAT and keeps its size; the wavefront travels- // inside it, so the ring is a place on a surface, not a sprite that- // scales up.- ' transformed = rgC + vec3(aCorner.x, 0.0, aCorner.y)',- ' * (uRingSize * iExtra.y);',-].join('\n');--const RING_FRAGMENT_HEAD = [- 'uniform vec3 uRingColor;',- 'uniform vec3 uRingTrough;',- 'uniform float uRingWidth;',- 'uniform float uRingOpacity;',-].join('\n');--const RING_FRAGMENT = [- ' float rgR = length(vUv * 2.0 - 1.0);',- ' if (rgR > 1.0) discard;',- // Where the wave IS, not how faded a sprite is: the front runs out- // and DECELERATES, so a still frame catches rings bunched near the- // rim and wide apart near the impact.- ' float rgFront = 0.90 * pow(vAge, 0.62);',- ' float rgAA = max(fwidth(rgR), 0.002);',- ' float rgW = max(uRingWidth * (1.0 + rgFront), rgAA * 1.6);',- ' float rgA = (rgR - rgFront) / rgW;',- ' float rgCrest = exp(-rgA * rgA);',- // The capillary train behind the front, and the trough between the- // two. A lone bright circle is a decal; a crest with a dark- // shoulder is a wave on a surface.- ' float rgB = (rgR - rgFront * 0.62) / (rgW * 1.7);',- ' float rgTrain = 0.40 * exp(-rgB * rgB);',- ' float rgD = (rgR - rgFront * 0.84) / (rgW * 1.5);',- ' float rgDip = 0.30 * exp(-rgD * rgD);',- // Amplitude falls as the same water spreads over a longer front,- // then the whole ring dies with age; born soft so it cannot pop.- ' float rgFade = (1.0 - vAge) * smoothstep(0.0, 0.07, vAge)',- ' / (1.0 + 2.2 * rgFront);',- ' rgFade *= 1.0 - smoothstep(0.86, 1.0, rgR);',- // A ring narrower than a couple of pixels can only alias into a- // hard little square, so it does not draw until it has spread.- ' rgFade *= smoothstep(rgAA * 1.2, rgAA * 3.5, rgFront);',- ' float rgUp = rgCrest + rgTrain;',- ' float a = (rgUp + rgDip) * rgFade * uRingOpacity;',- ' if (a < 0.004) discard;',- ' vec3 rgCol = mix(uRingTrough, uRingColor,',- ' rgUp / max(rgUp + rgDip, 1e-4));',- // Warm one drop, cool the next, about the crest colour the caller- // gave: a field of identical rings reads as printed, and the swing- // is per IMPACT rather than per pixel so a single ring stays one- // wave rather than turning speckled.- ' rgCol *= 1.0 + vRgT * vec3(0.34, 0.14, -0.24);',- ' gl_FragColor = vec4(rgCol, clamp(a, 0.0, 1.0));',-].join('\n');--/**- * The expanding rings rain makes on open water.- *- * `rain.js`'s `makeSplashes` is the hard-ground half of this — crowns- * of spray thrown up off a road. On water there is no crown to speak- * of: what you see is a ring of surface travelling out from the- * impact, and the three things that make it read as a surface rather- * than a sprite are all here. The quad is FLAT and a fixed size, so- * the wavefront moves across a patch of water instead of the whole- * card scaling up. The front DECELERATES and its amplitude falls as it- * spreads, so a frozen frame shows rings bunched and faint at the rim- * and wide and sharp near the drop. And each ring is a crest, a- * trailing capillary crest and a DARK trough between them, so it- * bends the water rather than painting a white circle on it.- *- * Impacts relocate every cycle, hashed on the cycle index, so the- * field is rain and not a fixed row of drippers. Add the mesh at the- * scene ROOT (it is world-space, like `rain.js`) and drive it from- * `tick`: `obj.userData.update(t)`, or one `tickShaders(scene, t)`.- *- * It lies `0.012` above `y` to clear a coplanar water plane, and it is- * kept out of the depth passes: a transparent card is a solid wall to- * the ambient-occlusion override material, and this is a field of them.- *- * @param {object} [opts]- * `area` (default `{x: 0, z: 0, w: 24, d: 24}`, or a number for a- * square) the water rect the rings land on;- * `rate` (default 1.6) impacts per second per site;- * `size` (default 0.55) metres across a fully spread ring;- * `y` (default 0) world Y of the water surface;- * `seed` (default 7) placement and phase seed;- * `count` (default 320) impact sites — one draw call regardless;- * `color` (default 0xdfeaf0) the crest, which catches the sky;- * `trough` (default 0x2a3a44) the dark shoulder between the crests;- * `width` (default 0.055) crest thickness as a fraction of `size`;- * `opacity` (default 0.42) peak alpha.- * @returns {THREE.Mesh} Mesh named 'RainRings' with- * `userData.update(t)` advancing the rings.- */-export function makeRainRings(opts = {}) {- // A number is truthy, so `area: 12` would read w/d as undefined and- // put every ring at NaN — measured in rain.js, same trap.- const area = typeof opts.area === 'number'- ? { x: 0, z: 0, w: opts.area, d: opts.area }- : (opts.area || { x: 0, z: 0, w: 24, d: 24 });- const rate = opts.rate === undefined ? 1.6 : opts.rate;- const size = opts.size === undefined ? 0.55 : opts.size;- const y = opts.y === undefined ? 0 : opts.y;- const count = Math.max(1, opts.count === undefined ? 320 : opts.count);- const width = opts.width === undefined ? 0.055 : opts.width;- const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;- const rand = lehmer(opts.seed === undefined ? 7 : opts.seed);-- const off = new Float32Array(count * 3);- const ext = new Float32Array(count * 3);- for (let i = 0; i < count; i++) {- off[i * 3] = area.x + (rand() - 0.5) * area.w;- off[i * 3 + 1] = y + LIFT;- off[i * 3 + 2] = area.z + (rand() - 0.5) * area.d;- ext[i * 3] = rand(); // phase: a still shows all radii- ext[i * 3 + 1] = 0.7 + rand() * 0.6; // size of this drop's ring- ext[i * 3 + 2] = rand() * 97.0; // identity, for the relocation- }- // Culling reads the geometry's SPHERE and `position` is all zeros,- // so a real radius here is what stops three dropping the whole field- // the moment the origin leaves frame.- const reach = Math.hypot(Math.abs(area.x) + area.w * 0.5 + size,- Math.abs(area.z) + area.d * 0.5 + size);- const geo = instancedQuad(count, 1, 1,- Math.hypot(reach, Math.abs(y) + size));- geo.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));- geo.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ext, 3));-- const mat = makeShaderMaterial({- name: 'RainRings',- transparent: true,- depthWrite: false,- side: THREE.DoubleSide,- uniforms: {- uRingRate: { value: rate },- uRingSize: { value: Math.max(size, 1e-3) },- // Relocate inside this site's own share of the rect, so the- // drops cover the water instead of clumping.- uRingJit: {- value: Math.sqrt(Math.max(area.w * area.d, 0) / count),- },- uRingColor: { value: toColor(opts.color, 0xdfeaf0) },- uRingTrough: { value: toColor(opts.trough, 0x2a3a44) },- uRingWidth: { value: Math.max(width, 1e-3) },- uRingOpacity: { value: unit(opacity) },- },- varyings: 'varying vec2 vUv;\nvarying float vAge;\n'- + 'varying float vRgT;',- vertexHead: RING_VERTEX_HEAD,- vertexMain: RING_VERTEX,- fragmentHead: RING_FRAGMENT_HEAD,- fragmentMain: RING_FRAGMENT,- });-- const mesh = new THREE.Mesh(geo, mat);- mesh.name = 'RainRings';- mesh.renderOrder = 2;- mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };- return attachDisposal(keepOutOfDepthPasses(mesh), snapshotResources(mesh));-}--const ICE_VARYING = 'varying vec2 vAstraIceUv;';--const ICE_HEAD = [- 'uniform float uIceThick;',- 'uniform float uIceDens;',- 'uniform float uIceFrost;',- 'uniform float uIceRim;',- 'uniform vec3 uIceColor;',- 'uniform vec2 uIceSeed;',- // Arc length to the nearest of `n` rays from the cell's origin, and- // WHICH ray (mod n, so an arm survives atan's seam). Scaling the- // phase by n makes 2n keep every ray of n and add one between.- 'vec2 astraIceRay(vec2 d, float n, float j) {',- ' float x = (atan(d.y, d.x) * 0.15915494 + j) * n;',- ' float k = floor(x + 0.5);',- ' float g = abs(x - k) / n * 6.2831853 * max(length(d), 0.18);',- ' return vec2(g, mod(k, n));',- '}',- // A crack BRANCHES: the ray count doubles every step out and the two- // levels cross-fade, so an old crack runs on while a new one grows- // from it. Each arm runs its OWN length, or the fan is a snowflake.- 'float astraIceCracks(vec2 p, float w) {',- ' vec2 id = floor(p);',- ' vec2 o = vec2(astraHash21(id), astraHash21(id + 19.7)) - 0.5;',- ' vec2 d = fract(p) - 0.5 - o * 0.6 + 1e-4;',- ' float r = length(d);',- ' float lv = floor(r * 3.0);',- ' float j = astraHash21(id + 3.1);',- ' float n = 3.0 * exp2(lv);',- ' vec2 ra = astraIceRay(d, n, j);',- ' vec2 rb = astraIceRay(d, n * 2.0, j);',- ' float f = fract(r * 3.0);',- ' float g = mix(ra.x, rb.x, f);',- ' float reach = mix(astraHash21(id + ra.y * 0.37 + 5.0),',- ' astraHash21(id + rb.y * 0.37 + 5.0), f);',- ' reach = 0.30 + 0.55 * reach;',- ' return (1.0 - smoothstep(w * 0.35, w, g))',- ' * (1.0 - smoothstep(reach * 0.55, reach, r));',- '}',-].join('\n');--const ICE_BODY = [- // Refract at the surface and run the ray down by the thickness: the- // interior then SLIDES against the surface as the eye moves, which- // is the parallax that reads as looking through something.- ' vec3 iceV = normalize(vAstraWorld - cameraPosition);',- ' vec3 iceN = normalize(vAstraWorldN);',- ' iceN = faceforward(iceN, iceV, iceN);',- // Air into ice is eta < 1, so refract() can never return the zero- // vector here and there is no total-internal-reflection case.- ' vec3 iceRf = refract(iceV, iceN, 0.763);',- ' vec2 icePar = vAstraWorld.xz',- ' + iceRf.xz * (uIceThick / max(abs(iceRf.y), 0.25));',- // Thickness is a column like the water's: what is under the sheet- // dims and takes the ice's colour the further down it sits. Ice is- // CLEAR — a hand's width of it is nearly nothing — so the- // coefficient is 1.6 per metre. At the 3.0 this shipped with, a- // 10 cm sheet mixed a quarter of a pale mint over the dark water and- // landed at an albedo of 0.25 linear, which on a sunlit horizontal- // plane is 200/255 before a single crack is drawn: a milk plate.- ' float iceK = 1.0 - exp(-uIceThick * 1.6);',- ' vec3 iceC = mix(diffuseColor.rgb, uIceColor, iceK);',- ' float iceB = astraFbm2(icePar * 2.6 + uIceSeed, 3);',- ' iceC *= 0.78 + 0.52 * iceB;',- ' iceC = mix(iceC, uIceColor + 0.22,',- ' smoothstep(0.52, 0.86, iceB) * iceK * 0.7);',- // Frozen-in air is not one colour: the bubble clouds scatter warm- // where the light reaches them and the clear ice between runs blue.- ' iceC = astraHueBreak(iceC, icePar * 1.4, 1.0, 0.30);',- // FRESNEL. Everything above came from INSIDE the sheet, and only- // what the surface let in ever got there — at a grazing angle almost- // nothing does, which is why a frozen pond across a bay is a sheet- // of sky and its cracks appear as you walk out onto it. The renderer- // already adds that reflection as specular, so without this term the- // sheet is paid for the sky twice and lands on a white card- // (measured here: 200/255 flat at an 11 deg view, cracks invisible).- ' float iceFz = astraFresnel(iceN, -iceV, 5.0);',- ' iceC *= 1.0 - 0.78 * iceFz;',- // The cracks live on the SURFACE, so they take the unrefracted- // point and they are NOT behind that fresnel: crack over bubble is- // what fixes the two at their depths.- ' vec2 iceP = vAstraWorld.xz * uIceDens + uIceSeed;',- ' iceP += (astraNoise2(iceP * 0.9 + 5.7) - 0.5) * 0.35;',- // A crack is 2 cm of ice wherever it is, so its width is stated in- // METRES and converted by the density — a width in cell units would- // be 5 cm on a dense sheet and 20 cm on a sparse one.- ' float iceW = max(uIceDens * 0.022,',- ' max(fwidth(iceP.x), fwidth(iceP.y)) * 1.3);',- // The second layer is COARSER and turned: a few long masters over- // the finer network, where a finer second layer is only speckle.- ' vec2 iceQ = vec2(iceP.x * 0.6 - iceP.y * 0.8,',- ' iceP.x * 0.8 + iceP.y * 0.6) * 0.55 + 31.7;',- ' float iceCr = max(astraIceCracks(iceP, iceW),',- ' astraIceCracks(iceQ, iceW * 0.55));',- // A fissure is TWO things at once: the fracture planes scatter white- // and the gap between them is a slot of the dark water below. Drawn- // as one bright line it is a chalk mark on a plate, so the core of- // the same field — free, it is already computed — darkens back.- ' float iceCore = smoothstep(0.55, 0.98, iceCr);',- ' iceC = mix(iceC, vec3(0.87, 0.93, 0.96) * (0.84 + 0.30 * iceB),',- ' clamp(iceCr, 0.0, 1.0) * 0.80);',- ' iceC *= 1.0 - 0.55 * iceCore;',- // The rim is the sheet's own UV border — cut the sheet to the bank- // and that border IS the bank — torn by noise, because a bank does- // not rule a straight line.- ' float iceE = min(min(vAstraIceUv.x, 1.0 - vAstraIceUv.x),',- ' min(vAstraIceUv.y, 1.0 - vAstraIceUv.y));',- ' iceE += (astraFbm2(vAstraWorld.xz * 1.7 + uIceSeed, 3) - 0.44)',- ' * uIceRim * 0.9;',- ' float iceFr = astraContact(iceE, uIceRim) * uIceFrost;',- ' float iceFn = astraFbm2(vAstraWorld.xz * 9.0 + uIceSeed, 3);',- ' iceFr *= 0.45 + 0.75 * iceFn;',- // Frost is crystal, not paint. It sits ABOVE the surface, so it does- // not pay the fresnel either, and it is never one white: each patch- // takes its own light and its own warm/cool cast.- ' vec3 iceFc = astraHueBreak(',- ' vec3(0.90, 0.94, 0.97) * (0.84 + 0.28 * iceFn),',- ' vAstraWorld.xz, 0.8, 0.22);',- ' iceC = mix(iceC, iceFc, clamp(iceFr, 0.0, 1.0));',- // A sheet is a wide smooth ramp of thickness, bubble and frost, and- // a smooth ramp is where 8-bit output lays down contour bands.- ' iceC *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.03;',- ' diffuseColor.rgb = clamp(iceC, 0.0, 1.0);',-].join('\n');--/**- * A sheet of thin ice over water or stone: depth, cracks, frosted rim.- *- * Patch the SHEET, and give it the colour of what is UNDER it — the- * dark water or the stone — because that is what the shader takes as- * the thing seen through the ice. Three layers at three depths are- * what makes it a slab rather than a white plane. The interior is- * sampled at the point the eye ray reaches after REFRACTING at the- * surface and running down by `thickness`, so bubbles and murk slide- * against the surface as the camera moves and the sheet acquires a- * near and a far face. The cracks are sampled unrefracted, so they sit- * ON the surface above that interior. The frost sits on top of both.- *- * The interior is behind a FRESNEL and the two surface layers are not.- * Only what the air-ice interface let in ever reached the bubbles, so- * at a grazing angle the interior all but vanishes and what remains is- * the sky the renderer reflects off the sheet as specular: a frozen- * pond across a bay IS a sheet of sky, and its cracks appear as you- * walk out onto it. Without that term the sheet is paid for the sky- * twice and every grazing angle lands on a white card.- *- * The cracks radiate and BRANCH: rays leave a jittered origin per- * cell, and the ray count doubles every step outward with the phase- * scaled to match, which keeps every existing ray and grows a new one- * between them. That is a fork; one noise call is a smear, and it is- * the difference between ice and cracked paint. Two rotated layers are- * maxed together so the cell grid does not read as a grid.- *- * The frosted rim is found from the sheet's own UV border, wandered by- * noise: cut the sheet to fit the bank and that border IS the bank.- * A geometry with no uv has no border, and frosts everywhere — give- * the sheet a PlaneGeometry's uv or pass `frost: 0`.- *- * Gloss goes through `composeRoughness`: this patch writes only at- * `<color_fragment>`, before `<roughnessmap_fragment>`, and does not use- * `patchStandard`'s `roughnessBody`, so roughness is a material value,- * and frostier ice is duller.- *- * @param {THREE.Material} material A built-in material, patched in- * place.- * @param {object} [opts] `thickness` metres of ice, driving the- * parallax and the tint (default 0.08); `crackDensity` crack cells- * per metre (default 0.7 — an origin every metre and a half);- * `frost` how heavy the rim, 0..1 (default 0.8); `rim` width of that- * band in UV, so 0.12 is a tenth of the sheet (default 0.12);- * `color` THREE.Color or hex of the ice itself (default a cold- * green-white); `seed` moves cracks and bubbles (default 1).- * @returns {THREE.Material} The same material, with its uniforms live- * on `material.userData.uniforms`.- */-export function patchThinIce(material, opts = {}) {- const thick = opts.thickness === undefined ? 0.08 : opts.thickness;- const dens = opts.crackDensity === undefined ? 0.7- : opts.crackDensity;- const frost = opts.frost === undefined ? 0.8 : opts.frost;- const rim = opts.rim === undefined ? 0.12 : opts.rim;- // Ice is glossy and frost is not, so the sheet's roughness is the- // one thing here that cannot be a uniform.- composeRoughness(material, 'submerged:thinIce',- 0.18 + 0.62 * unit(frost));- return withBase(material, BASE, {- name: 'submerged:thinIce',- uniforms: {- uIceThick: { value: Math.max(thick, 1e-3) },- uIceDens: { value: Math.max(dens, 1e-3) },- uIceFrost: { value: unit(frost) },- uIceRim: { value: Math.max(rim, 1e-3) },- uIceColor: { value: toColor(opts.color, 0x9fc4c6) },- uIceSeed: { value: seedOffset(opts.seed) },- },- vertexHead: ICE_VARYING,- vertexBody: ' vAstraIceUv = uv;',- fragmentHead: [ICE_VARYING, ICE_HEAD].join('\n'),- fragmentBody: ICE_BODY,- });-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.jsindex 54776857..650bcfae 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/urban.js@@ -12,7 +12,7 @@* billboard without its structure is a floating decal.** COST CONTRACT: `patchCurtainWall` spends NO render target. The scene- * has exactly one (`lib/wetground.js` `makeMirrorFloor` or an ocean),+ * has exactly one (an ocean's reflection),* and a facade is never what should spend it — see the patch's own JSDoc for what it does instead.*/@@ -133,8 +133,8 @@ const CW_BODY = [' vec3 cwRefl = mix(uCwGround, uCwHaze,',' smoothstep(-0.30, 0.01, cwRay.y));',' cwRefl = mix(cwRefl, uCwSky, smoothstep(0.0, 0.55, cwRay.y));',- // Glass FILTERS what is behind it — the room patchWindowInteriors put- // in diffuseColor — and never replaces it; the tint is a hue, so a+ // Glass FILTERS what is behind it — the room already in+ // diffuseColor — and never replaces it; the tint is a hue, so a// dark green glass does not black the interior out.' float cwTm = max(max(uCwTint.r, uCwTint.g), max(uCwTint.b, 1e-3));',' vec3 cwFilt = mix(vec3(1.0), uCwTint / cwTm, 0.85);',@@ -188,8 +188,7 @@ const CW_BODY = [* NO RENDER TARGET, which is the constraint that shapes it. The scene* gets ONE whole-scene reflection pass and a facade must never be what* spends it: a Reflector re-renders the scene (+48 ms/frame- * measured), and `wetground.js` `makeMirrorFloor` spends that one on- * the ground. The other way out costs something this does not: an+ * measured). The other way out costs something this does not: an* envMap material needs an equirect BAKE and hands three's IBL a* roughness-blurred lookup that cannot show the per-panel break-up,* and it does not show the room behind the glass. Here@@ -199,13 +198,12 @@ const CW_BODY = [* Pair it with an `envMap` when you want that; three's IBL runs* underneath this untouched.*- * COMPOSE, do not duplicate: apply `patchWindowInteriors` FIRST and- * this second. It never assigns over `diffuseColor.rgb` — it FILTERS+ * It never assigns over `diffuseColor.rgb` — it FILTERS* what is already there by the glass tint, dims it by what the mirror* takes, and adds the reflection through `totalEmissiveRadiance`. So- * the rooms that patch shades stay visible head-on and are progressively+ * what is behind the glass stays visible head-on and is progressively* replaced by sky toward grazing, which is what the eye reads as glass.- * It chains with `patchMicroBreakup` the same way.+ * It chains with `patchMicroBreakup`.** @param {THREE.Material} material A lit built-in material (MeshStandard* / MeshPhysical — the reflection needs `totalEmissiveRadiance`),diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.jsindex b00c6c70..802253bf 100644--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/veils.js@@ -1,7 +1,7 @@/*** Weather seen AT DISTANCE: the veils, not the drops.*- * `rain.js` gives the drops near the camera — a wrap box a few metres+ * Drops near the camera are a wrap box a few metres* wide, streaks measured in centimetres. A rainy valley needs the other* thing entirely: the pale sheets of rain crossing the far hillside,* tens of metres tall, slanted with the wind, that tell you the weatherdiff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.jsdeleted file mode 100644index 83a69e4a..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/waterfall.js+++ /dev/null@@ -1,205 +0,0 @@-/**- * A gravity-driven sheet spilling over a lip, with advected surface detail,- * thinning optical depth, aeration, impact foam and the existing ballistic spray.- * Origin is the impact water level; the lip is [0,height,0], flow heads toward +Z.- * This is an authored weir/free-fall model, not a fluid or collision solver.- * The caller supplies the cliff, upstream water and receiving pool.- */-import * as THREE from 'three';-import { keepOutOfDepthPasses, option, patchStandard, positive } from './shader.js';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { mulberry32 } from './noise.js';-import { makeSpray } from './watermist.js';--const GRAVITY = 9.81;-const TIERS = { low: [32,48], balanced: [56,96], high: [80,160] };-const clamp = (x,a=0,b=1) => Math.max(a,Math.min(b,x));--const HEAD = /* glsl */`-uniform float uFallHeight;-uniform float uFallWidth;-uniform float uFallFlight;-uniform float uFallSpeed;-uniform float uFallThickness;-uniform float uFallBreakup;-uniform float uFallFoam;-uniform float uFallSeed;-uniform vec4 uFallWaves[4];-varying vec2 vFallUv;-varying vec3 vFallView;-varying float vFallThickness;-float fallWidth(float u, float t) {- return 1.0-.10*u+.025*uFallBreakup*u*sin((t-u*uFallFlight)*3.1+uFallSeed);-}-vec3 fallPosition(vec2 uv,float t) {- float u=uv.y, travel=u*uFallFlight, emitted=t-travel;- float lateral=(uv.x-.5)*uFallWidth;- vec3 p=vec3(lateral*fallWidth(u,t),uFallHeight-4.905*travel*travel,uFallSpeed*travel);- vec3 n=normalize(vec3(0.0,uFallSpeed,9.81*travel));- float ripple=0.0;- for(int i=0;i<4;i++) {- vec4 wave=uFallWaves[i];- ripple+=wave.z*sin(lateral*wave.x-emitted*wave.y+wave.w);- }- return p+n*ripple*(16.0*u*u*(1.0-u)*(1.0-u));-}-`;--/**- * makeWaterfall({width:2,height:3,speed:1,thickness:.045,breakup:.6,- * foam:.65,spray:true,seed:17,quality:'balanced'}) -> Group.- * Metres and seconds. speed is horizontal lip velocity; gravity accelerates- * the sheet downward. thickness is lip depth; downstream thickness follows- * width * velocity * thickness conservation. Set spray:false or foam:0 for- * a clear quiet sheet. No reflection capture is added. Physical transmission- * reads opaque scene colour only, with an approximate thin-film optical path.- * sample(u,lateral,t) uses u=0 at the lip, u=1 at impact, lateral=-.5..+.5.- * Update once with absolute seconds; dispose releases construction-owned data.- */-export function makeWaterfall(opts = {}) {- const L='makeWaterfall: ';- const width=option(opts.width,2,L+'width',.02,500), height=option(opts.height,3,L+'height',.02,500);- const speed=option(opts.speed,1,L+'speed',.02,50);- const thickness=positive(opts.thickness,.045,L+'thickness',Math.min(width,height)*.5);- const breakup=option(opts.breakup,.6,L+'breakup',0,1), foam=option(opts.foam,.65,L+'foam',0,1);- const seed=option(opts.seed,17,L+'seed'), quality=opts.quality??'balanced';- if(!Object.hasOwn(TIERS,quality)) throw new RangeError(`${L}quality must be one of ${Object.keys(TIERS)}`);- // Infinity is a valid attenuation distance: perfectly clear water.- const attenuationDistance=opts.attenuationDistance===Infinity?Infinity:positive(opts.attenuationDistance,8,L+'attenuationDistance');- const sprayRate=option(opts.sprayRate,Math.min(500,100*width),L+'sprayRate',0,100000);- const flight=Math.sqrt(2*height/GRAVITY), impactZ=speed*flight;- const random=mulberry32(seed), waves=[];- for(let i=0;i<4;i++) waves.push(new THREE.Vector4(- (17+i*11.1)/Math.max(width,.05),20.8+i*19.65,- Math.min(width,height)*.004*breakup/(1+i*.8),random()*Math.PI*2));- const phase=random()*6.28;- const widthAt=(u,t) => width*(1-.10*u+.025*breakup*u*Math.sin((t-u*flight)*3.1+phase));- const positionAt=(u,lateral,t) => {- const travel=u*flight,emitted=t-travel;- const n=new THREE.Vector3(0,speed,GRAVITY*travel).normalize();- let ripple=0;- for(const w of waves) ripple+=w.z*Math.sin(lateral*width*w.x-emitted*w.y+w.w);- return new THREE.Vector3(lateral*widthAt(u,t),height-.5*GRAVITY*travel*travel,speed*travel)- .addScaledVector(n,ripple*16*u*u*(1-u)*(1-u));- };- const material=new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:.12,metalness:0,- transmission:1,ior:1.333,thickness,attenuationDistance,- attenuationColor:new THREE.Color(opts.waterColor??0xc9e5df),side:THREE.DoubleSide});- const uniforms={- uFallHeight:{value:height},uFallWidth:{value:width},uFallFlight:{value:flight},- uFallSpeed:{value:speed},uFallThickness:{value:thickness},uFallBreakup:{value:breakup},- uFallFoam:{value:foam},uFallSeed:{value:phase},uFallWaves:{value:waves},- };- patchStandard(material,{name:'WaterfallFilm',uniforms,vertexHead:HEAD,fragmentHead:HEAD,- vertexBody:/* glsl */`- vFallUv=uv;- transformed=fallPosition(uv,uTime);- vFallView=(modelViewMatrix*vec4(transformed,1.0)).xyz;- float velocity=length(vec2(uFallSpeed,9.81*uv.y*uFallFlight));- vFallThickness=uFallThickness*uFallSpeed/(velocity*fallWidth(uv.y,uTime));- `,- fragmentBody:/* glsl */`- float fallEmitted=uTime-vFallUv.y*uFallFlight;- vec2 fallCoordinate=vec2((vFallUv.x-.5)*uFallWidth,fallEmitted);- vec2 fallCoarse=fallCoordinate*vec2(31.0,29.4)+uFallSeed;- vec2 fallFine=fallCoordinate*vec2(137.0,97.0)+uFallSeed;- float fallRibbon=astraNoise2(fallCoarse);- float fallFineResolved=1.0-smoothstep(.30,1.0,max(length(dFdx(fallFine)),length(dFdy(fallFine))));- float fallGrain=mix(.5,astraNoise2(fallFine),fallFineResolved);- float fallStrand=astraNoise2(fallCoordinate*vec2(19.0,4.1)+uFallSeed);- float fallEdge=pow(abs(vFallUv.x-.5)*2.0,10.0);- float fallAir=uFallFoam*smoothstep(.55,1.0,vFallUv.y)- *smoothstep(.36,.72,fallStrand*.35+fallRibbon*.65)*.16- +uFallFoam*fallEdge*.035;- float fallRelief=(fallRibbon*.0007+fallGrain*.00014)*(1.0-fallAir*.6);- diffuseColor.rgb=mix(vec3(1.0),vec3(.91,.96,.97),fallAir);- `,- alphaBody:/* glsl */`- // Aerated edge strands separate late in the fall. The core remains a- // continuous film; discarded gaps reveal the actual background.- float fallGap=smoothstep(.60,.98,vFallUv.y)*uFallBreakup;- if(fallEdge*fallGap*(1.0-fallRibbon)>.33) discard;- `,- normalBody:/* glsl */`- vec3 fallDx=dFdx(vFallView),fallDy=dFdy(vFallView);- vec3 fallN=normalize(cross(fallDx,fallDy));- vec3 fallR1=cross(fallDy,fallN),fallR2=cross(fallN,fallDx);- float fallDet=dot(fallDx,fallR1);- vec3 fallGradient=dFdx(fallRelief)*fallR1+dFdy(fallRelief)*fallR2;- normal=normalize(abs(fallDet)*fallN-sign(fallDet)*fallGradient);- `,- roughnessBody:'roughnessFactor=mix(roughnessFactor,.56,fallAir);',- transmissionBody:'material.transmission*=1.0-fallAir*.97; material.thickness=vFallThickness;',- });- const [nx,ny]=TIERS[quality], positions=[],uvs=[],normals=[],indices=[];- for(let iy=0;iy<=ny;iy++) for(let ix=0;ix<=nx;ix++) {- const u=iy/ny,lateral=ix/nx-.5,p=positionAt(u,lateral,0);- positions.push(...p.toArray());uvs.push(ix/nx,u);- const n=new THREE.Vector3(0,speed,GRAVITY*u*flight).normalize();normals.push(...n.toArray());- if(ix<nx && iy<ny) {- const a=iy*(nx+1)+ix,b=a+1,c=a+nx+1,d=c+1;- indices.push(a,c,b,b,c,d);- }- }- const geometry=new THREE.BufferGeometry();- geometry.setAttribute('position',new THREE.Float32BufferAttribute(positions,3));- geometry.setAttribute('normal',new THREE.Float32BufferAttribute(normals,3));- geometry.setAttribute('uv',new THREE.Float32BufferAttribute(uvs,2));geometry.setIndex(indices);- const margin=waves.reduce((s,w)=>s+w.z,0)+width*.03;- geometry.boundingBox=new THREE.Box3(new THREE.Vector3(-width*.54,-margin,-margin),- new THREE.Vector3(width*.54,height+margin,impactZ+margin));- geometry.boundingSphere=geometry.boundingBox.getBoundingSphere(new THREE.Sphere());- const group=new THREE.Group();group.name=opts.name??'Waterfall';- const sheet=new THREE.Mesh(geometry,material);sheet.name='FallingWaterFilm';- keepOutOfDepthPasses(sheet);group.add(sheet);- let foamMaterial=null;- if(foam>0) {- foamMaterial=new THREE.MeshStandardMaterial({color:0xdce7e7,roughness:.73,transparent:true,- opacity:foam,depthWrite:false,side:THREE.DoubleSide});- patchStandard(foamMaterial,{name:'WaterfallImpact',uniforms:{uImpactFoam:{value:foam},uImpactSeed:{value:phase}},- vertexHead:'varying vec2 vImpactUv;',vertexBody:'vImpactUv=uv;',- fragmentHead:'varying vec2 vImpactUv;\nuniform float uImpactFoam;\nuniform float uImpactSeed;',- fragmentBody:/* glsl */`- vec2 p=vec2(vImpactUv.x-.5,.5-vImpactUv.y)*2.0;- float downstream=p.y+.32;- float boundary=1.0-smoothstep(.63,1.0,length(vec2(p.x,downstream*.9)));- float cells=astraFbm2(vec2(p.x*17.0,p.y*13.0-uTime*1.8)+uImpactSeed,3);- float turbulence=smoothstep(.25,.58,cells);- float core=exp(-p.x*p.x*2.8-downstream*downstream*30.0);- diffuseColor.a*=boundary*clamp(core*.67+turbulence*.37,0.0,.78);- if(diffuseColor.a<.015) discard;- `});- const foamMesh=new THREE.Mesh(new THREE.PlaneGeometry(width*1.6,Math.max(width*.9,height*.45)),foamMaterial);- foamMesh.name='WaterfallImpactFoam';foamMesh.rotation.x=-Math.PI/2;- foamMesh.position.set(0,.012,impactZ+Math.max(width*.9,height*.45)*.16);- keepOutOfDepthPasses(foamMesh);group.add(foamMesh);- }- const owned=snapshotResources(group);- let spray=null;- if(opts.spray!==false && sprayRate>0) {- spray=makeSpray({origin:[0,.015,impactZ],radius:width*.28,- rate:sprayRate,speed:Math.min(3.4,Math.sqrt(GRAVITY*height)*.36),- size:Math.max(.004,Math.min(.025,width*.009)),seed:seed+107});- group.add(spray);owned.add({dispose:()=>spray.userData.dispose()});- }- group.userData.update=t=>{- if(!Number.isFinite(t)) throw new RangeError('Waterfall.update: time must be finite');- material.userData.uniforms.uTime.value=t;- if(foamMaterial) foamMaterial.userData.uniforms.uTime.value=t;- if(spray) spray.userData.update(t);- };- group.userData.sample=(u,lateral=0,t=material.userData.uniforms.uTime.value)=>{- if(![u,lateral,t].every(Number.isFinite)) throw new RangeError('Waterfall.sample: inputs must be finite');- u=clamp(u);lateral=clamp(lateral,-.5,.5);- const position=positionAt(u,lateral,t),epsilon=1e-4;- const along=positionAt(clamp(u+epsilon),lateral,t).sub(positionAt(clamp(u-epsilon),lateral,t));- const across=positionAt(u,clamp(lateral+epsilon,-.5,.5),t).sub(positionAt(u,clamp(lateral-epsilon,-.5,.5),t));- const velocity=new THREE.Vector3(0,-GRAVITY*u*flight,speed),actualWidth=widthAt(u,t);- return {position,normal:along.cross(across).normalize(),velocity,width:actualWidth,- thickness:thickness*speed*width/(velocity.length()*actualWidth),travelTime:u*flight};- };- group.userData.impact=new THREE.Vector3(0,0,impactZ);- group.userData.flightTime=flight;- group.userData.quality=quality;- return attachDisposal(group,owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.jsdeleted file mode 100644index a252d80d..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/wetground.js+++ /dev/null@@ -1,399 +0,0 @@-/**- * Mirror and rain-wet floors: a real planar reflection under a rough- * overlay. A bare Reflector is SHARP (reads as marble, never damp- * asphalt), so the overlay sets the finish. COST: the Reflector- * re-renders the WHOLE scene per frame — use a mirror floor OR a water- * plane, never both.- *- * PORT NOTE (2026-09-01, our renderer: ACES, exposure 1.0, no post- * chain). The shipped pair blends the two layers by a CONSTANT, and- * measured here that is the one thing that stops the effect reading as- * ground: at the mid camera a 30 x 22 m plaza came back as a milky- * sheet, mean luminance 0.687 and p95 0.884 over its near half — the- * sky, mirrored 1:1, brighter than the ground it lay in. Real water- * films obey Fresnel: a few per cent looking down at them, near-total- * at grazing. So the pair now works like a film over a substrate.- *- * - The OVERLAY carries the Fresnel, in its alpha, through- * `shader.js`'s patchStandard so a `patch*` module can still chain- * onto the same floor. Once, and only there: attenuating the mirror- * as well squares the falloff and puts the night plaza at dark_frac- * 0.14 — a black hole where lit wet asphalt belongs.- * - The MIRROR ships its own Reflector shader: a swell that slides the- * reflection, a short vertical smear (which also hides the 512 px- * RTT's stair-stepping on every reflected edge), and the scene's own- * fog and dithering, which a ShaderMaterial opts out of — so the- * stock mirror stayed crisp and banded while the world around it- * fogged.- * - Both read ONE ripple field, so the highlight rides the wobble that- * made it.- *- * Same fixture after: near half 0.523 mean / 0.647 p95, night- * dark_frac 0.001, and the pools read as water rather than smoke.- */--import * as THREE from 'three';-import { attachDisposal, snapshotResources } from './lifecycle.js';-import { Reflector } from 'three/addons/objects/Reflector.js';-import { fbm2, noiseDataTexture } from './noise.js';-import { GLSL_UTIL, patchStandard, planarCapture } from './shader.js';--/**- * The film's swell, shared verbatim by the mirror and the overlay.- *- * Both layers have to agree on it: the overlay's Fresnel decides HOW- * MUCH reflection a pixel shows and the mirror decides WHAT it shows,- * so two different noise fields would slide the highlight off the- * wobble that made it. One string, included in both shaders.- */-const WET_RIPPLE_GLSL = /* glsl */`- // Slope of the film at a world XZ point. dist fades the amplitude- // with range: this is a per-pixel noise with no mip chain, so left- // at full strength across a 30 m floor the far half shimmers into- // salt-and-pepper. Fading it is the LOD this effect can afford.- vec2 wetRippleGrad(vec2 xz, float scale, float amp, float dist) {- vec2 p = xz * scale;- float h0 = astraFbm2(p, 2);- float a = amp / (1.0 + dist * 0.08);- return vec2(astraFbm2(p + vec2(0.3, 0.0), 2) - h0,- astraFbm2(p + vec2(0.0, 0.3), 2) - h0) * a;- }-- // Schlick for a water film. The exponent is 3, not the textbook 5:- // a real film is a stack of slopes, not one plane, and every slope- // that faces you admits more — measured at 5 a 30 m floor is dry to- // its last two metres and the wet read is lost, at 4 the mid-ground- // is a flat grey card, and at 3 the reflection comes in as a- // gradient the way a photograph of wet ground does.- float wetFresnel(vec3 n, vec3 v, float strength) {- float ndv = clamp(dot(normalize(n), normalize(v)), 0.0, 1.0);- return mix(1.0, 0.03 + 0.97 * pow(1.0 - ndv, 3.0), strength);- }-`;--/**- * Reflector shader with a ripple, a smear, fog and dithering. It- * decides WHAT the film reflects; the overlay's Fresnel decides how- * much of it survives. Everything in here is the SCENE's own radiance- * — no authored water colour — so the floor re-grades itself with the- * sky, the hour and the lights above it.- */-const WET_REFLECTOR_SHADER = {- name: 'WetReflectorShader',-- uniforms: THREE.UniformsUtils.merge([- THREE.UniformsLib.fog,- {- color: { value: null },- tDiffuse: { value: null },- textureMatrix: { value: null },- uBlur: { value: 0.010 },- uRipple: { value: 1.0 },- uRippleScale: { value: 4.0 },- },- ]),-- vertexShader: /* glsl */`- uniform mat4 textureMatrix;- varying vec4 vUv;- varying vec3 vWorldPos;- varying vec3 vWorldNormal;-- #include <common>- #include <fog_pars_vertex>- #include <logdepthbuf_pars_vertex>-- void main() {- vUv = textureMatrix * vec4(position, 1.0);- vec4 worldPosition = modelMatrix * vec4(position, 1.0);- vWorldPos = worldPosition.xyz;- vWorldNormal = inverseTransformDirection(normalize(normalMatrix * normal), viewMatrix);- vec4 mvPosition = viewMatrix * worldPosition;- gl_Position = projectionMatrix * mvPosition;- #include <logdepthbuf_vertex>- #include <fog_vertex>- }`,-- fragmentShader: /* glsl */`- uniform vec3 color;- uniform sampler2D tDiffuse;- uniform float uBlur;- uniform float uRipple;- uniform float uRippleScale;- varying vec4 vUv;- varying vec3 vWorldPos;- varying vec3 vWorldNormal;-- #include <common>- #include <logdepthbuf_pars_fragment>- #include <fog_pars_fragment>- #include <dithering_pars_fragment>-` + GLSL_UTIL + WET_RIPPLE_GLSL + /* glsl */`-- float wetBlendOverlay(float base, float blend) {- return base < 0.5 ? (2.0 * base * blend)- : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend));- }-- vec3 wetBlendOverlay(vec3 base, vec3 blend) {- return vec3(wetBlendOverlay(base.r, blend.r),- wetBlendOverlay(base.g, blend.g),- wetBlendOverlay(base.b, blend.b));- }-- // texture2DProj divides by w, so an offset in normalised projected- // space has to be pre-multiplied by w or the smear length swings- // with depth across the plane.- vec3 wetTap(vec2 o) {- return texture2DProj(- tDiffuse, vUv + vec4(o * vUv.w, 0.0, 0.0)).rgb;- }-- void main() {- #include <logdepthbuf_fragment>-- vec3 V = normalize(cameraPosition - vWorldPos);- float ndv = clamp(dot(normalize(vWorldNormal), V), 0.0, 1.0);-- // The film is never a plane, and its swell slides what it- // reflects. HOW MUCH of this layer survives is the overlay's job- // (Fresnel there composites once; doing it here as well squared- // it and put the night plaza at dark_frac 0.14) — this layer only- // decides what the reflection looks like.- vec2 grad = wetRippleGrad(vWorldPos.xz, uRippleScale, uRipple,- distance(cameraPosition, vWorldPos));- // A short vertical smear on top: a wet surface is never a clean- // mirror, and it is also what hides the 512 px RTT's- // stair-stepping on every reflected edge.- float smear = uBlur * (0.35 + 0.65 * (1.0 - ndv));- vec2 o = grad * 0.12;- vec3 refl = wetTap(o + vec2(0.0, -2.0 * smear)) * 0.12- + wetTap(o + vec2(0.0, -smear)) * 0.22- + wetTap(o) * 0.32- + wetTap(o + vec2(0.0, smear)) * 0.22- + wetTap(o + vec2(0.0, 2.0 * smear)) * 0.12;-- gl_FragColor = vec4(wetBlendOverlay(refl, color), 1.0);-- #include <tonemapping_fragment>- #include <colorspace_fragment>- #include <fog_fragment>- #include <dithering_fragment>- }`,-};--/**- * Make the overlay's cover view-dependent — the change that turns the- * pair into wet ground rather than a sheet of glass with grit on it.- *- * A water film is not a constant blend. Looking DOWN at it you see- * through to the substrate (3% reflected) and looking ALONG it you see- * nothing but reflection. So the authored `overlayOpacity` (times the- * puddle mask) is the GRAZING limit, and the cover rises towards fully- * dry as the view steepens: `a = 1 - F * (1 - a0)`.- *- * Two consequences worth stating, both measured on our host:- * - It composites ONCE. Attenuating the mirror layer as well squared- * the falloff and dropped the night plaza to dark_frac 0.14 — a- * black hole where the near floor should show lit wet asphalt.- * - `fresnel: 0` reproduces the pre-port constant blend exactly, which- * is what a polished indoor floor under its own lighting wants.- *- * `alphamap_fragment` runs after this hook and multiplies the mask in- * again, so the mask is divided back out here; that is why the patch- * samples the map itself instead of reading `diffuseColor.a`.- */-function patchWetFilm(material, opts) {- return patchStandard(material, {- name: 'WetGroundFilm',- uniforms: {- uWgFresnel: { value: opts.fresnel },- uWgRipple: { value: opts.ripple },- uWgRippleScale: { value: opts.rippleScale },- },- vertexHead: 'varying vec3 vWgWorldPos;',- vertexBody: 'vWgWorldPos = (modelMatrix * vec4(transformed, 1.0)).xyz;',- fragmentHead: [- 'uniform float uWgFresnel;',- 'uniform float uWgRipple;',- 'uniform float uWgRippleScale;',- 'varying vec3 vWgWorldPos;',- WET_RIPPLE_GLSL,- ].join('\n'),- fragmentBody: [- 'float wgMask = 1.0;',- '#ifdef USE_ALPHAMAP',- ' wgMask = texture2D(alphaMap, vAlphaMapUv).g;',- '#endif',- // The factory lays this plane flat, so the film's normal is world- // up tilted by the swell — and the same swell the mirror slides- // its reflection by, so highlight and wobble stay married.- 'vec3 wgV = cameraPosition - vWgWorldPos;',- 'vec2 wgGrad = wetRippleGrad(vWgWorldPos.xz, uWgRippleScale,',- ' uWgRipple, length(wgV));',- 'vec3 wgN = normalize(vec3(-wgGrad.x, 1.0, -wgGrad.y));',- 'float wgF = wetFresnel(wgN, wgV, uWgFresnel);',- 'float wgA0 = diffuseColor.a * wgMask;',- 'diffuseColor.a = (1.0 - wgF * (1.0 - wgA0)) / max(wgMask, 0.001);',- ].join('\n'),- });-}--/** The damp field: one seeded fBm all three overlay maps read, so a- * pool is darker, smoother AND more mirror in the same place. 0 dry,- * 1 pooled. */-function dampField(u, v, seed) {- const n = fbm2(u * 4, v * 4, { seed: seed });- // The shipped band was 0.24 wide, which over a 30 m floor put the- // whole shoreline in a 6 m gradient: the pools read as smoke, not- // water. 0.11 still leaves 2-3 texels of softness at 256 px.- const t = (n + 0.02) / 0.11;- const k = Math.min(1, Math.max(0, t));- return 1 - k * k * (3 - 2 * k);-}--/**- * A mirror-reflective floor with a rough overlay that sets its finish:- * low overlay opacity reads as polished marble, 0.7+ with `puddleMask`- * as damp asphalt where only puddles hold the mirror.- *- * @param {number} w Floor width (X) in metres.- * @param {number} d Floor depth (Z) in metres.- * @param {object} [opts] `rttSize` (default 512) reflection target- * resolution; `color` (default 0x6f767c) tints/darkens the mirror- * like damp ground — an overlay blend, so a value under 0.5 grey- * darkens and one over it brightens; `overlayOpacity` (default 0.65,- * use 0.7-0.8 for asphalt, 0.4-0.55 for gloss marble); `overlayColor`- * (default 0x4a4642, the graded wet-asphalt tone); `puddleMask`- * (default false) breaks the overlay with a seeded fBm alpha mask so- * the mirror shows only in puddle pools; `seed` (default 1) shapes- * the puddles; `fresnel` (default 1, 0..1) how view-dependent the- * film is — the authored opacity becomes the GRAZING limit and the- * cover closes up as you look straight down, and 0 restores the flat- * blend a polished indoor floor wants; `ripple` (default 1.0) slope- * of the film's swell, which both slides the reflection and tilts- * the Fresnel that admits it — 0 for still water; `rippleScale`- * (default 4.0) ripples per metre; `detail` (default 1) scales the- * overlay's colour, damp and roughness break-up, 0 for a flat sheet.- * @returns {THREE.Group} Group named `MirrorFloor`, resting at y = 0.- */-export function makeMirrorFloor(w, d, opts = {}) {- const rttSize = opts.rttSize === undefined ? 512 : opts.rttSize;- // 0x889199 shipped as the default and it is 0.53 grey: blendOverlay- // BRIGHTENS with it, so "tints/darkens like damp ground" did the- // opposite. 0x6f767c is the same cool damp hue below the 0.5 pivot.- const color = opts.color === undefined ? 0x6f767c : opts.color;- const overlayOpacity =- opts.overlayOpacity === undefined ? 0.65 : opts.overlayOpacity;- const overlayColor =- opts.overlayColor === undefined ? 0x4a4642 : opts.overlayColor;- const seed = opts.seed === undefined ? 1 : opts.seed;- const fresnel = opts.fresnel === undefined ? 1 : opts.fresnel;- const ripple = opts.ripple === undefined ? 1.0 : opts.ripple;- const rippleScale =- opts.rippleScale === undefined ? 4.0 : opts.rippleScale;- const detail = opts.detail === undefined ? 1 : opts.detail;-- const group = new THREE.Group();- group.name = 'MirrorFloor';-- const mirror = new Reflector(new THREE.PlaneGeometry(w, d), {- clipBias: 0.003,- // MSAA on a 512 px reflection under a rough overlay is- // invisible and measured 39 ms a frame on software GL.- multisample: 0,- textureWidth: rttSize,- textureHeight: rttSize,- color: color,- shader: WET_REFLECTOR_SHADER,- });- mirror.rotation.x = -Math.PI / 2;- mirror.name = 'MirrorSurface';- // BOTH uniforms, or the mirror's swell and the overlay's Fresnel- // stop describing the same water.- mirror.material.uniforms.uRipple.value = ripple;- mirror.material.uniforms.uRippleScale.value = rippleScale;- // A ShaderMaterial opts OUT of both by default: without these the- // mirror is the one surface in the scene that neither fogs nor- // dithers, and a 20 m sky reflection is exactly the smooth gradient- // that bands in 8 bits.- mirror.material.fog = true;- mirror.material.dithering = true;- group.add(mirror);-- // Reflector projects mesh-local positions through a rigid-frame capture;- // map that projection back onto the actual (possibly affine) geometry.- const capture = mirror.onBeforeRender;- planarCapture(mirror, (renderer, scene, camera, toRigid) => {- capture.call(mirror, renderer, scene, camera);- mirror.material.uniforms.textureMatrix.value.multiply(toRigid);- });-- const overlayMat = new THREE.MeshStandardMaterial({- color: overlayColor,- roughness: 1,- metalness: 0,- transparent: true,- opacity: overlayOpacity,- });- if (opts.puddleMask) {- // alphaMap: bright = dry overlay, dark = puddle showing the mirror.- // Smoothstep gives pooled shapes with soft shorelines; the 0.15- // floor keeps a thin damp film even inside puddles.- overlayMat.alphaMap = noiseDataTexture(256, (u, v) => (- 0.15 + 0.85 * (1 - dampField(u, v, seed))- ));- }- if (detail > 0) {- // One flat albedo over 600 m2 is the tell of a fake floor. Ground- // carries broad warm/cool patches (grit, oil, old repairs) and the- // damp field darkens what it wets, so the map is the two together.- overlayMat.map = noiseDataTexture(256, (u, v) => {- const h = fbm2(u * 3 + 17, v * 3 - 9, { seed: seed + 11 }) * detail;- const b = fbm2(u * 1.7 - 5, v * 1.7 + 3, { seed: seed + 41 }) * detail;- const g = fbm2(u * 13, v * 13, { seed: seed + 29 }) * detail;- const wet = dampField(u, v, seed) * detail;- // Water fills the pores and traps the light: a wet patch of any- // ground is about half the albedo of the dry patch beside it.- // Looking straight DOWN that darkening is the only thing that- // says "puddle" — Fresnel has admitted almost no reflection at- // that angle, so an albedo field this strong is not decoration,- // it is the whole near-field read. The 1.22 divides the peak- // back to 1, which makes `overlayColor` the driest crest rather- // than the average.- const l = (1 - 0.50 * wet) * (1 + 0.24 * b) * (1 + 0.18 * g) / 1.22;- // Warm where it is dry, cool where the water sits — the swing a- // photograph of wet asphalt actually carries, and the reason- // this floor does not read as one die-cut grey. Not a hue- // rotation: red up and blue down about a fixed green, so the- // tone stays put while the cast moves.- const c = 0.55 * h - 0.30 * (wet - 0.5);- return [l * (1 + c), l * (1 + 0.05 * c), l * (1 - c)];- });- // Base roughness stays 1 (the material contract); the map only- // takes it DOWN, and only a little. The SMOOTH thing here is the- // water surface, which is the mirror layer — dropping the- // substrate to 0.45 as well double-counts the film's specular and- // measured +20/255 of flat sky sheen over the whole plaza, which- // is what turned it into a light grey card.- overlayMat.roughnessMap = noiseDataTexture(256, (u, v) => {- const wet = dampField(u, v, seed) * detail;- const g = fbm2(u * 13, v * 13, { seed: seed + 29 }) * detail;- return Math.max(0.05, 0.97 - 0.18 * wet + 0.06 * g);- });- }- patchWetFilm(overlayMat, { fresnel, ripple, rippleScale });- const overlay = new THREE.Mesh(new THREE.PlaneGeometry(w, d), overlayMat);- overlay.rotation.x = -Math.PI / 2;- overlay.position.y = 0.002;- overlay.receiveShadow = true;- overlay.name = 'GroundOverlay';- group.add(overlay);-- const owned = snapshotResources(group);- owned.add(mirror.getRenderTarget());- for (const texture of [overlayMat.map, overlayMat.alphaMap, overlayMat.roughnessMap]) {- if (texture) owned.add(texture);- }- return attachDisposal(group, owned);-}diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.jsdeleted file mode 100644index acbde41b..00000000--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/windows.js+++ /dev/null@@ -1,392 +0,0 @@-/**- * Night windows that are ROOMS, not glowing rectangles.- *- * A lit window is the strongest habitation cue a night city has, and an- * emissive rectangle is the flattest way to draw one: it has no inside,- * so a whole facade reads as a decal. This shades the INTERIOR instead —- * from the surface UV and the view direction it intersects a shallow box- * behind the glass and shades the wall the ray lands on, so every window- * has a back wall, side walls, a floor and a ceiling that slide with the- * camera. No extra geometry and no second draw call: it is a- * `patchStandard` on the facade material the mesh already has.- */--import * as THREE from 'three';-import { clonePatchedMaterial, patchStandard, seedLattice, toColor } from './shader.js';-import { attachDisposal } from './lifecycle.js';--const WIN_VARYINGS = [- 'varying vec2 vWinUv;',- 'varying vec3 vWinW;',- 'varying vec3 vWinN;',- 'varying vec3 vWinKey;',-].join('\n');--// `transformed` is still object-space at <begin_vertex>, so an instanced-// facade needs instanceMatrix folded in by hand.-const WIN_VERTEX = [- ' vec4 winP = vec4(transformed, 1.0);',- ' vec3 winNo = normal;',- ' vec4 winO = vec4(0.0, 0.0, 0.0, 1.0);',- '#ifdef USE_INSTANCING',- ' winP = instanceMatrix * winP;',- ' winNo = astraNormalTransform(mat3(instanceMatrix), winNo);',- ' winO = instanceMatrix * winO;',- '#endif',- ' vWinUv = uv;',- ' vWinW = (modelMatrix * winP).xyz;',- ' vWinN = astraNormalTransform(mat3(modelMatrix), winNo);',- // The draw's own origin, constant across the mesh: it keys the lit- // pattern per BUILDING even where a whole city shares one material.- ' vWinKey = (modelMatrix * winO).xyz;',-].join('\n');--const WIN_HEAD = [- 'uniform vec3 uWinWarm;',- 'uniform vec3 uWinCool;',- 'uniform vec2 uWinGrid;',- 'uniform float uWinDepth;',- 'uniform float uWinLit;',- 'uniform float uWinSeed;',- 'uniform float uWinEmissive;',- // The pane inside its cell; the rest of the cell stays facade, which- // is what makes a grid of glass read as openings in a wall.- 'const vec2 ASTRA_WIN_EDGE = vec2(0.18, 0.22);',- // A facade is any box face at any orientation and carries no tangent- // attribute, so the frame comes from the screen-space derivatives.- 'mat3 astraWinFrame(vec3 p, vec2 st, vec3 n, out vec2 mpu) {',- ' vec3 dp1 = dFdx(p), dp2 = dFdy(p);',- ' vec2 du1 = dFdx(st), du2 = dFdy(st);',- ' vec3 a = cross(dp2, n), b = cross(n, dp1);',- ' vec3 t = a * du1.x + b * du2.x;',- ' vec3 c = a * du1.y + b * du2.y;',- ' float k = inversesqrt(max(max(dot(t, t), dot(c, c)), 1e-12));',- // Metres per unit of UV: the only way a shader can tell a wall panel- // from a mullion box carrying its own full 0..1 UV.- ' float det = max(abs(du1.x * du2.y - du2.x * du1.y), 1e-12);',- ' mpu = vec2(length(dp1 * du2.y - dp2 * du1.y),',- ' length(dp2 * du1.x - dp1 * du2.x)) / det;',- ' return mat3(t * k, c * k, n);',- '}',- // Interior mapping: the nearest wall of a room one cell wide whose- // back sits `depth` behind the glass. z runs 0 (glass) to -depth, and- // `face` comes back as the weight of the axis that was hit.- 'vec3 astraWinRoom(vec3 o, vec3 d, float depth, out vec3 face) {',- ' vec3 ds = max(abs(d), vec3(1e-4)) * sign(d + 1e-9);',- ' vec3 tHi = (vec3(1.0, 1.0, 0.0) - o) / ds;',- ' vec3 tLo = (vec3(0.0, 0.0, -depth) - o) / ds;',- ' vec3 tm = max(tLo, tHi);',- ' float t = min(min(tm.x, tm.y), tm.z);',- ' face = step(tm, vec3(t));',- ' face /= max(face.x + face.y + face.z, 1.0);',- ' return o + d * t;',- '}',-].join('\n');--const WIN_BODY = [- ' vec2 winG = vWinUv * uWinGrid;',- ' vec2 winF = fract(winG);',- ' vec2 winAa = fwidth(winG) + 1e-4;',- // Derivatives are undefined under divergent control flow, so the pane- // is a mask mixed in at the end, never an early return.- ' vec2 winE = smoothstep(ASTRA_WIN_EDGE - winAa,',- ' ASTRA_WIN_EDGE + winAa, winF)',- ' * (1.0 - smoothstep(1.0 - ASTRA_WIN_EDGE - winAa,',- ' 1.0 - ASTRA_WIN_EDGE + winAa, winF));',- ' float winPane = winE.x * winE.y;',- ' vec3 winNn = normalize(vWinN);',- ' vec3 winV = normalize(cameraPosition - vWinW);',- ' vec2 winMpu;',- ' mat3 winTbn = astraWinFrame(vWinW, vWinUv, winNn, winMpu);',- // A cell under a metre across is a mullion or a spandrel band wearing- // its own 0..1 UV, never a window; that member keeps its own surface.- ' winPane *= smoothstep(0.55, 1.0, min(winMpu.x / uWinGrid.x,',- ' winMpu.y / uWinGrid.y));',- // And once a pixel spans a third of a cell the room can only alias- // into sparkle, so the facade is handed back instead.- ' winPane *= 1.0 - smoothstep(0.3, 0.8, max(winAa.x, winAa.y));',- ' vec3 winD = -vec3(dot(winV, winTbn[0]), dot(winV, winTbn[1]),',- ' dot(winV, winTbn[2]));',- // Edge-on and back-facing fragments would otherwise divide by ~0 and- // smear one room across the whole wall.- ' winD = normalize(vec3(winD.xy, min(winD.z, -0.02)));',- // Quantised normal + draw origin: one key per face per building, so- // four facades of one box are not the same lit pattern four times.- //- // EVERY term here is rounded to a whole number, and that is the whole- // reason the pattern holds still. `vWinKey` is one constant handed to- // every vertex, but a perspective-correct varying is (sum w/q)/(sum 1/q)- // and comes back a few ULPs apart per pixel; astraHash21 amplifies an- // input wobble by about a thousand (measured: 1 ULP at coordinate 120- // moves it 0.008), so hashing the raw key and then hashing THAT into- // the cell id chains two amplifications and turns `winOn` into a- // per-pixel coin flip — a facade of static, which is what this- // rendered before the floor()s went in. On an integer lattice inside- // +-700 the same hash is bit-exact per cell and still well spread- // (mean 0.504, sigma 0.291, adjacent |dh| 0.333).- ' vec3 winKq = floor(vWinKey * 16.0 + 0.5);',- ' float winFace = dot(floor(winNn * 4.0 + 0.5), vec3(11.0, 29.0, 53.0));',- ' float winB = floor(astraHash21(winKq.xz + winKq.y) * 29.0) + winFace;',- ' vec2 winId = floor(winG)',- ' + vec2(uWinSeed + winB, floor(uWinSeed * 1.7) - winB);',- ' float winOn = step(astraHash21(winId), uWinLit);',- // Three independent draws per room. A facade whose only variable is- // on/off reads as a stencil; what a night city actually has is a wide- // spread of BRIGHTNESS and a wide spread of HUE, and the fittings.- ' float winHt = astraHash21(winId + 3.3);',- ' float winHf = astraHash21(winId + 19.7);',- ' float winHl = astraHash21(winId + 41.1);',- ' vec2 winQ = clamp((winF - ASTRA_WIN_EDGE)',- ' / max(1.0 - 2.0 * ASTRA_WIN_EDGE, vec2(1e-3)), 0.0, 1.0);',- ' vec3 winHitFace;',- ' vec3 winHit = astraWinRoom(vec3(winQ, 0.0), winD,',- ' max(uWinDepth, 0.02), winHitFace);',- // The back wall carries the room, the ceiling catches the fitting and- // the floor stays dark; side walls fall off with how deep they are hit.- ' float winShade = winHitFace.z + winHitFace.x * 0.45',- ' + winHitFace.y * mix(0.22, 0.8, step(0.5, winHit.y));',- ' winShade *= mix(1.0, 0.5,',- ' clamp(-winHit.z / max(uWinDepth, 0.02), 0.0, 1.0));',- // The fitting is on the CEILING, so a room falls off downward: without- // this the back wall is one flat card and the box reads as a printed- // panel however well the ray traced it.- ' winShade *= mix(0.58, 1.14, smoothstep(0.0, 1.0, winHit.y));',- // A room is never an empty box: furniture against the back wall. The- // noise lattice is entered through the cell hash, not through winId- // itself, so the coordinate stays small enough to interpolate.- ' vec2 winNz = winHit.xy * 3.0 + vec2(winHt, winHl) * 37.0;',- ' winShade *= mix(0.55, 1.0, astraNoise2(winNz));',- // A blind pulled down over the top of a slice of the windows. The old- // hard step() cut a razor line across the pane at exactly one height on- // every floor of the building, which is the tell of a decal; this is a- // soft hem, and it slides with the room because it rides winQ.- ' winShade *= mix(1.0, 0.24, step(0.74, winHf)',- ' * smoothstep(0.46, 0.64, winQ.y));',- // And a curtain drawn across another slice: cloth SCATTERS, so that- // room stops being a box and becomes an even glowing panel, brightest- // where the fitting sits behind it. A facade of nothing but open rooms- // is as uniform as a facade of nothing but rectangles.- ' float winCurt = step(winHf, 0.30) * 0.85;',- ' winShade = mix(winShade, 0.52 + 0.34 * (1.0 - winQ.y), winCurt);',- // COLOUR. A two-tone warm/cool lerp gives a facade exactly two bulbs;- // the rotation and the saturation draw spread those into a hundred,- // which is the difference between a lit block and a printed one. The- // rotation is small (+-5 degrees) because a night window that leaves- // the tungsten-to-daylight axis stops reading as a window.- ' vec3 winTint = mix(uWinWarm, uWinCool, smoothstep(0.45, 0.75, winHt));',- ' winTint = astraHueShift(winTint, (winHl - 0.5) * 0.18);',- ' float winGry = dot(winTint, vec3(0.2126, 0.7152, 0.0722));',- ' winTint = max(mix(vec3(winGry), winTint,',- ' mix(0.72, 1.24, astraHash21(winId + 7.9))), 0.0);',- // Cloth washes the bulb toward its own pale, never toward white: a- // curtain over a tungsten room is still a warm curtain.- ' winTint = mix(winTint, mix(winTint, vec3(winGry * 1.25), 0.3), winCurt);',- // Brightness spread. Squared, so most rooms sit low and a few carry- // the facade — the shape a photograph of a lit block actually has.- ' float winLevel = mix(0.30, 1.15, winHl * winHl * (3.0 - 2.0 * winHl));',- ' vec3 winRoom = winTint * (winShade * winLevel);',- // Unlit cells keep the same room at a trickle and add the sky the- // glass reflects: a black rectangle reads as a hole in the wall. The- // sky it reflects is the SCENE's, not a constant — fog carries the- // horizon's own hue, so the same facade goes pale blue at noon and- // deep blue at midnight with no per-scene tuning. uWinCool stays in as- // the floor, so a face-on pane in a scene with no fog is dark glass- // rather than a hole.- ' vec3 winSky = uWinCool;',- '#ifdef USE_FOG',- ' winSky = mix(uWinCool, fogColor, 0.7);',- '#endif',- // Glass mirrors the GROUND as well as the sky, and the line between- // the two sweeping across a facade is most of what a curtain wall- // looks like from the street. The split rides the reflected ray, so it- // moves with the camera and bends round a corner instead of sitting on- // the surface; the per-pane term is the batch spread real glazing has.- ' vec3 winRefl = reflect(-winV, winNn);',- ' winSky *= mix(0.34, 1.0, smoothstep(-0.30, 0.30, winRefl.y))',- ' * mix(0.8, 1.25, winHt);',- ' float winFr = astraFresnel(winNn, winV, 3.0);',- ' vec3 winDark = winRoom * 0.06 + uWinCool * 0.015',- ' + winSky * (0.05 + 0.6 * winFr);',- // Every gradient above is a shallow ramp over a dark room, which is- // where 8-bit banding lives. One LSB of hash grain kills the contours- // and is under the noise floor of every display it will be seen on.- ' vec3 winGrain = vec3((astraHash21(gl_FragCoord.xy) - 0.5) * 0.004);',- ' diffuseColor.rgb = mix(diffuseColor.rgb,',- ' max(mix(winDark, winRoom * 0.35, winOn) + winGrain * 0.25, 0.0),',- ' winPane);',- // diffuseColor is ALBEDO: without lifting the emissive term as well, a- // lit room can only ever be a pale wall.- ' totalEmissiveRadiance += max(winRoom + winGrain, 0.0)',- ' * (uWinEmissive * winOn * winPane);',- // And the SAME argument decides the unlit pane, which is the half of- // this effect that a night scene actually shows most of. A reflection- // is radiance, not albedo: written to diffuseColor alone it is- // multiplied by the light landing on the wall, and at night that is- // nothing — so every dark pane collapses to the black hole in the- // facade that `winDark` exists to prevent. A whisper of the room- // behind it rides along, so an unlit window still parallaxes.- ' totalEmissiveRadiance += (winSky * (0.06 + 0.9 * winFr)',- ' + max(winRoom + winGrain, 0.0) * 0.05)',- ' * ((1.0 - winOn) * winPane);',-].join('\n');--/**- * A seed becomes a far-apart WHOLE-NUMBER lattice offset.- *- * Seeds 7 and 8 offsetting the hash lattice by 1 would merely TRANSLATE- * the pattern by one window, which reads as the same building twice —- * hence the multiplier. It is an integer, and stays under a few hundred,- * because the shader hashes `uWinSeed + <integers>` as a lattice- * coordinate: a fractional offset would put every cell id between two- * lattice points, where the hash is a thousand times more sensitive to- * the last bit of the inputs than it is to the cell.- */-const seedOffset = (seed) => seedLattice(seed, 16807, 257);--/**- * Shade the ROOM behind each window instead of the window itself.- *- * From the surface UV and the view direction this intersects a shallow- * box behind every cell of the facade and shades the wall the ray hits,- * so a lit window slides and parallaxes like an opening rather than- * sitting flat like a sticker — at ONE draw call for the whole facade,- * with no added geometry. Unlit cells keep the same interior at a- * trickle plus a fresnel sky reflection, because a black rectangle reads- * as a hole punched in the wall.- *- * No two rooms are the same room. `warm`/`cool` set the ends of the- * tungsten-to-daylight axis, and each cell then draws its own small hue- * rotation, its own saturation and its own BRIGHTNESS off that axis, so- * a facade carries a spread of bulbs rather than two. About a third of- * them are dressed: a blind hung over the top of the pane, or a curtain- * drawn right across, which stops being a box and becomes an even- * glowing panel. The sky an unlit pane mirrors is the SCENE's — it is- * read from the fog colour where the scene has fog, split at the- * reflected horizon so glass takes the ground below and the sky above —- * and it is added as RADIANCE, not albedo, so a dark pane still reads as- * glass in a night scene where nothing is lighting the wall.- *- * Two constraints it encodes. The grid is measured in UV, and three's- * BoxGeometry gives EVERY box face a full 0..1 UV whatever its size, so- * a facade merged from many boxes (`building.js` `block()`) would repeat- * the whole grid on every mullion; cells that work out under a metre- * across therefore fade out, and such a member keeps its own surface.- * Best on a wall whose UV spans it — a shell, a slab, a plane. And the- * lift is applied to `totalEmissiveRadiance` as well as `diffuseColor`,- * which needs a lit material — MeshStandard/MeshPhysical, not Basic.- *- * @param {THREE.Material} material A built-in material, patched in place.- * @param {object} [opts] `rows`/`cols` window cells per unit of UV,- * rounded so the grid closes at the seam (default 8/6); `depth` how far- * the back wall sits behind the glass, in cell widths (default 0.6);- * `lit` fraction of windows lit (default 0.35); `warm`/`cool`- * THREE.Color or hex room tints, mostly warm with the odd cool room —- * `cool` also floors the sky an unlit pane reflects where the scene- * carries no fog; `seed` the lit pattern (default 1); `emissive` the- * radiance of a lit room, which peaks around 1.3x this (default 1.6,- * so ~2.1 — keep it in 1.5..4 to bloom instead of clipping white);- * `name` the program cache key (default 'windows:interior' —- * every option here is a UNIFORM, so one name is correct and two- * differently tuned facades still share one compiled program).- * @returns {THREE.Material} The same material, its uniforms live on- * `material.userData.uniforms` for a scene that dims the city at dawn.- */-export function patchWindowInteriors(material, opts = {}) {- const rows = opts.rows === undefined ? 8 : opts.rows;- const cols = opts.cols === undefined ? 6 : opts.cols;- const depth = opts.depth === undefined ? 0.6 : opts.depth;- const lit = opts.lit === undefined ? 0.35 : opts.lit;- const emissive = opts.emissive === undefined ? 1.6 : opts.emissive;- return patchStandard(material, {- name: opts.name || 'windows:interior',- uniforms: {- uWinWarm: { value: toColor(opts.warm, 0xffc98a) },- uWinCool: { value: toColor(opts.cool, 0x9fc0e8) },- uWinGrid: { value: new THREE.Vector2(- Math.max(1, Math.round(cols)), Math.max(1, Math.round(rows))) },- uWinDepth: { value: Math.max(0.02, depth) },- uWinLit: { value: Math.min(1, Math.max(0, lit)) },- uWinSeed: { value: seedOffset(opts.seed) },- uWinEmissive: { value: Math.max(0, emissive) },- },- vertexHead: WIN_VARYINGS,- vertexBody: WIN_VERTEX,- fragmentHead: [WIN_VARYINGS, WIN_HEAD].join('\n'),- fragmentBody: WIN_BODY,- });-}--// What a facade is called across this library: block() names its wall-// mesh 'Walls', and a curtain wall or a shell is the same surface.-const FACADE_RE = /facade|wall|shell|curtain/i;--/** Bounding-box area: the facade is the biggest surface a building has. */-function boxArea(geometry) {- if (!geometry) return 0;- if (!geometry.boundingBox) geometry.computeBoundingBox();- const b = geometry.boundingBox;- if (!b) return 0;- const x = b.max.x - b.min.x;- const y = b.max.y - b.min.y;- const z = b.max.z - b.min.z;- return x * y + y * z + z * x;-}--/** The meshes carrying the facade: by name where there is one, else size. */-function facadeMeshes(root) {- const all = [];- root.traverse((o) => { if (o.isMesh && o.material) all.push(o); });- const named = all.filter(- (o) => FACADE_RE.test(o.name)- || [].concat(o.material).some((m) => m && FACADE_RE.test(m.name)));- if (named.length) return named;- if (all.length < 2) return all;- return [all.reduce(- (a, b) => (boxArea(b.geometry) > boxArea(a.geometry) ? b : a))];-}--/**- * Give a building night windows without knowing how it is built.- *- * `block()` and `tower()` return a GROUP of merged meshes — walls, trim,- * glazing, reveals — and only one of them is the facade, so a caller- * that reached for `mesh.material` would window the cornice or miss- * entirely. This finds the facade slot (by name, falling back to the- * largest surface), patches every slot it found once, and hands the- * object back. It also CLONES a material `materials.js` marked shared:- * that library returns one instance to every caller that asked for the- * same look, so patching in place would put windows on the whole city.- * On a `block()` that facade is merged mullions and spandrel bands, so- * the size gate stands the patch down and `block({ lit })` — which- * models those openings — still owns the look. It earns its keep on the- * plain shells and slabs a skyline is mostly made of.- *- * @param {THREE.Object3D} mesh A building mesh or group (a `block()`, a- * `tower()`, a whole `cityFabric()` group, or one InstancedMesh).- * @param {object} [opts] Passed straight to `patchWindowInteriors`.- * @returns {THREE.Object3D} The same object, so it can be added inline.- */-export function makeNightWindows(mesh, opts = {}) {- if (!mesh || !mesh.traverse) return mesh;- const done = new Map();- const owned = new Set();- for (const target of facadeMeshes(mesh)) {- const slots = [].concat(target.material);- const next = slots.map((m) => {- if (!m) return m;- if (done.has(m.uuid)) return done.get(m.uuid);- const out = (m.userData && m.userData.shared) ? clonePatchedMaterial(m) : m;- if (out !== m) owned.add(out);- patchWindowInteriors(out, opts);- done.set(m.uuid, out);- return out;- });- target.material = Array.isArray(target.material) ? next : next[0];- }- if (owned.size) {- const previous = mesh.userData.dispose;- if (previous) owned.add({ dispose: previous });- attachDisposal(mesh, owned);- }- return mesh;-}diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.pyindex 69192e39..f6e20f57 100644--- a/harness/codeverse3d/languages/urdf/__init__.py+++ b/harness/codeverse3d/languages/urdf/__init__.py@@ -757,7 +757,7 @@ class UrdfBlenderRuntime(RuntimeLayout):# 5. the rest pose — the only pose that decides the build (D17); every other pose is# the round's joint_sweep gate (spatial.joints_sweep.sweep_gate), which the tool reports too- report = sweep_collisions(robot, [{}], volumes=False)+ report = sweep_collisions(robot, [{}])findings = sweep_findings(report, rest_max_m=REST_PENETRATION_MAX_M)# 6. canonical GLB at restdiff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.pyindex 6ebdd5a0..0079afd8 100644--- a/harness/codeverse3d/models/gemini.py+++ b/harness/codeverse3d/models/gemini.py@@ -22,7 +22,7 @@ from google import genaifrom google.genai import errors as genai_errorsfrom google.genai import types-from codeverse3d.config import Rate, get_settings+from codeverse3d.config import get_settingsfrom codeverse3d.contracts.chat import (ChatMessage,ChatRequest,@@ -222,10 +222,7 @@ def shared_pool(keys: list[str], *, max_in_flight: int | None = None) -> KeyPooldef _rate() -> Any:- try:- return get_settings().rate- except Exception: # pragma: no cover - settings must never break a model call- return Rate()+ return get_settings().ratedef _default_keys() -> list[str]:diff --git a/harness/codeverse3d/models/parts.py b/harness/codeverse3d/models/parts.pyindex d2b7c1c1..d089aabf 100644--- a/harness/codeverse3d/models/parts.py+++ b/harness/codeverse3d/models/parts.py@@ -10,19 +10,14 @@ from collections.abc import Callablefrom pathlib import Pathfrom typing import Any-from codeverse3d.config import Settings, get_settings+from codeverse3d.config import get_settingsfrom codeverse3d.contracts.chat import ChatMessage, ImagePart, TextPartfrom codeverse3d.models.base import ModelErrordef image_bytes(part: ImagePart) -> tuple[bytes, str]:- """Return ``(raw_bytes, mime)`` for an ``ImagePart`` (path or base64).- Raises ``ModelError(retryable=False)`` when the part carries no data."""- if part.data_b64:- try:- return base64.b64decode(part.data_b64), part.mime or "image/png"- except (ValueError, TypeError) as exc:- raise ModelError(f"ImagePart.data_b64 is not valid base64: {exc}") from exc+ """Return ``(raw_bytes, mime)`` for an ``ImagePart``.+ Raises ``ModelError(retryable=False)`` when the part has no readable path."""if part.path:p = Path(part.path)if not p.is_file():@@ -31,7 +26,7 @@ def image_bytes(part: ImagePart) -> tuple[bytes, str]:if not mime or mime == "image/png" and p.suffix.lower() not in ("", ".png"):mime = mimetypes.guess_type(p.name)[0] or "image/png"return p.read_bytes(), mime- raise ModelError("ImagePart has neither path nor data_b64")+ raise ModelError("ImagePart has no path")def image_b64(part: ImagePart) -> tuple[str, str]:@@ -57,10 +52,7 @@ def message_blocks(msg: ChatMessage, *, text: Callable[[str], Any], image: Calladef default_timeout_s() -> float:"""``Settings.model_timeout_s`` — the per-attempt HTTP ceiling every API adapter uses."""- try:- return float(get_settings().model_timeout_s)- except Exception: # pragma: no cover - settings must never break a model call- return float(Settings.model_fields["model_timeout_s"].default)+ return float(get_settings().model_timeout_s)class SdkModel:diff --git a/harness/codeverse3d/models/pricing.py b/harness/codeverse3d/models/pricing.pyindex fc2a4630..6ebda915 100644--- a/harness/codeverse3d/models/pricing.py+++ b/harness/codeverse3d/models/pricing.py@@ -28,14 +28,8 @@ log = logging.getLogger(__name__)#: date the tables below were last reconciled against the providers' pricing pagesCHECKED = "2026-08-23"-#: ``Price.source`` ids; a row with no source was read off its provider's own page-SOURCES: dict[str, str] = {- "gemini": "https://ai.google.dev/gemini-api/docs/pricing",- "anthropic": "https://platform.claude.com/docs/en/about-claude/pricing",- "openai": "https://developers.openai.com/api/docs/pricing",- "inferred": "inferred from the closest sibling model (no published row)",- "provider-cost": "reproduced from a provider-reported cost in our own run telemetry",-}+#: the pricing pages the rows are read off: ai.google.dev/gemini-api/docs/pricing,+#: platform.claude.com/docs/en/about-claude/pricing, developers.openai.com/api/docs/pricing@dataclass(frozen=True)@@ -54,8 +48,7 @@ class Price:``cache_write`` = cache creation (Anthropic explicit caching, 5-minute TTL);``thoughts`` are billed at the output rate.- Provenance: ``source`` is a :data:`SOURCES` key ("" = the provider's own pricing page),- ``checked`` the day it was last read there, and ``status``:+ Provenance: ``checked`` is the day it was last read off the provider's pricing page, and ``status``:* ``verified`` — read off the provider's public pricing page on ``checked``* ``inferred`` — no published row; copied from the nearest sibling@@ -68,7 +61,6 @@ class Price:cache_write: float | None = Noneapproximate: bool = Falselong_context: LongContext | None = None- source: str = ""checked: str = CHECKEDstatus: str = "verified"note: str = ""diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.pyindex eac7c74e..32a1e4aa 100644--- a/harness/codeverse3d/models/retry.py+++ b/harness/codeverse3d/models/retry.py@@ -16,7 +16,7 @@ The pool:``timeout_s``. ``max_in_flight`` additionally caps how many calls may be out atonce on the whole machine, and :meth:`KeyPool.release` (a ``finally`` in``rotate_with_retries``) hands the slot back. ``try_acquire()`` is the never-waiting- variant a hedged retry uses for its extra keys; ``session_key()`` picks a key for a+ variant a hedged retry uses for its extra keys; ``lease_session_key()`` picks a key for avendor CLI session, which makes its own calls and holds no slot. There is no RPM /TPM bucket: the ledgers since the api-agent went (2026-08-29 .. 09-22, 2 080 calls)peaked at 3.9 % of one key's TPM and 2.6 % of its RPM, so the buckets never engaged@@ -230,7 +230,6 @@ class KeyPool:slots_dir: Path | str | None = None,cooldown_s: float = MAX_WAIT_S,dead_cooldown_s: float = 3600.0,- min_health: float = 0.3,clock: Callable[[], float] = time.monotonic,sleep: Callable[[float], None] = time.sleep,start: int = 0,@@ -243,7 +242,6 @@ class KeyPool:self._sleep = sleepself._cooldown_s = float(cooldown_s)self._dead_cooldown_s = float(dead_cooldown_s)- self._min_health = min_healthself._lock = threading.Lock()self._rr = start % len(uniq)self._in_flight = 0@@ -265,10 +263,6 @@ class KeyPool:def __len__(self) -> int:return len(self._states)- @property- def keys(self) -> list[str]:- return [s.key for s in self._states]-def acquire(self,*,@@ -322,21 +316,11 @@ class KeyPool:self._hold(slot)return key- def session_key(- self,- *,- exclude: set[str] | frozenset[str] | None = None,- timeout_s: float | None = ACQUIRE_TIMEOUT_S,- ) -> str:- """A key for a session that makes its own calls — a vendor CLI: rotation, 429- cooldowns and dead-key benching exactly like :meth:`acquire`, but no in-flight slot- and nothing to release. A session is minutes of agent time; a machine-wide slot- held that long would let a few dozen sessions starve every planner and judge call- on the box (docs/COST.md §23)."""- return self._acquire_key(exclude, timeout_s)-def lease_session_key(self, leases: Path | str, *, timeout_s: float | None = ACQUIRE_TIMEOUT_S) -> tuple[str, int | None]:- """:meth:`session_key`, one live session per key MACHINE-wide while there are keys enough.+ """A key for a session that makes its own calls — a vendor CLI: rotation, 429 cooldowns+ and dead-key benching like :meth:`acquire`, but no in-flight slot (a session is minutes of+ agent time; a machine-wide slot held that long would starve every planner and judge call)+ — and one live session per key MACHINE-wide while there are keys enough.A key's per-minute quota is what a long CLI session runs out of (live, 2026-10-13: oneagy session, 11 M prompt tokens in 18 min, 429'd), and every parallel ``3dcode make``@@ -500,7 +484,7 @@ class KeyPool:st.recover(now)if st.cooldown_until > now:continue- if st.health >= self._min_health:+ if st.health >= MIN_HEALTH:self._rr = (idx + 1) % nreturn stif best is None or st.health > best.health:@@ -521,6 +505,7 @@ class KeyPool:#: This is the CEILING; a caller that cannot afford it passes a smaller ``max_total_s``#: (``ChatRequest.max_wait_s``) — audit 2026-08-26 §5.1: 66 give-up spans of 900 s, up to#: three in a row on one agent turn, were 30 % of a storm day's waiting.+MIN_HEALTH = 0.3 # a key below this health is passed over while a healthier one is readyRETRY_DEADLINE_S = 1800.0 # owner 2026-08-27: generous time, zero timeouts (was 900)#: how many keys a retry is spread over once a call has met its first 503/529.diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.pyindex d10b5e9d..dae8e7be 100644--- a/harness/codeverse3d/orchestrator.py+++ b/harness/codeverse3d/orchestrator.py@@ -36,22 +36,15 @@ log = logging.getLogger(__name__)# ===================================================================== stateclass StageState(BaseModel):- """One completed stage: inputs hash + where its result JSON lives."""+ """One completed stage: its inputs hash (the result JSON is at ``stages/<name>.json``)."""- name: strinputs_hash: str- result_path: str = ""- finished_at: datetime = Field(default_factory=lambda: datetime.now(UTC))- duration_s: float = 0.0class RunState(BaseModel):"""Everything the orchestrator needs to resume a run — except the round history, which isthe round journal's alone (``rounds/rNN.json`` + each round's commit; ``lifecycle.reconcile_resume``- reads it). A state saved before 2026-09-22 also caches that journal (``completed_rounds`` /- ``round_commits`` / ``current_round``) and names a best round (``best_round`` / ``best_commit`` /- ``best_score`` / ``best_considered_through``): unknown keys, ignored — a resume goes on from the- journal's LAST round."""+ reads it)."""status: RunStatus = RunStatus.PLANNINGstages: dict[str, StageState] = Field(default_factory=dict)@@ -192,7 +185,7 @@ class StageRunner:path.parent.mkdir(parents=True, exist_ok=True)self.ws.write_json(path, {"stage": name, "inputs_hash": h, "result": _jsonable(result)})with self._lock:- self.state.stages[name] = StageState(name=name, inputs_hash=h, result_path=str(path), duration_s=dt)+ self.state.stages[name] = StageState(inputs_hash=h)self.state.save(self.ws)self.events.emit("stage.done", stage=name, inputs_hash=h, duration_s=round(dt, 2))return result@@ -586,9 +579,9 @@ class BudgetGuard:left = max(0.0, (self.soft_minutes() if soft else self.hard_minutes) - self.elapsed_minutes()) * 60.0return int(max(floor_s, min(float(want_s), left) if left > 0 else floor_s))- def left_s(self, *, soft: bool = False) -> float:- """Seconds left before the hard ceiling (the soft one with ``soft``), never negative."""- return max(0.0, (self.soft_minutes() if soft else self.hard_minutes) - self.elapsed_minutes()) * 60.0+ def left_s(self) -> float:+ """Seconds left before the hard ceiling, never negative."""+ return max(0.0, self.hard_minutes - self.elapsed_minutes()) * 60.0def summary(self) -> dict[str, float]:"""``record.extra["budget"]``: the clock at the end, beside its ceiling."""@@ -597,7 +590,6 @@ class BudgetGuard:class BudgetSnapshot(BaseModel):"""What survives a resume (``run_state.extra["budget_snapshot"]``): cumulative ACTIVE- seconds. A snapshot written before 2026-09-22 also carries the guard's money- (``spent`` / ``billed_usd`` / ``calls`` / ``by_stage``): unknown keys, ignored."""+ seconds."""active_s: float = 0.0diff --git a/harness/codeverse3d/proc.py b/harness/codeverse3d/proc.pyindex 1dd7ffb6..99742d26 100644--- a/harness/codeverse3d/proc.py+++ b/harness/codeverse3d/proc.py@@ -113,6 +113,7 @@ def _group_alive(pgid: int) -> bool:#: can no longer grow the harness RSS (or the trajectory files, which record full#: stdout — only the model-facing SHELL_OUT_CAP existed before) without bound.STREAM_BUDGET_BYTES = 8 * 1024 * 1024+TERMINATE_GRACE_S = 5.0#: longest chunk one pump read returns. A child that emits gigabytes with no#: newline would otherwise accumulate the whole "line" in RAM before the stream@@ -184,7 +185,7 @@ class ManagedProcess:* ``__exit__``: on ANY exception — KeyboardInterrupt above all, because``start_new_session`` children never receive the terminal's Ctrl-C SIGINT —or with the child still running at scope exit, the whole group gets- SIGTERM → ``grace_s`` → SIGKILL, the pumps are drained for at most+ SIGTERM → :data:`TERMINATE_GRACE_S` → SIGKILL, the pumps are drained for at most:data:`DRAIN_TIMEOUT_S`, and the child is reaped with ``wait()`` so no zombieis left. A descendant that setsid'd away and still holds a pipe cannot stallthe drain: closing the stream from this thread would block on the buffer lock@@ -202,14 +203,11 @@ class ManagedProcess:stdin_text: str | None = None,preexec_fn: Callable[[], None] | None = None,on_line: Callable[[str, str], None] | None = None,- stream_budget: int = STREAM_BUDGET_BYTES,- grace_s: float = 5.0,) -> None:self._on_line = on_line- self._grace_s = grace_sself._stop = threading.Event() # tells an abandoned pump to quit feedingself._abandoned = "" # the truncation note to append, once we know which one- self._sinks = {"stdout": _BoundedSink(stream_budget), "stderr": _BoundedSink(stream_budget)}+ self._sinks = {"stdout": _BoundedSink(STREAM_BUDGET_BYTES), "stderr": _BoundedSink(STREAM_BUDGET_BYTES)}# started and registered under the guard: a stop between the two can neither miss# this group nor let a worker start a new one once the stop has begunwith _LIVE_GUARD:@@ -265,11 +263,6 @@ class ManagedProcess:stdin.close()# ------------------------------------------------------------- what the wrappers need- @property- def pid(self) -> int:- """The child's pid — also its process-GROUP id (``start_new_session``)."""- return self.proc.pid-@propertydef returncode(self) -> int | None:return self.proc.returncode@@ -303,10 +296,8 @@ class ManagedProcess:with contextlib.suppress(ProcessLookupError):self.proc.kill()- def terminate(self, grace_s: float | None = None) -> None:- """SIGTERM the group, escalate to SIGKILL after ``grace_s`` (default: the- constructor's ``grace_s`` — the old ``watchdog.kill_process_group`` contract)."""- grace = self._grace_s if grace_s is None else grace_s+ def terminate(self) -> None:+ """SIGTERM the group, escalate to SIGKILL after :data:`TERMINATE_GRACE_S`."""try:# killpg after the leader was reaped is a microsecond pid-reuse race the# code has always taken; a live grandchild is the certain cost of not doing it@@ -315,7 +306,7 @@ class ManagedProcess:returnexcept PermissionError: # cannot signal the group — go for the child itselfself.proc.terminate()- deadline = time.monotonic() + grace+ deadline = time.monotonic() + TERMINATE_GRACE_Swhile time.monotonic() < deadline:self.proc.poll() # reap first: an unreaped zombie leader keeps the group "alive"if not _group_alive(self.proc.pid):@@ -323,7 +314,7 @@ class ManagedProcess:time.sleep(0.02)self.kill()with contextlib.suppress(subprocess.TimeoutExpired):- self.proc.wait(timeout=self._grace_s)+ self.proc.wait(timeout=TERMINATE_GRACE_S)def __enter__(self) -> ManagedProcess:return self@@ -745,36 +736,17 @@ def exclusive(run_root: Path | str, *, what: str = "", action: str = "enter") -># ===================================================================== fanout-def _in_caller_context(snapshot: contextvars.Context, fn: Callable[[int], None], i: int) -> None:- """Run ``fn(i)`` with the values the caller's context held at fan-out time.-- ``Context.run`` cannot be re-entered from several threads, so each worker- replays the snapshot's variables into its own (already fresh) context.- """- for var, value in snapshot.items():- var.set(value)- fn(i)--def fan_out[T, R](items: Sequence[T] | Iterable[T],fn: Callable[[T], R],- max_workers: int = 8,+ max_workers: int,*,label: str = "fanout",item_name: Callable[[T], str] | None = None,- on_done: Callable[[int, T, R | Exception, float], None] | None = None,) -> list[R | Exception]:"""Run ``fn`` over ``items`` in a thread pool; return results in input order.- Each result is the return value or the raised ``Exception``. ``on_done``- (if given) is called from the worker thread with ``(index, item, result,- seconds)`` — keep it cheap and thread-safe (e.g. an EventLog.emit).-- ``max_workers`` is a *fallback*: every caller in the harness states its own,- sized from the measured ceilings in ``docs/COST.md`` Part III- (``Settings.limits`` for the subprocess side, ``Settings.rate.max_in_flight``- for model calls). 8 is the largest width that is inside both knees.+ Each result is the return value or the raised ``Exception``."""items = list(items)# Workers inherit the caller's context so ambient state set with contextvars@@ -800,15 +772,13 @@ def fan_out[T, R](dt = time.time() - t0results[i] = outlog.info("%s[%s] done in %.1fs (%s)", label, name, dt, "error" if isinstance(out, Exception) else "ok")- if on_done is not None:- on_done(i, item, out, dt)if workers == 1:for i in range(len(items)):_run(i)else:with ThreadPoolExecutor(max_workers=workers, thread_name_prefix=label) as pool:- list(pool.map(lambda i: contextvars.copy_context().run(_in_caller_context, ctx_snapshot, _run, i),+ list(pool.map(lambda i: ctx_snapshot.copy().run(_run, i),range(len(items))))n_failed = sum(1 for r in results if isinstance(r, Exception))diff --git a/harness/codeverse3d/prompts/__init__.py b/harness/codeverse3d/prompts/__init__.pyindex 062e8234..af1f329f 100644--- a/harness/codeverse3d/prompts/__init__.py+++ b/harness/codeverse3d/prompts/__init__.py@@ -57,11 +57,6 @@ def _resolve(variant: str, rel_path: str) -> Path: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)diff --git a/harness/codeverse3d/prompts/scene_threejs/contract.md b/harness/codeverse3d/prompts/scene_threejs/contract.mdindex 54c8c0e3..3eb2556d 100644--- a/harness/codeverse3d/prompts/scene_threejs/contract.md+++ b/harness/codeverse3d/prompts/scene_threejs/contract.md@@ -198,11 +198,8 @@ does not inflate the content box or the overview fit); an interior's lid meshes* A sky-dome material needs `fog: false`, `side: THREE.BackSide`, `depthWrite: false` (and thetonemap / colorspace chunks `makeShaderMaterial` adds) or it renders black or fogged.* `mergeGeometries` returns `null` on mismatched attributes — check before `computeVertexNormals`.-* `walk(fig, t)` (lib/figure.js) runs only inside `userData.update(t)`; at build time it throws- `time must be finite`.* A GLB hero is visible only if the zone clones `ctx.assets['<snake>']` (nothing loads a GLBitself); its pivot is at its base; `clone.userData.clipOffset = <seconds>` de-phases a copy.-* `makeText` (lib/signage.js) is async: await it ONCE at module top level, `.clone()` per copy.* Water: inside any shoreline the terrain must lie below the water level or the shore z-fights.* A camera below the terrain under it, or inside a mesh, is a gate ERROR capped at 0.50: theplan's camera heights are absolute metres, so compute y from `heightAt(x, z)` (or the floordiff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.mdindex c3e86919..3ea11dd6 100644--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md@@ -17,12 +17,8 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,| Want | Call || --- | --- || a small flame or wax candle | `makeFire({ radius, height, seed, quality: 'high' })` · `makeCandle({ radius, height, seed, lit: true })` — `lib/fire.js`; volumetric flame, moving illumination, wick and wax. Returns a Group with `userData.update(t, dt)`; use metres (candle radius about 0.025, height 0.15). Fire is transparent: avoid intersecting glass volumes. |-| a campfire, large fuel bed or flames through a building | `makeFireField({ emitters: [{ position: [0,0,0], radius: 0.3, height: 1, strength: 1 }], wind: [0.15,0], smoke: {height: 3, density: 0.65}, occluders: [fuel, walls], quality: 'balanced', seed })` — `lib/firefield.js`; all sources share one flame/soot integration. Wind is local metres/second. Optional borrowed opaque occluders truncate rays, including instancing/alpha cuts; custom deformation needs customDepthMaterial. No glass interleaving, skinned occluders or log-depth capture. Layout/wind are baked: rebuild to change them. Group provides update/dispose, bounds, sampleField(x,y,z,t), sampleEmber(index,t) and cost. Start with one field: each field adds a ray march over 3D textures, plus a depth pass when occluders are given. || rising smoke, steam from a cup or vent | `makeSmoke({ height: 3, radius: 0.14, wind: [0.06, 0], riseSpeed: 0.7, seed, quality: 'balanced' })` · `makeSteam({ height: 0.5, radius: 0.03 })` — `lib/smoke.js`; bounded 3D density with upward advection, widening, dilution and internal light attenuation. Mesh origin is the emitter at local y=0. `userData.update(t)`, `userData.sampleDensity(x,y,z,t)` and `userData.dispose()`. Directional/point/ambient scene lights illuminate it. Keep opaque geometry outside its `userData.bounds`; intersections and overlapping transparent volumes are not depth-resolved. || the OCEAN, a lake or any sizeable water body | `makeOceanSurface({ width, depth, waveHeight, wavelength, windDirection: [1, 0.2], seed })` — `lib/ocean.js`, the ocean: dispersive Gerstner waves on real displaced geometry, reflected scene, crest foam; Group with `userData.update(t, dt)` and `userData.sampleHeight(x, z, t)`. Its flat option, for calm or distant water where no wave shape reads (a pond, a far lake): `makeOcean(w, d, { sunDir })` — `lib/water.js`, a normal-mapped mirror plane. Each planar reflector re-renders the scene once per frame: keep the total inside the fps / draw budget `scene_probe` reports (one is the safe default). |-| a curved shallow STREAM | `makeStream({ points: [[0, 0.6, -8], [2, 0.3, 0], [0, 0, 8]], width: 2, depth: 0.3, speed: 1, seed })` — `lib/stream.js`; points run upstream → downstream, decreasing Y. Refracts the opaque bed/scene through depth-varying water; flowing ripples, stone wakes and approximate caustics. `waterColor: 0x80b6a6, attenuationDistance: 3` controls volume absorption over a distance in metres. Optional `reflectionSize: 512` captures the banks; default 0, and at most ONE planar reflector per scene. Group with `userData.update(t, dt)`, `userData.sample(u, lateral, t)`. Keep terrain BELOW the bed inside the channel. |-| a falling sheet of water over a weir | `makeWaterfall({ width: 2, height: 3, speed: 1, thickness: 0.045, foam: 0.65, seed })` — `lib/waterfall.js`; gravity accelerates and thins the sheet, with advected ripples, local aeration and impact spray. Origin is impact water level, lip is `[0,height,0]`, flow is +Z. Supply the upstream water, cliff and pool. `userData.sample(u,lateral,t)` uses u=0..1 and lateral=-0.5..0.5; `userData.impact` gives the receiving point. No collision/fluid solver; opaque-scene refraction only. |-| thick broken ice with actual open fissures | `makeFracturedIce({ size: [8,6], thickness: 0.28, crackDensity: 0.65, frost: 0.35, seed })` — `lib/ice.js`; closed floes, bevels, internal air and local optical thickness. Nominal top is y=0. `userData.sampleHeight(x,z)` returns local top height or null in a gap. Supply an opaque lakebed/water backing: transparent volumes are not recursively refracted. || dunes, wind ripples, sand grains | `makeSandTerrain({ size: [60, 60], duneHeight: 3, duneSpacing: 18, windDirection: [1, 0.3], seed })` — `lib/sand.js`; Group with `userData.sampleHeight(x, z)` and `userData.update(t, dt)`. Sample height for every prop. || a close-view fractured rock or a talus field | `makeRock({ type: 'sandstone', size: [2, 1.5, 2], seed, moisture: 0.2 })` · `makeRockField` — `lib/rock.js`; types sandstone / granite / basalt; closed geometry, stratification and weathering. Rock rests at local y≈0; place using terrain height. || close-view grass with folded blades and flowing wind | `makeMeadow({ size: [8, 8], height: 0.3, density: 900, heightAt, mask, seed, wind: { dir: [1, 0.3], strength: 1.2, speed: 1 } })` — `lib/meadow.js`; every effect's wind option (wind; the veils' direction and drift; the ocean's and sand's windDirection) is read by ONE reader, `readWind` in `lib/shader.js` — a number, `[x, z]`, a vector or this object — so one wind object moves meadow, grass, trees, fire, smoke and rain alike; mask(x,z) is 0..1 coverage; Group with `userData.update(t, dt)`. Set `ground: false` over an existing terrain. Fit the sun shadow frustum tightly; blades need millimetre-scale shadow texels. |@@ -33,17 +29,12 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,| bark, and a forest at distance | `patchBark` · `makeImposters` — `lib/woodland.js` || light through a canopy | `patchDappledLight` · `patchCanopyShade` — `lib/dapple.js`; goes on the surface being LIT, not on the tree || flowers, drifting petals or leaves | `makeFlowers` · `makeFalling` — `lib/flowers.js` |-| midges, butterflies, fireflies; reeds in water | `makeInsects` · `makeReeds` — `lib/smalllife.js` || birds or fish in motion | `makeFlock({ count, kind, extent, height, path })` — `lib/flock.js` || mist over moving water, spray where it lands | `makeWaterMist` · `makeSpray` — `lib/watermist.js` || a waterline | `patchShoreWet` · `patchShoreFoam` · `patchShallowWater` — `lib/waterside.js` |-| anything BELOW the water, rain rings, thin ice | `patchUnderwater` · `makeRainRings` · `patchThinIce` — `lib/submerged.js` |-| the moving net of light under water | `patchCaustics(material, { level, sunDir })` — `lib/caustics.js`; goes on the surface being LIT, not on the water || moss, damp near water, dried mud | `patchMoss` · `patchMoisture` · `patchCrackedMud` — `lib/damp.js` |-| a polished or wet floor | `makeMirrorFloor(w, d)` — `lib/wetground.js`; re-renders the scene like the water bodies — use one or the other || rock, cliff, ground | `patchTriplanar` · `patchSlopeSplat` — `lib/terrain_shade.js` || ground and cliff geometry | `ground({ size, rand: mulberry32(seed), relief, flat })` returns `{ mesh, height }` — one terrain option (a displaced plane with a seeded heightfield and an optional flat mask; with no seeded rand it is flat); whatever the env's heightAt(x, z) returns must be its real height · `cliff({ length, height, rand })` — `lib/terrain.js`. The brief decides the landform; a floor, terraces or a canyon are not this call. |-| placing a camera or a prop by intent | `seat` · `establishingShot` · `faceToward` · `alongPath` · `crowdOn` — `lib/place.js` || a cliff that reads as rock | `patchRockStrata` · `patchErosionStreaks` — `lib/strata.js`; bedding by world altitude, so every cliff in a scene shares one bedding plane || countryside continuing beyond the content | `makeOutskirts({ inner, baseY, heightAt, shellRadius, colors, seed })` — `lib/environment.js`; seam-matched relief, field patchwork and wooded clusters — one option for a rural setting. The requirement is that no camera sees the ground end against the sky (`world_edge_visible`) or a diorama on an empty plane (judged); how the world continues — a street that keeps going, a sea, a canyon wall, a city, fog that closes — is the brief's. || a Blender hero's own keyframed motion (the GLB carries a clip) | nothing to call — the assembled scene plays every clone's clips; `clone.userData.clipOffset = 0.7` de-phases a copy |@@ -55,22 +46,17 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,| stars, the Milky Way, aurora, heat shimmer | `makeStars` · `makeAurora` · `makeHeatShimmer` — `lib/celestial.js` || fog on the ground, distance haze | `makeHeightFog` · `patchAerialPerspective` — `lib/atmosphere.js` || shafts of light | `makeGodRays({ count, height, sunDir, ambient })` — `lib/godrays.js`; the default is daylight — pass `ambient` BELOW 0.35 only for a genuinely unlit interior, where the shafts switch to adding light |-| rain sheets at distance, snowfall, motes | `makeRainVeil` · `makeSnowfall` · `makeMotes` — `lib/veils.js`; weather you see ACROSS the valley, not the drops by the lens |-| rain, splashes, puddles | `makeRain` · `makeSplashes` · `wetten` · `makePuddle` — `lib/rain.js` |-| snow or drifted sand lying on things | `patchSnow` · `patchSand` — `lib/accumulation.js`; one deposit rule across the whole scene is what makes weather read |+| rain sheets at distance, snowfall, motes | `makeRainVeil` · `makeSnowfall` · `makeMotes` — `lib/veils.js`; weather you see ACROSS the valley || a building, a cottage, a city block | `block` · `cottage` · `cityFabric` — `lib/building.js` |-| lit windows at night | `makeNightWindows(mesh)` · `patchWindowInteriors` — `lib/windows.js` || a glazed facade, power lines, a hoarding | `patchCurtainWall` · `makePowerLines` · `makeBillboard` — `lib/urban.js`; the facade spends no second render target || a neon sign, and the light it throws | `makeNeonTube` · `patchNeonSpill` · `makeLightTrails` — `lib/neon.js`; a sign that does not light its own wall is a decal |-| readable lettering on a sign | `makeText` (async — await ONCE at module top level, `.clone()` per copy) — `lib/signage.js` || a road, a path, a worn surface | `patchRoadSurface` · `patchSeamBand` · `patchTracks` — `lib/roadway.js` || foreground cobbles or rectangular stone setts with real joints | `makePaving({ size: [4,4], stoneSize: 0.24, pattern: 'cobble', joint: 0.012, thickness: 0.10, relief: 0.014, seed })` — `lib/paving.js`; merged closed bevelled stones and a recessed joint bed, two meshes and a bounded stone count. Nominal top is y=0, bottom=-thickness. `userData.sampleHeight(x,z)` returns the exact local stone/joint height; seat props using it. Use material-only cobbles for distant surfaces. || a flag, a hanging banner, a wheat field | `makeFlag` · `makeBanner` · `makeWheatField` — `lib/cloth.js`; the wave TRAVELS || a surface that has stood somewhere | `patchDripStains` · `patchRust` · `patchDust` — `lib/aging.js` || any surface at all | `patchMicroBreakup` · `patchEdgeWear` — `lib/surface_wear.js` || paper, wax, jade, petals; oil film, beetle shell | `patchTranslucency` · `patchIridescence` — `lib/finish.js` |-| a person | `figure({ height, fem, rand })` · `sit` · `walk` · `carry` — `lib/figure.js`; a pose is one of those three calls on the figure, not an option — left alone it stands |-| the same asset hundreds of times, in one draw call | `instanceAsset` · `scatterGrid` — `lib/instancing.js` · `mergeStatic(meshes)` — `lib/merge.js` |+| the same asset hundreds of times, in one draw call | `mergeStatic(meshes)` — `lib/merge.js` || a textured standard material without a texture file | `brick` · `granite` · `cobble` · `asphalt` · `weatheredWood` · `brushedSteel` · `fabric` · `foliage` · `soil` · `skin` · `glass` (21 in all) · `tint(mat, variant)` — `lib/materials.js` || noise on the CPU (heightfields the shader must agree with) | `fbm2` · `fbm3` · `mulberry32` · `displaceY` — `lib/noise.js` || your own shader, safely | `makeShaderMaterial` · `patchStandard` · `shadowLike` · `tickShaders` — `lib/shader.js` |@@ -79,14 +65,14 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,## The four rules that apply to all of them-**New natural-element factories use one lifecycle.** Fire, fire field, candle, ocean, stream,-sand, meadow, smoke, steam, waterfall, tree, shrub, cloud volume, ice and paving provide+**New natural-element factories use one lifecycle.** Fire, candle, ocean,+sand, meadow, smoke, steam, tree, shrub, cloud volume and paving provide`object.userData.update(t, dt)` (absolute seconds)and `object.userData.dispose()`. Store the returned objects and update each ONCEfrom the zone's `userData.update`. Their dimensions, paths and height queries areLOCAL coordinates; move/rotate the whole returned object to place it. Call thefactory before positioning props that sample its surface: `userData.sampleHeight(x, z)`-returns the surface height there, or `null` off the patch (and in an ice gap). It+returns the surface height there, or `null` off the patch. Itnever throws, so test for `null` before seating a prop. These are realtimeprocedural effects, not fluid/combustion solvers. Read the module's JSDoc foroptions and bounds: an option left out or `null` takes its default, and an invalid@@ -119,9 +105,9 @@ function update(t, dt) {and in a zone, call the effect's own hook from the group's `update`:```js-const rain = makeRain();-g.add(rain);-g.userData.update = (t, dt) => { rain.userData.update(t, dt); };+const motes = makeMotes();+g.add(motes);+g.userData.update = (t, dt) => { motes.userData.update(t, dt); };```Calling a missing hook throws and can stop the whole scene's animation.diff --git a/harness/codeverse3d/prompts/tracks/plan_scene.j2 b/harness/codeverse3d/prompts/tracks/plan_scene.j2index ddd58330..38b37bc5 100644--- a/harness/codeverse3d/prompts/tracks/plan_scene.j2+++ b/harness/codeverse3d/prompts/tracks/plan_scene.j2@@ -13,9 +13,8 @@ LANGUAGE CONTRACT THE BUILDERS WILL FOLLOW:SHIPPED LIBRARY (optional toolbox):The scene workspace already contains, under `src/lib/`: `fire.js` (`makeFire`, `makeCandle`),-`firefield.js` (`makeFireField`), `smoke.js` (`makeSmoke`, `makeSteam`), `cloudvolume.js`-(`makeCloudVolume`), `ocean.js` (`makeOceanSurface`), `stream.js` (`makeStream`),-`waterfall.js` (`makeWaterfall`), `ice.js` (`makeFracturedIce`), `sand.js` (`makeSandTerrain`),+`smoke.js` (`makeSmoke`, `makeSteam`), `cloudvolume.js`+(`makeCloudVolume`), `ocean.js` (`makeOceanSurface`), `sand.js` (`makeSandTerrain`),`rock.js` (`makeRock`, `makeRockField`: sandstone / granite / basalt rocks and talus),`tree.js` (`makeTree`: oak / birch / willow; `makeShrub`), `meadow.js` (`makeMeadow`) and`paving.js` (`makePaving`). Use a call when its output fits the brief: name it, its module anddiff --git a/harness/codeverse3d/record/deliverable.py b/harness/codeverse3d/record/deliverable.pyindex c6640ea3..fcd6845b 100644--- a/harness/codeverse3d/record/deliverable.py+++ b/harness/codeverse3d/record/deliverable.py@@ -17,8 +17,7 @@ be zipped and sent on its own:WHICH round is not decided here: since 2026-09-22 the run keeps every round and ends at thelast one, and ``codeverse3d.addons.select`` picks a round and packages it. Renders per-round, gates, judge verdicts and measurements stay in the evidence bucket (``artifacts/`` =-``evidence/``); tokens, prices and settings stay in ``telemetry/``.+round, gates, judge verdicts and measurements stay in ``artifacts/``; tokens, prices and settings stay in ``telemetry/``."""from __future__ import annotations@@ -32,15 +31,12 @@ from pathlib import Pathfrom codeverse3d.contracts.common import ENTRY_FILE, Language, Trackfrom codeverse3d.contracts.run import DeliverableFile, RoundRecord, RunDeliverable, RunRecord-from codeverse3d.proc import sha256_file, write_json_atomic+from codeverse3d.proc import write_json_atomicfrom codeverse3d.record import git_historyfrom codeverse3d.workspace import Workspacelog = logging.getLogger(__name__)-MAX_FILE_BYTES = 128 * 1024 * 1024-MAX_TOTAL_BYTES = 512 * 1024 * 1024-#: a round's build output → its role in the hand-over. Exactly these (and ``meshes/``)#: are what a round keeps under ``artifacts/rNN/``: the census, build.json, the .blend and#: the export scratch dirs are evidence of the build, not part of what was built.@@ -78,52 +74,25 @@ def keep_round_artifacts(ws: Workspace, round_index: int) -> list[str]:class _Writer:- """Collects files into ``deliverable/`` and remembers role/size/hash."""+ """Collects files into ``deliverable/`` and remembers role/size/hash. Every file is a real+ copy, never a hard link: a user editing the delivered file would otherwise mutate the+ canonical evidence in ``artifacts/`` and break the sha256 recorded in the manifest."""def __init__(self, ws: Workspace):self.ws = wsself.files: list[DeliverableFile] = []- self.skipped: dict[str, str] = {}self.total = 0def add_bytes(self, rel: str, data: bytes, role: str) -> None:- if len(data) > MAX_FILE_BYTES:- self.skipped[rel] = f"file too large ({len(data)} bytes)"- return- if self.total + len(data) > MAX_TOTAL_BYTES:- self.skipped[rel] = "deliverable size cap reached"- returndest = self.ws.deliverable / reldest.parent.mkdir(parents=True, exist_ok=True)dest.write_bytes(data)self.total += len(data)self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=len(data), sha256=hashlib.sha256(data).hexdigest()))- def add_file(self, src: Path, rel: str, role: str) -> bool:- if not src.is_file():- return False- size = src.stat().st_size- if size > MAX_FILE_BYTES:- self.skipped[rel] = f"file too large ({size} bytes)"- return False- if self.total + size > MAX_TOTAL_BYTES:- self.skipped[rel] = "deliverable size cap reached"- return False- dest = self.ws.deliverable / rel- dest.parent.mkdir(parents=True, exist_ok=True)- _place(src, dest)- self.total += size- self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=size,- sha256=sha256_file(src)))- return True---def _place(src: Path, dest: Path) -> None:- """ALWAYS a real copy, never a hard link: a user editing the delivered file- would otherwise mutate the canonical evidence in ``artifacts/`` and silently- break the sha256 recorded in the manifest. The size caps above already bound- the copy cost."""- shutil.copy2(src, dest)+ def add_file(self, src: Path, rel: str, role: str) -> None:+ if src.is_file():+ self.add_bytes(rel, src.read_bytes(), role)def _code_tree(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:@@ -174,10 +143,7 @@ def _copy_sheet(ws: Workspace, rnd: RoundRecord | None, w: _Writer) -> None:def _copy_captions(ws: Workspace, record: RunRecord, w: _Writer) -> None:caps = record.extra.get("captions") or {}if not caps.get("detailed"):- side = ws.root / "captions.json"- if side.is_file():- w.add_file(side, "captions.json", "captions")- return+ w.add_file(ws.root / "captions.json", "captions.json", "captions")returnkeys = ("detailed", "instruction", "factory")w.add_bytes("captions.json", json.dumps({k: str(caps.get(k, "") or "") for k in keys},@@ -215,7 +181,7 @@ def build_deliverable(ws: Workspace, record: RunRecord, round_index: int | None,manifest = RunDeliverable(round=(rnd.index if rnd is not None else None), commit=(rnd.commit if rnd is not None else ""), code_source=code_source,entry=f"deliverable/{entry}" if entry in files else "",- files=sorted(w.files, key=lambda f: f.path), total_bytes=w.total, skipped=w.skipped,+ files=sorted(w.files, key=lambda f: f.path), total_bytes=w.total,generated_at=datetime.now(UTC),)manifest.generated_at = _stable_timestamp(previous, manifest)diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.pyindex 327a35dc..5a49bac0 100644--- a/harness/codeverse3d/record/telemetry.py+++ b/harness/codeverse3d/record/telemetry.py@@ -21,7 +21,6 @@ from __future__ import annotationsimport hashlibimport jsonimport logging-from typing import Anyfrom codeverse3d.config import get_settingsfrom codeverse3d.contracts.run import (@@ -44,16 +43,12 @@ log = logging.getLogger(__name__)# --------------------------------------------------------------------------- settings snapshotdef price_table_version() -> str:"""Content hash of the USD price table — the run was costed with THIS table."""- try:- from codeverse3d.models.pricing import PRICES+ from codeverse3d.models.pricing import PRICES- payload = json.dumps(- {f"{p}/{m}": [v.input, v.output, v.cached, v.cache_write, v.approximate] for (p, m), v in sorted(PRICES.items())},- sort_keys=True,- )- except Exception as e: # pragma: no cover - defensive- log.debug("price table unavailable: %s", e)- return ""+ payload = json.dumps(+ {f"{p}/{m}": [v.input, v.output, v.cached, v.cache_write, v.approximate] for (p, m), v in sorted(PRICES.items())},+ sort_keys=True,+ )return hashlib.sha256(payload.encode()).hexdigest()[:12]@@ -98,16 +93,10 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:"""The resolved 'how was this run configured' block (no secrets, ever)."""spec = record.specrubric = rubric_of(record)- render: dict[str, Any] = {}- limits: dict[str, Any] = {}- keys = 0- try:- s = get_settings()- render = s.render.model_dump(mode="json")- limits = s.limits.model_dump(mode="json")- keys = len(s.gemini_api_keys)- except Exception as e: # pragma: no cover - settings should always load- log.debug("settings unavailable: %s", e)+ s = get_settings()+ render = s.render.model_dump(mode="json")+ limits = s.limits.model_dump(mode="json")+ keys = len(s.gemini_api_keys)env = dict(record.environment)variant, variant_version, variant_hash = _variant_fields(record)return SettingsSnapshot(diff --git a/harness/codeverse3d/reference.py b/harness/codeverse3d/reference.pyindex df076fe9..22f309f8 100644--- a/harness/codeverse3d/reference.py+++ b/harness/codeverse3d/reference.py@@ -6,8 +6,7 @@ dimension band vs the picture's outline (:func:`dimension_conflict` — when thedisagree the BRIEF wins and the picture is a shape target only), and one visioncall that lists concrete mismatches (:func:`compare`). The planner, thegenerator's ``compare_reference`` tool, the silhouette gate and the judge-(:class:`codeverse3d.judges.vlm_judge.ReferenceJudge`) all read it. Nothing here-generates an image: the harness has no image-generation step.+(:class:`codeverse3d.judges.vlm_judge.ReferenceJudge`) all read it."""from __future__ import annotationsdiff --git a/harness/codeverse3d/skills/__init__.py b/harness/codeverse3d/skills/__init__.pyindex 7d913a74..99ff1c9f 100644--- a/harness/codeverse3d/skills/__init__.py+++ b/harness/codeverse3d/skills/__init__.py@@ -23,7 +23,7 @@ roots, :func:`library_roots`), its ``_claims/`` is consulted firstextra 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`.+validate`` / ``list`` walk every shipped root through :func:`shipped_roots`.Public surface for the rest of the harness::@@ -160,7 +160,7 @@ class ShippedRoot: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 directorya 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+ ``list`` walk THIS rather than :func:`bundle_dirs` alone: an overlay bundlea loop iteration wrote is routed the moment its variant is active (:func:`all_skills`), so amalformed one must fail validation here, not vanish from a session with a logged warning whilethe row that named it routes nothing. ``variants`` names the ones to walk; the default is everydiff --git a/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md b/harness/codeverse3d/skills/c3d-scene-composition/SKILL.mdindex ca328671..c1d47a12 100644--- a/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-composition/SKILL.md@@ -89,10 +89,7 @@ So compute the eye from the terrain and aim each camera at the subject the briefconst y = heightAt(x, z) + EYE; // terrain FIRST, then the eye height the brief's shot has```-Where a camera stands, how many there are and what each frames is the brief's. A strong-option for the establishing shot is `establishingShot` from `lib/place.js`, which takes the-hero object and derives distance and height from its measured box; `seat` and `shot` in-the same module place a camera or a prop on the surfaces you pass. Whatever you use, the+Where a camera stands, how many there are and what each frames is the brief's. Thefirst camera in the array is the one measured as establishing.Two notes that save a wasted repair round:diff --git a/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md b/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.mdindex be0c9c9d..06ae57e3 100644--- a/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md+++ b/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md@@ -19,8 +19,6 @@ const eye = (x, z) => heightAt(x, z) + EYE; // the brief's eye height, onFrom there every camera is the brief's: what it looks at, from where, how many. A hero'sposition comes from the zone that built it, not from a number you remember. The firstcamera in the array is measured as the establishing shot (>= 20 % of its frame content).-`establishingShot`, `seat` and `shot` in `lib/place.js` derive a camera from an object's-measured box and the surfaces you pass, if you want the arithmetic done for you.## 2. When a finding fires: what to changediff --git a/harness/codeverse3d/skills/c3d-scene-materials/SKILL.md b/harness/codeverse3d/skills/c3d-scene-materials/SKILL.mdindex 15c8e49a..d99f72d8 100644--- a/harness/codeverse3d/skills/c3d-scene-materials/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-materials/SKILL.md@@ -37,7 +37,7 @@ Requirement: copies of one asset do not read as identical at the authored cameradistance (judged: `monotonous_vegetation`, `asset_quality_detail`). Vary what the thingreally varies — a tree in scale, yaw and hue; a lamp post in nothing but yaw; a crate inyaw and wear. `tint` from `lib/materials.js` makes a hue/lightness variant of a material-(clone per VARIANT, not per instance); `instanceAsset` from `lib/instancing.js` takes+(clone per VARIANT, not per instance); an InstancedMesh takesper-placement scale and rotation.## Roughness is the realism dial@@ -78,7 +78,7 @@ silhouette, size or hue, and placed in a ring or a grid rather than clusters". Sthan one species where the place has more than one (`makeTree` / `makeShrub` from`lib/tree.js` for near trees, `makeCanopy` for every broadleaf crown and hedge,`makeImposters` for a forest at distance), clusters with clearings rather than a lattice-(`scatterGrid` with jitter times a clump mask from `fbm2` is one option), and a ground+(a jittered grid times a clump mask from `fbm2` is one option), and a groundcover layer (`makeGrass`, `makeMeadow`) so plants grow out of the ground instead of standingon it.@@ -96,8 +96,7 @@ structure meets the ground, so the seam is not a hard undressed line (`flat_grouRequirement: every placed copy's feet are within the placement gate's tolerance of what isunder them — the gate reports `floating` and `sunken` with the gap it measured, and`interpenetration` where boxes overlap; instanced clouds are exempt and are never supports.-Seat on the shared `heightAt` (`seat` from `lib/place.js` seats an object on the surfaces-you pass); sink only what the thing really sinks (a rock, a post, a tree root) and by less+Seat on the shared `heightAt`; sink only what the thing really sinks (a rock, a post, a tree root) and by lessthan the gate's `sunk_m`, or the WARN names it.## Shadows resolvediff --git a/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.md b/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.mdindex 7b3bc7bf..1d681325 100644--- a/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.md+++ b/harness/codeverse3d/skills/c3d-scene-materials/references/terrain-and-scatter.md@@ -38,7 +38,7 @@ Three multiplied gates, in order of visual weight:1. Clump mask: low-frequency noise thresholded — groves and clearings.2. Slope rejection: no trees on cliffs; rocks roll off steep faces in the viewer's head.-3. A jittered grid (`scatterGrid` from `lib/instancing.js`) — the Poisson look without+3. A jittered grid — the Poisson look withoutthe Poisson cost.Per instance: y from the height authority, yaw and scale varied, hue/lightness fromdiff --git a/harness/codeverse3d/skills/c3d-scene-motion/SKILL.md b/harness/codeverse3d/skills/c3d-scene-motion/SKILL.mdindex f18f8724..eab4e3aa 100644--- a/harness/codeverse3d/skills/c3d-scene-motion/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-motion/SKILL.md@@ -181,17 +181,17 @@ Requirement: weather and fire read as the phenomenon at the authored cameras andhard-edged quads or discs (judged: `hard_edged_particles`); a particle cloud moves or itis a decal. Options that read:-* **A walking figure**: `figure` + `walk` from `lib/figure.js`; or your own hierarchy+* **A walking figure**: your own hierarchywith pivots AT the joints, legs opposite-phase from `t`, a per-person seed on phase andspeed so a crowd is not in lockstep — frozen mid-stride reads perfectly.-* **Paths**: `alongPath` / `route` / `crowdOn` in `lib/place.js`, or a `CatmullRomCurve3`+* **Paths**: a `CatmullRomCurve3`sampled at `(t * speed / len + u0) % 1`, facing the tangent; distinct `u0` offsets spacethe traffic.-* **Rain** as elongated streaks (`makeRain`, `makeRainVeil` at distance) — elongation is+* **Rain** as elongated streaks (`makeRainVeil` at distance) — elongation isthe motion cue; **snow** as soft sprites with per-flake sway (`makeSnowfall`); **motes**and pollen from `makeMotes`; every particle gets its own phase so a frozen frame ismid-motion, never at a synchronized extreme.-* **Fire additive, smoke normal**: `makeFire` / `makeFireField` with a flickering light,+* **Fire additive, smoke normal**: `makeFire` with a flickering light,`makeSmoke` / `makeSteam` as a bounded density — a chain of spheres is not steam.## Depthdiff --git a/harness/codeverse3d/skills/c3d-scene-night/SKILL.md b/harness/codeverse3d/skills/c3d-scene-night/SKILL.mdindex 5a55bbc0..dde31c82 100644--- a/harness/codeverse3d/skills/c3d-scene-night/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-night/SKILL.md@@ -25,10 +25,8 @@ lit like a fairground. Read c3d-scene-lighting's linear-vs-hex section first —Requirement: a lit facade is lit with variation — not every window, not one flat glow —and the street under it agrees with the windows above (emissive illuminates nothing, so a-facade with no light beside it floats in the dark). Strong option: `makeNightWindows(mesh)`-and `patchWindowInteriors` from `lib/windows.js`, which light a jittered fraction of the-grid with per-window colour; pair each big lit facade with one dim matching PointLight.-`references/window-canvas.md` describes the hand-made canvas version.+facade with no light beside it floats in the dark). Pair each big lit facade with one dim+matching PointLight. `references/window-canvas.md` describes the canvas version.## Glow without postprocessing@@ -57,8 +55,7 @@ does it with its own ceiling. If the shaft reads clearly in a thumbnail, it is tA near-black road is one of the dark-ground cases the lighting skill warns about: it passesthe band only because it mirrors something. Low roughness, high metalness, and a nightenvironment bake whose LOWER half carries the window and neon colours (see-c3d-scene-atmosphere for the bake) — `makeMirrorFloor` from `lib/wetground.js` and-`wetten` / `makePuddle` from `lib/rain.js` are the shipped versions. Without a coloured bake+c3d-scene-atmosphere for the bake) — without a coloured bakethe wet road has nothing to mirror and just goes black.## Light that agrees with itselfdiff --git a/harness/codeverse3d/skills/c3d-scene-night/references/window-canvas.md b/harness/codeverse3d/skills/c3d-scene-night/references/window-canvas.mdindex 3b481eff..8f5e4488 100644--- a/harness/codeverse3d/skills/c3d-scene-night/references/window-canvas.md+++ b/harness/codeverse3d/skills/c3d-scene-night/references/window-canvas.md@@ -1,8 +1,4 @@-# The emissive window canvas — the hand-made version--`makeNightWindows` and `patchWindowInteriors` in `lib/windows.js` do this for you; what-follows is how to build the same thing by hand when a facade needs a layout the library-does not have.+# The emissive window canvasOne CanvasTexture per building ARCHETYPE, not per building:diff --git a/harness/codeverse3d/skills/c3d-scene-water/SKILL.md b/harness/codeverse3d/skills/c3d-scene-water/SKILL.mdindex 353e09c7..64c8df06 100644--- a/harness/codeverse3d/skills/c3d-scene-water/SKILL.md+++ b/harness/codeverse3d/skills/c3d-scene-water/SKILL.md@@ -39,10 +39,9 @@ why real water is dark at your feet and mirror-bright at the horizon.`makeOceanSurface` from `lib/ocean.js` for the ocean, a lake or any sizeable body(dispersive Gerstner waves on displaced geometry, reflected scene, crest foam);`makeOcean` from `lib/water.js` for calm or distant water where no wave shape reads;-`makeStream` for a curved shallow stream that refracts its bed; `makeWaterfall` for a sheet-over a weir with its own spray; `makeWaterMist` / `makeSpray` from `lib/watermist.js`;+`makeWaterMist` / `makeSpray` from `lib/watermist.js`;`patchShoreWet` / `patchShoreFoam` / `patchShallowWater` from `lib/waterside.js` on the-bank; `patchCaustics` on the bed and `patchUnderwater` on anything below the surface. Each+bank. Eachcarries `userData.update(t, dt)` — call it from the zone's own update.## Your own material@@ -72,7 +71,7 @@ displaces (Gerstner waves, dispersive — `makeOceanSurface` ships them; your owsteepness sum below 1 or the crests loop over, and takes normals from the displacedsurface) rather than only scrolling normals on a flat plane. A waterfall reads with scrolledvertical streaks thresholded to white over translucent water and soft mist at the base-(`makeWaterfall`, `makeWaterMist`); a fountain's particles as pure ballistic arcs of `t` still+(`makeWaterMist`); a fountain's particles as pure ballistic arcs of `t` stillread frozen mid-flight. `references/gerstner-and-foam.md` has the wave maths.## Verify before you finishdiff --git a/harness/codeverse3d/spatial/complexity.py b/harness/codeverse3d/spatial/complexity.pyindex 46bdeeac..f1d62e1d 100644--- a/harness/codeverse3d/spatial/complexity.py+++ b/harness/codeverse3d/spatial/complexity.py@@ -145,10 +145,6 @@ class ComplexityVector(BaseModel):)extra: dict[str, Any] = Field(default_factory=dict, description="descriptors that do not enter the index")- @property- def axes(self) -> dict[str, float]:- return {a: float(getattr(self, a)) for a in COMPLEXITY_WEIGHTS}-# --------------------------------------------------------------------- silhouettedef _raster(pts2: np.ndarray, res: int) -> np.ndarray:diff --git a/harness/codeverse3d/spatial/connectivity.py b/harness/codeverse3d/spatial/connectivity.pyindex 12ba22e3..54302da1 100644--- a/harness/codeverse3d/spatial/connectivity.py+++ b/harness/codeverse3d/spatial/connectivity.py@@ -165,7 +165,7 @@ class Penetration:class _PartCache:"""Per-part collision geometry built once and shared across every pair: the- ``fcl.CollisionObject`` (None when fcl is missing), the oriented islands the+ ``fcl.CollisionObject``, the oriented islands thecontainment test runs on, and the thickness. Before 2026-08-30 the islands werere-split per pair — on a 20-part model that is ~190 splits of the same 20 meshes."""@@ -200,35 +200,19 @@ def pair_distance(obj_a: Any = None,obj_b: Any = None,) -> PairDistance:- """Exact (fcl) or sampled minimum distance between two meshes with closest points.+ """Exact (fcl) minimum distance between two meshes with closest points.``obj_a``/``obj_b`` accept prebuilt ``fcl.CollisionObject``\\ s (see:func:`codeverse3d.spatial.joints_collide.fcl_collision_object`) so a callertesting many pairs builds each part's BVH once instead of once per pair."""- if collide._fcl is not None:- try:- oa = obj_a if obj_a is not None else fcl_collision_object(a)- ob = obj_b if obj_b is not None else fcl_collision_object(b)- req = collide._fcl.DistanceRequest(enable_nearest_points=True)- res = collide._fcl.DistanceResult()- d = collide._fcl.distance(oa, ob, req, res)- pa, pb = res.nearest_points- return PairDistance(name_a, name_b, float(max(d, 0.0)), tuple(map(float, pa)), tuple(map(float, pb)))- except Exception:- pass # fall through to the sampled estimate- rng = np.random.default_rng(_RNG_SEED)- best: PairDistance | None = None- for src, dst, flip in ((a, b, False), (b, a, True)):- pts = np.vstack([src.vertices, _sample(src, N_SAMPLES, rng)])- closest, dist, _ = trimesh.proximity.closest_point(dst, pts)- i = int(np.argmin(dist))- p_src, p_dst = tuple(map(float, pts[i])), tuple(map(float, closest[i]))- cand = PairDistance(name_a, name_b, float(dist[i]), *((p_dst, p_src) if flip else (p_src, p_dst)))- if best is None or cand.distance < best.distance:- best = cand- assert best is not None- return best+ oa = obj_a if obj_a is not None else fcl_collision_object(a)+ ob = obj_b if obj_b is not None else fcl_collision_object(b)+ req = collide._fcl.DistanceRequest(enable_nearest_points=True)+ res = collide._fcl.DistanceResult()+ d = collide._fcl.distance(oa, ob, req, res)+ pa, pb = res.nearest_points+ return PairDistance(name_a, name_b, float(max(d, 0.0)), tuple(map(float, pa)), tuple(map(float, pb)))def _sample(mesh: trimesh.Trimesh, n: int, rng: np.random.Generator) -> np.ndarray:diff --git a/harness/codeverse3d/spatial/joints_collide.py b/harness/codeverse3d/spatial/joints_collide.pyindex c3d34a5b..b61e6919 100644--- a/harness/codeverse3d/spatial/joints_collide.py+++ b/harness/codeverse3d/spatial/joints_collide.py@@ -1,6 +1,6 @@"""Per-link collision bodies for the pose sweep (:mod:`joints_sweep`).-FCL (``python-fcl``, a hard dependency) answers the boolean surface-collide and+FCL (``python-fcl``) answers the boolean surface-collide andthe exact separation distance on BVH models. Penetration *depth* is measureddeterministically on the link's **watertight islands**: a surface sample ofbody A counts as inside body B when a fixed-direction parity ray test (forward@@ -10,30 +10,21 @@ mesh winding (agent meshes routinely come out inverted) and does not depend on``Trimesh.contains`` / signed normals on the merged link mesh, which is usuallynon-watertight (touching panels share vertices) and was re-cast with *random*rays. Islands that are not watertight are tested the same way but flagged-``approx``. When FCL is missing the same deterministic inside test doubles as-the collision predicate (``backend == "trimesh"``).+``approx``."""from __future__ import annotations+import fcl as _fclimport numpy as npimport trimeshfrom trimesh.ray import ray_util-try: # declared in pyproject; guarded so a broken wheel degrades to the trimesh path- import fcl as _fcl-except Exception: # pragma: no cover - depends on the environment- _fcl = None-_MAX_SAMPLE_POINTS = 1500#: fixed, non-axis-aligned ray direction for parity tests (never re-cast at random)_RAY_DIR = np.array([0.4395064455, 0.617598629942, 0.652231566745])-def backend_name() -> str:- return "fcl" if _fcl is not None else "trimesh"--def components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]:"""Connected components of ``names`` under ``edges`` (union-find) — the contactgraph of the connectivity gate and the fixed-joint groups of the pose sweep."""@@ -54,14 +45,11 @@ def components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]:def fcl_collision_object(mesh: trimesh.Trimesh):- """``fcl.CollisionObject`` for ``mesh`` (identity transform; None when- python-fcl is unavailable). Convex meshes get the cheap ``fcl.Convex``+ """``fcl.CollisionObject`` for ``mesh`` (identity transform). Convex meshes get the cheap ``fcl.Convex``(same choice trimesh's CollisionManager makes — building a BVH for a300k-tri convex part costs ~0.7 s); everything else gets a BVH. Shared by:class:`LinkBody` and the connectivity gate so each mesh's collisiongeometry is built exactly once."""- if _fcl is None:- return Noneif mesh.is_convex:fs = np.concatenate((3 * np.ones((len(mesh.faces), 1), dtype=np.int64), mesh.faces), axis=1)return _fcl.CollisionObject(_fcl.Convex(np.asarray(mesh.vertices, dtype=float), len(fs), fs.flatten()),@@ -127,8 +115,7 @@ class LinkBody:def set_pose(self, T: np.ndarray) -> None:self.T = Tself.T_inv = np.linalg.inv(T)- if self.obj is not None:- self.obj.setTransform(_fcl.Transform(np.ascontiguousarray(T[:3, :3]), np.ascontiguousarray(T[:3, 3])))+ self.obj.setTransform(_fcl.Transform(np.ascontiguousarray(T[:3, :3]), np.ascontiguousarray(T[:3, 3])))@propertydef posed(self) -> trimesh.Trimesh:@@ -172,12 +159,10 @@ def aabb_gap(a: np.ndarray, b: np.ndarray) -> float:def collide(a: LinkBody, b: LinkBody) -> bool:- """Surfaces intersect (FCL) — or, without FCL, a surface sample of one lies inside the other."""- if a.obj is not None and b.obj is not None:- req = _fcl.CollisionRequest(num_max_contacts=1, enable_contact=False)- res = _fcl.CollisionResult()- return int(_fcl.collide(a.obj, b.obj, req, res)) > 0- return contained(a, b, n=None)+ """Surfaces intersect (FCL)."""+ req = _fcl.CollisionRequest(num_max_contacts=1, enable_contact=False)+ res = _fcl.CollisionResult()+ return int(_fcl.collide(a.obj, b.obj, req, res)) > 0def contained(a: LinkBody, b: LinkBody, n: int | None = 24) -> bool:@@ -193,12 +178,9 @@ def contained(a: LinkBody, b: LinkBody, n: int | None = 24) -> bool:def distance(a: LinkBody, b: LinkBody) -> float:"""Minimum surface separation (0 when touching/overlapping)."""- if a.obj is not None and b.obj is not None:- req = _fcl.DistanceRequest()- res = _fcl.DistanceResult()- return max(0.0, float(_fcl.distance(a.obj, b.obj, req, res)))- d = min(float(b.surface_distance(a.points).min()), float(a.surface_distance(b.points).min()))- return max(0.0, d)+ req = _fcl.DistanceRequest()+ res = _fcl.DistanceResult()+ return max(0.0, float(_fcl.distance(a.obj, b.obj, req, res)))def penetration(a: LinkBody, b: LinkBody) -> tuple[float, bool]:@@ -206,13 +188,3 @@ def penetration(a: LinkBody, b: LinkBody) -> tuple[float, bool]:when an island is not watertight (the inside test is then heuristic)."""depth = max(b.depth_of(a.points), a.depth_of(b.points))return depth, not (a.watertight and b.watertight)---def intersection_volume(a: LinkBody, b: LinkBody) -> float | None:- if not (a.watertight and b.watertight):- return None- try:- inter = trimesh.boolean.intersection([a.posed, b.posed], engine="manifold")- return float(abs(inter.volume)) if isinstance(inter, trimesh.Trimesh) and not inter.is_empty else 0.0- except Exception:- return Nonediff --git a/harness/codeverse3d/spatial/joints_model.py b/harness/codeverse3d/spatial/joints_model.pyindex 28e48551..45c170fc 100644--- a/harness/codeverse3d/spatial/joints_model.py+++ b/harness/codeverse3d/spatial/joints_model.py@@ -159,11 +159,6 @@ class Joint:def movable(self) -> bool:return self.type in MOVABLE_TYPES- @property- def driven(self) -> bool:- """Moves, but not on its own: its value follows another joint's."""- return self.movable and self.mimic is not None-def motion(self, q: float) -> np.ndarray:"""Local motion transform for joint value ``q`` (identity for fixed)."""T = np.eye(4)@@ -182,10 +177,6 @@ class Link:visual_origin: np.ndarray = field(default_factory=lambda: np.eye(4))mesh_file: str | None = None- @property- def tri_count(self) -> int:- return 0 if self.mesh is None else int(len(self.mesh.faces))-@dataclassclass Robot:@@ -193,7 +184,6 @@ class Robot:links: dict[str, Link]joints: dict[str, Joint]root: str- urdf_path: str = ""# -------------------------------------------------------------- topologydef parent_joint(self, link: str) -> Joint | None:@@ -405,7 +395,7 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, loroots = [n for n in links if n not in children]if len(roots) != 1:raise UrdfError(f"expected exactly one root link, found {roots}")- robot = Robot(name=root_el.get("name", "robot"), links=links, joints=joints, root=roots[0], urdf_path=str(urdf_path))+ robot = Robot(name=root_el.get("name", "robot"), links=links, joints=joints, root=roots[0])if len(robot.link_order()) != len(links):raise UrdfError("joint graph contains a cycle or unreachable links")return robotdiff --git a/harness/codeverse3d/spatial/joints_sweep.py b/harness/codeverse3d/spatial/joints_sweep.pyindex 64b0c52b..fc8a8c0d 100644--- a/harness/codeverse3d/spatial/joints_sweep.py+++ b/harness/codeverse3d/spatial/joints_sweep.py@@ -35,7 +35,6 @@ class Overlap(BaseModel):a: strb: strdepth_m: float = Field(description="max distance of a penetrating surface point from the other surface")- volume_m3: float | None = Noneapprox: bool = Field(default=False, description="depth estimated on non-watertight meshes")rigid: bool = Field(default=False, description="only fixed joints between the links: the overlap is structural ""(a weld), identical in every pose — judged with the rest policy")@@ -65,13 +64,11 @@ class SweepSummary(BaseModel):n_links: intmax_penetration_m: float = 0.0worst_pose: str = ""- worst_pair: tuple[str, str] | None = Nonerest_max_penetration_m: float = 0.0overlapping_poses: list[str] = Field(default_factory=list)floating_links: list[str] = Field(default_factory=list, description="floating in ANY sampled pose")floating_at_rest: list[str] = Field(default_factory=list)link_islands: dict[str, int] = Field(default_factory=dict)- backend: str = "fcl"class SweepReport(BaseModel):@@ -104,7 +101,6 @@ def sweep_collisions(*,tol_m: float = 0.002,contact_gap_m: float = CONTACT_GAP_M,- volumes: bool = True,hinge_clearance_m: float = 0.01,) -> SweepReport:"""Collide every link pair in every pose. Overlaps deeper than ``tol_m``@@ -146,8 +142,7 @@ def sweep_collisions(depth, approx = collide.penetration(ba, bb)if round(depth, 4) > tol_m: # 0.1 mm: float32 mesh coordinates carry no finer meaningoverlaps.append(- Overlap(a=a, b=b, depth_m=round(depth, 6), approx=approx, rigid=rigid,- volume_m3=collide.intersection_volume(ba, bb) if volumes else None)+ Overlap(a=a, b=b, depth_m=round(depth, 6), approx=approx, rigid=rigid))else:dist = collide.distance(ba, bb)@@ -180,12 +175,12 @@ def sweep_collisions(def _summarise(per_pose: list[PoseReport], n_links: int, islands: dict[str, int]) -> SweepSummary:- s = SweepSummary(n_poses=len(per_pose), n_links=n_links, link_islands=islands, backend=collide.backend_name())+ s = SweepSummary(n_poses=len(per_pose), n_links=n_links, link_islands=islands)floating_any: set[str] = set()for pr in per_pose:for o in pr.overlaps:if o.depth_m > s.max_penetration_m:- s.max_penetration_m, s.worst_pose, s.worst_pair = o.depth_m, pr.label, (o.a, o.b)+ s.max_penetration_m, s.worst_pose = o.depth_m, pr.labelif pr.label == "rest" or o.rigid: # structural overlaps count as rest penetrations.rest_max_penetration_m = max(s.rest_max_penetration_m, o.depth_m)if pr.overlaps:@@ -215,7 +210,7 @@ def sweep_findings(report: SweepReport, *, rest_max_m: float = 0.005, hinge_cleaf"shrink/move one of '{o.a}', '{o.b}' so they touch (≤ {report.tol_m*1000:.0f} mm) instead of overlapping."if at_rest elsef"Moving joint(s) {sorted(pr.q)} drives '{o.a}' into '{o.b}'. Either move the pivot/axis in robot.urdf so the part swings/slides clear, shrink the limits, or carve the clearance in model.py."),- data={"kind": "penetration", "pose": pr.q, "depth_m": o.depth_m, "volume_m3": o.volume_m3},+ data={"kind": "penetration", "pose": pr.q, "depth_m": o.depth_m},))for f in pr.floating:fixed = f.joint_type == "fixed"diff --git a/harness/codeverse3d/spatial/mcp_server.py b/harness/codeverse3d/spatial/mcp_server.pyindex b2056f79..aa3cf187 100644--- a/harness/codeverse3d/spatial/mcp_server.py+++ b/harness/codeverse3d/spatial/mcp_server.py@@ -142,7 +142,7 @@ def observation_content(obs: Observation) -> list[Any]:# the slice makes the ceiling hard: truncate's "N chars omitted" marker overshoots its# own budget by a few characters, and this is the last bound before the vendor's promptblocks: list[Any] = [types.TextContent(type="text", text=truncate(text, MAX_TEXT_CHARS)[:MAX_TEXT_CHARS])]- # images[0] is the contact sheet (image_budget keeps it first) and every later image is+ # images[0] is the contact sheet (the tools list it first) and every later image is# a per-view repeat of it, so the budget STOPS at the first one that does not fit rather# than skipping it: dropping the sheet and shipping three views of the same thing would# be the worst of both. Whatever is dropped is said in the text — a FAIL verdict thatdiff --git a/harness/codeverse3d/spatial/observe.py b/harness/codeverse3d/spatial/observe.pyindex 6f00643a..05a8691c 100644--- a/harness/codeverse3d/spatial/observe.py+++ b/harness/codeverse3d/spatial/observe.py@@ -2,12 +2,11 @@* ``fmt_numbers`` – one-line ``k=v`` rendering with sane float precision.* ``truncate`` – head/tail truncation with a marker (never mid-line when possible).-* ``image_budget`` – cap image lists (contact sheet kept first).* ``rel_path`` – workspace-relative display path (never leak host paths in text).* ``lint_lines`` / ``build_failure_lines`` – the one lint / BUILD FAILED reportformat shared by the ``build`` and ``gl_probe`` / ``gl_frames`` tools.* ``text_observation`` / ``gate_observation`` / ``render_observation`` – the- standard Observation builders (truncation + image budget applied once).+ standard Observation builders (truncation applied once)."""from __future__ import annotations@@ -20,7 +19,6 @@ from codeverse3d import procfrom codeverse3d.contracts.artifacts import BuildResult, GateReport, RenderSet, Severityfrom codeverse3d.spatial.registry import Observation-MAX_IMAGES = 6MAX_TEXT = 2400@@ -70,14 +68,6 @@ def truncate(text: str, n: int = MAX_TEXT, tail_ratio: float = 0.3) -> str:return f"{head}\n… [{len(text) - head_n - tail_n} chars omitted] …\n{tail}"-def image_budget(images: Sequence[str], max_n: int = MAX_IMAGES) -> list[str]:- """Keep at most ``max_n`` images; the first (contact sheet) always survives."""- imgs = [str(p) for p in images if p]- if len(imgs) <= max_n:- return imgs- return imgs[:max_n]--def rel_path(path: Path | str | None, root: Path) -> str:"""Display path relative to the workspace root (falls back to the file name)."""if path is None:@@ -108,15 +98,15 @@ def text_observation("""Observation from text lines: joined, truncated to ``limit``, images capped.The plain-text counterpart of :func:`gate_observation` / :func:`render_observation`- — every tool that assembles its own report (build, gl_probe, gl_frames,- texture_pass, …) goes through here so truncation and the image budget are- applied exactly once, in one place. ``ok=False`` is a verdict (LINT/BUILD+ — every tool that assembles its own report (build, gl_probe, gl_frames, …)+ goes through here so truncation and the image budget are applied exactly once, in+ one place. ``ok=False`` is a verdict (LINT/BUILDFAILED is the answer, and the text says so first); ``failed`` is only for atool that could not run."""body = lines if isinstance(lines, str) else "\n".join(str(x) for x in lines)return Observation(ok=ok, failed=failed, text=truncate(body, limit), numbers=dict(numbers or {}),- images=image_budget([str(i) for i in images]))+ images=[str(i) for i in images if i])@@ -245,4 +235,4 @@ def render_observation(rs: RenderSet, root: Path, *, note: str = "", max_individnumbers["console_errors"] = len(rs.console_errors)return Observation(ok=bool(rs.views) and not rs.console_errors,failed=not rs.views and not rs.console_errors,- text=truncate("\n".join(lines)), numbers=numbers, images=image_budget(images))+ text=truncate("\n".join(lines)), numbers=numbers, images=[str(i) for i in images if i])diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.pyindex 5cc1e28c..384e2cc9 100644--- a/harness/codeverse3d/spatial/probes.py+++ b/harness/codeverse3d/spatial/probes.py@@ -101,7 +101,7 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =# D3: nothing moves the JS copy of a scene Blender renders — no settle, no camera repairargs += ["--glb", str(Path(glb).resolve()), "--no-settle"] # node runs in runtime_js/: a relative path would misselse:- # every probe runs under the SAME settle / camera-repair / auto-exposure policy every+ # every probe runs under the SAME settle / camera-repair policy every# render uses — ONE parser, render_scene (review-3 S4: the build used to carry none of# the flags, so its gate measured a census the renders then contradicted)args += probe_env_args()@@ -366,7 +366,7 @@ def _draw_findings(c: dict[str, Any]) -> list[GateFinding]:return [_f(PROBE_GATE, sev,f"{draws:,} draw calls per frame (each visible mesh is one) exceed the {limit:,} budget"+ (f" — most in {where}" if where else "")- + "; instance repeated geometry with InstancedMesh (lib/instancing.js instanceAsset) or merge "+ + "; instance repeated geometry with InstancedMesh or merge ""static clutter with mergeGeometries (lib/merge.js mergeStatic)",target="scene", kind="draw_calls", draws=draws, limit=limit)]diff --git a/harness/codeverse3d/spatial/registry.py b/harness/codeverse3d/spatial/registry.pyindex b6c6b9db..f7bf67d9 100644--- a/harness/codeverse3d/spatial/registry.py+++ b/harness/codeverse3d/spatial/registry.py@@ -21,7 +21,7 @@ from __future__ import annotationsimport inspectfrom collections.abc import Callable-from dataclasses import dataclass, field+from dataclasses import dataclassfrom typing import Anyfrom pydantic import BaseModel, ConfigDict, Field, model_validator@@ -90,7 +90,6 @@ class ToolContext:round_index: int = 0language: str = ""track: str = ""- extra: dict[str, Any] = field(default_factory=dict)@dataclass(frozen=True)@@ -186,13 +185,6 @@ def tool_cards(*, track: str = "", language: str = "") -> str:return "\n".join(t.card() for t in list_tools(track=track, language=language))-_LOADED = False--def _ensure_loaded() -> None:"""Import the module that registers every tool (idempotent)."""- global _LOADED- if _LOADED:- return- _LOADED = Trueimport codeverse3d.spatial.tools # noqa: F401 — its @tool decorators fill _REGISTRYdiff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.pyindex 39b026f0..9f5a70a6 100644--- a/harness/codeverse3d/spatial/render_scene.py+++ b/harness/codeverse3d/spatial/render_scene.py@@ -153,10 +153,10 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:def probe_env_args() -> list[str]:- """Scene-driver flags from the ``C3D_SETTLE`` / ``C3D_CAMERA_REPAIR`` /- ``C3D_AUTO_EXPOSURE`` switches (``Settings``). Every driver invocation — standalone+ """Scene-driver flags from the ``C3D_SETTLE`` / ``C3D_CAMERA_REPAIR``+ switches (``Settings``). Every driver invocation — standaloneprobe, render, and the combined single-boot build — appends these, so a census is- always measured under the same settle / camera-repair / auto-exposure policy the+ always measured under the same settle / camera-repair policy therenders use."""s = get_settings()args: list[str] = []@@ -167,8 +167,6 @@ def probe_env_args() -> list[str]:# already keeps lenses out of furniture), and the one class it exists for# (fv_izakaya: three rounds of camera_in_geometry nobody could fix) is fatal.args.append("--camera-repair")- if s.auto_exposure: # opt-in: bounded scene-wide exposure into the healthy band- args.append("--auto-exposure")return argsdiff --git a/harness/codeverse3d/spatial/tool_common.py b/harness/codeverse3d/spatial/tool_common.pyindex 7bd52adb..22b1fb36 100644--- a/harness/codeverse3d/spatial/tool_common.py+++ b/harness/codeverse3d/spatial/tool_common.py@@ -32,9 +32,6 @@ VIEW_BY_NAME: dict[str, ViewPreset] = {v.name: v for v in OBJECT_VIEWS}# --------------------------------------------------------------------------- contextdef spec_dict(ctx: ToolContext) -> dict[str, Any]:- spec = ctx.extra.get("spec")- if spec is not None:- return spec.model_dump(mode="json") if hasattr(spec, "model_dump") else dict(spec)return read_json_or_none(ctx.workspace.spec_path) or {}diff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.pyindex b0b452bd..3ae13079 100644--- a/harness/codeverse3d/spatial/tools.py+++ b/harness/codeverse3d/spatial/tools.py@@ -33,7 +33,6 @@ from codeverse3d.spatial.observe import (error_file_display,fmt_numbers,gate_observation,- image_budget,lint_lines,rel_path,render_observation,@@ -680,6 +679,6 @@ def compare_reference(ctx: ToolContext, args: CompareReferenceArgs) -> Observatif"Look at the sheet and check, in this order: {CHECKLIST}",]lines.append(fmt_numbers({k: v for k, v in res.items() if k != "diff_png_path"}))- images = image_budget([str(sheet), str(diff_png), shaded.views[0].path])+ images = [str(sheet), str(diff_png), str(shaded.views[0].path)]return Observation(ok=True, text="\n".join(lines),numbers={"view": args.view, "reference_index": args.reference_index, **res}, images=images)diff --git a/harness/codeverse3d/texturing/__init__.py b/harness/codeverse3d/texturing/__init__.pydeleted file mode 100644index 3a97216a..00000000--- a/harness/codeverse3d/texturing/__init__.py+++ /dev/null@@ -1,2 +0,0 @@-"""The PBR material-family table (``materials``) that ``languages/blender`` reads. There is no-texture generation: the harness has no image-generation step."""diff --git a/harness/codeverse3d/tracks/candidates.py b/harness/codeverse3d/tracks/candidates.pyindex 99843066..803e9c60 100644--- a/harness/codeverse3d/tracks/candidates.py+++ b/harness/codeverse3d/tracks/candidates.py@@ -54,7 +54,6 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],"""Baseline round with ``ctx.policy.n_candidates`` parallel candidates; returns the r00 record."""n = max(1, ctx.policy.n_candidates)ctx.events.emit("candidates.start", round=0, n=n, parallel=min(n, ctx.settings.limits.max_parallel_agents))- ctx.ws.ensure_gitignore() # legacy run dirs may predate _cand/ in the standard linessubs = [make_candidate_context(track, ctx, k) for k in range(n)]def _one(k: int) -> CandidateRecord:@@ -144,7 +143,7 @@ def make_candidate_context(track: Any, ctx: RunContext, k: int) -> RunContext:if path.is_file():shutil.copyfile(path, sub_ws.root / path.name)if not ctx.single_shot:- ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=track.agent_contract_md(ctx), spatial_tools=True)+ ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=track.agent_contract_md(ctx))sub_ws.commit("skeleton")# own event log (the run log keeps only candidate.*) and a one-sample judge for rankingreturn replace(ctx, ws=sub_ws, extra={}, events=EventLog(sub_ws.events_path),diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.pyindex 21f41c0f..184da296 100644--- a/harness/codeverse3d/tracks/common.py+++ b/harness/codeverse3d/tracks/common.py@@ -114,16 +114,12 @@ class Services:return _import("codeverse3d.tracks.articulated_object", "default_joint_sweep")(ws, plan, out_dir)# ---- agents' workspace materialisation + tool cards- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, spatial_tools: bool) -> None:+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str) -> None:_import("codeverse3d.agents.materialize", "materialize_workspace")(- ws, agent_kind=agent_kind, contract_md=contract_md, spatial_tools=spatial_tools)+ ws, agent_kind=agent_kind, contract_md=contract_md)def tool_cards(self, track: str, language: str) -> str:- try:- return _import("codeverse3d.spatial.registry", "tool_cards")(track=track, language=language)- except Exception as e: # noqa: BLE001 — tool registry may be empty during bootstrap- log.warning("tool cards unavailable: %s", e)- return ""+ return _import("codeverse3d.spatial.registry", "tool_cards")(track=track, language=language)# ---- scene assembly + recorddef assemble_scene(self, runtime: SceneRuntime, ws: Workspace, plan: ScenePlan) -> Any:@@ -180,30 +176,18 @@ class RunContext:# ----------------------------------------------------------------------------- strategy-def single_shot_agent_id(agent_id: str, chat_model_id: str = "") -> str:- """The single-shot strategy id for this run, or "" when there is no chat model.-- Single-shot is ONE api call that returns the asset file — the cheap path the asset- stage tries before escalating to a full agent session. It needs a chat model, and- the coding agent is always a vendor CLI (which exposes none), so the model comes- from ``chat_model_id`` — the run's planner backend, which is always an API model.- Until 2026-08-28 it was derived from the in-process ``api-agent`` generator id;- that backend is gone."""- if is_single_shot(agent_id):- return agent_id- # a SHAPE check only, deliberately not models.registry.parse_model_id: whether the- # id resolves is the SERVICES' call (tests run fake providers like "fake:planner"),- # and single_shot_ctx already degrades to the agent path when chat_model() raises- return SINGLE_SHOT_PREFIX + chat_model_id if ":" in chat_model_id else ""--def single_shot_ctx(ctx: RunContext) -> RunContext | None:"""A copy of ``ctx`` bound to the single-shot strategy, or None when thegenerator has no usable chat model (CLI agents, tests with fake services)."""cached = ctx.extra.get("_single_shot_ctx")if cached is not None:return cached or None # False = known-unavailable- sid = single_shot_agent_id(ctx.agent_id, ctx.spec.backends.planner)+ planner = ctx.spec.backends.planner+ # Single-shot is ONE api call that returns the asset file; the coding agent is always a+ # vendor CLI (no chat model), so the model comes from the run's planner backend. A SHAPE+ # check only, deliberately not models.registry.parse_model_id: whether the id resolves is the+ # SERVICES' call (tests run fake providers like "fake:planner").+ sid = ctx.agent_id if is_single_shot(ctx.agent_id) else (SINGLE_SHOT_PREFIX + planner if ":" in planner else "")sub: RunContext | None = Noneif sid:try:diff --git a/harness/codeverse3d/tracks/depth.py b/harness/codeverse3d/tracks/depth.pyindex 5ce0f75e..73b78f46 100644--- a/harness/codeverse3d/tracks/depth.py+++ b/harness/codeverse3d/tracks/depth.py@@ -34,10 +34,13 @@ drafts the whole object.from __future__ import annotationsfrom dataclasses import dataclass-from typing import Any+from typing import TYPE_CHECKING, Anyfrom codeverse3d.conventions import MAX_TRIS_OBJECT+if TYPE_CHECKING:+ from codeverse3d.contracts.plan import StaticPlan+# --------------------------------------------------------------------------- triangle / time budget#: triangles a well-detailed single part is worth. Corpus: median tri/part ≈ 430, and the#: highest-scoring hard run (garden arch, 0.929) sits at 1936. Target the good end.@@ -74,10 +77,9 @@ DETAIL_ADVICE = ()-def depth_budget(plan: Any, *, build_timeout_s: int = 300) -> DepthBudget:+def depth_budget(plan: StaticPlan, build_timeout_s: int) -> DepthBudget:"""Triangle + build-time budget sized from the plan's part/instance count."""- parts = list(getattr(plan, "parts", None) or [])- n_units = sum(max(1, int(getattr(p, "leaf_count", None) or getattr(p, "instances", 1) or 1)) for p in parts) or 1+ n_units = plan.leaf_counttarget = _clamp(TRIS_PER_UNIT_TARGET * n_units, 6_000, 200_000)return DepthBudget(n_units=n_units,diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.pyindex 222b0253..7c6b9640 100644--- a/harness/codeverse3d/tracks/generation.py+++ b/harness/codeverse3d/tracks/generation.py@@ -55,7 +55,7 @@ from codeverse3d.contracts.common import (from codeverse3d.cost.context import call_contextfrom codeverse3d.cost.types import stage_for_labelfrom codeverse3d.models import get_chat_model-from codeverse3d.orchestrator import BudgetExceeded+from codeverse3d.orchestrator import BudgetExceeded, BudgetGuardfrom codeverse3d.proc import NULL_EVENTS, read_json_or_nonefrom codeverse3d.workspace import C3D_DIR, Workspace@@ -155,15 +155,15 @@ def _looks_like_code(text: str) -> bool:return bool(t) and ("\n" in t) and not t.lower().startswith(("i ", "here", "sure", "sorry"))-def safe_relpath(path: str, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> str:+def safe_relpath(path: str) -> str:"""Validate a model-provided relative path: inside the workspace + allowed roots."""p = _clean_path(path)if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):raise GenerationError(f"refusing to write outside the workspace: {path!r}")if p.endswith("/"): # '=== FILE: src/parts/ ===' names a directory, not a fileraise GenerationError(f"path {path!r} is a directory, not a file")- if not any(p.startswith(root) for root in allowed_roots):- raise GenerationError(f"path {p!r} is outside the allowed roots {allowed_roots}")+ if not any(p.startswith(root) for root in ALLOWED_ROOTS):+ raise GenerationError(f"path {p!r} is outside the allowed roots {ALLOWED_ROOTS}")return p@@ -171,14 +171,13 @@ def write_files(ws: Workspace,files: dict[str, str],*,- allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,only: Collection[str] | None = None,frozen: Collection[str] = (),on_skip: Callable[[str, str], None] | None = None,) -> list[FileChange]:"""Write parsed files under the workspace; returns git-style FileChange rows.- A block whose path is unsafe, outside ``allowed_roots`` (flash models love+ A block whose path is unsafe, outside ``ALLOWED_ROOTS`` (flash models loveto add README.md / package.json despite the format rule) or unwritable isSKIPPED — reported via ``on_skip`` — instead of aborting the whole write:the valid files were already paid for.@@ -195,7 +194,7 @@ def write_files(changes: list[FileChange] = []for raw, content in files.items():try:- rel = safe_relpath(raw, allowed_roots)+ rel = safe_relpath(raw)except GenerationError as e:if on_skip is not None:on_skip(raw, str(e))@@ -226,8 +225,7 @@ def write_files(on_skip(raw, str(e))log.warning("skipping unwritable file from generator: %s: %s", rel, e)continue- changes.append(FileChange(path=rel, status="modified" if existed else "added",- lines_added=content.count("\n") + 1))+ changes.append(FileChange(path=rel, status="modified" if existed else "added"))return changesSINGLE_SHOT_PREFIX = "single-shot:"@@ -304,7 +302,6 @@ class GenerationTask(BaseModel):)max_output_tokens: int = 65_536 # the model's declared ceiling; unused tokens cost nothingtimeout_s: int | None = None- write_roots: list[str] = Field(default_factory=lambda: ["src", "public"])edit_only: bool = Field(default=False,description="enforce files_hint as the only existing files this session may overwrite",@@ -336,18 +333,7 @@ class GenerationResult(BaseModel):files_changed: list[FileChange] = Field(default_factory=list)commit: str = ""notes: str = ""- text: str = Field(default="", description="model/agent final text (truncated)")- transcript_path: str = ""label: str = ""- turns: int = Field(- default=0, description="turns the agent session(s) took, as the backend counts them"- )- sessions: int = Field(- default=0, description="agent sessions run for this task (retry / wrap-up count)"- )- turn_capped: bool = Field(- default=False, description="a session hit the turn budget and was wrapped up"- )transient: bool = Field(default=False,description="the last session died of a provider failure (AgentResult.transient), or the call "@@ -420,9 +406,9 @@ def generate_files(*,model: Any,task: GenerationTask,- budget: Any | None = None,+ budget: BudgetGuard | None = None,events: Any | None = None,- allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,+) -> GenerationResult:"""Single-shot API codegen: ChatRequest → envelope → files on disk (no commit)."""events = NULL_EVENTS if events is None else events@@ -475,7 +461,6 @@ def generate_files(def _result(notes: str, changes: list[FileChange] | None = None) -> GenerationResult:return GenerationResult(ok=bool(changes), usage=usage, files_changed=changes or [], notes=notes,- text=(resp.text or "")[:2000], transcript_path=str(traj / "response.md"),label=task.label)if _is_truncated(resp):@@ -494,7 +479,7 @@ def generate_files(events.emit("generate.skipped_path", label=task.label, path=path, reason=reason[:200])only, frozen = _envelope_scope(ws, task)- changes = write_files(ws, files, allowed_roots=allowed_roots, only=only, frozen=frozen, on_skip=_skip)+ changes = write_files(ws, files, only=only, frozen=frozen, on_skip=_skip)events.emit("generate.done",label=task.label,@@ -505,7 +490,7 @@ def generate_files(return _result(f"skipped out-of-root paths: {', '.join(skipped)}" if skipped else "", changes)-def _deadline_preflight(budget: Any | None, wait_s: float, *, soft: bool = False,+def _deadline_preflight(budget: BudgetGuard | None, wait_s: float, *, soft: bool = False,floor_s: float = 120.0) -> float:"""Gate a session on the run clock: refuse to start past the HARD ceiling (atimed-out session that produced nothing bills nothing, so the accounting-driven@@ -513,11 +498,8 @@ def _deadline_preflight(budget: Any | None, wait_s: float, *, soft: bool = False30-minute session once ran 9 minutes past the ceiling, measured 2026-08-27)."""if budget is None:return wait_s- if hasattr(budget, "check"):- budget.check()- if hasattr(budget, "timeout_s"):- wait_s = budget.timeout_s(wait_s, floor_s=floor_s, soft=soft)- return wait_s+ budget.check()+ return budget.timeout_s(wait_s, floor_s=floor_s, soft=soft)_TRUNCATED_FINISH = {"max_tokens", "max_output_tokens", "length"}@@ -533,7 +515,7 @@ def run_agent_task(agent: Any,task: GenerationTask,settings: Any | None = None,- budget: Any | None = None,+ budget: BudgetGuard | None = None,events: Any | None = None,) -> GenerationResult:"""CodingAgent path. ``ok`` = the agent changed files (envelope-vs-disk truth).@@ -547,7 +529,6 @@ def run_agent_task(off mid-edit. Every session — first attempt, silent-bail retry, wrap-up — ischarged to ``budget`` as it ends, so nothing is lost when a later attempt raises."""events = NULL_EVENTS if events is None else events- before = ws.head()timeout = task.timeout_s or (settings or get_settings()).limits.agent_timeout_s# A task that chose its own window already clipped it the way its stage wanted# (scene.py: soft for env/zones/assets, hard for refine/rebuild) — re-clipping THAT@@ -559,7 +540,7 @@ def run_agent_task(# Sessions sharing a workspace wait for a lock. An absolute deadline keeps that# wait, retry attempts and the CLI's activity grace inside the run's hard clock.hard_deadline = None- if budget is not None and hasattr(budget, "timeout_s"):+ if budget is not None:# ``reserve_s`` (D112): a refine session cut by the run's own edge left its edits unbuilt and# unjudged (iteration 5, r1_09: the retry's camera fix was committed, never scored)hard_deadline = time.monotonic() + max(0.0, budget.timeout_s(float("inf"), floor_s=0, soft=False) - task.reserve_s)@@ -576,7 +557,6 @@ def run_agent_task(timeout_s=timeout,hard_deadline_s=hard_deadline,spatial_tools=True,- write_roots=task.write_roots,round=task.round,kind=task.kind,language=language,@@ -591,7 +571,7 @@ def run_agent_task()acc = _SessionAcc(task=task, budget=budget)res = acc.run(agent, job)- changes = res.files_changed or _attributed_fallback(ws, task, before)+ changes = res.files_changedif turn_capped(res):# the turns are gone, the money is not wasted: ask for a landing, not more work@@ -607,7 +587,7 @@ def run_agent_task(update={"prompt": WRAPUP_PROMPT + prompt, "max_turns": DEFAULT_WRAPUP_TURNS})res = acc.run(agent, wrap, wrapup=True, optional=True) or res- changes = res.files_changed or changes or _attributed_fallback(ws, task, before)+ changes = res.files_changed or changesif (not changes@@ -627,7 +607,7 @@ def run_agent_task(})res = acc.run(agent, job2, optional=True) or res- changes = res.files_changed or _attributed_fallback(ws, task, before)+ changes = res.files_changednotes = f"exit={res.exit_reason}" + (f"; errors={res.errors[:3]}" if res.errors else "")notes += ("; " + "; ".join(acc.errors)) if acc.errors else ""@@ -650,12 +630,7 @@ def run_agent_task(usage=acc.usage,files_changed=changes,notes=notes,- text=(res.text or "")[:2000],- transcript_path=res.transcript_path,label=task.label,- turns=acc.turns,- sessions=acc.sessions,- turn_capped=acc.wrapped,transient=bool(res.transient),quota=bool(res.quota),stalled=bool(res.stalled) and not changes,@@ -671,7 +646,7 @@ class _SessionAcc:``.a2`` hole of docs/COST.md §6. The run's clock is checked before and afterevery session, including sessions whose vendor returned no usage."""- def __init__(self, *, task: GenerationTask, budget: Any | None):+ def __init__(self, *, task: GenerationTask, budget: BudgetGuard | None):self.task = taskself.budget = budgetself.usage = Usage()@@ -784,23 +759,6 @@ def _read_only(language: str) -> list[str]:return []-def _attributed_fallback(ws: Workspace, task: GenerationTask, before: str) -> list[FileChange]:- """Change detection when the agent did not report its own ``files_changed``.-- A whole-worktree diff claims sibling tasks' files under fan_out (a task that- wrote nothing looked ok because its neighbours wrote files); attribute the diff- to this task instead: inside its write roots, never harness-owned paths, and —- ``shared_tree`` — inside its ``files_hint`` (the session's own attribution came back- empty, and this fallback used to hand the env task the asset files right back, D111)."""- raw = ws.changed_files(before) # Workspace serialises + retries the git index itself- try:- from codeverse3d.agents.cli_common import attribute_changes- except ImportError: # pragma: no cover — agents package always ships with tracks- return raw- return attribute_changes(raw, write_roots=list(task.write_roots),- only=task.files_hint if task.shared_tree else None)--def generate(ws: Workspace,*,@@ -809,7 +767,7 @@ def generate(agent: Any | None = None,model: Any | None = None,settings: Any | None = None,- budget: Any | None = None,+ budget: BudgetGuard | None = None,events: Any | None = None,) -> GenerationResult:"""Dispatch to the single-shot or the coding-agent strategy by ``agent_id``.@@ -826,7 +784,6 @@ def generate(task=task,budget=budget,events=events,- allowed_roots=tuple(r.rstrip("/") + "/" for r in task.write_roots),)if agent is None:from codeverse3d.agents import get_coding_agentdiff --git a/harness/codeverse3d/tracks/graphics.py b/harness/codeverse3d/tracks/graphics.pyindex 719d4086..de606d7c 100644--- a/harness/codeverse3d/tracks/graphics.py+++ b/harness/codeverse3d/tracks/graphics.py@@ -33,7 +33,7 @@ from codeverse3d.orchestrator import TaskGroupfrom codeverse3d.prompts import renderfrom codeverse3d.tracks.common import RunContextfrom codeverse3d.tracks.generation import GenerationTask-from codeverse3d.tracks.lifecycle import MATERIALIZE, SKELETON, BaseTrack+from codeverse3d.tracks.lifecycle import BaseTrackfrom codeverse3d.tracks.prompting import (base_prompt_context,judge_digest,@@ -149,7 +149,6 @@ class GraphicsTrack(BaseTrack):# refinement is always ONE whole-program taskallow_refine_fanout = Falsebaseline_temperature = 0.6- stages = (SKELETON, MATERIALIZE)def make_pipeline(self) -> GraphicsPipeline:return GraphicsPipeline()diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.pyindex 06d186f3..2479be51 100644--- a/harness/codeverse3d/tracks/lifecycle.py+++ b/harness/codeverse3d/tracks/lifecycle.py@@ -534,7 +534,7 @@ class BaseTrack:if n is None:n = spec.options.candidatesif n is None:- n = getattr(settings, "default_candidates", 1)+ n = settings.default_candidatesreturn max(1, int(n or 1))def make_judge(self, ctx: RunContext, *, n_samples: int | None = None) -> Any:@@ -585,7 +585,7 @@ class BaseTrack:kind = ctx.agent_kindif ctx.state.materialized_for == kind:return- self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx), spatial_tools=True)+ self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx))ctx.state.materialized_for = kindctx.state.save(ctx.ws)ctx.events.emit("workspace.materialized", agent_kind=kind)diff --git a/harness/codeverse3d/tracks/planner.py b/harness/codeverse3d/tracks/planner.pyindex ff5f124e..51c7e5b8 100644--- a/harness/codeverse3d/tracks/planner.py+++ b/harness/codeverse3d/tracks/planner.py@@ -459,18 +459,17 @@ def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None) -> Any:_fold_pass(ps)if brief is None:return plan_obj- items: list[AcceptanceItem] = list(getattr(plan_obj, "acceptance", None) or [])+ items: list[AcceptanceItem] = list(plan_obj.acceptance)for feature in brief.signature_features:add_acceptance_item(items, "sig", f"Signature feature visible: {feature.strip()}", "visual", priority="should")- if hasattr(plan_obj, "acceptance"):- plan_obj.acceptance = items- notes = getattr(plan_obj, "style_notes", "")+ plan_obj.acceptance = items+ notes = plan_obj.style_notesextra = []if brief.reference and brief.reference.lower() not in notes.lower():extra.append(f"Reference instance: {brief.reference}.")if brief.not_present:extra.append("Does NOT have: " + "; ".join(brief.not_present) + ".")- if extra and hasattr(plan_obj, "style_notes"):+ if extra:plan_obj.style_notes = " ".join([notes.strip(), *extra]).strip()return plan_obj@@ -835,14 +834,7 @@ def plan_temperature(track: Track) -> float:class PlanningError(RuntimeError):- """The planner could not produce a valid plan after MAX_VALIDATION_REASKS re-asks.-- Carries the ``usage`` already spent so callers can charge the budget even- when planning fails (a failed re-ask is still paid for)."""-- def __init__(self, message: str, usage: Usage | None = None):- super().__init__(message)- self.usage = usage or Usage()+ """The planner could not produce a valid plan after MAX_VALIDATION_REASKS re-asks."""def plan_event_stats(plan_obj: Any) -> dict[str, Any]:@@ -883,8 +875,7 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works``budget`` (the run's ``BudgetGuard``; ``guard`` below, because ``budget`` becomes thisrequest's PlanBudget) only clips each call's wait to the clock left; every call is aledger row of its own (the metered model), so success, ``PlanningError`` and a crash on- a LATER attempt all leave the earlier dollars on the ledger. ``PlanningError`` carries- the total usage for a caller that wants it."""+ a LATER attempt all leave the earlier dollars on the ledger."""guard = budgetevents = NULL_EVENTS if events is None else eventsif model is None:@@ -995,7 +986,7 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Worksif guard is not None:guard.check()return result- raise PlanningError(f"plan did not validate after re-ask: {last_error}", usage)+ raise PlanningError(f"plan did not validate after re-ask: {last_error}")def _echo(raw: Any, text: str) -> ChatMessage:@@ -1090,8 +1081,6 @@ def ensure_acceptance[P: BaseModel](plan_obj: P, spec: Spec) -> P:if solid and c.dimensions_m:dims = ", ".join(f"{k} = {v:.3f} m" for k, v in c.dimensions_m.items())add_acceptance_item(items, "dim", f"Overall dimensions match the request within 5%: {dims}", "measure")- if solid and c.max_triangles:- add_acceptance_item(items, "tri", f"Triangle count ≤ {c.max_triangles}", "measure")for m in c.must_have:add_acceptance_item(items, "must", f"Includes: {m}", "visual")for m in c.must_not:@@ -1149,11 +1138,3 @@ def normalise_names[P: BaseModel](plan_obj: P) -> P:for j in plan_obj.joints:j.parent, j.child = to_pascal(j.parent), to_pascal(j.child)return plan_obj---__all__ = ["MAX_PLAN_RESTARTS", "MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS",- "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_schema", "plan_template", "plan_temperature", "plan_tokens",- "restart_enabled", "restart_note"]diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.pyindex d316240c..caf916e9 100644--- a/harness/codeverse3d/tracks/prompting.py+++ b/harness/codeverse3d/tracks/prompting.py@@ -26,7 +26,7 @@ from codeverse3d.conventions import LANGUAGE_FRAME, fmt3, frame_doc, to_authorinfrom codeverse3d.prompts import renderfrom codeverse3d.prompts.catalog import contract_sections, language_prompt, language_textfrom codeverse3d.tracks.common import RunContext-from codeverse3d.tracks.depth import DETAIL_ADVICE, DepthBudget, depth_budget+from codeverse3d.tracks.depth import DETAIL_ADVICElog = logging.getLogger(__name__)@@ -105,8 +105,6 @@ def constraints_text(spec: Any) -> str:lines.append("Dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in c.dimensions_m.items()))- if c.max_triangles:- lines.append(f"Max triangles: {c.max_triangles}")if c.style:lines.append(f"Style: {c.style}")for m in c.must_have:@@ -171,8 +169,6 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:"part_details": part_details(plan) if plan else "","joints_table": joints_table(plan) if plan else "","acceptance": acceptance_lines(plan),- "entry_files": ", ".join(ctx.runtime.entry_globs),- "n_parts": len(getattr(plan, "parts", []) or []) if plan else 0,"detail_advice": DETAIL_ADVICE if plan and getattr(plan, "parts", None) else "","root_link": getattr(plan, "root_link", "") if plan else "","reference_note": reference_note(ctx),@@ -185,18 +181,6 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:return d-# ----------------------------------------------------------------------------- depth-def budget_for(ctx: RunContext) -> DepthBudget:- """This run's complexity-aware triangle + build-time budget (cached on ctx.extra)."""- got = ctx.extra.get("depth_budget")- if isinstance(got, DepthBudget):- return got- timeout = int(getattr(getattr(ctx.settings, "limits", None), "build_timeout_s", 300) or 300)- b = depth_budget(ctx.plan, build_timeout_s=timeout)- ctx.extra["depth_budget"] = b- return b--def reference_images(ctx: RunContext, limit: int = 3) -> list[ImagePart]:"""The spec's reference images as inline image parts (single-shot prompts)."""out: list[ImagePart] = []diff --git a/harness/codeverse3d/tracks/repair.py b/harness/codeverse3d/tracks/repair.pyindex 9bfff9ce..3d64c077 100644--- a/harness/codeverse3d/tracks/repair.py+++ b/harness/codeverse3d/tracks/repair.py@@ -16,7 +16,6 @@ import loggingfrom pydantic import BaseModel, Fieldfrom codeverse3d.contracts.artifacts import BuildResult, GateReport-from codeverse3d.contracts.common import Usagefrom codeverse3d.prompts import renderfrom codeverse3d.tracks import skills_hookfrom codeverse3d.tracks.common import RunContext, generate_for@@ -38,7 +37,6 @@ class RepairOutcome(BaseModel):build: BuildResultlint: GateReportattempts: list[GenerationResult] = Field(default_factory=list)- usage: Usage = Field(default_factory=Usage)max_attempts: int = Field(default=0, description="repair budget this outcome ran under")@property@@ -166,7 +164,6 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hictx.events.emit("repair.attempt", round=round_index, attempt=attempt, repeats=repeats, signature=sig[:200])res = generate_for(ctx, task)outcome.attempts.append(res)- outcome.usage = outcome.usage + res.usageif not res.ok:log.warning("repair attempt %d produced no files (%s)", attempt, res.notes)build, lint = build_once(ctx)diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.pyindex e2c3258d..691c143f 100644--- a/harness/codeverse3d/tracks/scene.py+++ b/harness/codeverse3d/tracks/scene.py@@ -57,12 +57,10 @@ from codeverse3d.tracks.prompting import ()from codeverse3d.tracks.repair import format_error_reportfrom codeverse3d.tracks.scene_assets import (- MAX_ASSETS,AssetResult,asset_api_summary,read_dedupe_note,run_asset_stage,- select_assets,ships_lib,)from codeverse3d.tracks.zone_layout import layout_block, layout_zones@@ -254,12 +252,10 @@ class SceneTrack(BaseTrack):"""What the zones are told about the assets. The asset results come back revived (a cachedstage is JSON), with the merge map the STAGE used: its cap depends on the soft budget at thetime (a degraded run folded more), so it is read back for a resumed run and the zones to- agree; the plan-only recomputation is the fallback for a workspace without the note."""+ agree."""plan: ScenePlan = ctx.plan # type: ignore[assignment]assets = {k: AssetResult.model_validate(v) if isinstance(v, dict) else v for k, v in (ctx.extra.get("assets") or {}).items()}alias = read_dedupe_note(ctx.ws)- if alias is None:- _, alias = select_assets(list(plan.assets), MAX_ASSETS)ctx.extra["assets"], ctx.extra["asset_alias"] = assets, aliasreturn asset_api_summary(plan, assets, alias, language=ctx.language, lib=ships_lib(ctx))@@ -410,8 +406,6 @@ class SceneTrack(BaseTrack):t0 = time.time()# one author for the whole world (D70; the fan-out control arm was removed 2026-09-21)zones = list(plan.zones)- if len(zones) > 1:- ctx.events.emit("zones.batched", batches=[[z.name for z in zones]])try:r = self._stage_session(ctx, "zones", "zone", lambda gen: self._zone_task(gen, zones))except Exception as e: # noqa: BLE001 — BudgetExceeded included: the stage is still@@ -537,7 +531,6 @@ class SceneTrack(BaseTrack):zones = [z for z in plan.zones if (ctx.ws.root / ctx.runtime.zone_file(z.name)).is_file()]if not zones:return False- ctx.extra.setdefault("asset_api", asset_api_summary(plan, ctx.extra.get("assets") or {}, ctx.extra.get("asset_alias")))self.note_degraded(ctx, f"salvage: assembled {len(zones)}/{len(plan.zones)} zones written before the budget stop")ctx.plan = plan.model_copy(update={"zones": zones})try:diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.pyindex 75a4f820..0e42709e 100644--- a/harness/codeverse3d/tracks/scene_assets.py+++ b/harness/codeverse3d/tracks/scene_assets.py@@ -183,7 +183,7 @@ def _bpy_api_line(a: AssetPlan, r: AssetResult | None, kept: str | None, size: sreturn 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]:+def run_asset_stage(ctx: RunContext) -> dict[str, AssetResult]:"""Generate every asset (parallel) and return results keyed by asset name."""plan: ScenePlan = ctx.plan # type: ignore[assignment]cap = MAX_ASSETS if ctx.budget.soft_ok() else DEGRADED_MAX_ASSETS@@ -198,14 +198,11 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,ctx.extra["asset_alias"] = aliasif not assets:return {}- ctx.ws.ensure_gitignore() # legacy run dirs may predate _assets/ in the standard linesdef _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)+ return build_blender_asset(ctx, asset, judge=True)+ return build_module_asset(ctx, asset, judge=True)workers = ctx.settings.limits.max_parallel_agentsif any(a.kind in ("blender_glb", "bpy") for a in assets): # both kinds check in a Blender process@@ -255,50 +252,37 @@ def _record_spec_hashes(ctx: RunContext, results: dict[str, AssetResult], assetswrite_json_atomic(path, recorded)-# ----------------------------------------------------------------------------- threejs asset-def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:- """Single-shot → deterministic check → ONE repair → (only then) an agent session."""- rel, pascal = ctx.runtime.asset_file(asset), to_pascal(asset.name)- # committed-child reuse (review-3 S2): a resume that re-enters the stage — budget- # stop after the commit, or a failed sibling — must not re-pay a finished asset.- # Deterministic node import-check only, no model call; the skeleton stub never- # passes it (single low-poly box), and `ran` guards the checker-unavailable path.- if (ctx.ws.root / rel).is_file() and _spec_hash_matches(ctx, asset):- chk0 = check_threejs_asset(ctx, rel, pascal, 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 (import check passed)")-- def check(c: RunContext) -> AssetCheck:- return check_threejs_asset(c, rel, pascal, expected_size_m=asset.approx_size_m)+# ----------------------------------------------------------------------------- module asset+def build_module_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:+ """A scene_threejs module (``build<Pascal>(THREE, {variant})``) or a scene_blender one+ (``src/assets/<snake>.py``, ``build_<snake>(ctx, variant=0)``): committed-child reuse, then+ single-shot → deterministic check → ONE repair → (only then) an agent session.- 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)+ placed."""+ bpy = asset.kind == "bpy"+ rel = ctx.runtime.asset_file(asset)+ name = to_snake(asset.name) if bpy else to_pascal(asset.name)+ check_fn = check_bpy_asset if bpy else check_threejs_asset+ language = Language.SCENE_BLENDER if bpy else Language.SCENE_THREEJS+ # committed-child reuse (review-3 S2): a resume that re-enters the stage — budget+ # stop after the commit, or a failed sibling — must not re-pay a finished asset.+ # Deterministic check only, no model call; the skeleton stub never passes it+ # (single low-poly box), and `ran` guards the checker-unavailable path.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)+ chk0 = check_fn(ctx, rel, name, 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)")+ return AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=chk0.size_m, strategy="reused",+ notes=f"committed module reused ({'Blender build' if bpy else 'import'} check passed)")def check(c: RunContext) -> AssetCheck:- return check_bpy_asset(c, rel, snake, expected_size_m=asset.approx_size_m)+ return check_fn(c, rel, name, expected_size_m=asset.approx_size_m)- strategy, chk, notes = _ladder(ctx, asset, rel, language=Language.SCENE_BLENDER, files=[rel], check=check,+ strategy, chk, notes = _ladder(ctx, asset, rel, language=language, 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)+ return _module_result(ctx, asset, rel, strategy, chk, notes, check=check, language=language, judge=judge)def _module_result(ctx: RunContext, asset: AssetPlan, rel: str, strategy: str, chk: AssetCheck | None, notes: str, *,@@ -481,7 +465,7 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Asif not ctx.single_shot:# the language contract alone, no harness_contract.md (intended, review 2 C4): the context file's hard rules# bound paths/imports, and its standalone-object acceptance (±1 cm bbox) contradicts the prop sheet's ±5 %- ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text, spatial_tools=True)+ ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text)files = sub.runtime.expected_files(sub.plan)timeout_s = asset_timeout_s(ctx, 180)label = f"asset_{snake}"@@ -1153,10 +1137,10 @@ def write_dedupe_note(ws: Workspace, alias: dict[str, str]) -> None:write_json_atomic(ws.root / "stages" / "asset_aliases.json", {"alias": alias})-def read_dedupe_note(ws: Workspace) -> dict[str, str] | None:- """The merge map the asset stage used, or None when no stage has run in this workspace."""+def read_dedupe_note(ws: Workspace) -> dict[str, str]:+ """The merge map the asset stage used, or ``{}`` when no stage has run in this workspace."""data = read_json_or_none(ws.root / "stages" / "asset_aliases.json")- return None if data is None else dict(data.get("alias") or {})+ return dict((data or {}).get("alias") or {})def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str], *,diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.pyindex 48f516ea..fcab6c72 100644--- a/harness/codeverse3d/tracks/static_object.py+++ b/harness/codeverse3d/tracks/static_object.py@@ -37,12 +37,11 @@ from codeverse3d.prompts import renderfrom codeverse3d.spatial.contract import planned_joinsfrom codeverse3d.spatial.silhouette import measure_referencefrom codeverse3d.tracks.common import RunContext-from codeverse3d.tracks.depth import budget_gate+from codeverse3d.tracks.depth import budget_gate, depth_budgetfrom codeverse3d.tracks.generation import GenerationTaskfrom codeverse3d.tracks.lifecycle import BaseTrackfrom codeverse3d.tracks.prompting import (base_prompt_context,- budget_for,judge_digest,judged_sheet,measurement_vs_plan,@@ -79,10 +78,9 @@ class ObjectPipeline:out.append(ctx.services.contract(measurement, ctx.plan, BBOX_TOLERANCE_M, ctx.language.value))- if measurement is not None and ctx.plan is not None:# is the object as dense as its own plan says? Deterministic, so the judge is# never asked "does it look detailed enough" (tracks/depth.py).- out.append(budget_gate(measurement, build, budget_for(ctx)))+ out.append(budget_gate(measurement, build, depth_budget(ctx.plan, ctx.settings.limits.build_timeout_s)))return outdef render(diff --git a/harness/codeverse3d/tracks/steps.py b/harness/codeverse3d/tracks/steps.pyindex 51402732..537eb9da 100644--- a/harness/codeverse3d/tracks/steps.py+++ b/harness/codeverse3d/tracks/steps.py@@ -122,7 +122,7 @@ def load_round_journal(ws: Workspace) -> list[RoundRecord]:def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask], *,- steps: list[StepTime] | None = None) -> list[GenerationResult]:+ steps: list[StepTime]) -> list[GenerationResult]:"""Run tasks side by side — one ``generate`` step: its sessions share one clock. Raises``RoundFailed`` when none succeeded."""if not tasks:@@ -133,7 +133,7 @@ def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask], *,# fan_out also for ONE task: a crashing generator (503 storm, parse error) becomes a failed# result → RoundFailed (a refine round then stops the run as no_change) instead of killing it.- with timed("generate", [] if steps is None else steps, round_index=tasks[0].round):+ with timed("generate", steps, round_index=tasks[0].round):results = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,label="generate", item_name=lambda t: t.label)out: list[GenerationResult] = []@@ -354,19 +354,11 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResrenders = rec.rendersjv = getattr(pipeline, "judge_views", None)if callable(jv) and renders is not None:- try:- renders = jv(ctx, renders) or renders- except Exception as e: # noqa: BLE001 — view selection is an optimisation, never a blocker- log.warning("judge_views selection failed: %s", e)- renders = rec.renders+ renders = jv(ctx, renders) or rendersgeometry = Nonegv = getattr(pipeline, "geometry_views", None) if geometry_views else Noneif callable(gv):- try:- geometry = gv(ctx, index, build)- except Exception as e: # noqa: BLE001 — clay views are optional judge context- log.warning("geometry views failed in round %d: %s", index, e)- ctx.events.emit("judge.geometry_views_failed", round=index, error=f"{type(e).__name__}: {e}")+ geometry = gv(ctx, index, build)inp = round_input(ctx.spec, ctx.plan, rec, renders=renders, gates=gates, previous=previous,extra_context=pipeline.judge_context(ctx.ws, ctx.plan, index, build, gates),geometry_views=geometry, glb_path=build.glb_path)@@ -405,7 +397,7 @@ def rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, prctx.events.emit("judge.retry", round=rec.index)notes: list[str] = [rec.notes] if rec.notes else []# a round recorded before step timing keeps counting its own clock (RoundRecord.minutes)- with timed("judge", rec.steps if rec.steps is not None else [], round_index=rec.index) as spent:+ with timed("judge", rec.steps, round_index=rec.index) as spent:judgment = _judge(ctx, pipeline, rec.index, rec.build, list(rec.gates), rec, previous, notes)# paid either way: a retry that failed AGAIN keeps its money and its note on the recordrec.usage = rec.usage + spent.usagediff --git a/harness/codeverse3d/tracks/zone_layout.py b/harness/codeverse3d/tracks/zone_layout.pyindex 66b21f65..5c7192dc 100644--- a/harness/codeverse3d/tracks/zone_layout.py+++ b/harness/codeverse3d/tracks/zone_layout.py@@ -200,10 +200,7 @@ def layout_zones(plan: ScenePlan, model: Any, *, budget: Any = None, events: Any(an exception or double rejection yields no layout for that zone, never a dead run)."""events = NULL_EVENTS if events is None else events- def _safe(zone: ZonePlan) -> ZoneLayout | None:- return _one_layout(zone, plan, model, budget, events)-- results = fan_out(list(plan.zones), _safe, max_workers=max_workers, label="layouts",+ results = fan_out(list(plan.zones), lambda z: _one_layout(z, plan, model, budget, events), max_workers=max_workers, label="layouts",item_name=lambda z: z.name)out: dict[str, ZoneLayout] = {}for zone, r in zip(plan.zones, results, strict=True):diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.pyindex 860cf9c5..a43cd93c 100644--- a/harness/codeverse3d/workspace.py+++ b/harness/codeverse3d/workspace.py@@ -24,36 +24,21 @@ from pydantic import BaseModelfrom codeverse3d.contracts.agent import FileChangefrom codeverse3d.proc import write_json_atomic-#: the three top-level buckets of a run directory (docs/RUN_LAYOUT.md)+#: the top-level buckets of a run directory (docs/RUN_LAYOUT.md); ``artifacts/`` is the evidenceDELIVERABLE_DIR = "deliverable" # (a) what the user asked for-EVIDENCE_DIR = "evidence" # (b) why we believe it is good (alias of artifacts/)TELEMETRY_DIR = "telemetry" # (c) what it cost and how it was configured#: harness-owned read-only files inside the workspace (task images: ``tracks/generation.IMAGES_DIR``)C3D_DIR = ".3dcode"-#: physical directories every run owns. ``artifacts/`` is the physical home of the-#: evidence (six packages and ~50 recorded runs write paths into it); ``evidence/``-#: is an alias for it — see docs/RUN_LAYOUT.md for why the alias points that way.+#: directories every run ownsLAYOUT_DIRS = ("src", "public", "artifacts", "artifacts/renders", "artifacts/gates", "artifacts/judge","trajectories", DELIVERABLE_DIR, TELEMETRY_DIR)-#: navigation aliases: ``alias path`` → ``symlink target`` (relative to the alias's parent).-#: The alias is always the symlink, never the physical file: writers (events.jsonl append,-#: atomic run_state.json rewrite) keep using the paths they already use, and a tmp+rename-#: on the physical path can never replace a symlink out from under a reader.-LAYOUT_ALIASES: tuple[tuple[str, str], ...] = (- (EVIDENCE_DIR, "artifacts"),- (f"{TELEMETRY_DIR}/events.jsonl", "../events.jsonl"),- (f"{TELEMETRY_DIR}/run_state.json", "../run_state.json"),- (f"{TELEMETRY_DIR}/stages", "../stages"),- (f"{TELEMETRY_DIR}/trajectories", "../trajectories"),-)-#: harness-owned paths that never belong in the code snapshot_GITIGNORE_LINES = ("# harness-owned run state is never part of the code snapshot",- "artifacts/", "trajectories/", "stages/", "rounds/", "_assets/", "_cand/", ".3dcode/", ".3dcv/", ".gemini/", ".claude/", ".agents/",- "deliverable/", "telemetry/", "evidence", "captions.json",+ "artifacts/", "trajectories/", "stages/", "rounds/", "_assets/", "_cand/", ".3dcode/", ".gemini/", ".claude/", ".agents/",+ "deliverable/", "telemetry/", "captions.json","events.jsonl", "run_state.json", "record.json", "*.log", "node_modules/", "*.tmp", "__pycache__/",)@@ -260,43 +245,10 @@ class Workspace:self._git_init()return self- def ensure_layout(self, *, dry_run: bool = False) -> dict[str, str]:- """Create the directory buckets + navigation aliases. Idempotent, never- destructive: an alias path that already holds real data is left alone.-- Returns ``{path: action}`` with action in ``created`` / ``relinked`` /- ``kept`` / ``skipped:<reason>`` — the migration helper prints it.- ``dry_run`` reports the same actions without touching the filesystem."""- actions: dict[str, str] = {}+ def ensure_layout(self) -> None:+ """Create the directory buckets. Idempotent."""for d in LAYOUT_DIRS:- p = self.root / d- if not p.exists():- if not dry_run:- p.mkdir(parents=True, exist_ok=True)- actions[d] = "created"- for name, target in LAYOUT_ALIASES:- actions.update(self._ensure_alias(name, target, dry_run=dry_run))- return actions-- def _ensure_alias(self, name: str, target: str, *, dry_run: bool = False) -> dict[str, str]:- link = self.root / name- if link.is_symlink():- if os.readlink(link) == target:- return {}- if not dry_run:- link.unlink()- os.symlink(target, link)- return {name: "relinked"}- if link.exists(): # a real file/dir sits there — never clobber run data- return {name: "kept"}- if dry_run:- return {name: "created"}- link.parent.mkdir(parents=True, exist_ok=True)- try:- os.symlink(target, link)- except OSError as e: # filesystem without symlinks (some Windows shares)- return {name: f"skipped:{type(e).__name__}"}- return {name: "created"}+ (self.root / d).mkdir(parents=True, exist_ok=True)def exists(self) -> bool:return self.spec_path.is_file()@@ -369,7 +321,7 @@ class Workspace:self._git("add", "-A")self._git("commit", "-q", "-m", "init", "--allow-empty")- def ensure_gitignore(self, *, dry_run: bool = False) -> bool:+ def ensure_gitignore(self) -> bool:"""Make sure every harness-owned path is ignored by the run's git repo.Idempotent: missing lines are appended, existing ones are left in place.Returns True when the file changed."""@@ -377,8 +329,8 @@ class Workspace:existing = path.read_text().splitlines() if path.is_file() else []have = {line.strip() for line in existing}missing = [line for line in _GITIGNORE_LINES if line not in have]- if not missing or dry_run:- return bool(missing)+ if not missing:+ return Falselines = existing + ([""] if existing and existing[-1].strip() else []) + missingpath.write_text("\n".join(lines).rstrip("\n") + "\n")return True@@ -412,25 +364,16 @@ class Workspace:def changed_files(self, since: str | None = None) -> list[FileChange]:"""Files changed vs ``since`` (a commit) or vs HEAD (uncommitted work)."""- with self._lock: # add -N + two diffs are one unit: a sibling commit between them mislabels a status+ with self._lock: # add -N + the diff are one unit: a sibling commit between them mislabels a statusself._sanitise_git_config() # `add` applies clean filters; -c cannot unset a local oneself._git("add", "-A", "-N") # register untracked so they show up in diff- args = ["diff", *GIT_SAFE_DIFF_FLAGS, "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])- out = self._git(*args).stdout- status = {}- for line in self._git("diff", *GIT_SAFE_DIFF_FLAGS, "--name-status", since or "HEAD").stdout.splitlines():- if "\t" in line:- st, path = line.split("\t", 1)- status[path] = {"A": "added", "D": "deleted"}.get(st[0], "modified")+ out = self._git("diff", *GIT_SAFE_DIFF_FLAGS, "--name-status", "--no-renames", "--diff-filter=ADM",+ since or "HEAD").stdoutchanges = []for line in out.splitlines():- parts = line.split("\t")- if len(parts) != 3:- continue- add, rem, path = parts- changes.append(FileChange(path=path, status=status.get(path, "modified"),- lines_added=int(add) if add.isdigit() else 0,- lines_removed=int(rem) if rem.isdigit() else 0))+ st, sep, path = line.partition("\t")+ if sep:+ changes.append(FileChange(path=path, status={"A": "added", "D": "deleted"}.get(st[0], "modified")))return changesdef restore(self, commit: str) -> None:diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 7a43d3d0..92501224 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -193,8 +193,6 @@ codeverse3d/duck-typed `.judge(JudgeInput) -> Judgment`reference.py a user `--image` against the render: proportions (does the picture agreewith the brief?) and the render-vs-reference mismatch diff- texturing/ materials.py only: the named PBR material-family table `languages/blender` reads- (no texture is generated: the harness has no image-generation step)orchestrator.py the round loop's LIBRARY, not the loop: the round knobs (RoundPolicy —no stop knob besides max_rounds), refine-task compilation + grouping,StageRunner + RunState (resume), BudgetGuard (the clock). The loop itself is@@ -267,12 +265,11 @@ codeverse3d/The other half of the split: codeverse3d/skills/ is what an AGENT choosesto read (SKILL.md + references/ + a _claims file pinning its numbers tolive constants). A file that tries to be both is the bug this prevents.- cli/ main.py (app wiring, make/resume/mcp + the tools/gallery+ cli/ main.py (app wiring, make/resume/mcp + the doctor/tools/gallerycommands), inspect_cmd.py (render/judge on one existing run), layout_cmd.py(THE single-run view: `show` = STATUS / DELIVERABLE / QUALITY EVIDENCE / COST &SETTINGS; `status` = `show --section status`, which also reads a run in flight),- flywheel_cmd.py, cost_cmd.py (`3dcode cost`), doctor.py- (`--skills` checks the library + its discovery wiring),+ flywheel_cmd.py, cost_cmd.py (`3dcode cost`),skills_cmd.py (`3dcode skills list|show|validate|report` — the read-rate report)eval/bench/ run_bench.py + report.py (the battery launcher, `python -m bench.run_bench` / `bench.report`;the report renders through codeverse3d/addons/gallery), compare_backends.py@@ -306,7 +303,7 @@ runtime_js/ export_glb.mjs (placement policy, instance baking, selfcheto disable; object renders never come through this driver.tests/ agents blender_cadquery core cost flywheel_cli gallery graphicsinstall judges languages models orchestrator_tracks prompts reference scene_gates- scene_prompts scene_runtime skills spatial_tools texturing threejs_render urdf_joints+ scene_prompts scene_runtime skills spatial_tools threejs_render urdf_joints(22 dirs; the count is `pytest --collect-only`'s; the bench tests are ../eval/tests)```@@ -314,8 +311,8 @@ tests/ agents blender_cadquery core cost flywheel_cli gallery graOne run is one directory, `runs/<slug>/`: `src/` is the code (git, one commit per round),`artifacts/` the last round's build plus every round's own `artifacts/rNN/`, and a pick-writes `deliverable/` + `selection.json`. The full tree, the three buckets and the-back-compatibility rules are in `docs/RUN_LAYOUT.md`, its one home.+writes `deliverable/` + `selection.json`. The full tree and the+three buckets are in `docs/RUN_LAYOUT.md`, their one home.## 4. Per-language authoring contracts (raw code; the harness owns export)@@ -631,7 +628,7 @@ captions.json, renders/}`) of the PICKED round (`addons/select`; the last builtwhen none was judged) with **quality tiers** from that round's verdict (A passed & 0 gateerrors, B passed, C score ≥ 0.6, D else), acceptance checklists, gate summaries and`(code fingerprint, prompt)` dedupe (`--drop-duplicates`; side-car captions via-`--captions-dir`); `metadata.parquet`/`.jsonl` + sqlite index carry tier, gate+`--captions-dir`); `metadata.parquet`/`.jsonl` carry tier, gateerrors, cost, fingerprints, `duplicate_of`; `--pack` tars with byte-range locators.`flywheel pairs` emits preference pairs (round i < j by judge Δ ≥ τ) and round-levelrepair pairs (in-session trajectory mining died with the api-agent, 2026-08-28 —diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.mdindex 409cffc2..8bd70a48 100644--- a/harness/docs/INSTALL.md+++ b/harness/docs/INSTALL.md@@ -87,7 +87,7 @@ Moving to another Python later is the same four-line change (`requires-python`,| **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 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) |+| C toolchain | usually no | — | only if pip has to build a wheel from source (`python-fcl` ships wheels for cp310–cp313 x86_64) |Disk: ~100 MB for `runtime_js/node_modules`, ~640 MB for puppeteer's Chrome,~1 GB for a Blender tarball, plus whatever `runs/` and `~/.cache/codeverse3d` grow@@ -138,7 +138,7 @@ openai.| `cad` | cadquery | the `cadquery` language (`--language cadquery`) || `urdf` | yourdfpy, scipy | the `articulated_object` track: URDF parse/validate + joint math || `graphics` | moderngl | the `graphics` track (`glsl_shader`, `opengl_python`) — headless GL rendering in `spatial/gl_render.py` |-| `mesh` | shapely, networkx, manifold3d, matplotlib | `cross_section` (filled area / hollow ratio from shapely, the image drawn by the judge-slice renderer in matplotlib), mesh split / connectivity (networkx), joint-sweep boolean intersections (`trimesh.boolean(engine="manifold")`), judge cross-section slices on gate-ERROR rounds (`judge_slices`, D48; without the extra the judge logs a warning and sends the pre-D48 payload) |+| `mesh` | shapely, networkx, matplotlib | `cross_section` (filled area / hollow ratio from shapely, the image drawn by the judge-slice renderer in matplotlib), mesh split / connectivity (networkx), judge cross-section slices on gate-ERROR rounds (`judge_slices`, D48; without the extra the judge logs a warning and sends the pre-D48 payload) || `mcp` | mcp | `3dcode mcp` / `codeverse3d.spatial.mcp_server`, i.e. spatial tools for the `agy` (Gemini-API mode), `claude-code` and `codex` backends || `flywheel` | pyarrow | `3dcode flywheel export --pack` (parquet shards). A plain `flywheel export` needs nothing: without pyarrow it writes `metadata.jsonl` and skips `metadata.parquet` with a warning. || `all` | all of the above | — |@@ -147,8 +147,7 @@ openai.`graphics`, `mesh`, `mcp` and `flywheel` are lazily imported: without them theharness installs and starts fine and only the named feature raises `ImportError`at the moment you use it. `3dcodeverse doctor` lists every one of these modules-under `python deps` and only tolerates the optional-extra modules — `manifold3d`,-`shapely` (mesh), `yourdfpy` (urdf), `mcp`, `moderngl` (graphics), `cadquery` (cad) —+under `python deps` and only tolerates the optional-extra modules — `shapely` (mesh), `yourdfpy` (urdf), `mcp`, `moderngl` (graphics), `cadquery` (cad) —as WARN, naming the extra to install; everything else missing is a FAIL.Run the offline test suite to confirm the install:@@ -514,8 +513,8 @@ that the keys work end to end):| row | status | meaning | fix ||---|---|---|---|| `python` | — | interpreter running the CLI | if it is not the interpreter you installed into, your shell is picking up another `3dcodeverse` — `which -a 3dcodeverse`, reinstall with `python -m pip install -e harness` |-| `python deps` | FAIL | a core import is missing/broken | `pip install -e 'harness[all]'`; a broken native lib (`fcl`, `manifold3d`) shows up here too — reinstall that wheel (`pip install --force-reinstall python-fcl`) |-| `python deps` | WARN | only optional-extra modules missing (`manifold3d` / `shapely` / `yourdfpy` / `mcp` / `moderngl` / `cadquery`) | install the extra the row names, e.g. `pip install -e 'harness[mesh,urdf,mcp,graphics,cad]'` (§4) |+| `python deps` | FAIL | a core import is missing/broken | `pip install -e 'harness[all]'`; a broken native lib (`fcl`) shows up here too — reinstall that wheel (`pip install --force-reinstall python-fcl`) |+| `python deps` | WARN | only optional-extra modules missing (`shapely` / `yourdfpy` / `mcp` / `moderngl` / `cadquery`) | install the extra the row names, e.g. `pip install -e 'harness[mesh,urdf,mcp,graphics,cad]'` (§4) || `blender` | FAIL | no binary found, or `--version` failed | §6 — install Blender, or `export C3D_BINARIES__BLENDER=/path/to/blender`. If it is found but fails, run it by hand: a `libSM.so.6`/`libICE.so.6` error means you need the `LD_LIBRARY_PATH` wrapper || `blender cycles` | WARN | Cycles sees no CUDA device | scene_blender's judged frames render on the CPU (~3.3x slower, measured) — fine without an NVIDIA GPU; on WSL2 install the vendor WSL GPU driver. The row also names the judged-frame engine / samples / device (`C3D_RENDER__BLENDER_*`) || `blender eevee` | WARN / FAIL | the EEVEE smoke frame ran on llvmpipe (software GL), or did not render | only matters with `C3D_RENDER__BLENDER_ENGINE=eevee`: the harness runs EEVEE under the Mesa d3d12 env (`spatial/gl_render.GPU_ENV`); llvmpipe here means that env found no GPU. `--no-gpu` skips the smoke frame |@@ -538,13 +537,6 @@ that the keys work end to end):| `gemini live call` (`--live`) | FAIL | key rejected / no network | check the key value and outbound access; a `503 … high demand` is transient, not an install problem || `in-flight slots` | WARN | every machine-wide slot is held right now (`busy n/n`), or `max_in_flight=0` switched the cap off | busy: other harness processes are mid-call and new calls wait for a slot (docs/COST.md §23) — nothing to fix unless it stays full; a slot is held only while a call is out and a killed process frees its slots at once. Off: unset `C3D_MAX_IN_FLIGHT` || `gemini pool` (`--live`) | WARN | a key is benched as dead | that key 401/403'd; rotate or remove it — the pool re-probes it after an hour. The row also shows in-flight and this process's 429/5xx counts |-| `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 |---@@ -629,7 +621,7 @@ and the `# Added by Antigravity CLI installer` PATH lines in `~/.bashrc` / `~/.p| component | version | where ||---|---|---|| 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/` |+| 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 · 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) | `~/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` |diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.mdindex 277cf183..e38e4ee3 100644--- a/harness/docs/INTERFACES.md+++ b/harness/docs/INTERFACES.md@@ -68,7 +68,6 @@ KeyPool(keys, *, max_in_flight=0, slots_dir=None, cooldown_s=3, dead_cooldown_s=# the slots are flock'd files every process shares (Slots(n, root): try_take / take(timeout) / give / busy)pool.acquire(*, exclude=None, timeout_s=120) -> key # a slot + a key; raises immediately when every key is dead/cooling past the deadlinepool.try_acquire(*, exclude=None) -> key | None # never waits (a hedged retry's extra key); holds a slot like acquire-pool.session_key(*, exclude=None, timeout_s=120) -> key # a vendor CLI session's key: no slot, nothing to releasepool.lease_session_key(leases_dir, *, timeout_s=120) -> (key, lease|None) # + one live session per key machine-wide (flock); KeyPool.end_lease(lease)KeyPool(keys, ..., start=0) # shared_pool passes a random start: parallel processes spreadpool.report(key, "ok"|"429"|"5xx"|"error"|"dead"|"skip", *, retry_after_s=None) # Δ "dead": health 0, benched dead_cooldown_s,@@ -163,8 +162,7 @@ from codeverse3d.prompts.variants import VARIANTS_DIR, VariantInfo, list_variant# 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.prompts import load_text, render # every name resolves through the active variantfrom codeverse3d.skills import library_roots, all_skills, load_skill, variants_table, parse_routes, VariantRoutes, RouteBoost, variant_dirlibrary_roots(variant=None) -> [skills_dir(), <skills_dir>/variants/<v>] # the second only when it existsall_skills() -> base ∪ overlay (same name shadows, new names added); all_skills(root) -> that root alone@@ -187,9 +185,9 @@ Every run is read from its ledger alone (`addons.costreport.audit.read_run` / `r## agents/```python-from codeverse3d.agents import get_coding_agent # (agent_id) -> CodingAgent .run(job) .available() .id .kind .model+from codeverse3d.agents import get_coding_agent # (agent_id) -> CodingAgent .run(job) .available() .kind .modelfrom codeverse3d.agents.materialize import materialize_workspace, codex_mcp_overrides-materialize_workspace(ws, *, agent_kind, contract_md, spatial_tools, mcp_command=None) -> None+materialize_workspace(ws, *, agent_kind, contract_md, mcp_command=None) -> None# Δ D107: no cookbook_text — no language ships a cookbook; the body is hard rules + tool cards + the language contract# mcp_command defaults to cli_common.default_mcp_command(ws) = [sys.executable, -m codeverse3d.spatial.mcp_server --workspace …]# (None/[] = the default — no ValueError); tracks/common.Services.materialize takes no mcp_command@@ -230,12 +228,12 @@ generation derives it from the remaining hard run clock before queueing; every Cattempt clips its watchdog after acquiring the workspace lock, including retries.An expired job never launches a CLI. Recomputed on resume; `None` keeps standalonesession grace. Process termination and final packaging can finish after the deadline),-`mcp_command` (override), `files_hint` (workspace-relative files/dirs the task is+`files_hint` (workspace-relative files/dirs the task isexpected to touch — used to attribute `files_changed`; harness-owned paths are dropped;agent sessions on one workspace are serialised, so there is no sibling filter), **Δ D111**`shared_tree: bool` (harness writers that take no session lock — the scene asset single-shots — writethe tree while the session runs: `files_changed` is the `files_hint` paths only-(`cli_common.attribute_changes(files, write_roots=, only=)`, also `generation._attributed_fallback`) and the+(`cli_common.attribute_changes(files, write_roots=, only=)`) and thewatchdog polls only those files (`cli_common.activity_paths(s, steps=())`; **Δ D112** plus `steps`, where the CLIrecords each step it takes — agy passes its session HOME's `backends.AGY_STEP_DIRS` (brain/, conversations/) through`invoke(..., activity=)` for every agy session, shared_tree or not); needs a `files_hint`, never with@@ -481,7 +479,7 @@ sweep_gate(ws) -> (GateReport "joint_sweep", Robot | None) # THE verdict (Δ 2# report exactly this; the tool used to run its own sweep (fail on any overlap > 2 mm or any gap, no buried links)from codeverse3d.spatial.joints_collide import components # (names, edges) -> list[set[str]]: THE union-find (connectivity + sweep)# joints_collide.py: deterministic penetration (oriented islands + fixed-direction parity ray test; python-fcl is a-# core dependency, the trimesh fallback is deterministic too)+# core dependency)from codeverse3d.spatial.gl_render import GlHost, GlResult, GlHostError, write_contact_sheet, write_gifGlHost(gpu="auto|on|off", timeout_s=240, fps=30, max_steps=240).render_fragment_shader(frag_src, out_dir, *, width=1280, height=720, times=..., buffer_a_src=None, feedback=False)@@ -615,11 +613,11 @@ from codeverse3d.tracks.articulated_object import default_motion_checks, expectefrom codeverse3d.tracks.static_object import silhouette_gate, reference_refine_tasks # gate "reference_silhouette" (IoU<0.6 → WARN + refine task)from codeverse3d.tracks.depth import depth_budget, DepthBudget, DETAIL_ADVICE # complexity-aware budgets# (Δ D110: scope_groups / PartScope / interfaces_text / scoped_generation_enabled deleted with the scoped baseline)-depth_budget(plan, *, build_timeout_s=300) -> DepthBudget # min/target/max triangles + max_build_s sized from+depth_budget(plan, build_timeout_s) -> DepthBudget # min/target/max triangles + max_build_s sized from# the plan's LEAF count (parts × instances × children); only budget_gate reads it — no prompt states it.# DETAIL_ADVICE: the numberless "spend detail inside the planned parts" bullet the generate/refine# templates show as {{ detail_advice }}-from codeverse3d.tracks.prompting import base_prompt_context, reference_images, budget_for # Δ split out of+from codeverse3d.tracks.prompting import base_prompt_context, reference_images # Δ split out of# Δ D107: select_cookbook_chapters / is_always_chapter / COOKBOOK_SYNONYMS and the graphics recipe seeding# (tracks/graphics.seed_recipes, cookbook_functions, the "recipes" stage, Settings.limits.seed_recipes /# C3D_SEED_RECIPES) are deleted with the cookbooks; base_prompt_context carries no cookbook_excerpt@@ -656,16 +654,16 @@ tracks.common.generate_for(ctx: RunContext, task: GenerationTask) -> GenerationR# THE call every stage makes (env, zones, rounds, repairs, asset ladder, judged fix): generate()# with everything ctx knows; Δ D103 no storm fallback (D68's single-shot retry, GenerationResult.storm and# the asset ladder's storm-repair rung are gone): a transient death reaches the round loop's one retry-tracks.common.single_shot_agent_id(agent_id, chat_model_id='') -> str · single_shot_ctx(ctx) -> RunContext | None+tracks.common.single_shot_ctx(ctx) -> RunContext | None# moved from tracks.scene_assets 2026-09-07 (never scene-specific)- # GenerationResult adds turns / sessions / turn_capped. A turn cap is applied ONLY if the machine+ # The generate.done event carries turns / sessions / turn_capped. A turn cap is applied ONLY if the machine# asks: $C3D_AGENT_MAX_TURNS > settings.limits.agent_max_turns ># DEFAULT_AGENT_MAX_TURNS (0 = leave AgentJob.max_turns at the backend's own default — a 28-turn# default was measured and rejected, docs/COST.md §17). A session that hits a cap that IS set is# 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 / 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)+# scene assets (tracks/scene_assets.py): build_module_asset (three.js and bpy modules) / build_blender_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 testtracks.scene.SCENE_TEMPLATES: dict[Language, SceneTemplates] # the env / zone / refine / asset templates per scene language@@ -677,7 +675,7 @@ tracks.planner.PLAN_TEMPLATES: dict[tuple[Track, Language | None], str] # (tratracks.planner.plan_template(track, language=None) -> str # fallback; (SCENE, SCENE_BLENDER) = tracks/plan_scene_bpy.j2tracks.planner.plan_schema(spec, plan_model) -> dict # the planner call's response schema: a scene's names ITS language'scontracts.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))+tracks.scene_assets.build_module_asset(ctx, asset, *, judge) -> AssetResult # bpy: src/assets/<snake>.py (build_<snake>(ctx, variant=0)); three.js: build<Pascal># on the one ladder; no render_asset, so the scene judge sees the module placedtracks.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@@ -711,12 +709,6 @@ post-render gates → the build's own `BuildResult.gates` (also when the build f`ReferenceJudge` (rubric `reference` for static_object; `LikenessJudge` on graphics/scene —`vlm_judge.judge_for`) and images attached to generation prompts.-## texturing/ (the PBR table only)-```python-from codeverse3d.texturing.materials import family_for, pbr_for, MATERIALS # family_for(*texts) -> FamilyMatch | None; pbr_for(family) -> Pbr | None- # read by languages/blender; no texture is generated anywhere (the image-generation pass was removed 2026-11-03)-```-## record/ + addons/ + cli/```pythonfrom codeverse3d.record.record import finalize_record, load_record, iter_runs, effective_judgment, effective_score@@ -787,14 +779,12 @@ from codeverse3d.addons.gallery.index import build_index, default_roots # THE# build_static(roots, out_html, *, embed=False) -> (path, n, index)# render_static(index, *, embed=…, extra_html="") — eval/bench/report.py's page# GalleryApp(roots, reload=False).route(path, query) -> Response (pure, testable)- # serve(roots, *, host=None, host_explicit=False, port=8765, reload=False)+ # serve(roots, *, host=None, port=8765, reload=False)from codeverse3d.addons.gallery.urls import safe_join # (root, rel) -> Path inside root, else PathErrorfrom codeverse3d.addons.gallery.urls import content_type # .glb→model/gltf-binary, .py/.js/.frag→text/plain; charset=utf-8-from codeverse3d.addons.dataset.index import build_index, query, summary # sqlite + parquet: adds quality_tier, gate_errors, cost_usd,- # rounds, status, code_fingerprint, prompt_hash, duplicate_of, has_captions3dcodeverse make [--no-pick]|resume [--no-pick]|pick|status|show|render|judge|tools|mcp|cost {<slug>,show,cache,prices,estimate}- |flywheel {export,pairs,refine,caption,index}|gallery {serve,build}+ |flywheel {export,pairs,refine,caption}|gallery {serve,build}|skills {list,show,validate,report}|doctor # alias: 3dcode; batteries: eval/ (python -m bench.run_bench)```diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex 2f0152e5..3760ca89 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -40,7 +40,7 @@ one home); each setting's default and description is its `Settings` field in3dcode make "neon cyberpunk rain on a window with bokeh city lights" --track graphics --language glsl_shader3dcode make "instanced pastel cubes with bloom" --track graphics --language opengl_python```-Useful flags (`3dcode make --help`): `--generator`, `--planner`, `--judge`, `--captioner`+Useful flags (`3dcode make --help`): `--generator`, `--planner`, `--judge`(backend ids, §3), `--image <png>` (repeatable; reference images → `ReferenceJudge` +silhouette gate + IoU refine tasks), `--rounds N` (refine rounds after the baseline — arun does exactly N, each built on the one before it, unless the clock or a hard failure@@ -148,8 +148,7 @@ the picked round's judge verdict + issues + improvement plan, the measurement tafull render set, the cost breakdown and the code.Filters live in the query string, so a view can be curled or bookmarked:-`curl -s 'http://127.0.0.1:8765/?track=graphics&tier=A&sort=cost'`, and-`/api/runs?...` / `/api/summary?...` return the same selection as JSON.+`curl -s 'http://127.0.0.1:8765/?track=graphics&tier=A&sort=cost'`.`--reload` re-scans on every page load, which is what you want while a bench is writing:a run with no `record.json` yet shows as a *pending* card and a half-written one as*broken*, never as a crash. The server binds `127.0.0.1` and refuses any other address@@ -181,7 +180,7 @@ unless you type `--host` yourself; it never serves a path outside the declared r# pairwise = the pairwise judge between the top two when within 0.03 (one# paid verdict per pair, cached); --round N = that round.# `make`/`resume` run `pick --by score` for you-3dcode render <slug> [--round N] [--mode shaded|wire|normals|clay|silhouette] [--out dir]+3dcode render <slug> [--mode shaded|wire|normals|clay|silhouette] [--out dir]3dcode judge <slug> [--round N] [--rubric static_object] [--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.json3dcode tools list [--cards] · 3dcode tools measure --workspace runs/<slug> · 3dcode tools gl_frames --workspace … --json '{"times":[0,1,2.5]}'@@ -197,7 +196,6 @@ unless you type `--host` yourself; it never serves a path outside the declared r# INTERFACES has the call signatures. Training formats live# in finetune/llamafactory/, not here.3dcode flywheel caption <slug> [--model …] [--out caps/] # --out = side-car mode, run untouched-3dcode flywheel index runs/ runs_index.sqlitepython -m codeverse3d.addons.calibration runs/<slug> [runs/<slug2> …] --model gemini:gemini-3.1-pro-preview --n 3 --out out/# re-judges recorded rounds; writes calibration_<model>.md/.json (never touches runs/)```diff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.mdindex 201e743c..bd6947b2 100644--- a/harness/docs/RUN_LAYOUT.md+++ b/harness/docs/RUN_LAYOUT.md@@ -1,14 +1,13 @@# Run directory layoutOne run = one directory (`runs/<slug>/`, `eval/bench/out/<battery>/runs/<slug>/`).-It answers three different questions, and since 2026-08-23 it keeps them in-three separate buckets:+It answers three different questions and keeps them in three separate buckets:| bucket | question | contents ||---|---|---|| `deliverable/` | **what did I get?** | ONE round, the one a pick chose (`3dcode pick`; `3dcode make` picks by score after the run): its code snapshot, its artifact (`object.glb` / `robot.urdf` + `meshes/` / `frames/` + `preview.gif` / the scene bundle), its contact sheet, `captions.json`, `manifest.json` |-| `evidence/` (= `artifacts/`) | **why should I believe it?** | every round's own build (`rNN/`), `renders/rNN/`, `gates/rNN/`, `judge/rNN.json`, `measurement.json`, `census.json`, `tool_renders/` |-| `telemetry/` | **what did it cost and how was it configured?** | `cost.jsonl` (the ledger), `settings.json`, `cost.json`, plus `events.jsonl`, `run_state.json`, `stages/`, `trajectories/` |+| `artifacts/` | **why should I believe it?** | every round's own build (`rNN/`), `renders/rNN/`, `gates/rNN/`, `judge/rNN.json`, `measurement.json`, `census.json`, `tool_renders/` |+| `telemetry/` | **what did it cost and how was it configured?** | `cost.jsonl` (the ledger), `settings.json`, `cost.json` |The run's **identity** stays at the root, where every tool has always looked for it.This is the one full tree; every other doc points here:@@ -24,8 +23,7 @@ runs/<slug>/around every session, rNN <kind>; ends at the LAST round)public/ (scene) compiled assets public/assets/<snake>.glbdeliverable/ (a) the hand-over — one round, written by a pick- evidence/ -> artifacts/ (b) the proof- artifacts/ the LAST round's build: object.glb object.stl|step robot.urdf meshes/ build.json census.json+ artifacts/ (b) the proof: the LAST round's build: object.glb object.stl|step robot.urdf meshes/ build.json census.jsonmeasurement.json …; graphics: frames/fNN_tT.png frames_sheet.png preview.gif metrics.jsonrNN/ each round's own build, copied when it built (below)renders/rNN/ view_<name>.png sheet.png views.json (judge flags) (+ poses/ articulated; <cam>_t<t>.png@@ -35,10 +33,6 @@ runs/<slug>/tool_renders/rNN_<name>/telemetry/ (c) the accountingcost.jsonl settings.json cost.json- events.jsonl -> ../events.jsonl- run_state.json -> ../run_state.json- stages -> ../stages- trajectories -> ../trajectoriesstages/<name>.json each cached pre-round stage's result (keyed, ARCHITECTURE §7.1)rounds/rNN.json rounds/candidates.json the round journal; best-of-N's summary (= record.extra["candidates"])rounds/aborted_rNN.json a round the budget or a crash cut: what it burned, never resumed from@@ -52,37 +46,15 @@ runs/<slug>/AGENTS.md CLAUDE.md .antigravityignore (vendor-CLI context; no .3dcode/cookbook.md since D107)```-## Why the aliases point that way--Only **one** physical copy of anything exists; the second name is a relative-symlink. Which side is physical was not a matter of taste:--* **`artifacts/` stays physical, `evidence/` is the alias.** Six packages- (`spatial`, `languages`, `tracks`, `judges`, `flywheel`) write- into `ws.artifacts`, and ~50 completed runs have absolute `artifacts/...`- paths frozen inside `record.json`, `rounds/rNN.json` and `views.json`.- Moving the bytes would either break those paths or force a rewrite of files- we treat as immutable evidence. The alias costs nothing and gives the- directory listing the name that explains what is inside.-* **`events.jsonl` / `run_state.json` / `stages/` / `trajectories/` stay at the- root, `telemetry/` links to them.** `events.jsonl` is opened in append mode- by long-lived writers and `run_state.json` is rewritten atomically- (tmp + rename) — a rename onto a *symlink* replaces the link, so the symlink- must be on the alias side, never on the side that gets written.-* **`deliverable/`, `telemetry/settings.json` and `telemetry/cost.json` are real- files.** They are *derived*: `telemetry/` is rebuilt from the run's own- artifacts, trajectories and events every time the run is finalised,- `deliverable/` from a round's commit and its `artifacts/rNN/` every time a round- is picked, and both on the fly by `3dcode show` / the exporters for a run that- predates them — old runs are read as-is, never rewritten. `deliverable/` is self-contained so it can be zipped and handed to- someone (the flywheel exporter only falls back to it when git cannot answer).- `telemetry/cost.jsonl` is the ledger itself, appended while the run happens, and has- one name: the root `cost_ledger.jsonl` and `telemetry/usage.jsonl` symlinks runs written- before 2026-09-22 carry are no longer written or read.--`.gitignore` inside the run ignores `deliverable/`, `telemetry/` and `evidence`-(as well as `artifacts/`, `stages/`, `trajectories/`, …) so the derived buckets-never enter the code snapshot.+`deliverable/`, `telemetry/settings.json` and `telemetry/cost.json` are *derived*: `telemetry/` is+rebuilt from the run's own artifacts, trajectories and events every time the run is finalised, and+`deliverable/` from a round's commit and its `artifacts/rNN/` every time a round is picked.+`deliverable/` is self-contained so it can be zipped and handed to someone (the flywheel exporter+only falls back to it when git cannot answer). `telemetry/cost.jsonl` is the ledger itself,+appended while the run happens.++`.gitignore` inside the run ignores `deliverable/`, `telemetry/` (as well as `artifacts/`,+`stages/`, `trajectories/`, …) so the derived buckets never enter the code snapshot.## Every round, kept (`artifacts/rNN/`)@@ -103,8 +75,7 @@ The rest of a round is already per round: its code is its git commit (a scene'sare `renders/rNN/` (a graphics round's judged frames among them), its gates `gates/rNN/`,its verdict `judge/rNN.json` and `rounds/rNN.json`. The census, `build.json`, the `.blend`and the measurement are evidence of the LAST build only. A round that did not build keeps-nothing. A run recorded before 2026-09-22 has no `rNN/`: its canonical files are the build-of the best round its `record.json` still names (`round_outputs` reads it that way).+nothing.## `deliverable/`@@ -131,8 +102,7 @@ Beside `record.json`, `selection.json` says which round that is and why: `{round`addons.select.summarise` reads it, so every reader reports the round that was handed over.Every file is hashed with sha256 and is a real copy (never a hard link), so editing the-hand-over folder can never touch the evidence. A file over 128 MB (or a bucket over-512 MB) is left out and named in `manifest.skipped`. Rebuilding is idempotent: the manifest+hand-over folder can never touch the evidence. Rebuilding is idempotent: the manifestkeeps its previous `generated_at` when the content is unchanged, so re-running the packagerproduces no diff.@@ -145,15 +115,11 @@ produces no diff.harness version + git sha; key-pool size; **price-table hash**; resolvedrender and limit settings. Sampling values are what the track stamped as it ran,`record.extra["sampling"]` (the planner's `plan_temperature(track)`, the judge's own- temperature / thinking / samples; `source="run"`) — a vendor CLI owns its knobs, and a- record written before 2026-09-22 carries no stamp, so they are left empty, never guessed- (they were read off the call sites' signature defaults, which reported the default judge- sample count whatever the run used).+ temperature / thinking / samples; `source="run"`) — a vendor CLI owns its knobs.* **`cost.jsonl`** — THE ledger: one priced row per model call or CLI session, in the**`codeverse3d.cost` ledger format** (`CallCost`: tokens, unit prices, priceprovenance, stage, role, outcome), written by the metered models and agents while the- run happens. It is the only record of money; a run without one (recorded before- 2026-08-23) has no rows — nothing is reconstructed.+ run happens. It is the only record of money.* **`cost.json`** (`CostSummary`) — the run-layout view of those rows, computed by theledger's own `summarise`: the total (= `record.total_usage`, the ledger's sum at listprice — post-run work a pick buys joins it the next time the run is packaged), tokens, per@@ -167,11 +133,6 @@ produces no diff.The hand-over is described by `deliverable/manifest.json` and `selection.json`, not by`record.json`. Round artifacts live in `artifacts/rNN/`.-Historical record migration is not supported: retired `passed` / `plateau` / `stopped`-statuses, `best_round` manifest aliases, pre-step timing fallbacks and canonical-artifact-ownership inference have been removed. Use the repository revision that wrote an old run-if you need to read it. Existing local run data is not migrated or deleted.-## Reading a run```@@ -189,11 +150,8 @@ For the money itself across many runs — waste, $ per run, price provenance —package's own command, `3dcode cost --runs-dir <root>`.`3dcode show` is the single-run view; both read the same ledger rows.-## Back-compatibility contract+## Reading artifacts-* Old runs load unchanged — `load_record`, `3dcode status`, `3dcode judge`,- `3dcode render`, `flywheel export/pairs/index`, `gallery` all work with no- `deliverable/` or `telemetry/` present.* Consumers resolve artifacts through`record.deliverable.deliverable_path(ws, name)`: `deliverable/<name>` first,`artifacts/<name>` second. A reader that wants a given ROUND's file asksdiff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.mdindex af9e7b74..15b01685 100644--- a/harness/docs/SKILLS.md+++ b/harness/docs/SKILLS.md@@ -201,7 +201,7 @@ means the AGENT opened the control: counted by the report and flagged, never dro```3dcode skills report eval/bench/out/<battery> # deep-read rate per skill per backend (--json)-3dcode doctor --skills # library + discovery wiring+3dcode skills validate # bundles, overlays, routes```Target: ≥ 60 % deep-read, counted only over sessions the control says were measurable. **A skill@@ -315,8 +315,7 @@ Re-read from the binaries 2026-09-22 (claude-code 2.1.280, codex 0.155.1, agy 1.harness's own launch path: same roots, all activate the routed bundles; agy's`--disable-slash-commands`, which the harness passes, only stops `/name` expansion of the prompt.Two things this settled that had only been argued: `Skill` was absent from `ALLOWED_TOOLS`-(claude-code would have denied its own skill tool — added, and `3dcode doctor --skills` checks-it); and the negative control — a bundle whose description does not match, "do not read any+(claude-code would have denied its own skill tool — added); and the negative control — a bundle whose description does not match, "do not read anyfiles, do not activate any skill" — found every CLI opening `SKILL.md` **and** `references/`,each only under the root it owns (claude-code both roots): the independent confirmation of theroot mapping, and the reason `deep` cannot mean "the agent chose to go deeper" on atime alone (§1).diff --git a/harness/pyproject.toml b/harness/pyproject.tomlindex 6ee4d5fc..04546bbb 100644--- a/harness/pyproject.toml+++ b/harness/pyproject.toml@@ -41,7 +41,7 @@ dependencies = [cad = ["cadquery>=2.4"] # language `cadquery`urdf = ["yourdfpy>=0.0.56", "scipy>=1.11"] # track `articulated_object` (urdf_blender)graphics = ["moderngl>=5.8"] # track `graphics` (glsl_shader / opengl_python)-mesh = ["shapely>=2.0", "networkx>=3.2", "manifold3d>=2.3", "matplotlib>=3.8"] # cross_section area, mesh split, joint-sweep booleans, judge slices (D48)+mesh = ["shapely>=2.0", "networkx>=3.2", "matplotlib>=3.8"] # cross_section area, mesh split, judge slices (D48)mcp = ["mcp>=1.0"] # `3dcode mcp` spatial-tool server for the agentic CLIsflywheel = ["pyarrow>=15"] # `3dcode flywheel export --pack` (parquet)all = ["3dcodeverse[cad,urdf,graphics,mesh,mcp,flywheel]"]diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjsindex fb40099b..50a1493c 100644--- a/harness/runtime_js/lib/host_page.mjs+++ b/harness/runtime_js/lib/host_page.mjs@@ -53,7 +53,7 @@ export function requestFailureLine(url, base, hasResponse, errorText) {* the scene module is imported and createScene() runs (probe_scene.mjs: the watchdog's phase, D111).* @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}*/-export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false, post = true, postOptions = null, glb = null, onBoot = null } = {}) {+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, post = true, postOptions = null, glb = null, onBoot = null } = {}) {wsRoot = path.resolve(wsRoot);// an offline scene (`glb`: its census GLB) boots the harness adapter, never a workspace moduleconst sceneFile = glb || path.join(wsRoot, sceneRel);@@ -103,7 +103,7 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'autoif (onBoot) onBoot();const boot = await page.evaluate((o) => window.__c3v.boot(o),- { sceneUrl, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, autoExposure, post, postOptions },+ { sceneUrl, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, post, postOptions },);const close = async () => {// page first, then release: a SHARED browser (connect-first reuse) must getdiff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjsindex c7fc6b11..9d1b88aa 100644--- a/harness/runtime_js/lib/scene_host.mjs+++ b/harness/runtime_js/lib/scene_host.mjs@@ -54,8 +54,6 @@ const state = {cameraRepair: false,cameraRepairs: [],repairedSpecs: new Map(),- autoExposure: false,- autoExposureInfo: null,post: null,postInfo: null,};@@ -88,11 +86,6 @@ function makeHostRenderer(width, height, opts) {return { renderer: makeRenderer(canvas, width, height, { logDepth: !!opts.logDepth }), canvas };}-/** Auto-exposure's target mean-luminance band. Its floor is the scene_frames gate's dark line- * (`frame_metrics.DARK_MEAN_LUM`, pinned by a test): at 0.10 a frame lifted to 0.10-0.119- * still drew "frame too dark". */-const EXPOSURE_BAND = [0.12, 0.45];-/** The authored cameras, and each problem as {severity, text}: the severity is decided HERE,* where the problem is known (the python gate used to re-derive it from the wording).* The plan's own cameras pass the same fov / position / name rules (contracts/plan.CameraPlan). */@@ -283,8 +276,6 @@ async function boot(opts) {state.cameraRepair = !!opts.cameraRepair;state.cameraRepairs = [];state.repairedSpecs = new Map();- state.autoExposure = !!opts.autoExposure;- state.autoExposureInfo = null;state.width = opts.width || 1024;state.height = opts.height || 576;window.requestAnimationFrame = () => { state.rafCalls += 1; return 0; };@@ -344,8 +335,7 @@ async function boot(opts) {// post chain (browser/post.js): ON for scene renders unless `post: false`.// Built here — after the first update, so a scene that sets its grade hint- // while building has already set it — and before auto-exposure, which must- // measure the frame that will actually be judged. A chain that cannot be+ // while building has already set it. A chain that cannot be// built is a host WARNING, never a boot failure: the raw path still renders.if (opts.post !== false) {info.stage = 'post';@@ -381,33 +371,6 @@ async function boot(opts) {info.settled = state.settleInfo.count;}- // auto-exposure (opt-in, --auto-exposure): one scene-wide bounded exposure, like a- // photographer picking ISO once. fv_izakaya_night sat at mean_lum 0.07 for three- // rounds with the 'frame too dark' ERROR in every refine prompt and nobody fixed it;- // the frame gate's healthy band is 0.12..0.35. Factor clamped to [0.5, 3.0] so a- // deliberately moody scene is brightened, never rewritten; recorded in the census.- if (opts.autoExposure && state.cameras.length) {- info.stage = 'auto_exposure';- try {- const probeCam = () => buildCameraRaw(state.cameras[0]);- const lum = () => { renderOnce(probeCam()); return frameStats(state.canvas).mean_lum; };- const before = lum();- let factor = 1;- let after = before;- const [lo, hi] = EXPOSURE_BAND;- for (let i = 0; i < 4 && (after < lo || after > hi); i++) {- const step = after < lo ? 1.6 : 0.7;- const next = Math.min(3.0, Math.max(0.5, factor * step));- if (next === factor) break;- factor = next;- state.renderer.toneMappingExposure = factor;- after = lum();- }- if (factor !== 1) state.autoExposureInfo = { factor: +factor.toFixed(2), lum_before: before, lum_after: after };- } catch (e) {- state.hostWarnings.push(`auto-exposure failed: ${String((e && e.message) || e).slice(0, 200)}`);- }- }state.booted = true;info.ok = cameras.length > 0;// A camera-less scene used to fail with info.error EMPTY, so the caller@@ -723,7 +686,6 @@ function census() {c.glb_assets = glbUsage(state.scene);if (state.settleInfo) c.settle = state.settleInfo;if (state.cameraRepairs.length) c.camera_repair = state.cameraRepairs.slice();- if (state.autoExposureInfo) c.auto_exposure = state.autoExposureInfo;if (state.postInfo) c.post = state.postInfo;state.contentBox = c.content_bbox;state.fullBox = c.bbox;diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjsindex 20bae5f3..ebacada6 100644--- a/harness/runtime_js/probe_scene.mjs+++ b/harness/runtime_js/probe_scene.mjs@@ -37,7 +37,6 @@ import { compileIntoReport, staticShaderReport } from './lib/shader_report.mjs';const args = parseCli({'no-settle': { type: 'boolean', default: false },'camera-repair': { type: 'boolean', default: false },- 'auto-exposure': { type: 'boolean', default: false },// The probe is a 320x180 GEOMETRY instrument, never a judged picture: it runs raw// so its shader report names the scene's own programs and nothing of ours. The// flag parses (drivers share a switch list) and changes nothing.@@ -83,7 +82,6 @@ async function main() {createSceneTimeoutMs: createTimeoutMs(timeoutMs),settle: !args['no-settle'],cameraRepair: !!args['camera-repair'],- autoExposure: !!args['auto-exposure'],post: false,onBoot: () => { phase = 'scene'; },});diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjsindex 0c6ca4d9..ab417109 100644--- a/harness/runtime_js/render_scene.mjs+++ b/harness/runtime_js/render_scene.mjs@@ -31,7 +31,6 @@ import { fitOrbitCameras, framingBox } from './lib/orbit.mjs';const args = parseCli({'no-settle': { type: 'boolean', default: false },'camera-repair': { type: 'boolean', default: false },- 'auto-exposure': { type: 'boolean', default: false },// post chain (GTAO + soft bloom + grade): ON for scene pictures, `--no-post` (python// emits it for C3D_POST=0) to render raw. Object renders never come through here.'no-post': { type: 'boolean', default: false },@@ -90,7 +89,6 @@ async function main() {createSceneTimeoutMs: createTimeoutMs(timeoutMs),settle: !args['no-settle'],cameraRepair: !!args['camera-repair'],- autoExposure: !!args['auto-exposure'],post: !args['no-post'],postOptions: readJsonArg(args['post-options'], 'post-options'),});diff --git a/harness/tests/agents/conftest.py b/harness/tests/agents/conftest.pyindex f80836d0..2c70af36 100644--- a/harness/tests/agents/conftest.py+++ b/harness/tests/agents/conftest.py@@ -10,10 +10,7 @@ import pytestdef write_fake_cli(path: Path, body: str) -> Path:- """Write an executable python script ``path`` whose main body is ``body``.-- The script receives argv like the real CLI and must print to stdout.- """+ """An executable python script whose main body is ``body`` (it gets argv like the real CLI)."""path.write_text("#!" + sys.executable + "\nimport sys, os, json, time\n" + body)path.chmod(path.stat().st_mode | stat.S_IXUSR)return path@@ -32,8 +29,7 @@ def fake_bin(tmp_path: Path):@pytest.fixturedef scoped_ws(tmp_ws):- """A workspace with an entry file and two part files — the tree every write-scope- test (the CLI post-hoc restore and the single-shot envelope alike) needs."""+ """A workspace with an entry file and two part files, for the write-scope tests."""(tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)(tmp_ws.src / "model.py").write_text("# entry\n")(tmp_ws.src / "parts" / "seat.py").write_text("# seat\n")@@ -50,7 +46,5 @@ def _clean_agent_env(monkeypatch):@pytest.fixture(autouse=True)def _fast_watchdog_poll(monkeypatch):- """A fake CLI exits in milliseconds; the watchdog's 1 s poll then dominated every- agent.run() in this directory (~13 s across the suite). Production keeps 1 s —- a real vendor CLI runs for minutes and does not care."""+ """A fake CLI exits in milliseconds; the watchdog's 1 s poll would dominate every agent.run()."""monkeypatch.setattr("codeverse3d.agents.cli_common.POLL_S", 0.02)diff --git a/harness/tests/agents/test_agent_job_wiring.py b/harness/tests/agents/test_agent_job_wiring.pyindex 9c984188..6fc42a6f 100644--- a/harness/tests/agents/test_agent_job_wiring.py+++ b/harness/tests/agents/test_agent_job_wiring.py@@ -3,14 +3,9 @@ prompt section, a hard-clock session window, the backend's turn count."""from __future__ import annotations-import time--import pytest--from codeverse3d.contracts.agent import AgentJob, AgentResult+from codeverse3d.contracts.agent import AgentJob, AgentResult, FileChangefrom codeverse3d.contracts.chat import ImagePart-from codeverse3d.contracts.common import Budget, Usage-from codeverse3d.orchestrator import BudgetExceeded, BudgetGuard+from codeverse3d.contracts.common import Usagefrom codeverse3d.tracks.generation import GenerationTask, run_agent_taskfrom codeverse3d.workspace import Workspace@@ -26,6 +21,7 @@ class StubAgent:ws = Workspace(job.workspace)(ws.src / "a.txt").write_text("x\n")return AgentResult(ok=True, exit_reason="completed", turns=0,+ files_changed=[FileChange(path="src/a.txt", status="added")],usage=Usage(backend="stub", input_tokens=10, cost_usd=0.01))@@ -50,76 +46,13 @@ def test_images_reach_the_agent_as_paths_in_the_prompt(tmp_ws: Workspace, tmp_paassert "Images for this task" not in agent.jobs[1].prompt-def test_session_window_is_clipped_to_the_hard_clock_not_the_soft_share(tmp_ws: Workspace):- """Clipping against the soft share handed a late refine the 120 s floor (2026-08-29)."""- guard = BudgetGuard(Budget(max_minutes=100), soft_fraction=0.5)- guard.start_time -= 60 * 60 # 60 of 100 minutes gone: the soft share is spent, 40 min remain- assert not guard.soft_ok()- agent = StubAgent()- run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="refine", prompt="p", timeout_s=900), budget=guard)- assert agent.jobs[0].timeout_s == 900-def test_run_deadline_overrides_the_session_timeout_floor(tmp_ws: Workspace):- guard = BudgetGuard(Budget(max_minutes=1))- guard.start_time -= 50- agent = StubAgent()- start = time.monotonic()- run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="refine", prompt="p"), budget=guard)- job = agent.jobs[0]- assert job.timeout_s == 120 # the existing soft session floor- assert start < job.hard_deadline_s <= start + 10---def test_silent_retry_keeps_the_original_absolute_deadline(tmp_ws: Workspace):- class BailOnce(StubAgent):- def run(self, job):- if not self.jobs:- self.jobs.append(job)- return AgentResult(ok=False, exit_reason="completed")- return super().run(job)-- agent = BailOnce()- run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="baseline", prompt="p"),- budget=BudgetGuard(Budget(max_minutes=1)))- assert len(agent.jobs) == 2- assert agent.jobs[0].hard_deadline_s is not None- assert agent.jobs[0].hard_deadline_s == agent.jobs[1].hard_deadline_s---def test_empty_usage_cannot_bypass_the_clock_and_start_a_retry(tmp_ws: Workspace):- guard = BudgetGuard(Budget(max_minutes=1))-- class EmptyOverrun(StubAgent):- def run(self, job):- self.jobs.append(job)- guard.start_time -= 61- return AgentResult(ok=False, exit_reason="completed")-- agent = EmptyOverrun()- with pytest.raises(BudgetExceeded):- run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="baseline", prompt="p"), budget=guard)- assert len(agent.jobs) == 1--[email protected]("thinking, effort", [("", None), ("off", None), ("low", "low"), ("medium", "medium"),- ("high", "high")])-def test_the_task_effort_reaches_the_job_only_when_asked(tmp_ws: Workspace, thinking, effort):- """``GenerationTask.thinking`` '' (the default) leaves the backend's own effort — agy: high."""- agent = StubAgent()- run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="t", prompt="p", thinking=thinking))- assert agent.jobs[0].effort == effort-def test_the_session_ledger_row_carries_the_effort_the_cli_ran_at(tmp_ws: Workspace):- from codeverse3d.cost.instrument import metered_agent, run_ledger- from codeverse3d.cost.ledger import load_ledger- class Ran(StubAgent):- def run(self, job):- return super().run(job).model_copy(update={"effort": "high"})- with run_ledger(tmp_ws.root, run="r"):- metered_agent(Ran()).run(AgentJob(workspace=str(tmp_ws.root), prompt="p", label="baseline"))- (row,) = load_ledger(tmp_ws.root)- assert row.model_extra.get("effort") == "high"++++diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.pyindex b0e103a6..4eba6ade 100644--- a/harness/tests/agents/test_antigravity.py+++ b/harness/tests/agents/test_antigravity.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-import shutilfrom pathlib import Pathimport pytest@@ -38,35 +37,6 @@ os.makedirs("src", exist_ok=True)open("src/hello.txt", "w").write("hi")open("src/prompt.txt", "w").write(prompt)mode = os.environ.get("FAKE_MODE", "ok")-if mode == "retried": # agy 1.2.8 retried two 503s and a 429 inside the turn, then answered- from datetime import datetime, timedelta- t0 = datetime.now() - timedelta(seconds=21)- with open(log, "w") as f:- f.write(t0.strftime("I%m%d %H:%M:%S.%f") + " 66 server.go:609] Language server will attempt to listen\n")- for i, (dt, why, wait) in enumerate([(0, "Error 503, Message: busy, Status: UNAVAILABLE", "4s"),- (4, "Error 503, Message: busy, Status: UNAVAILABLE", "6.069232705s"),- (10, "Error 429, Message: slow down, Status: RESOURCE_EXHAUSTED", "10.690413026s")]):- f.write((t0 + timedelta(seconds=dt)).strftime("I%m%d %H:%M:%S.%f")- + f" 284 run.go:395] Run: attempt {i + 1} failed ({why}, Details: []), retrying in {wait}\n")-if mode == "died": # a turn that ended on the API: AGY_ERROR on stderr, exit code 3- print(json.dumps({"conversation_id": "c9", "status": "ERROR", "response": "", "error": "generating: Error 503"}))- print('AGY_ERROR: {"short_error":"generating: Error 503","status":"UNAVAILABLE","error_code":503,'- '"code_kind":"http","retryable":true,"error_id":"x"}', file=sys.stderr)- sys.exit(3)-if mode == "print_timeout": # agy's own clock (1.4.12): SUCCESS, no response, `finished_reason` and one stderr line- print(json.dumps({"conversation_id": "c8", "status": "SUCCESS", "response": "", "num_turns": 1,- "finished_reason": "print_timeout"}))- print("[agy] print timeout after 8m0s with turn in progress; returning partial output", file=sys.stderr)- sys.exit(0)-if mode == "print_timeout_old": # agy <= 1.4.10: the stderr line was the only signal- print(json.dumps({"conversation_id": "c8", "status": "SUCCESS", "response": "", "num_turns": 1}))- print("[agy] print timeout after 8m0s with turn in progress; returning partial output", file=sys.stderr)- sys.exit(0)-if mode == "error_at_timeout": # 1.4.12 live, 2026-11-03: the clock fired while agy retried a 503 — its verdict is `error`- print(json.dumps({"conversation_id": "c7", "status": "ERROR", "response": "", "num_turns": 1, "finished_reason": "error",- "error": "API error (attempt 1): Error 503, Message: high demand, Status: UNAVAILABLE, Details: []"}))- print("[agy] print timeout after 2s with turn in progress; returning partial output", file=sys.stderr)- sys.exit(0)if mode == "text":print("plain text answer")else:@@ -96,66 +66,14 @@ def test_fake_run_json_and_text(tmp_ws: Workspace, fake_bin, monkeypatch):assert res2.ok and res2.text == "plain text answer" and res2.usage.input_tokens == 0-def test_the_retries_in_agys_own_log_are_its_provider_wait(tmp_ws: Workspace, fake_bin, monkeypatch):- """agy 1.2.8 logs every model call it retries, with the back-off it announces (fake API,- 2026-09-22: 503, 503, 429, then an answer 20.8 s later) — the burst runs from the first- failure to the last one plus its back-off."""- from codeverse3d.agents.backends import agy_retries- from codeverse3d.agents.cli_common import provider_wait- a = AntigravityAgent("gemini-4-argon-high", binary=fake_bin("agy", FAKE_AGY))- monkeypatch.setenv("FAKE_MODE", "retried")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="r", timeout_s=30))- assert res.ok, res.errors- rows = agy_retries(Path(res.transcript_path).parent / "agy.log")- assert [(round(b, 3), why.split(",")[0]) for _, b, why in rows] == [- (4.0, "Error 503"), (6.069, "Error 503"), (10.69, "Error 429")]- assert [round(t - rows[0][0], 3) for t, _, _ in rows] == [0.0, 4.0, 10.0]- assert provider_wait([(t, b) for t, b, _ in rows], end=rows[0][0] + 60) == pytest.approx(20.690413, abs=1e-3)- # the fake wrote a log 21 s in the past: the session's own wait is capped at its length- assert 0.0 < res.provider_wait_s <= res.duration_s-def test_agy_says_itself_whether_a_dead_turn_is_worth_a_retry(tmp_ws: Workspace, fake_bin, monkeypatch):- a = AntigravityAgent("gemini-4-argon-high", binary=fake_bin("agy", FAKE_AGY))- monkeypatch.setenv("FAKE_MODE", "died")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="d", timeout_s=30))- assert not res.ok and res.exit_reason == "error" and res.transient and not res.quota- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())- assert rec["agy_error"]["retryable"] is True and rec["agy_error"]["error_code"] == 503[email protected]("mode", ["print_timeout", "print_timeout_old"])-def test_agys_own_print_timeout_is_a_timeout_not_an_empty_answer(tmp_ws: Workspace, fake_bin, monkeypatch, mode):- a = AntigravityAgent("gemini-4-argon-high", binary=fake_bin("agy", FAKE_AGY))- monkeypatch.setenv("FAKE_MODE", mode)- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="pt", timeout_s=30))- assert not res.ok and res.exit_reason == "timeout" and not res.transient- assert "--print-timeout" in res.errors[0] and "empty response" not in " ".join(res.errors)- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())- assert rec["finished_reason"] == ("print_timeout" if mode == "print_timeout" else "")-def test_the_envelopes_verdict_outranks_the_stderr_line(tmp_ws: Workspace, fake_bin, monkeypatch):- """rc 0, `status: ERROR`, `finished_reason: error` AND the print-timeout line (1.4.12, live): an error."""- a = AntigravityAgent("gemini-4-argon-high", binary=fake_bin("agy", FAKE_AGY))- monkeypatch.setenv("FAKE_MODE", "error_at_timeout")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="et", timeout_s=30))- assert not res.ok and res.exit_reason == "error"- assert "status=ERROR" in res.errors[0] and "--print-timeout" not in res.errors[0]- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())- assert rec["finished_reason"] == "error" and rec["killed_reason"] != "agy_print_timeout"---def test_live_agy_tiny(tmp_ws: Workspace):- if not shutil.which("agy"):- pytest.skip("agy not installed")- a = AntigravityAgent("gemini-4-argon-low")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Use your file-writing tool to create src/hello.txt containing exactly 'hi'. Reply DONE.",- timeout_s=300, label="live", spatial_tools=False))- assert res.ok, res.errors- assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"+#: agy in Gemini-API mode, as the harness drives it: everything it needs is in its own HOME@@ -220,34 +138,5 @@ def _effort_job(tmp_ws: Workspace, **kw) -> AgentJob:return AgentJob(workspace=str(tmp_ws.root), prompt="hello", timeout_s=30, spatial_tools=False, **kw)[email protected]("model, asked, runs_at", [- ("gemini-4-argon", None, "high"), # every track today: no ask → AGY_API_EFFORT (owner, 2026-10-15)- ("gemini-4-argon", "medium", "medium"), # an explicit ask reaches --effort- ("gemini-4-argon-low", "medium", "low"), # the model id's suffix still wins- ("gemini-4-argon-high", None, "high"),-])-def test_effort_reaches_the_argv_the_invoke_line_and_the_result(tmp_ws: Workspace, fake_bin, model, asked, runs_at):- a = AntigravityAgent(model, binary=fake_bin("agy", FAKE_AGY_API))- res = a.run(_effort_job(tmp_ws, label=f"e_{asked}", effort=asked))- assert res.ok, res.errors- assert json.loads((tmp_ws.src / "seen.json").read_text())["effort"] == runs_at- assert res.effort == runs_at- tdir = Path(res.transcript_path).parent- invoke = next(json.loads(ln) for ln in (tdir / "transcript.jsonl").read_text().splitlines()- if json.loads(ln)["kind"] == "invoke")- assert invoke["effort"] == runs_at and invoke["argv"][invoke["argv"].index("--effort") + 1] == runs_at- assert json.loads((tdir / "result.json").read_text())["effort"] == runs_at---def test_object_and_scene_tasks_run_argon_at_high(tmp_ws: Workspace, fake_bin):- """The object tracks' draft / refine and the scene's zone task ask for no effort, so a bare- ``agy:gemini-4-argon`` session runs at high on every track (owner, 2026-10-15)."""- from codeverse3d.tracks.generation import GenerationTask, session_effort-- a = AntigravityAgent("gemini-4-argon", binary=fake_bin("agy", FAKE_AGY_API))- for task in (GenerationTask(label="baseline", prompt="p", kind="baseline"),- GenerationTask(label="refine", prompt="p", kind="refine", temperature=0.4),- GenerationTask(label="zone_quay", prompt="p", kind="zone")):- assert session_effort(task) is None- res = a.run(_effort_job(tmp_ws, label=task.label, effort=session_effort(task)))- assert res.ok and json.loads((tmp_ws.src / "seen.json").read_text())["effort"] == "high"++diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.pyindex 4f03b854..08e5c395 100644--- a/harness/tests/agents/test_claude_code.py+++ b/harness/tests/agents/test_claude_code.py@@ -3,14 +3,13 @@from __future__ import annotationsimport json-import shutil+import sysfrom pathlib import Pathimport pytestfrom codeverse3d.agents.backends import (ClaudeCodeAgent,- parse_claude_json,primary_served_model,usage_from_envelope,)@@ -19,16 +18,6 @@ from codeverse3d.agents.materialize import materialize_workspacefrom codeverse3d.contracts.agent import AgentJobfrom codeverse3d.workspace import Workspace-ENVELOPE = {- "type": "result", "subtype": "success", "is_error": False, "duration_ms": 4200, "duration_api_ms": 3900,- "num_turns": 3, "result": "Created src/hello.txt", "session_id": "abc", "total_cost_usd": 0.0123,- "usage": {"input_tokens": 10, "cache_creation_input_tokens": 200, "cache_read_input_tokens": 5000, "output_tokens": 40},- "modelUsage": {"claude-opus-5-5": {"inputTokens": 10, "outputTokens": 40, "costUSD": 0.0123}},-}--#: what a real `claude -p --model sonnet` session bills: the work model PLUS the small-#: background model the CLI uses for its own housekeeping — and claude 2.1.243 lists the-#: AUXILIARY one FIRST. Token counts and costs are the ones observed in the CC-1 repro.TWO_MODEL_ENVELOPE = {"type": "result", "subtype": "success", "is_error": False, "duration_ms": 10000,"num_turns": 1, "result": "pong", "session_id": "xyz", "total_cost_usd": 0.023795,@@ -38,6 +27,33 @@ TWO_MODEL_ENVELOPE = {"claude-sonnet-5-5": {"inputTokens": 2, "outputTokens": 4, "costUSD": 0.02284},},}+FAKE_KILLED_CLAUDE = r'''+for ev in json.loads(os.environ["FAKE_EVENTS"]):+ print(json.dumps(ev), flush=True)+ time.sleep(0.05)+time.sleep(60) # an overloaded provider: claude keeps retrying until the watchdog kills it+'''+_MSG_USAGE = {"input_tokens": 2, "cache_creation_input_tokens": 19190, "cache_read_input_tokens": 20354, "output_tokens": 5}++KILLED_STREAM = [+ {"type": "system", "subtype": "init", "session_id": "k", "model": "claude-sonnet-5-5", "skills": []},+ {"type": "assistant", "message": {"id": "msg_1", "model": "claude-sonnet-5-5", "usage": _MSG_USAGE,+ "content": [{"type": "text", "text": "Reading the plan"}]}},+ {"type": "assistant", "message": {"id": "msg_1", "model": "claude-sonnet-5-5", "usage": _MSG_USAGE, # same message+ "content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {}}]}},+ {"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1"}]}},+ {"type": "system", "subtype": "api_retry", "attempt": 1, "max_retries": 10, "retry_delay_ms": 500,+ "error_status": 529, "error": "overloaded"},+ {"type": "system", "subtype": "api_retry", "attempt": 2, "max_retries": 10, "retry_delay_ms": 1000,+ "error_status": 529, "error": "overloaded"},+]++ENVELOPE = {+ "type": "result", "subtype": "success", "is_error": False, "duration_ms": 4200, "duration_api_ms": 3900,+ "num_turns": 3, "result": "Created src/hello.txt", "session_id": "abc", "total_cost_usd": 0.0123,+ "usage": {"input_tokens": 10, "cache_creation_input_tokens": 200, "cache_read_input_tokens": 5000, "output_tokens": 40},+ "modelUsage": {"claude-opus-5-5": {"inputTokens": 10, "outputTokens": 40, "costUSD": 0.0123}},+}FAKE_CLAUDE = r'''@@ -74,29 +90,17 @@ print(json.dumps(env))'''-def test_parse_envelope_variants():- assert parse_claude_json(json.dumps(ENVELOPE))["session_id"] == "abc"- assert parse_claude_json("noise\n" + json.dumps(ENVELOPE))["num_turns"] == 3- assert parse_claude_json(json.dumps([{"type": "assistant"}, ENVELOPE]))["type"] == "result"- assert parse_claude_json("") is None- u = usage_from_envelope(ENVELOPE, "sonnet")- assert u.cached_tokens == 5000 and u.cost_usd == 0.0123 and u.model == "claude-opus-5-5"- # input_tokens is the TOTAL prompt (10 uncached + 5 000 read + 200 written), as for every- # other backend: the uncached 10 alone let CostBucket clamp 4 990 cached + the 200 away- assert u.input_tokens == 5210def test_the_mcp_config_is_the_typed_jobs_never_the_workspace_file(tmp_ws: Workspace):- cmd = ["python", "-m", "codeverse3d.spatial.mcp_server", "--workspace", str(tmp_ws.root)]- materialize_workspace(tmp_ws, agent_kind="claude-code", contract_md="c", spatial_tools=True,- mcp_command=cmd)+ materialize_workspace(tmp_ws, agent_kind="claude-code", contract_md="c")a = ClaudeCodeAgent("sonnet", binary="claude")- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", mcp_command=cmd), "claude-code")+ s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p"), "claude-code")(tmp_ws.root / ".mcp.json").write_text(json.dumps({"mcpServers": {"3dcode": {"command": "/tmp/evil", "args": []}}}))argv = a.build_argv(s)cfg = Path(argv[argv.index("--mcp-config") + 1])assert cfg.parent == s.traj.dir- assert json.loads(cfg.read_text())["mcpServers"]["3dcode"]["command"] == "python"+ assert json.loads(cfg.read_text())["mcpServers"]["3dcode"]["command"] == sys.executableassert "mcp__3dcode__*" in argv[argv.index("--allowedTools") + 1]s2 = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "claude-code")assert "--mcp-config" not in a.build_argv(s2)@@ -120,30 +124,6 @@ def test_fake_run_success_and_error(tmp_ws: Workspace, fake_bin, monkeypatch):assert res2.transient is False # the task's own failure[email protected]("mode, reason, transient, quota", [- ("usage_limit", "budget", False, True), # the subscription is spent- ("overloaded", "error", True, False), # a 529 is the provider's, not the task's- ("rate_limited", "budget", True, False),-])-def test_a_provider_exit_is_typed(tmp_ws: Workspace, fake_bin, monkeypatch, mode, reason, transient, quota):- a = ClaudeCodeAgent("sonnet", binary=fake_bin("claude", FAKE_CLAUDE))- monkeypatch.setenv("FAKE_MODE", mode)- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="o", timeout_s=30))- assert not res.ok and res.exit_reason == reason and res.transient is transient and res.quota is quota---def test_live_claude_tiny(tmp_ws: Workspace):- if not shutil.which("claude"):- pytest.skip("claude not installed")- a = ClaudeCodeAgent("haiku")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Create src/hello.txt containing exactly 'hi'. Reply DONE.",- timeout_s=300, label="live", spatial_tools=False, max_turns=6))- assert res.ok, res.errors- assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"- assert res.usage.output_tokens > 0--def test_the_served_model_is_the_work_model_not_the_housekeeping_one():"""`claude -p` bills two models and lists the auxiliary one first (CC-1)."""assert usage_from_envelope(TWO_MODEL_ENVELOPE, "").model == "claude-sonnet-5-5"@@ -152,28 +132,6 @@ def test_the_served_model_is_the_work_model_not_the_housekeeping_one():assert primary_served_model(env, "sonnet") == "claude-sonnet-5-5" # the dearest wins-# --------------------------------------------------------------------------- killed sessions-FAKE_KILLED_CLAUDE = r'''-for ev in json.loads(os.environ["FAKE_EVENTS"]):- print(json.dumps(ev), flush=True)- time.sleep(0.05)-time.sleep(60) # an overloaded provider: claude keeps retrying until the watchdog kills it-'''-_MSG_USAGE = {"input_tokens": 2, "cache_creation_input_tokens": 19190, "cache_read_input_tokens": 20354, "output_tokens": 5}-KILLED_STREAM = [- {"type": "system", "subtype": "init", "session_id": "k", "model": "claude-sonnet-5-5", "skills": []},- {"type": "assistant", "message": {"id": "msg_1", "model": "claude-sonnet-5-5", "usage": _MSG_USAGE,- "content": [{"type": "text", "text": "Reading the plan"}]}},- {"type": "assistant", "message": {"id": "msg_1", "model": "claude-sonnet-5-5", "usage": _MSG_USAGE, # same message- "content": [{"type": "tool_use", "id": "t1", "name": "Read", "input": {}}]}},- {"type": "user", "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1"}]}},- {"type": "system", "subtype": "api_retry", "attempt": 1, "max_retries": 10, "retry_delay_ms": 500,- "error_status": 529, "error": "overloaded"},- {"type": "system", "subtype": "api_retry", "attempt": 2, "max_retries": 10, "retry_delay_ms": 1000,- "error_status": 529, "error": "overloaded"},-]--def test_a_killed_session_is_booked_from_its_messages_and_its_retries_are_provider_wait(tmp_ws: Workspace,fake_bin, monkeypatch):"""A killed claude prints no result event: usage comes from each message, wait from api_retry."""diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.pyindex 5dcfae29..814ab062 100644--- a/harness/tests/agents/test_cli_common.py+++ b/harness/tests/agents/test_cli_common.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport jsonimport osimport sys-import timeimport pytest@@ -13,16 +12,10 @@ from codeverse3d.agents import cli_commonfrom codeverse3d.agents.cli_common import (begin_session,clean_env,- finish_session,hardened_env,invoke,- is_quota_failure,- is_rate_limited,- is_transient_failure,- provider_wait,)from codeverse3d.contracts.agent import AgentJob-from codeverse3d.contracts.common import Usagefrom codeverse3d.workspace import Workspace@@ -33,36 +26,17 @@ def test_clean_and_hardened_env_drop_secrets_but_the_kept_ones(monkeypatch, tmp_env = clean_env({"CODEX_API_KEY"})assert not {"OPENAI_API_KEY", "FOO_TOKEN", "GEMINI_API_KEYS"} & set(env)assert env["CODEX_API_KEY"] == "s" and env["NODE_OPTIONS"] == "--x" and "PATH" in env and "HOME" in env- assert env["C3D_AGENT_CONTEXT"] == "1" and "GIT_CEILING_DIRECTORIES" not in env+ assert "GIT_CEILING_DIRECTORIES" not in env# the hardened env adds the job's env and the git ceiling, and still drops the secretsenv = hardened_env(tmp_ws, AgentJob(workspace=str(tmp_ws.root), prompt="p", env={"EXTRA": "2"}), keep=set())assert env["EXTRA"] == "2" and env["GIT_CEILING_DIRECTORIES"] == str(tmp_ws.root.parent)assert "FAKE_SERVICE_API_KEY" not in env-def test_retry_same_label_round_keeps_first_attempt_trajectory(tmp_ws: Workspace):- """run_agent_task re-runs a silently-bailing job with the same label+round: attempt 1's files must survive."""- job = AgentJob(workspace=str(tmp_ws.root), prompt="first", label="baseline", round=0)- s1 = begin_session(job, "fake")- s1.traj.write_text("stdout.json", "attempt 1 stdout")- r1 = finish_session(s1, ok=False, exit_reason="error", text="", usage=Usage(cost_usd=0.5), errors=["bailed"])- s2 = begin_session(job.model_copy(update={"prompt": "second"}), "fake")- assert s2.traj.dir != s1.traj.dir and s2.traj.dir.name == "baseline.a2_r00" and s2.attempt == 2- (tmp_ws.src / "a.py").write_text("x = 1\n")- r2 = finish_session(s2, ok=True, exit_reason="completed", text="done", usage=Usage(cost_usd=0.01))- d1 = json.loads(s1.traj.result_path.read_text())- assert d1["exit_reason"] == "error" and d1["errors"] == ["bailed"] and d1["usage"]["cost_usd"] == 0.5 and d1["attempt"] == 1- assert (s1.traj.dir / "stdout.json").read_text() == "attempt 1 stdout" and s1.traj.prompt_path.read_text() == "first"- d2 = json.loads(s2.traj.result_path.read_text())- assert d2["attempt"] == 2 and d2["job_label"] == "baseline" and d2["label"] == "baseline.a2" and d2["ok"]- assert [f.path for f in r2.files_changed] == ["src/a.py"] and r1.files_changed == []- log = tmp_ws._git("log", "--oneline").stdout- assert "agent:baseline.a2" in log and "pre:baseline" in logdef test_the_prompt_goes_on_stdin_byte_for_byte_and_never_on_argv(tmp_ws: Workspace):"""A 200 kB, 2 500-line prompt (past argv's 128 KiB cap) reaches the CLI whole."""- import syss = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="x", label="p"), "fake")prompt = " leading spaces\n" + "\n".join(f"line {i}: ünïcode ✓" for i in range(2500)) + "\nSENTINEL\n\n"@@ -75,95 +49,16 @@ def test_the_prompt_goes_on_stdin_byte_for_byte_and_never_on_argv(tmp_ws: Workspassert not (s.traj.dir / "task_prompt.md").exists()-def test_one_failure_vocabulary():- """Transient = a retry may get through; quota = a spent usage limit, never transient."""- for text in ("Attempt 3 failed with status 503", "API Error: 529 overloaded_error", "got status: UNAVAILABLE",- "Error: 429 RESOURCE_EXHAUSTED", "TypeError: fetch failed sending request", "read ECONNRESET",- "stream disconnected before completion", "got an empty response from the model"):- assert is_transient_failure("x", text), text- for text in ("SyntaxError: bad code", "at process.processTicksAndRejections (node:internal/process/task_queues:95)",- "killed by watchdog (idle) after 305s", "mcp tool build timed out", "the tool is unavailable", ""):- assert not is_transient_failure(text), text # a node stack trace says "internal" in lower case- for text in ("You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more credits",- "Claude AI usage limit reached|1790000000", "You've hit your limit · resets 3pm",- "insufficient_quota: You exceeded your current quota", "You're out of extra usage"):- assert is_quota_failure(text) and not is_transient_failure(text, "503"), text- # gemini's per-key rate limits say "quota" too, and the key pool rotates past them- gemini_429 = "Quota exceeded for quota metric 'Generate Content API requests per minute'"- assert not is_quota_failure(gemini_429) and not is_quota_failure("You exceeded your current quota")- assert is_rate_limited("status 429") and is_rate_limited("RESOURCE_EXHAUSTED") and not is_rate_limited("503")---def test_queued_invocations_share_the_run_deadline(tmp_ws: Workspace, monkeypatch):- clock = [100.0]- windows = []-- def watchdog(argv, **kwargs):- windows.append((kwargs["soft_timeout_s"], kwargs["hard_timeout_s"]))- return cli_common.CompletedProc(rc=0, stdout="", stderr="", duration_s=0)-- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", timeout_s=120,- hard_deadline_s=110.0), "fake")- monkeypatch.setattr(cli_common.time, "monotonic", lambda: clock[0])- monkeypatch.setattr(cli_common, "run_with_watchdog", watchdog)- clock[0] = 104.0 # waiting for a workspace lock consumed four seconds- invoke(s, ["unused"], {}, prompt="p")- clock[0] = 109.0- invoke(s, ["unused"], {}, prompt="p")- assert windows == [(6.0, 6.0), (1.0, 1.0)]- clock[0] = 111.0- expired = invoke(s, ["unused"], {}, prompt="p")- assert len(windows) == 2 and expired.timed_out and expired.duration_s == 0- assert "before CLI launch" in (s.traj.dir / "stderr.log").read_text()- assert [r["started"] for r in s.traj.read_transcript() if r["kind"] == "invoke"] == [True, True, False]---def test_standalone_invocation_keeps_its_activity_grace(tmp_ws: Workspace, monkeypatch):- windows = []-- def watchdog(argv, **kwargs):- windows.append((kwargs["soft_timeout_s"], kwargs["hard_timeout_s"]))- return cli_common.CompletedProc(rc=0, stdout="", stderr="", duration_s=0)-- monkeypatch.setattr(cli_common, "run_with_watchdog", watchdog)- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", timeout_s=120), "fake")- invoke(s, ["unused"], {}, prompt="p")- assert windows == [(120.0, 420.0)]--[email protected](20, method="thread")-def test_invoke_stops_an_active_cli_at_the_run_deadline(tmp_ws: Workspace, monkeypatch):- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", timeout_s=120,- hard_deadline_s=time.monotonic() + 1), "fake")- monkeypatch.setattr(cli_common, "POLL_S", 0.05)- code = "import time\nwhile True:\n print('still active', flush=True); time.sleep(0.05)"- started = time.monotonic()- proc = invoke(s, [sys.executable, "-c", code], dict(os.environ), prompt="p")- assert proc.timed_out and proc.killed_reason == "hard_timeout"- assert "still active" in proc.stdout- assert time.monotonic() - started < 10---def test_provider_wait_counts_each_burst_from_the_request_that_failed():- # progress at 0 and 100; a burst of three failures, back-off announced, then progress again- assert provider_wait([(10.0, 5.0), (20.0, 10.0), (35.0, 20.0)], end=500.0, progress=[0.0, 100.0]) == 55.0- # unannounced back-off (gemini-cli 5xx lines): a lower bound, the failed request's own time- assert provider_wait([(40.0, 0.0), (80.0, 0.0)], end=500.0, progress=[30.0, 120.0]) == 50.0- # a burst nothing followed — the CLI gave up, or the watchdog killed it mid-storm — runs to the end- assert provider_wait([(40.0, 0.0), (50.0, 0.0)], end=300.0, progress=[0.0, 30.0]) == 270.0- # progress between two failures splits them into two bursts- assert provider_wait([(10.0, 1.0), (30.0, 1.0)], end=100.0, progress=[0.0, 20.0, 50.0]) == 22.0- # a CLI that records no progress (agy's log): each burst from its first failure to the retry- assert provider_wait([(10.0, 4.0), (14.0, 6.0), (20.0, 10.0)], end=31.0, progress=None) == 20.0- assert provider_wait([], end=10.0, progress=[1.0]) == 0.0---def test_finish_session_carries_the_typed_failure_and_the_wait(tmp_ws: Workspace):- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", label="w"), "fake")- res = finish_session(s, ok=False, exit_reason="error", text="", usage=Usage(), transient=True, quota=True,- provider_wait_s=1e9)- assert res.quota and not res.transient # a spent usage limit is never "retry me"- assert 0.0 <= res.provider_wait_s <= res.duration_s # never more than the session lasted++++++++++def test_mcp_command_resolution(tmp_ws: Workspace):@@ -173,16 +68,13 @@ def test_mcp_command_resolution(tmp_ws: Workspace):job = AgentJob(workspace=str(tmp_ws.root), prompt="p", language="blender", track="static_object", round=2)cmd = mcp_command_for(tmp_ws, job)assert cmd[1:3] == ["-m", "codeverse3d.spatial.mcp_server"] and "--language" in cmd and cmd[cmd.index("--round") + 1] == "2"- job2 = AgentJob(workspace=str(tmp_ws.root), prompt="p", mcp_command=["python", "-m", "x"])- assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"]# a workspace .mcp.json NEVER wins: the agent works in that directory and could# otherwise choose what the next round's CLI launches (audit 2026-08-27)- materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", spatial_tools=True,+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c",mcp_command=default_mcp_command(tmp_ws, language="cadquery"))- assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"] # still the typed job+ assert mcp_command_for(tmp_ws, job) == cmd # still the typed job(tmp_ws.root / ".mcp.json").write_text(json.dumps({"mcpServers": {"3dcode": {"command": "/tmp/evil", "args": ["--pwn"]}}}))- assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"]assert "/tmp/evil" not in mcp_command_for(tmp_ws, job)diff --git a/harness/tests/agents/test_cli_write_scope.py b/harness/tests/agents/test_cli_write_scope.pyindex 8fcfbf65..03df5e21 100644--- a/harness/tests/agents/test_cli_write_scope.py+++ b/harness/tests/agents/test_cli_write_scope.py@@ -20,29 +20,6 @@ def _finish(s, *, ok: bool = True):# --------------------------------------------------------------------------- serialisation-def test_two_cli_sessions_on_one_workspace_are_serialized(tmp_ws: Workspace):- """Two threads, one workspace: the begin→finish windows must not overlap."""- windows: dict[str, tuple[float, float]] = {}- started = threading.Barrier(2)-- def session(name: str) -> None:- started.wait(timeout=30) # both threads race begin_session together- s = begin_session(_job(tmp_ws, name), "codex")- t0 = time.monotonic()- (tmp_ws.src / f"{name}.py").write_text(f"# {name}\n")- time.sleep(0.15) # long enough that overlapping windows would be seen- t1 = time.monotonic()- _finish(s)- windows[name] = (t0, t1)-- threads = [threading.Thread(target=session, args=(n,)) for n in ("a", "b")]- for t in threads:- t.start()- for t in threads:- t.join(timeout=60)- assert set(windows) == {"a", "b"}- (a0, a1), (b0, b1) = windows["a"], windows["b"]- assert a1 <= b0 or b1 <= a0, f"sessions interleaved: a={windows['a']} b={windows['b']}"# --------------------------------------------------------------------------- post-hoc scope@@ -106,32 +83,8 @@ def test_harness_control_files_are_never_agent_writable(scoped_ws: Workspace):assert [f.path for f in res.files_changed] == ["src/parts/leg.py"]-def test_control_files_are_enforced_even_with_an_empty_write_scope(scoped_ws: Workspace):- """The empty-scope early-out once left every control file writable."""- ws = scoped_ws- (ws.root / "AGENTS.md").write_text("# original rules\n")- s = begin_session(_job(ws, "free"), "codex") # no write_roots at all- (ws.src / "model.py").write_text("# rewritten entry\n") # in scope: everything non-control- (ws.root / "AGENTS.md").write_text("# forged rules\n")- res = _finish(s)- assert not res.ok and (ws.root / "AGENTS.md").read_text() == "# original rules\n"- assert (ws.src / "model.py").read_text() == "# rewritten entry\n", "ordinary writes stay allowed"-def test_entry_file_writes_need_ownership(scoped_ws: Workspace):- ws = scoped_ws- job = _job(ws, "part", edit_only=True, files_hint=["src/parts/seat.py"])- s = begin_session(job, "gemini-cli")- (ws.src / "model.py").write_text("# hijacked entry\n")- res = _finish(s)- assert not res.ok and (ws.src / "model.py").read_text() == "# entry\n"-- owned = _job(ws, "assemble", edit_only=True, files_hint=["src/parts/seat.py"],- always_writable=["src/model.py"])- s2 = begin_session(owned, "gemini-cli")- (ws.src / "model.py").write_text("# entry + import\n")- res2 = _finish(s2)- assert res2.ok and (ws.src / "model.py").read_text() == "# entry + import\n"def test_a_harness_owned_file_is_restored_when_the_agent_rewrites_it(tmp_ws, monkeypatch):@@ -149,3 +102,28 @@ def test_a_harness_owned_file_is_restored_when_the_agent_rewrites_it(tmp_ws, monassert (tmp_ws.root / owned).read_text().startswith("float aurora"), "harness file must be restored"assert (tmp_ws.src / "shader.frag").is_file(), "the agent's own file survives"assert not res.ok and any(owned in e for e in res.errors)+++def test_two_cli_sessions_on_one_workspace_are_serialized(tmp_ws: Workspace):+ """Two threads, one workspace: the begin→finish windows must not overlap."""+ windows: dict[str, tuple[float, float]] = {}+ started = threading.Barrier(2)++ def session(name: str) -> None:+ started.wait(timeout=30) # both threads race begin_session together+ s = begin_session(_job(tmp_ws, name), "codex")+ t0 = time.monotonic()+ (tmp_ws.src / f"{name}.py").write_text(f"# {name}\n")+ time.sleep(0.15) # long enough that overlapping windows would be seen+ t1 = time.monotonic()+ _finish(s)+ windows[name] = (t0, t1)++ threads = [threading.Thread(target=session, args=(n,)) for n in ("a", "b")]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=60)+ assert set(windows) == {"a", "b"}+ (a0, a1), (b0, b1) = windows["a"], windows["b"]+ assert a1 <= b0 or b1 <= a0, f"sessions interleaved: a={windows['a']} b={windows['b']}"diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.pyindex 3494691e..8a92c268 100644--- a/harness/tests/agents/test_codex.py+++ b/harness/tests/agents/test_codex.py@@ -3,13 +3,11 @@from __future__ import annotationsimport json-import shutil-import timefrom pathlib import Pathimport pytest-from codeverse3d.agents.backends import CodexAgent, parse_codex_jsonl, split_model_effort+from codeverse3d.agents.backends import CodexAgent, split_model_effortfrom codeverse3d.agents.cli_common import begin_sessionfrom codeverse3d.contracts.agent import AgentJobfrom codeverse3d.workspace import Workspace@@ -45,31 +43,13 @@ if mode == "usage_limit":if mode == "storm":events = events[:2] + [{"type": "error", "message": "stream disconnected before completion: 503 Service Unavailable"},{"type": "turn.failed", "error": {"message": "exceeded retry limit, last status: 503"}}]-if mode == "killed": # the turn never completes: the watchdog kills the session mid-turn- events = events[:5]for e in events:print(json.dumps(e)); sys.stdout.flush()-if mode == "killed":- import time; time.sleep(60)'''-def test_parse_jsonl():- ev = parse_codex_jsonl("\n".join(json.dumps(e) for e in EVENTS) + "\nnot json\n")- assert ev.thread_id == "th1" and ev.messages == ["Done."] and ev.tool_calls == 2 and ev.turns_completed == 1- u = ev.usage("gpt-6.1-sol")- assert u.input_tokens == 1000 and u.cached_tokens == 600 and u.output_tokens == 50 and u.tool_calls == 2-def test_reasoning_tokens_are_not_billed_twice():- """`output_tokens` already contains `reasoning_output_tokens` (Responses API)."""- ev = parse_codex_jsonl(json.dumps(- {"type": "turn.completed", "usage": {"input_tokens": 1000, "output_tokens": 9000,- "reasoning_output_tokens": 5000}}))- u = ev.usage("gpt-6.1-sol")- assert (u.output_tokens, u.thoughts_tokens) == (4000, 5000)- # 1000 in @ $2/M + 9000 billable output @ $10/M — the reasoning share counted once- assert u.cost_usd == pytest.approx(1000 * 2.0 / 1e6 + 9000 * 10.0 / 1e6)def test_argv_sandboxes_the_workspace_approves_mcp_calls_and_states_the_effort(tmp_ws: Workspace):@@ -83,11 +63,6 @@ def test_argv_sandboxes_the_workspace_approves_mcp_calls_and_states_the_effort(tassert "mcp_servers" not in " ".join(argv)# `codex exec` defaults to medium; every harness call states the effort insteadassert argv[argv.index("-c") + 1] == "model_reasoning_effort=high"- a = CodexAgent("gpt-6-sol@medium", binary="codex")- assert (a.model, a.reasoning_effort, a.id) == ("gpt-6-sol", "medium", "codex:gpt-6-sol")- assert "model_reasoning_effort=medium" in a.build_argv(s)- assert "model_reasoning_effort" not in " ".join(CodexAgent("gpt-6.1-sol", binary="codex",- reasoning_effort="").build_argv(s))assert split_model_effort("gpt-6-luna", "high") == ("gpt-6-luna", "high")with pytest.raises(ValueError, match="reasoning effort"):CodexAgent("gpt-6.1-sol", binary="codex", reasoning_effort="ludicrous")@@ -113,49 +88,3 @@ def test_fake_run_and_every_failure_is_typed(tmp_ws: Workspace, fake_bin, monkeymonkeypatch.setenv("FAKE_MODE", "storm")res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="t", timeout_s=30))assert not res.ok and res.transient and not res.quota and res.provider_wait_s == 0.0 # codex does not say- # killed mid-turn: codex reported no usage, so the session books an estimate from its stream- # (it used to book $0 — 1 of 357 recorded sessions, a 10-minute baseline among them)- monkeypatch.setenv("FAKE_MODE", "killed")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="k", timeout_s=3,- hard_deadline_s=time.monotonic() + 3))- assert not res.ok and res.exit_reason == "timeout" and res.usage_estimated- # 3 requests (two items + the one in flight), each re-reading a context of ≥ the 20k-token codex system prompt- assert 60_000 < res.usage.input_tokens < 61_000 and 0 < res.usage.cached_tokens < res.usage.input_tokens- assert res.usage.cost_usd > 0 and res.usage.tool_calls == 2- assert json.loads((Path(res.transcript_path).parent / "result.json").read_text())["usage_estimated"] is True---def test_live_codex_mcp_tool_call_is_not_cancelled(tmp_ws: Workspace):- """Regression: without default_tools_approval_mode=approve codex auto-cancels every 3dcode MCP call."""- if not shutil.which("codex"):- pytest.skip("codex not installed")- import trimesh-- from codeverse3d.agents.cli_common import default_mcp_command- from codeverse3d.agents.materialize import materialize_workspace-- trimesh.creation.box().export(tmp_ws.artifacts / "object.glb")- materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", spatial_tools=True,- mcp_command=default_mcp_command(tmp_ws, language="threejs"))- a = CodexAgent("")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Call the 3dcode MCP tool `measure` exactly once, then reply with the "- "measured part count and DONE. Do not edit files.", timeout_s=300, label="mcpt",- spatial_tools=True, language="threejs"))- assert res.ok, res.errors- events = [json.loads(ln) for ln in (Path(res.transcript_path).parent / "stdout.jsonl").read_text().splitlines()- if ln.startswith("{")]- calls = [e["item"] for e in events if e.get("type") == "item.completed" and (e.get("item") or {}).get("type") == "mcp_tool_call"]- assert calls and all(c.get("status") != "failed" for c in calls), calls---def test_live_codex_tiny(tmp_ws: Workspace):- if not shutil.which("codex"):- pytest.skip("codex not installed")- a = CodexAgent("gpt-6.1-sol")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Create src/hello.txt containing exactly 'hi'. Reply DONE.",- timeout_s=300, label="live", spatial_tools=False))- assert res.ok, res.errors- assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"- assert res.usage.input_tokens > 0diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.pyindex 5f5b4b38..61852889 100644--- a/harness/tests/agents/test_materialize.py+++ b/harness/tests/agents/test_materialize.py@@ -2,7 +2,6 @@from __future__ import annotations-import jsonimport osimport subprocessimport sys@@ -18,94 +17,21 @@ from codeverse3d.workspace import WorkspaceCONTRACT = "## blender contract\nWrite pure bpy into src/model.py."-def _mat(ws: Workspace, kind: str = "agy", spatial: bool = True):- return materialize_workspace(ws, agent_kind=kind, contract_md=CONTRACT, spatial_tools=spatial,+def _mat(ws: Workspace, kind: str = "agy"):+ return materialize_workspace(ws, agent_kind=kind, contract_md=CONTRACT,mcp_command=default_mcp_command(ws))-def test_bodies_document_only_this_tracks_tools(tmp_ws: Workspace):- """Scene/graphics agents were once taught dead-end object-GLB tools (V11a)."""- tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "scene", "language": "scene_threejs", "prompt": "p"}))- _mat(tmp_ws, kind="agy")- body = (tmp_ws.root / "AGENTS.md").read_text()- for absent in ("`joint_sweep`", "`gl_probe`", "`texture_pass`", "`render_sheet`", "`check_contract`", "`cross_section`"):- assert absent not in body, absent- assert "`scene_views`" in body and "`scene_probe`" in body and "`build`" in body- assert "check_contract` to prove" not in body, "the object workflow sentence must not survive filtering"- # an object workspace keeps the full object toolset and its workflow sentence- tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "p"}))- _mat(tmp_ws, kind="agy")- body = (tmp_ws.root / "AGENTS.md").read_text()- assert "`render_sheet`" in body and "`measure`" in body and "`check_contract`" in body- # no spec.json (bare workspaces in tests/tools): unfiltered fallback, nothing crashes- tmp_ws.spec_path.unlink()- _mat(tmp_ws, kind="agy")- assert "`joint_sweep`" in (tmp_ws.root / "AGENTS.md").read_text()---def test_no_mcp_config_and_no_gemini_body_is_written_into_the_workspace(tmp_ws: Workspace):- """3dcode reaches each CLI through a harness-owned per-session file (audit 2026-08-27), and- agy reads GEMINI.md as well as AGENTS.md — a third copy of the body would be loaded twice."""- for kind in ("agy", "claude-code", "codex"):- _mat(tmp_ws, kind=kind)- assert not (tmp_ws.root / ".mcp.json").exists(), "claude-code writes its own per-session mcp.json"- assert not (tmp_ws.root / ".gemini").exists() and not (tmp_ws.root / "GEMINI.md").exists()- assert {p.name for p in tmp_ws.root.glob("*.md")} >= {"AGENTS.md", "CLAUDE.md"}---def test_the_body_is_rules_tools_and_contract_and_never_mentions_a_cookbook(tmp_ws: Workspace):- """No language ships a cookbook (D107, owner 2026-10-15): the body is Hard rules → Spatial tools →- Language contract, says nothing about a cookbook (a note that one is missing only sends the agent- looking), and writes nothing under ``.3dcode/`` for the agent to read."""- tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "p"}))- _mat(tmp_ws)- body = (tmp_ws.root / "AGENTS.md").read_text()- assert "cookbook" not in body.lower()- assert body.index("## Hard rules") < body.index("## Spatial tools") < body.index("## Language contract")- assert not (tmp_ws.root / ".3dcode").exists() or not any((tmp_ws.root / ".3dcode").iterdir())-----def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):- """Ignored paths are hidden from the agent: census and tool renders stay readable."""- import fnmatch-- from codeverse3d.agents.materialize import IGNORE_LINES-- _mat(tmp_ws)-- def ignored(rel: str, lines: tuple[str, ...]) -> bool:- for pat in lines:- if pat.endswith("/"):- if rel.startswith(pat) or f"/{pat}" in f"/{rel}":- return True- elif fnmatch.fnmatch(rel, pat):- return True- return False-- for f in (".antigravityignore",):- lines = tuple(ln for ln in (tmp_ws.root / f).read_text().splitlines() if ln.strip())- assert lines == IGNORE_LINES- assert "artifacts/" not in lines and "trajectories/" in lines- for readable in ("artifacts/census.json", "artifacts/build.json", "artifacts/measurement.json",- "artifacts/gates/r00/contract_tool.json", "artifacts/tool_renders/r00_ab/sheet.png",- "src/model.py", ".3dcode/images/ref.png"):- assert not ignored(readable, lines), readable- for hidden in ("artifacts/renders/r00/sheet.png", "trajectories/baseline_r00/stdout.json",- "trajectories/baseline_r00/prompt.md", "trajectories/baseline_r00/agy.log",- "trajectories/baseline_r00/stderr.log", "node_modules/three/x.js", ".git/HEAD"):- assert ignored(hidden, lines), hidden---def test_kind_specific_tool_hint_and_spatial_disabled_documents_absence(tmp_ws: Workspace):- _mat(tmp_ws, kind="claude-code")- assert "mcp__3dcode__" in (tmp_ws.root / "CLAUDE.md").read_text()- _mat(tmp_ws, kind="agy")- body = (tmp_ws.root / "AGENTS.md").read_text()- assert "MCP server `3dcode`" in body and "codeverse3d.cli.main tools" not in body # always MCP: no shell fallback- _mat(tmp_ws, spatial=False)- assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()++++++++++def test_codex_mcp_preserves_explicit_engine_selection(tmp_path, monkeypatch):diff --git a/harness/tests/agents/test_shared_tree.py b/harness/tests/agents/test_shared_tree.pyindex baf598e2..54443279 100644--- a/harness/tests/agents/test_shared_tree.py+++ b/harness/tests/agents/test_shared_tree.py@@ -9,22 +9,15 @@ the attribution and the activity watch to ``files_hint``.from __future__ import annotations-import sys-from pathlib import Path-import pytestfrom pydantic import ValidationErrorfrom codeverse3d.agents.cli_common import (- activity_paths,- attribute_changes,begin_session,finish_session,- run_with_watchdog,)-from codeverse3d.contracts.agent import AgentJob, FileChange+from codeverse3d.contracts.agent import AgentJobfrom codeverse3d.contracts.common import Usage-from codeverse3d.tracks.generation import GenerationTask, _attributed_fallbackfrom codeverse3d.workspace import WorkspaceENV, ASSET = "src/env.js", "src/assets/lantern.js"@@ -41,12 +34,6 @@ def _job(ws: Workspace, **kw) -> AgentJob:return AgentJob(workspace=str(ws.root), prompt="p", label="env", round=0, files_hint=[ENV], **kw)-def test_attribution_under_only_drops_what_the_hint_does_not_name():- files = [FileChange(path=ENV, status="modified"), FileChange(path=ASSET, status="modified"),- FileChange(path="src/lib/x.js", status="added")]- assert [f.path for f in attribute_changes(files, write_roots=["src"])] == [ENV, ASSET, "src/lib/x.js"]- assert [f.path for f in attribute_changes(files, write_roots=["src"], only=[ENV])] == [ENV]- assert [f.path for f in attribute_changes(files, write_roots=["src"], only=["src/assets/"])] == [ASSET]def test_a_shared_tree_session_that_wrote_nothing_is_not_credited_with_a_concurrent_write(tmp_ws: Workspace):@@ -58,61 +45,12 @@ def test_a_shared_tree_session_that_wrote_nothing_is_not_credited_with_a_concurrassert (tmp_ws.root / ASSET).read_text().startswith("// the asset single-shot"), "never reverted: not edit_only"-def test_a_shared_tree_session_that_wrote_its_file_is_credited_with_it_alone(tmp_ws: Workspace):- _tree(tmp_ws)- s = begin_session(_job(tmp_ws, shared_tree=True), "agy")- (tmp_ws.root / ENV).write_text("// the real env\n")- (tmp_ws.root / ASSET).write_text("// concurrent\n")- res = finish_session(s, ok=True, exit_reason="completed", text="", usage=Usage())- assert [f.path for f in res.files_changed] == [ENV]-def test_a_plain_session_still_owns_the_whole_diff(tmp_ws: Workspace):- """Not shared_tree: a refine session that also fixed a file outside its hint keeps it (a narrower- attribution would turn real work into ``ok=False`` and a RoundFailed)."""- _tree(tmp_ws)- s = begin_session(_job(tmp_ws), "agy")- (tmp_ws.root / ASSET).write_text("// fixed here too\n")- res = finish_session(s, ok=True, exit_reason="completed", text="", usage=Usage())- assert [f.path for f in res.files_changed] == [ASSET]-def test_the_generation_fallback_attributes_the_same_way(tmp_ws: Workspace):- _tree(tmp_ws)- before = tmp_ws.head()- (tmp_ws.root / ASSET).write_text("// concurrent\n")- shared = GenerationTask(label="env", prompt="p", files_hint=[ENV], shared_tree=True)- plain = shared.model_copy(update={"shared_tree": False})- assert _attributed_fallback(tmp_ws, shared, before) == []- assert [f.path for f in _attributed_fallback(tmp_ws, plain, before)] == [ASSET]-def test_a_shared_tree_session_watches_only_its_own_files(tmp_ws: Workspace):- _tree(tmp_ws)- s = begin_session(_job(tmp_ws, shared_tree=True), "agy")- try:- assert activity_paths(s) == [tmp_ws.root / ENV]- finally:- finish_session(s, ok=False, exit_reason="error", text="", usage=Usage())- s = begin_session(_job(tmp_ws), "agy")- try:- assert activity_paths(s) == [tmp_ws.src, tmp_ws.public]- finally:- finish_session(s, ok=False, exit_reason="error", text="", usage=Usage())---def test_writes_to_other_files_do_not_keep_a_watched_file_session_alive(tmp_path: Path):- """The watchdog with a FILE as its activity path: a sibling's writes beside it are not activity."""- src = tmp_path / "src"- src.mkdir()- own = src / "env.js"- own.write_text("x")- code = ("import time\n"- f"p = {str(src / 'asset.js')!r}\n"- "for i in range(40):\n open(p, 'a').write('x'); time.sleep(0.25)\n")- res = run_with_watchdog([sys.executable, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=0.5, idle_grace_s=1.0,- hard_timeout_s=30, poll_s=0.1, scan_s=0.2, activity_dirs=[own])- assert res.killed_reason == "idle" and res.duration_s < 8, (res.killed_reason, res.duration_s)def test_shared_tree_needs_a_hint_and_excludes_edit_only(tmp_ws: Workspace):diff --git a/harness/tests/agents/test_tool_trace.py b/harness/tests/agents/test_tool_trace.pyindex 9fb6d72c..d6f5091a 100644--- a/harness/tests/agents/test_tool_trace.py+++ b/harness/tests/agents/test_tool_trace.py@@ -6,78 +6,11 @@ import jsonimport sqlite3from codeverse3d.agents.backends import (- ClaudeCodeAgent,- ClaudeStream,agy_tool_calls,)-from codeverse3d.agents.cli_common import (- TOOL_CALL_ROW,- TOOL_TRACE_ROW,- TRACE_ARG_CHARS,- ToolCall,- begin_session,- record_tool_calls,-)-from codeverse3d.contracts.agent import AgentJob-from codeverse3d.workspace import WorkspaceWS = "/tmp/probe/live/claude1"-# --------------------------------------------------------------------------- claude-code-CLAUDE_STREAM = [- {"type": "system", "subtype": "init", "cwd": WS, "session_id": "893f6373", "model": "claude-opus-5-5",- "claude_code_version": "2.1.280", "tools": ["Bash", "Read", "Skill"],- "skills": ["c3d-bbox-contract", "c3d-blender-forms", "c3d-part-contact", "c3d-repeats-and-mirrors",- "zz-c3d-read-control", "dataviz"]},- {"type": "system", "subtype": "thinking_tokens", "estimated_tokens": 12},- {"type": "assistant", "message": {"model": "claude-opus-5-5", "id": "msg_1", "role": "assistant", "content": [- {"type": "text", "text": "I'll start by loading the mandatory skills for this task"}]}},- {"type": "assistant", "message": {"model": "claude-opus-5-5", "id": "msg_1", "role": "assistant", "content": [- {"type": "tool_use", "id": "toolu_01KmUt", "name": "Skill", "input": {"skill": "c3d-bbox-contract"},- "caller": {"type": "direct"}}]}},- {"type": "user", "message": {"role": "user", "content": [- {"type": "tool_result", "tool_use_id": "toolu_01KmUt", "content": "Launching skill: c3d-bbox-contract"}]},- "tool_use_result": {"success": True, "commandName": "c3d-bbox-contract"}},- {"type": "assistant", "message": {"model": "claude-opus-5-5", "id": "msg_2", "role": "assistant", "content": [- {"type": "tool_use", "id": "toolu_02", "name": "Read",- "input": {"file_path": f"{WS}/.claude/skills/c3d-bbox-contract/references/worked_example.md"}}]}},- {"type": "user", "message": {"role": "user", "content": [- {"type": "tool_result", "tool_use_id": "toolu_02", "content": "..."}]}},- {"type": "assistant", "message": {"model": "claude-opus-5-5", "id": "msg_3", "role": "assistant", "content": [- {"type": "tool_use", "id": "toolu_03", "name": "mcp__3dcode__check_contract", "input": {}}]}},- {"type": "user", "message": {"role": "user", "content": [- {"type": "tool_result", "tool_use_id": "toolu_03", "is_error": True,- "content": "check_contract: plan.json not found in the workspace"}]}},- {"type": "result", "subtype": "success", "is_error": False, "num_turns": 25, "result": "done",- "session_id": "893f6373", "total_cost_usd": 0.95, "usage": {"input_tokens": 32, "output_tokens": 30106}},-]---def _stream_text(events) -> str:- return "\n".join(json.dumps(e) for e in events) + "\n"---def test_claude_stream_folds_the_index_the_skill_calls_and_their_failures():- s = ClaudeStream()- for line in _stream_text(CLAUDE_STREAM).splitlines():- s.feed(line)- assert s.skills[:5] == ["c3d-bbox-contract", "c3d-blender-forms", "c3d-part-contact",- "c3d-repeats-and-mirrors", "zz-c3d-read-control"]- assert [(c.tool, c.skill, c.failed) for c in s.calls] == [- ("Skill", "c3d-bbox-contract", False), ("Read", "", False), ("mcp__3dcode__check_contract", "", True)]- s.feed("not json") # chatter and a chunked >1 MB line are skipped, never raised- s.feed('{"type": "assistant", "message": {"content": [')- assert len(s.calls) == 3---def test_claude_is_launched_streaming(tmp_ws: Workspace):- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "claude-code")- argv = ClaudeCodeAgent("sonnet", binary="claude").build_argv(s)- assert "Skill" in argv[argv.index("--allowedTools") + 1].split(",")- assert "--disable-slash-commands" not in argv # claude-code: "Disable all skills"- assert argv[argv.index("--output-format") + 1] == "stream-json" and "--verbose" in argv--# --------------------------------------------------------------------------- agydef _pb(field: int, payload: bytes) -> bytes:"""One length-delimited protobuf field (the only wire type the fixture needs)."""@@ -118,18 +51,3 @@ def test_agy_tool_calls_come_out_of_its_conversation_database(tmp_path):# --------------------------------------------------------------------------- the rows-def test_record_tool_calls_writes_compact_rows_and_one_closing_marker(tmp_ws: Workspace):- s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "codex")- n = record_tool_calls(s, [ToolCall("Write", {"file_path": "src/a.py", "content": "x" * 5000}),- ToolCall("Skill", {"skill": "c3d-part-contact"}, skill="c3d-part-contact"),- ToolCall("apply", {"changes": [{"path": "src/b.py"}]}, failed=True)],- source="unit", skills_index=["c3d-part-contact"])- rows = s.traj.read_transcript()- assert n == 3 and [r["kind"] for r in rows] == [TOOL_CALL_ROW] * 3 + [TOOL_TRACE_ROW]- assert rows[0]["args"]["file_path"] == "src/a.py" and len(rows[0]["args"]["content"]) == TRACE_ARG_CHARS + 1- assert rows[1]["skill"] == "c3d-part-contact" and "skill" not in rows[0] and "failed" not in rows[0]- assert rows[2]["failed"] is True and rows[2]["args"]["changes"] == '[{"path": "src/b.py"}]'- assert rows[3] == {**rows[3], "calls": 3, "source": "unit", "skills_index": ["c3d-part-contact"]}- # a session that called nothing still closes its trace: silence is then a fact- assert record_tool_calls(s, [], source="unit") == 0- assert s.traj.read_transcript()[-1]["calls"] == 0diff --git a/harness/tests/agents/test_transcript.py b/harness/tests/agents/test_transcript.pydeleted file mode 100644index 5d5bd1d6..00000000--- a/harness/tests/agents/test_transcript.py+++ /dev/null@@ -1,27 +0,0 @@-"""codeverse3d/agents/transcript.py — the per-session transcript budget."""--from __future__ import annotations--from pathlib import Path--from codeverse3d.agents import cli_common as tr-from codeverse3d.agents.cli_common import Trajectory---def test_the_transcript_stops_at_its_budget_with_a_marker_row(tmp_path: Path, monkeypatch):- """Rows were byte-capped one by one but the FILE was not: a child emitting 100k- lines wrote a 27 MB transcript.jsonl (~406 MB at the 4000-char row cap)."""- monkeypatch.setattr(tr, "LINE_BUDGET_ROWS", 5)- t = Trajectory(tmp_path / "traj")- for i in range(20):- t.append("stdout", line=f"line {i}")- rows = t.read_transcript()- assert [r["kind"] for r in rows] == ["stdout"] * 5 + ["line_budget_exhausted"]- assert rows[-1]["rows"] == 5-- monkeypatch.setattr(tr, "LINE_BUDGET_BYTES", 400)- t2 = Trajectory(tmp_path / "traj2")- for _ in range(50):- t2.append("stdout", line="x" * 100)- rows2 = t2.read_transcript()- assert len(rows2) < 6 and rows2[-1]["kind"] == "line_budget_exhausted"diff --git a/harness/tests/agents/test_watchdog.py b/harness/tests/agents/test_watchdog.pyindex ab06a1a5..238823f1 100644--- a/harness/tests/agents/test_watchdog.py+++ b/harness/tests/agents/test_watchdog.py@@ -22,18 +22,6 @@ def test_hard_timeout_kills_active_process(tmp_path: Path):assert time.time() - t0 < 15-def test_file_mtime_counts_as_activity(tmp_path: Path):- src = tmp_path / "src"- src.mkdir()- # silent process that touches a file every 0.5s for 3s; soft=1 grace=1.5 → alive until done- code = (- "import time\n"- f"p = {str(src / 'a.txt')!r}\n"- "for i in range(6):\n open(p, 'a').write('x'); time.sleep(0.5)\n"- )- res = run_with_watchdog([PY, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=1, idle_grace_s=1.5,- hard_timeout_s=30, poll_s=0.2, scan_s=0.3, activity_dirs=[src])- assert res.rc == 0 and not res.timed_out@pytest.mark.timeout(60, method="thread")diff --git a/harness/tests/blender_cadquery/conftest.py b/harness/tests/blender_cadquery/conftest.pyindex 618e61a2..2e83903f 100644--- a/harness/tests/blender_cadquery/conftest.py+++ b/harness/tests/blender_cadquery/conftest.py@@ -2,6 +2,7 @@from __future__ import annotations+import importlib.utilimport shutilimport pytest@@ -41,8 +42,4 @@ def blender_bin() -> str:def has_cadquery() -> bool:- try:- import cadquery # noqa: F401- except ImportError:- return False- return True+ return importlib.util.find_spec("cadquery") is not Nonediff --git a/harness/tests/blender_cadquery/test_artifact_stage.py b/harness/tests/blender_cadquery/test_artifact_stage.pyindex 0ebbd909..e43b8662 100644--- a/harness/tests/blender_cadquery/test_artifact_stage.py+++ b/harness/tests/blender_cadquery/test_artifact_stage.py@@ -5,42 +5,22 @@ from __future__ import annotationsfrom codeverse3d.workspace import Workspace-def _seed(ws: Workspace) -> None:- (ws.artifacts / "build.json").write_text('{"ok": true}')- (ws.artifacts / "object.glb").write_bytes(b"old glb")- meshes = ws.artifacts / "meshes"- meshes.mkdir(exist_ok=True)- (meshes / "old.glb").write_bytes(b"old mesh")--def test_stage_invalidates_on_enter_discards_on_exit_and_promotes(tmp_ws: Workspace) -> None:- _seed(tmp_ws)- with tmp_ws.stage_artifacts("build.json", "object.glb", "meshes") as stage:- # the previous round's outputs are gone BEFORE any work (or early return) happens- assert not (tmp_ws.artifacts / "build.json").exists()- assert not (tmp_ws.artifacts / "object.glb").exists()- assert not (tmp_ws.artifacts / "meshes").exists()- assert stage.staging_dir.is_dir() and stage.staging_dir.parent.name == ".staging"+ (tmp_ws.artifacts / "build.json").write_text('{"ok": true}')+ (tmp_ws.artifacts / "object.glb").write_bytes(b"old glb")+ with tmp_ws.stage_artifacts("build.json", "object.glb") as stage:+ assert not (tmp_ws.artifacts / "build.json").exists() and not (tmp_ws.artifacts / "object.glb").exists() # before any workstage.path("object.glb").write_bytes(b"half built") # never promoted- # exit without promote: canonical stays absent, staging discarded- assert not (tmp_ws.artifacts / "object.glb").exists()- staging_root = tmp_ws.artifacts / ".staging"- assert not staging_root.exists() or not any(staging_root.iterdir())-- # the default promote skips names never written+ assert not (tmp_ws.artifacts / "object.glb").exists() # exit without promote: canonical stays absentwith tmp_ws.stage_artifacts("build.json", "object.stl") as stage:stage.path("build.json").write_text('{"ok": true}')- published = stage.promote() # object.stl was never staged → skipped, not an error+ published = stage.promote() # object.stl was never staged: skipped, not an errorassert [p.name for p in published] == ["build.json"]- assert not (tmp_ws.artifacts / "object.stl").exists()-- # promote replaces an existing dir- meshes = tmp_ws.artifacts / "meshes"+ meshes = tmp_ws.artifacts / "meshes" # promote replaces an existing dirmeshes.mkdir()(meshes / "old.glb").write_bytes(b"old")- stage = tmp_ws.stage_artifacts("meshes") # standalone (no enter → no invalidation)+ stage = tmp_ws.stage_artifacts("meshes")stage.path("meshes").mkdir()(stage.path("meshes") / "new.glb").write_bytes(b"new")stage.promote()- stage.discard()- assert [p.name for p in meshes.iterdir()] == ["new.glb"] # old members do not survive+ assert [p.name for p in meshes.iterdir()] == ["new.glb"]diff --git a/harness/tests/blender_cadquery/test_blender_layout.py b/harness/tests/blender_cadquery/test_blender_layout.pyindex 8586e4f1..9ee732c0 100644--- a/harness/tests/blender_cadquery/test_blender_layout.py+++ b/harness/tests/blender_cadquery/test_blender_layout.py@@ -61,21 +61,6 @@ def test_lint_workspace_layout_rules(tmp_ws) -> None:assert all(f.fix_hint for f in rep.errors)-def test_lint_workspace_missing_entry_too_deep_source_and_forbidden_calls(tmp_ws) -> None:- assert not lint_workspace(tmp_ws).passed # no model.py at all- # a literal nested past the parser's stack is a finding, not a MemoryError that kills the round- deep = "x = " + "-" * 20_000 + "1\n"- _write(tmp_ws, "src/model.py", deep)- _write(tmp_ws, "src/parts/seat.py", deep)- rep = lint_workspace(tmp_ws)- assert not rep.passed and {f.target for f in rep.errors} >= {"src/model.py", "src/parts/seat.py"}- _write(tmp_ws, "src/model.py", MODEL)- _write(tmp_ws, "src/parts/seat.py", SEAT + "\nbpy.ops.render.render()\n")- _write(tmp_ws, "src/parts/leg.py", LEG)- rep = lint_workspace(tmp_ws)- assert any(f.target == "src/parts/seat.py" and "bpy.ops.render.render" in f.message for f in rep.errors)--def _load_wrapper():spec = importlib.util.spec_from_file_location("run_bpy_under_test", WRAPPER)mod = importlib.util.module_from_spec(spec)@@ -106,16 +91,6 @@ def test_wrapper_maps_errors_to_the_failing_src_file(tmp_path, monkeypatch) -> Ndel sys.modules[name]err = run(str(src / "model.py"))assert err["error_type"] == "SyntaxError" and err["error_file"] == "src/parts/leg.py" and err["error_line"] == 1- # missing builder → hint names the file and the function- (src / "parts" / "leg.py").write_text("def build_legs():\n pass\n")- err = run(str(src / "model.py"))- assert err["error_type"] == "ImportError" and err["error_file"] == "src/model.py" and err["error_line"] == 1- assert "def build_leg()" in err["error_message"] and "parts/leg.py" in err["error_message"]- # missing module → hint says to create the file- (src / "model.py").write_text("import math\nfrom parts.armrest import build_armrest\n")- err = run(str(src / "model.py"))- assert err["error_type"] in ("ModuleNotFoundError", "ImportError")- assert err["error_line"] == 2 and "src/parts/armrest.py" in err["error_message"](src / "model.py").write_text("import sys\nsys.exit(0)\n") # not a failure: the scene is what was builtassert wrapper.run_script(str(src / "model.py")) == (None, None)for name in [m for m in sys.modules if m == "parts" or m.startswith("parts.")]:diff --git a/harness/tests/blender_cadquery/test_blender_lint.py b/harness/tests/blender_cadquery/test_blender_lint.pyindex b2a250d9..800725e4 100644--- a/harness/tests/blender_cadquery/test_blender_lint.py+++ b/harness/tests/blender_cadquery/test_blender_lint.py@@ -5,40 +5,11 @@ from __future__ import annotationsfrom codeverse3d.contracts.artifacts import Severityfrom codeverse3d.languages.blender import lint_blender_source-GOOD = '''-import bpy-import bmesh-from mathutils import Vector--bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5), scale=(1, 1, 1))-obj = bpy.context.object-obj.name = "Body"-bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)-mat = bpy.data.materials.new("BodyMat")-mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (1, 0, 0, 1)-obj.data.materials.append(mat)-bm = bmesh.new()-bm.from_mesh(obj.data)-bm.verts.ensure_lookup_table()-v = bm.verts[0]-bm.free()-with bpy.context.temp_override(object=obj):- bpy.ops.object.modifier_apply(modifier='Bevel')-'''-def _msgs(report, sev=None):return [f.message for f in report.findings if sev is None or f.severity == sev]-def test_good_script_passes() -> None:- r = lint_blender_source(GOOD)- assert r.gate == "lint:blender" and r.passed, _msgs(r)- assert not _msgs(r, Severity.ERROR)- assert any("Body" in m for m in _msgs(r, Severity.INFO))- assert not any("modifier_apply" in m for m in _msgs(r, Severity.WARN)) # temp_override is the fix, not a pitfall--def test_missing_bpy_import_and_forbidden_calls() -> None:src = "import os\nimport subprocess\nbpy.ops.render.render()\nbpy.ops.export_scene.gltf(filepath='x')\nbpy.ops.wm.save_mainfile()\nopen('f').read()\nos.system('ls')\n"r = lint_blender_source(src)@@ -52,28 +23,6 @@ def test_missing_bpy_import_and_forbidden_calls() -> None:assert any("subprocess" in m for m in errs)-def test_bmesh_lookup_table_missing_is_error_even_if_mentioned_in_comment() -> None:- src = "import bpy, bmesh\nbm = bmesh.new()\nv = bm.verts[0] # forgot ensure_lookup_table\n"- r = lint_blender_source(src)- f = [x for x in r.findings if "ensure_lookup_table" in x.message]- assert f and f[0].severity == Severity.ERROR and f[0].data["line"] == 3 and "ensure_lookup_table()" in f[0].fix_hint---def test_bmesh_lookup_rule_ignores_non_bmesh_bases() -> None:- """Finding: e.verts[0] (BMEdge) / me.edges[i] (Mesh) never need ensure_lookup_table."""- src = ("import bpy, bmesh\n"- "bm = bmesh.new()\n"- "side = [e for e in bm.edges if abs(e.verts[0].co.z - e.verts[1].co.z) > 1e-9]\n"- "o = bpy.context.object\n"- "o.data.edges[0].use_seam = True\n"- "me = o.data\n"- "me.edges[2].use_seam = True\n"- "bm.free()\n")- r = lint_blender_source(src)- assert not any("ensure_lookup_table" in f.message for f in r.findings), _msgs(r)- assert r.passed--def test_removed_bsdf_inputs() -> None:"""A removed input is an ERROR unless its access sits under `'<key>' in x.inputs` (theversion-proof `elif` 18 of 984 recorded scripts use, e.g. the laptop_urdf model.py)."""@@ -88,32 +37,6 @@ def test_removed_bsdf_inputs() -> None:assert "Specular IOR Level" in f[0].fix_hint-def test_valid_bsdf_inputs_not_flagged() -> None:- """Finding: 'Anisotropic' and 'Specular Tint' exist in Blender 4.x/5.0.1 — never ERROR."""- src = ("import bpy\nm = bpy.data.materials.new('x')\nb = m.node_tree.nodes['Principled BSDF']\n"- "b.inputs['Anisotropic'].default_value = 0.6\n"- "b.inputs['Specular Tint'].default_value = (1, 1, 1, 1)\n")- r = lint_blender_source(src)- assert r.passed and not _msgs(r, Severity.ERROR), _msgs(r)- tint = [f for f in r.findings if "Specular Tint" in f.message]- assert tint and tint[0].severity == Severity.INFO and "4-tuple" in tint[0].fix_hint---def test_camera_light_and_render_settings_warn() -> None:- src = "import bpy\nbpy.ops.object.light_add(type='SUN')\ncam = bpy.data.cameras.new('c')\nbpy.context.scene.render.engine = 'CYCLES'\nbpy.context.scene.camera = None\n"- r = lint_blender_source(src)- assert r.passed # warnings only- w = _msgs(r, Severity.WARN)- assert any("light_add" in m for m in w) and any("cameras.new" in m for m in w) and any("render settings" in m for m in w)---def test_a_join_after_setting_the_active_object_is_not_warned() -> None:- """A join that sets the active object first (one joined object per urdf link) — what the join warning asks for."""- src = ("import bpy\nobjs = [o for o in bpy.data.objects]\nfor o in objs: o.select_set(True)\n"- "bpy.context.view_layer.objects.active = objs[0]\nbpy.ops.object.join()\n")- assert not any("join" in m for m in _msgs(lint_blender_source(src), Severity.WARN))--def test_headless_pitfalls() -> None:src = ("import bpy\nbpy.ops.mesh.primitive_cube_add(scale=(1, 2, 3))\nbpy.ops.object.transform_apply(scale=True)\n""bpy.ops.object.modifier_apply(modifier='Bevel')\nbpy.ops.object.join()\nsel = bpy.context.selected_objects\n"@@ -142,11 +65,3 @@ def test_blender_52_gn_inputs_and_fast_solver_are_errors() -> None: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/blender_cadquery/test_blender_live_gates.py b/harness/tests/blender_cadquery/test_blender_live_gates.pyindex 78b3b4fd..bc5d6bed 100644--- a/harness/tests/blender_cadquery/test_blender_live_gates.py+++ b/harness/tests/blender_cadquery/test_blender_live_gates.py@@ -12,31 +12,6 @@ from codeverse3d.languages.blender import REMOVED_BSDF_INPUTS, BlenderRuntime, bpytestmark = pytest.mark.blender-BSDF_PROBE = (- "import bpy, json\n"- "m = bpy.data.materials.new('probe')\n"- "b = m.node_tree.nodes['Principled BSDF']\n"- "print('BSDF_INPUTS=' + json.dumps([i.name for i in b.inputs]))\n"-)---def test_lint_bsdf_table_matches_real_principled_inputs(blender_bin) -> None:- """Finding: 'Anisotropic'/'Specular Tint' are REAL inputs in Blender 5.0.1 — lint must agree."""- proc = subprocess.run([blender_bin, "-b", "--factory-startup", "--python-expr", BSDF_PROBE],- capture_output=True, text=True, timeout=120, env=blender_env())- line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("BSDF_INPUTS="))- real = set(json.loads(line[len("BSDF_INPUTS="):]))- # every key the lint calls removed must actually be absent (no false 'KeyError at runtime')- still_there = {k for k in REMOVED_BSDF_INPUTS if k in real}- assert not still_there, f"lint flags valid Principled BSDF inputs: {sorted(still_there)}"- # the names the lint (and the contract docs) steer agents toward must all exist- expected = {"Anisotropic", "Specular Tint", "Specular IOR Level", "Subsurface Weight",- "Transmission Weight", "Coat Weight", "Coat Roughness", "Sheen Weight",- "Emission Color", "Emission Strength", "Base Color", "Roughness", "Metallic"}- assert expected <= real, f"missing from Blender: {sorted(expected - real)}"--#: one build for three census findings: excluded-collection objects, unused / past-the-end#: material slots (read off the EVALUATED mesh inside Blender, not a fixture), and a lightCENSUS_MODEL = '''import bmesh@@ -58,12 +33,6 @@ def part(name, n_slots, location):part("FlatArm", 3, (0, 0, 0.1)) # 3 materials, every polygon on slot 0-painted = part("PaintedArm", 3, (0.5, 0, 0.1))-for i, poly in enumerate(painted.data.polygons):- poly.material_index = i % 3-overrun = part("OverrunArm", 1, (1.0, 0, 0.1))-for poly in overrun.data.polygons:- poly.material_index = 2 # past the last slot: Blender clampsbpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5))main = bpy.context.object@@ -97,19 +66,41 @@ def test_census_matches_export_and_reports_what_the_export_hides(tmp_ws, blenderc = r.censusrec = {o["name"]: o for o in c["objects"]}assert rec["InColl"]["in_scene"] and not rec["InColl"]["in_view_layer"] and rec["InColl"]["hidden"]- assert c["tri_count"] == 4 * 12 and c["n_mesh_objects"] == 4 # Main + the three arms, never InColl+ assert c["tri_count"] == 2 * 12 and c["n_mesh_objects"] == 2 # Main + the arm, never InCollassert c["scene_bbox_max"][2] <= 1.0 + 1e-4 # bbox not stretched to (10,10,10)warns = c["warnings"]assert any("excluded from the view layer" in w and "InColl" in w for w in warns)assert not any("no material" in w for w in warns) # no spurious warning for InCollscene = trimesh.load(r.glb_path)# census matches the export (a multi-material mesh loads as one node per material: <name>_<hash>)- meshes = {"Main", "FlatArm", "PaintedArm", "OverrunArm"}+ meshes = {"Main", "FlatArm"}assert {n if n in meshes else n.rsplit("_", 1)[0] for n in scene.graph.nodes_geometry} == meshesassert rec["FlatArm"]["material_indices_used"] == [0]- assert rec["PaintedArm"]["material_indices_used"] == [0, 1, 2](unused,) = [w for w in warns if "slots no polygon uses" in w]- assert "'FlatArm' (3 slots, 1 used)" in unused and "PaintedArm" not in unused- (clamped,) = [w for w in warns if "past the last slot" in w]- assert "'OverrunArm'" in clamped+ assert "'FlatArm' (3 slots, 1 used)" in unusedassert any("light" in w for w in warns)+++BSDF_PROBE = (+ "import bpy, json\n"+ "m = bpy.data.materials.new('probe')\n"+ "b = m.node_tree.nodes['Principled BSDF']\n"+ "print('BSDF_INPUTS=' + json.dumps([i.name for i in b.inputs]))\n"+)+++def test_lint_bsdf_table_matches_real_principled_inputs(blender_bin) -> None:+ """Finding: 'Anisotropic'/'Specular Tint' are REAL inputs in Blender 5.0.1 — lint must agree."""+ proc = subprocess.run([blender_bin, "-b", "--factory-startup", "--python-expr", BSDF_PROBE],+ capture_output=True, text=True, timeout=120, env=blender_env())+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("BSDF_INPUTS="))+ real = set(json.loads(line[len("BSDF_INPUTS="):]))+ # every key the lint calls removed must actually be absent (no false 'KeyError at runtime')+ still_there = {k for k in REMOVED_BSDF_INPUTS if k in real}+ assert not still_there, f"lint flags valid Principled BSDF inputs: {sorted(still_there)}"+ # the names the lint (and the contract docs) steer agents toward must all exist+ expected = {"Anisotropic", "Specular Tint", "Specular IOR Level", "Subsurface Weight",+ "Transmission Weight", "Coat Weight", "Coat Roughness", "Sheen Weight",+ "Emission Color", "Emission Strength", "Base Color", "Roughness", "Metallic"}+ assert expected <= real, f"missing from Blender: {sorted(expected - real)}"diff --git a/harness/tests/blender_cadquery/test_blender_multifile.py b/harness/tests/blender_cadquery/test_blender_multifile.pydeleted file mode 100644index 353b0e7c..00000000--- a/harness/tests/blender_cadquery/test_blender_multifile.py+++ /dev/null@@ -1,124 +0,0 @@-"""Multi-file blender models on the real binary: a hand-written 2-part model's errors map to-the failing PART file + line; the contract's one executable interface example builds and exports.-(The multi-file skeleton build is test_blender_runtime's.)"""--from __future__ import annotations--import json-import re--import pytest--from codeverse3d.languages.blender import BlenderRuntime-from codeverse3d.prompts import PROMPTS_DIR-from codeverse3d.workspace import Workspace--_LABELLED_PY = re.compile(r"`((?:src|public)/[^`]+)`\n```py\n(.*?)```", re.DOTALL)---def labelled_py_files(rel: str) -> dict[str, str]:- """``src/...`` labelled ```py blocks of a prompt file → {path: content} (multi-file examples)."""- return dict(_LABELLED_PY.findall((PROMPTS_DIR / rel).read_text()))---def _write_files(ws: Workspace, files: dict[str, str]) -> None:- for rel, body in files.items():- p = ws.root / rel- p.parent.mkdir(parents=True, exist_ok=True)- p.write_text(body)---SEAT = '''import bpy, bmesh--SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45--def build_seat():- bm = bmesh.new()- bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=SEAT_D / 2, radius2=SEAT_D / 2, depth=SEAT_T)- me = bpy.data.meshes.new("Seat"); bm.to_mesh(me); bm.free()- obj = bpy.data.objects.new("Seat", me)- obj.location = (0, 0, SEAT_Z - SEAT_T / 2)- bpy.context.scene.collection.objects.link(obj)- return obj-'''-LEG = '''import bpy, bmesh, math--LEG_R, LEG_N, LEG_RING, LEG_H = 0.02, 3, 0.12, 0.414--def build_leg():- parent = bpy.data.objects.new("Legs", None)- bpy.context.scene.collection.objects.link(parent)- for i in range(LEG_N):- a = 2 * math.pi * i / LEG_N- bm = bmesh.new()- bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=LEG_R, radius2=LEG_R, depth=LEG_H)- me = bpy.data.meshes.new(f"Leg_{i}"); bm.to_mesh(me); bm.free()- obj = bpy.data.objects.new(f"Leg_{i}", me)- obj.location = (LEG_RING * math.cos(a), LEG_RING * math.sin(a), LEG_H / 2)- bpy.context.scene.collection.objects.link(obj)- obj.parent = parent- return parent-'''-MODEL = '''import bpy-from parts.seat import build_seat-import parts.leg--def main():- build_seat()- parts.leg.build_leg()--main()-'''---def test_live_multifile_errors_map_to_part_file_and_line(tmp_ws, blender_bin) -> None:- rt = BlenderRuntime(blender=blender_bin)- _write_files(tmp_ws, {"src/model.py": MODEL, "src/parts/seat.py": SEAT, "src/parts/leg.py": LEG})- assert rt.lint(tmp_ws).passed- leg = tmp_ws.src / "parts" / "leg.py"- # (a) syntax error in the part file → src/parts/leg.py:8- leg.write_text(LEG.replace(" for i in range(LEG_N):", " for i in range(LEG_N)"))- lint = rt.lint(tmp_ws)- assert not lint.passed and any(f.target == "src/parts/leg.py" and "SyntaxError" in f.message for f in lint.errors)- r = rt.build(tmp_ws, timeout_s=120)- assert not r.ok and r.error_type == "SyntaxError" and r.error_file == "src/parts/leg.py" and r.error_line == 8- bj = json.loads((tmp_ws.artifacts / "build.json").read_text()) # the BuildResult, not the wrapper's report- assert (bj["error_file"], bj["error_line"]) == ("src/parts/leg.py", 8)- assert bj["census"]["build_report"]["error_source"] == "for i in range(LEG_N)"-- # (b) runtime error deep in the part file → that frame, not model.py's import/call line- leg.write_text(LEG.replace(" obj.parent = parent", " obj.parent = parent\n obj.data.materials.append(None).foo"))- r = rt.build(tmp_ws, timeout_s=120)- assert not r.ok and r.error_type == "AttributeError" and r.error_file == "src/parts/leg.py" and r.error_line == 17- assert r.census["build_report"]["error_source"] == "obj.data.materials.append(None).foo"- bj = json.loads((tmp_ws.artifacts / "build.json").read_text())- assert bj["error_file"] == "src/parts/leg.py" and bj["error_line"] == 17- assert "leg.py" in bj["census"]["build_report"]["traceback"] and "leg.py" in bj["stderr_tail"]-- # (c) missing builder → lint error; build reports model.py's import line with a hint- leg.write_text(LEG.replace("def build_leg", "def build_legs"))- (tmp_ws.src / "model.py").write_text(MODEL.replace("import parts.leg", "from parts.leg import build_leg").replace("parts.leg.build_leg()", "build_leg()"))- lint = rt.lint(tmp_ws)- assert any(f.target == "src/parts/leg.py" and "does not define `def build_leg()`" in f.message for f in lint.errors)- r = rt.build(tmp_ws, timeout_s=120)- assert not r.ok and r.error_type == "ImportError" and r.error_file == "src/model.py" and r.error_line == 3- assert "def build_leg()" in r.error_message---def test_live_contract_multifile_example_builds(tmp_ws, blender_bin) -> None:- trimesh = pytest.importorskip("trimesh")- files = labelled_py_files("blender/contract.md")- assert set(files) == {"src/parts/body.py", "src/parts/knob.py", "src/model.py"}- _write_files(tmp_ws, files)- rt = BlenderRuntime(blender=blender_bin)- lint = rt.lint(tmp_ws)- assert lint.passed, [(f.target, f.message) for f in lint.errors]- r = rt.build(tmp_ws, timeout_s=120)- assert r.ok, (r.error_type, r.error_message, r.error_file, r.error_line)- scene = trimesh.load(r.glb_path)- assert set(scene.graph.nodes_geometry) == {"Body", "Knob_0", "Knob_1"} # one node per part / instance- lo, hi = scene.bounds- assert abs(lo[1]) < 1e-3 and hi[1] > 0.01 # Y-up GLB, lowest point on the ground-diff --git a/harness/tests/blender_cadquery/test_blender_nonfinite.py b/harness/tests/blender_cadquery/test_blender_nonfinite.pyindex a0c0d0d3..6ca4c9d4 100644--- a/harness/tests/blender_cadquery/test_blender_nonfinite.py+++ b/harness/tests/blender_cadquery/test_blender_nonfinite.py@@ -1,14 +1,12 @@"""D114 on the static path (``wrappers/run_bpy.py``, real Blender): a NaN transform or vertex in what thebuild would export is the script's error — the glTF exporter would drop a NaN translation silently and-ship the part at the origin — and ``--blend`` packs the images the script made in memory, so the-reopened ``object.blend`` is not black."""+ship the part at the origin —."""from __future__ import annotationsimport pytest-from codeverse3d.languages.blender import BlenderRuntime, blender_env-from codeverse3d.proc import run_subprocess+from codeverse3d.languages.blender import BlenderRuntimepytestmark = pytest.mark.blender@@ -28,35 +26,3 @@ def test_a_nan_location_fails_the_build_and_exports_nothing(tmp_ws, blender_bin)assert "'Seat': location=(0, nan, 0)" in r.error_messageassert not (tmp_ws.artifacts / "object.glb").exists()--def test_a_nan_vertex_fails_the_build(tmp_ws, blender_bin) -> None:- (tmp_ws.src / "model.py").write_text(PART + 'me.vertices[3].co.z = float("nan")\n')- r = BlenderRuntime(blender=blender_bin).build(tmp_ws, timeout_s=120)- assert not r.ok and r.error_type == "NonFiniteGeometry", (r.error_type, r.error_message)- assert "'Seat': 1 of 4 evaluated vertices" in r.error_message---def test_the_blend_keeps_a_texture_made_in_memory(tmp_ws, blender_bin) -> None:- (tmp_ws.src / "model.py").write_text(PART + '''-img = bpy.data.images.new("Weave", 8, 8)-img.pixels = [0.8, 0.3, 0.1, 1.0] * 64-hdr = bpy.data.images.new("Sheen", 4, 4, float_buffer=True)-hdr.pixels = [2.0, 0.5, 0.25, 1.0] * 16-mat = bpy.data.materials.new("Fabric")-for im in (img, hdr):- mat.node_tree.nodes.new("ShaderNodeTexImage").image = im-me.materials.append(mat)-''')- r = BlenderRuntime(blender=blender_bin).build(tmp_ws, timeout_s=120, stl=False, blend=True)- assert r.ok, (r.error_type, r.error_message)- blend = tmp_ws.artifacts / "object.blend"- code = (f"import bpy\nbpy.ops.wm.open_mainfile(filepath={str(blend)!r})\n"- "for n in ('Weave', 'Sheen'):\n"- " i = bpy.data.images[n]\n"- " print('PX', n, i.packed_file is not None, ','.join(f'{v:.3f}' for v in i.pixels[:4]))\n")- proc = run_subprocess([blender_bin, "-b", "--factory-startup", "--python-expr", code], cwd=tmp_ws.root,- env=blender_env(), timeout_s=120)- rows = {p[1]: (p[2], [float(v) for v in p[3].split(",")]) for p in- (ln.split() for ln in proc.stdout.splitlines() if ln.startswith("PX "))}- assert rows["Weave"][0] == "True" and rows["Weave"][1] == pytest.approx([0.8, 0.3, 0.1, 1.0], abs=1 / 255)- assert rows["Sheen"][0] == "True" and rows["Sheen"][1] == pytest.approx([2.0, 0.5, 0.25, 1.0], abs=1e-3) # EXR: HDR keptdiff --git a/harness/tests/blender_cadquery/test_blender_runtime.py b/harness/tests/blender_cadquery/test_blender_runtime.pyindex 6e4fa1c0..e5882648 100644--- a/harness/tests/blender_cadquery/test_blender_runtime.py+++ b/harness/tests/blender_cadquery/test_blender_runtime.py@@ -8,30 +8,10 @@ from pathlib import Pathimport pytestfrom codeverse3d.languages.blender import (- BlenderNotFoundError,BlenderRuntime,- blender_env,)-def test_missing_binary_raises(tmp_ws) -> None:- rt = BlenderRuntime(blender="/nonexistent/blender")- (tmp_ws.src / "model.py").write_text("import bpy\n")- with pytest.raises(BlenderNotFoundError):- rt.build(tmp_ws)---def test_blender_env_scrubs_secrets_and_host_python(monkeypatch) -> None:- """model.py runs inside blender: no credentials, no host PYTHONPATH."""- monkeypatch.setenv("PYTHONPATH", "/tmp/x")- monkeypatch.setenv("GEMINI_API_KEYS", "k1,k2")- monkeypatch.setenv("SOME_SERVICE_TOKEN", "t")- env = blender_env()- assert "PYTHONPATH" not in env and env["PYTHONNOUSERSITE"] == "1"- assert "GEMINI_API_KEYS" not in env and "SOME_SERVICE_TOKEN" not in env and "PATH" in env---# --------------------------------------------------------------------------- real Blender@pytest.mark.blenderdef test_live_skeleton_builds_and_exports_canonical_glb(tmp_ws, table_plan, blender_bin) -> None:trimesh = pytest.importorskip("trimesh")@@ -40,26 +20,17 @@ def test_live_skeleton_builds_and_exports_canonical_glb(tmp_ws, table_plan, blenrels = [p.relative_to(tmp_ws.root).as_posix() for p in paths]assert rels == ["src/model.py", "src/parts/table_top.py", "src/parts/leg.py", "src/parts/shelf.py"]assert rt.expected_files(table_plan) == rels # the layout IS the skeleton- lint = rt.lint(tmp_ws)- assert lint.passed, [(f.target, f.message) for f in lint.errors]- t0 = time.monotonic()+ assert rt.lint(tmp_ws).passedr = rt.build(tmp_ws, timeout_s=120)- dt = time.monotonic() - t0assert r.ok, (r.error_type, r.error_message, r.stderr_tail)- assert dt < 60assert "[selfcheck]" in r.stdout_tailassert Path(r.extra_paths["stl"]).stat().st_size > 0scene = trimesh.load(r.glb_path)names = set(scene.graph.nodes_geometry)- assert (tmp_ws.src / "parts" / "leg.py").is_file() # multi-file skeletonassert names == {"TableTop", "Shelf", "Leg_0", "Leg_1", "Leg_2", "Leg_3"}assert "Legs" not in scene.graph.nodes # instances are TOP-LEVEL: no parent Empty nodelo, hi = scene.boundsassert abs(lo[1]) < 1e-4 and abs(hi[1] - 0.6) < 1e-3 # Y-up, ground contact, height 0.6- assert abs(lo[0] + 0.25) < 1e-3 and abs(hi[2] - 0.25) < 1e-3- leg0 = scene.geometry[scene.graph["Leg_0"][1]]- assert len(leg0.faces) == 12 # a plain placeholder box: the skeleton chooses no edge treatment- assert leg0.visual.material.baseColorFactor[0] > leg0.visual.material.baseColorFactor[2] # oak-ishc = r.censusassert c["tri_count"] == sum(o["tri_count"] for o in c["objects"] if o["type"] == "MESH")assert c["n_mesh_objects"] == 6 and c["frame"] == "z_up_neg_y_front" and not c["cameras"]diff --git a/harness/tests/blender_cadquery/test_blender_skeleton.py b/harness/tests/blender_cadquery/test_blender_skeleton.pydeleted file mode 100644index 99b555e8..00000000--- a/harness/tests/blender_cadquery/test_blender_skeleton.py+++ /dev/null@@ -1,56 +0,0 @@-"""Offline tests for the bpy skeleton generator."""--from __future__ import annotations--import ast--import pytest--from codeverse3d.contracts.plan import BBox-from codeverse3d.languages.blender import (- finish_for,- instance_centers,- lint_blender_source,- part_file_source,-)---def test_part_file_source_is_self_contained(table_plan) -> None:- leg = table_plan.parts[1]- src = part_file_source(leg)- tree = ast.parse(src)- assert "def build_leg():" in src and "def make_material(" in src and "def add_box(" in src- assert "LEG_CENTER = (0.210, 0.210, 0.280)" in src and "LEG_INSTANCES = 4" in src- assert "tapered square leg" in src and "support" in src and "Attaches to: TableTop" in src and "oak" in src- assert "(0.340, 0.200, 0.100)" in src # oak: the hardwood base hint (texturing.materials)- assert "add_empty" not in src and "obj.parent" not in src- assert 'add_box(f"Leg_{i}"' in src and "return objs" in src and "TOP-LEVEL" in src- # defines builders only — nothing is built at import time- calls = [n.value.func for n in tree.body if isinstance(n, ast.Expr) and isinstance(n.value, ast.Call)]- assert [getattr(f, "id", "") for f in calls if isinstance(f, ast.Name)] == [] # only random.seed(0)- assert lint_blender_source(src, target="src/parts/leg.py").passed---def test_instance_centers_symmetry() -> None:- bb = BBox(center=(0.2, 0.3, 0.5), extents=(0.1, 0.1, 1.0))- assert instance_centers(bb, 1, "none") == [(0.2, 0.3, 0.5)]- assert instance_centers(bb, 2, "mirror_x") == [(0.2, 0.3, 0.5), (-0.2, 0.3, 0.5)]- four = instance_centers(bb, 4, "mirror_y")- assert len(four) == 4 and {(round(x, 3), round(y, 3)) for x, y, _ in four} == {(0.2, -0.3), (-0.2, -0.3), (-0.2, 0.3), (0.2, 0.3)}- rad = instance_centers(BBox(center=(0.5, 0.0, 0.1), extents=(0.1, 0.1, 0.1)), 3, "radial")- assert len(rad) == 3 and all(abs((x * x + y * y) ** 0.5 - 0.5) < 1e-9 for x, y, _ in rad)--[email protected]("text, family", [("solid oak", "hardwood"), ("brushed steel", "brushed_metal"),- ("ABS plastic", "rough_plastic"), ("black", None)])-def test_placeholder_finish_is_the_pbr_table(text, family) -> None:- """Audit 2026-09-24 N54: the skeleton's finishes had their own numbers (wood 0.55 vs the- table's 0.45, steel 0.35 vs 0.22, plastic 0.40 vs 0.62)."""- from codeverse3d.texturing.materials import MATERIALS-- rgb, rough, metal = finish_for(text)- if family is None:- assert (rough, metal) == (0.5, 0.0) and rgb == (0.05, 0.05, 0.05)- else:- pbr = MATERIALS[family]- assert (rgb, rough, metal) == (pbr.base_hint, pbr.roughness, pbr.metallic)diff --git a/harness/tests/blender_cadquery/test_cadquery_lint.py b/harness/tests/blender_cadquery/test_cadquery_lint.pyindex 2a93104d..b77bd545 100644--- a/harness/tests/blender_cadquery/test_cadquery_lint.py+++ b/harness/tests/blender_cadquery/test_cadquery_lint.py@@ -20,16 +20,6 @@ def test_missing_result_guarded_result_and_syntax_error() -> None:assert not r.passed and "SyntaxError" in r.findings[0].message-def test_forbidden_imports_and_calls() -> None:- src = ("import cadquery as cq\nimport os\nfrom OCP.BRepPrimAPI import BRepPrimAPI_MakeBox\nresult = cq.Workplane().box(1, 1, 1)\n"- "show_object(result)\ncq.exporters.export(result, 'x.step')\nresult.save('x.step')\nopen('f', 'w')\n")- r = lint_cadquery_source(src)- e = _msgs(r, Severity.ERROR)- assert any("`os`" in m for m in e) and any("`OCP`" in m for m in e)- assert any("show_object" in m for m in e) and any("cq.exporters.export" in m for m in e)- assert any("result.save" in m for m in e) and any("open()" in m for m in e)--def test_pitfalls() -> None:src = ("import cadquery as cq\nimport math\ns = cq.Solid.makeSphere(1)\nw = cq.Workplane().box(1, 1, 1).rotate((0, 0, 0), (0, 0, 1), math.pi / 2)\n""result = cq.Assembly()\nresult.add(w)\nresult.add(s, name='my_part')\n")@@ -47,11 +37,8 @@ def _rotate_src(expr: str, prelude: str = "") -> str:def test_rotate_angle_expression_table() -> None:- degrees = ("i * 360 / n_pins", "i * pitch_deg", "360 / spindles", "math.degrees(a) * 2",- "a * 180 / math.pi", "180 / math.pi * a", "360 * a / (2 * math.pi)",- "np.rad2deg(a) / 2", "math.degrees(math.pi / 4)", "90", "pitch_deg")- radians = ("math.pi / 2", "i * 2 * math.pi / n_pins", "math.pi", "math.radians(30) * 2",- "math.radians(a)", "math.tau / 4", "a * math.pi / 180", "np.deg2rad(30)", "-math.pi / 2")+ degrees = ("i * 360 / n_pins", "math.degrees(a) * 2", "a * 180 / math.pi", "90")+ radians = ("math.pi / 2", "i * 2 * math.pi / n_pins", "math.radians(30) * 2", "math.tau / 4", "np.deg2rad(30)")for expr in degrees:r = lint_cadquery_source(_rotate_src(expr))assert r.passed and not any("DEGREES" in m for m in _msgs(r)), (expr, _msgs(r))@@ -59,26 +46,3 @@ def test_rotate_angle_expression_table() -> None:r = lint_cadquery_source(_rotate_src(expr))assert not r.passed and any("DEGREES" in m for m in _msgs(r, Severity.ERROR)), (expr, _msgs(r))--def test_fillet_and_chamfer_calls_are_not_findings() -> None:- """The build reports an OCC refusal where it happens; the lint no longer emits a per-call INFO- carrying fillet practices (D106 rule: the lint states facts the build measures, never a template)."""- r = lint_cadquery_source("import cadquery as cq\nw = cq.Workplane().box(1, 1, 1).edges('|Z').fillet(0.1).edges('>Z').chamfer(0.01)\n"- "result = cq.Assembly()\nresult.add(w, name='Part', color=cq.Color(0.5, 0.5, 0.5))\n")- assert r.passed and not r.findings, [f.message for f in r.findings]---def test_contract_import_list_matches_the_lint() -> None:- """One rule, one text: the contract's Imports section names every module the lint allows and every- module it forbids — neither list may drift from ``ALLOWED_IMPORTS`` / ``FORBIDDEN_IMPORTS``."""- import re- from pathlib import Path-- from codeverse3d.languages.cadquery import ALLOWED_IMPORTS, FORBIDDEN_IMPORTS-- text = Path(__file__).resolve().parents[2] / "codeverse3d" / "prompts" / "cadquery" / "contract.md"- section = text.read_text().split("## Imports", 1)[1].split("\n## ", 1)[0]- allowed_para, forbidden_para = section.split("* Forbidden (lint ERROR):", 1)- named = lambda s: set(re.findall(r"`([A-Za-z_][A-Za-z0-9_]*)`", s)) # noqa: E731- assert named(allowed_para) >= ALLOWED_IMPORTS - {"cq", "np", "__future__"}, sorted(ALLOWED_IMPORTS - named(allowed_para))- assert named(forbidden_para.split("* Forbidden calls", 1)[0]) == set(FORBIDDEN_IMPORTS)diff --git a/harness/tests/blender_cadquery/test_cadquery_runtime.py b/harness/tests/blender_cadquery/test_cadquery_runtime.pyindex a9264591..90814a6d 100644--- a/harness/tests/blender_cadquery/test_cadquery_runtime.py+++ b/harness/tests/blender_cadquery/test_cadquery_runtime.py@@ -2,48 +2,24 @@from __future__ import annotations-import importlib.util-import json-import sys-import timefrom pathlib import Pathimport pytest-from codeverse3d.languages.cadquery import (- WRAPPER,- CadQueryRuntime,- cadquery_env,-)+from codeverse3d.languages.cadquery import CadQueryRuntimefrom tests.blender_cadquery.conftest import has_cadqueryneeds_cq = pytest.mark.skipif(not has_cadquery(), reason="cadquery not importable")-def test_missing_entry_invalidates_previous_outputs(tmp_ws) -> None:- """Stale outputs are invalidated before the missing-entry early return."""- for name in ("object.glb", "object.step", "object.stl"):- (tmp_ws.artifacts / name).write_bytes(b"stale")- tmp_ws.write_json(tmp_ws.artifacts / "build.json", {"ok": True})- tmp_ws.write_json(tmp_ws.artifacts / "census.json", {"tri_count": 3})- r = CadQueryRuntime().build(tmp_ws)- assert not r.ok and r.error_type == "MissingEntryFile"- for name in ("object.glb", "object.step", "object.stl", "census.json"):- assert not (tmp_ws.artifacts / name).exists(), name- disk = json.loads((tmp_ws.artifacts / "build.json").read_text())- assert disk["ok"] is False and disk["error_type"] == "MissingEntryFile"--@needs_cqdef test_skeleton_builds_named_coloured_glb(tmp_ws, table_plan) -> None:trimesh = pytest.importorskip("trimesh")rt = CadQueryRuntime()rt.skeleton(tmp_ws, table_plan)assert rt.lint(tmp_ws).passed- t0 = time.monotonic()r = rt.build(tmp_ws, timeout_s=120)assert r.ok, (r.error_type, r.error_message, r.stderr_tail)- assert time.monotonic() - t0 < 60assert set(r.extra_paths) == {"step", "stl"} and Path(r.extra_paths["step"]).stat().st_size > 0scene = trimesh.load(r.glb_path)assert set(scene.graph.nodes_geometry) == {"TableTop", "Shelf", "Leg_0", "Leg_1", "Leg_2", "Leg_3"}@@ -85,103 +61,22 @@ result.add(f, name='Sheet')assert r.ok, (r.error_type, r.error_message)scene = trimesh.load(r.glb_path)assert {"Base", "Peg_0", "Peg_1", "Plate", "Leg"} <= set(scene.graph.nodes_geometry)- p0 = scene.geometry[scene.graph["Peg_0"][1]]- lo, hi = p0.bounds- # world: x=0.1, y=-0.1 → glb z=+0.1; z from 0.02 (sub-assembly loc) to 0.12- assert abs((lo[0] + hi[0]) / 2 - 0.1) < 1e-6 and abs((lo[2] + hi[2]) / 2 - 0.1) < 1e-6- assert abs(lo[1] - 0.02) < 1e-6 and abs(hi[1] - 0.12) < 1e-6- assert list(p0.visual.material.baseColorFactor[:3]) == [255, 0, 0]- p1 = scene.geometry[scene.graph["Peg_1"][1]]- assert list(p1.visual.material.baseColorFactor[:3]) == [0, 255, 0] # inherited from parent assemblyparts = {p["name"]: p for p in r.census["parts"]}assert parts["Plate"]["n_solids"] == 1 and abs(parts["Plate"]["volume_m3"] - 0.1 * 0.1 * 0.01) < 2e-6assert parts["Leg"]["n_solids"] == 1 and parts["Leg"]["tri_count"] == 12warns = r.census["build_report"]["warnings"]assert any("'Plate'" in w and "Face" in w and "trailing selector" in w for w in warns), warnsassert any("'Leg'" in w and "Edge" in w for w in warns), warns- # a bare cq.Face added to an assembly stays a face but is flagged (n_solids == 0 surfaced)- assert parts["Sheet"]["n_solids"] == 0+ assert parts["Sheet"]["n_solids"] == 0 # a bare cq.Face stays a face but is flaggedassert any("'Sheet'" in w and "contains no solid" in w for w in warns), warns# bare-Workplane result with a trailing selector → single node 'Object' + warning, parent solid exported(tmp_ws.src / "model.py").write_text("import cadquery as cq\nresult = cq.Workplane('XY').box(0.1, 0.1, 0.01).faces('>Z')\n")r = rt.build(tmp_ws, timeout_s=120)- assert r.ok and r.census["result_kind"] == "single"- assert r.census["parts"][0]["n_solids"] == 1 and r.census["parts"][0]["tri_count"] == 12+ assert r.ok and r.census["result_kind"] == "single" and r.census["parts"][0]["n_solids"] == 1assert trimesh.load(r.glb_path).graph.nodes_geometry == ["Object"]- assert any("bare Workplane" in w for w in r.census["build_report"]["warnings"])- build_json = json.loads((tmp_ws.artifacts / "build.json").read_text())- assert build_json["ok"] is True# no solid anywhere in the chain (2D wires only) → a typed error naming the stack, not a silent sheet(tmp_ws.src / "model.py").write_text("import cadquery as cq\nresult = cq.Workplane('XY').rect(0.1, 0.1)\n")r = rt.build(tmp_ws, timeout_s=120)assert not r.ok and r.error_type == "ExportError" and "Wire" in r.error_message and "not a Solid" in r.error_message--def _wrapper_module():- spec = importlib.util.spec_from_file_location("run_cq_under_test", WRAPPER)- mod = importlib.util.module_from_spec(spec)- assert spec.loader is not None- spec.loader.exec_module(mod)- return mod---def test_wrapper_error_file_is_workspace_relative(tmp_path, monkeypatch) -> None:- """error_file must be ``src/<file>`` (like every other runtime) and point at the innermost src/ frame."""- monkeypatch.setattr(sys, "path", list(sys.path)) # run_script edits sys.path; keep the test process clean- monkeypatch.setattr(sys, "dont_write_bytecode", sys.dont_write_bytecode)- mod = _wrapper_module()- src = tmp_path / "src"- src.mkdir()- (src / "helpers.py").write_text("def make_part():\n raise RuntimeError('boom') # line 2\n")- (src / "model.py").write_text("from helpers import make_part\nresult = make_part()\n")- assert mod.src_relative(str(src / "model.py"), str(src)) == "src/model.py"- assert mod.src_relative(str(src / "parts" / "leg.py"), str(src)) == "src/parts/leg.py"- assert mod.src_relative(str(tmp_path / "other.py"), str(src)) is None- assert mod.entry_relative(str(src / "model.py")) == "src/model.py"-- def run(script):- exc, ns = mod.run_script(script)- assert exc is not None and ns is None- return mod.script_error(exc, script)-- err = run(str(src / "model.py"))- assert err["error_type"] == "RuntimeError" and err["error_file"] == "src/helpers.py" and err["error_line"] == 2- assert "raise RuntimeError" in err["error_source"] and "helpers.py" in err["traceback"]- # an error raised by model.py itself still maps to src/model.py (and so does a SyntaxError)- (src / "model.py").write_text("import math\nx = 1 / 0\n")- err = run(str(src / "model.py"))- assert err["error_file"] == "src/model.py" and err["error_line"] == 2- (src / "model.py").write_text("result = (\n")- err = run(str(src / "model.py"))- assert err["error_type"] == "SyntaxError" and err["error_file"] == "src/model.py"- # sys.exit(0) leaves no globals to read `result` from (main() reports it as SystemExit)- (src / "model.py").write_text("import sys\nsys.exit(0)\n")- assert mod.run_script(str(src / "model.py")) == (None, None)---@needs_cq-def test_helper_module_error_and_missing_result_report_src_paths(tmp_ws) -> None:- rt = CadQueryRuntime()- (tmp_ws.src / "helpers.py").write_text("import cadquery as cq\n\n\ndef make_part():\n wp = cq.Workplane('XY').box(1, 1, 1)\n"- " return wp.edges('|Z').fillet(5.0) # line 6: OCC fail\n")- (tmp_ws.src / "model.py").write_text("import cadquery as cq\nfrom helpers import make_part\n\nassy = cq.Assembly()\n"- "assy.add(make_part(), name='Part')\nresult = assy\n")- r = rt.build(tmp_ws, timeout_s=120)- assert not r.ok and r.error_type == "StdFail_NotDone"- assert r.error_file == "src/helpers.py" and r.error_line == 6 and (tmp_ws.root / r.error_file).is_file()- assert "helpers.py" in r.stderr_tail and "StdFail_NotDone" in r.stderr_tail # traceback reaches the repair report- (tmp_ws.src / "model.py").write_text("import cadquery as cq\nx = cq.Workplane('XY').box(1, 1, 1)\n")- r = rt.build(tmp_ws, timeout_s=120)- assert not r.ok and r.error_type == "MissingResult" and r.error_file == "src/model.py"---def test_cadquery_env_scrubs_secrets(monkeypatch) -> None:- """src/model.py executes under this env: credential-shaped vars must not reach it."""- monkeypatch.setenv("GEMINI_API_KEYS", "k")- monkeypatch.setenv("FOO_API_KEY", "x")- monkeypatch.setenv("PYTHONSTARTUP", "/tmp/s")- env = cadquery_env()- assert "GEMINI_API_KEYS" not in env and "FOO_API_KEY" not in env- assert "PYTHONSTARTUP" not in env- assert env["OMP_NUM_THREADS"] == "4" and "PATH" in envdiff --git a/harness/tests/blender_cadquery/test_common.py b/harness/tests/blender_cadquery/test_common.pyindex 7f83e477..48d6d5b3 100644--- a/harness/tests/blender_cadquery/test_common.py+++ b/harness/tests/blender_cadquery/test_common.py@@ -1,4 +1,4 @@-"""Unit tests for codeverse3d.languages._common (offline)."""+"""codeverse3d.languages._common.compose_build_result (offline)."""from __future__ import annotations@@ -6,17 +6,12 @@ import jsonfrom pathlib import Pathfrom codeverse3d.contracts.artifacts import BuildResult-from codeverse3d.languages._common import (- ProcResult,- compose_build_result,-)+from codeverse3d.languages._common import ProcResult, compose_build_resultfrom codeverse3d.proc import write_json_atomicdef _proc(**kw) -> ProcResult:- base = dict(returncode=0, stdout="", stderr="", timed_out=False, duration_ms=10)- base.update(kw)- return ProcResult(**base)+ return ProcResult(**{"returncode": 0, "stdout": "", "stderr": "", "timed_out": False, "duration_ms": 10, **kw})def test_compose_build_result(tmp_path: Path) -> None:@@ -24,24 +19,18 @@ def test_compose_build_result(tmp_path: Path) -> None:census_json=tmp_path / "c.json", glb_path=tmp_path / "o.glb", extra_paths={})assert not r.ok and r.error_type == "BuildTimeout"assert json.loads((tmp_path / "t.json").read_text())["error_type"] == "BuildTimeout" # a timeout is published too- r = compose_build_result(language="blender", proc=_proc(returncode=2, stderr="Traceback: bad"), build_json=tmp_path / "w.json",- census_json=tmp_path / "c.json", glb_path=tmp_path / "o.glb", extra_paths={})- assert not r.ok and r.error_type == "WrapperCrash" and "bad" in r.stderr_tail- # ok requires the GLB- b = tmp_path / "build.json"+ b = tmp_path / "build.json" # ok requires the GLBreport = {"ok": True, "error_type": "", "error_message": "", "duration_ms": 42, "warnings": ["w"]}write_json_atomic(b, report)write_json_atomic(tmp_path / "census.json", {"tri_count": 12})- r = compose_build_result(language="blender", proc=_proc(), build_json=b, census_json=tmp_path / "census.json",- glb_path=tmp_path / "o.glb", extra_paths={"stl": tmp_path / "o.stl"})+ kw = dict(language="blender", proc=_proc(), build_json=b, census_json=tmp_path / "census.json", glb_path=tmp_path / "o.glb")+ r = compose_build_result(**kw, extra_paths={"stl": tmp_path / "o.stl"})assert not r.ok and r.error_type == "ExportEmpty"- assert BuildResult.model_validate_json(b.read_text()) == r # the one status file: the final result, not the report(tmp_path / "o.glb").write_bytes(b"glTF" + b"\0" * 20)(tmp_path / "o.stl").write_bytes(b"solid")write_json_atomic(b, report) # the next build's wrapper reports again- r = compose_build_result(language="blender", proc=_proc(), build_json=b, census_json=tmp_path / "census.json",- glb_path=tmp_path / "o.glb", extra_paths={"stl": tmp_path / "o.stl", "blend": tmp_path / "nope.blend"})+ r = compose_build_result(**kw, extra_paths={"stl": tmp_path / "o.stl", "blend": tmp_path / "nope.blend"})assert r.ok and r.glb_path == str(tmp_path / "o.glb") and r.duration_ms == 42assert r.extra_paths == {"stl": str(tmp_path / "o.stl")}assert r.census["tri_count"] == 12 and r.census["build_report"]["warnings"] == ["w"]- assert BuildResult.model_validate_json(b.read_text()) == r+ assert BuildResult.model_validate_json(b.read_text()) == r # the one status file: the final result, not the reportdiff --git a/harness/tests/blender_cadquery/test_material_slots.py b/harness/tests/blender_cadquery/test_material_slots.pyindex 317fd0e4..4b396f4c 100644--- a/harness/tests/blender_cadquery/test_material_slots.py+++ b/harness/tests/blender_cadquery/test_material_slots.py@@ -1,6 +1,4 @@-"""The census warns about material slots the polygons never use (a judge-capped flat-colour run).--The real-Blender end-to-end build is test_blender_live_gates.py's census test."""+"""The census warns about material slots the polygons never use (a judge-capped flat-colour run)."""from __future__ import annotations@@ -11,35 +9,19 @@ from typing import AnyCENSUS = Path(__file__).resolve().parents[2] / "codeverse3d" / "languages" / "wrappers" / "_census.py"-def _census_module() -> Any:- """``_census`` is executed BY Blender (it must not import codeverse3d), so load it by path."""- spec = importlib.util.spec_from_file_location("census_under_test", CENSUS)- mod = importlib.util.module_from_spec(spec)- assert spec.loader is not None- spec.loader.exec_module(mod)- return mod--def _mesh(name: str, n_slots: int, used: list[int]) -> dict[str, Any]:- """One visible-mesh census record, exactly as ``_object_record`` writes it."""return {"name": name, "type": "MESH", "n_material_slots": n_slots, "material_indices_used": used}def test_material_slot_warnings() -> None:- warn = _census_module().material_slot_warnings- assert warn([_mesh("Body", 1, [0])]) == [] # the normal case: one material, one colour- assert warn([_mesh("Arm", 3, [0, 1, 2])]) == [] # every slot reached by some polygon- assert warn([_mesh("Cover", 0, [])]) == [] # no material at all is the other warning's job+ spec = importlib.util.spec_from_file_location("census_under_test", CENSUS) # executed BY Blender: load by path+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ warn = mod.material_slot_warnings+ assert warn([_mesh("Body", 1, [0]), _mesh("Arm", 3, [0, 1, 2]), _mesh("Cover", 0, [])]) == [](only,) = warn([_mesh("StandArm", 11, [0])])assert "'StandArm' (11 slots, 1 used)" in only and "material_index" in only- (partial,) = warn([_mesh("Head", 4, [0, 2])])- assert "'Head' (4 slots, 2 used)" in partial- # an index past the last slot is its own warning- (only,) = warn([_mesh("Tube", 2, [0, 1, 5])])- assert "'Tube' (index 5, 2 slot(s))" in only and "clamps" in only- # a clamped mesh is reported once, not twice: the unused-slot line would be noise here- assert "slots no polygon uses" not in only- # many offenders collapse into one capped warning: the build shows 10 warnings, a- # systemic no-op must not evict the other nine- (only,) = warn([_mesh(f"Part{i}", 4, [0]) for i in range(9)])- assert "(+3 more)" in only and "'Part5'" in only and "'Part6'" not in only+ (clamped,) = warn([_mesh("Tube", 2, [0, 1, 5])]) # an index past the last slot is its own warning, reported once+ assert "'Tube' (index 5, 2 slot(s))" in clamped and "slots no polygon uses" not in clamped+ (many,) = warn([_mesh(f"Part{i}", 4, [0]) for i in range(9)]) # many offenders collapse into one capped warning+ assert "(+3 more)" in many and "'Part5'" in many and "'Part6'" not in manydiff --git a/harness/tests/texturing/test_materials.py b/harness/tests/blender_cadquery/test_pbr.pysimilarity index 93%rename from harness/tests/texturing/test_materials.pyrename to harness/tests/blender_cadquery/test_pbr.pyindex bb4eb558..40c2c9f7 100644--- a/harness/tests/texturing/test_materials.py+++ b/harness/tests/blender_cadquery/test_pbr.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport pytest-from codeverse3d.texturing.materials import COARSE_TO_FINE, MATERIALS, family_for, pbr_for+from codeverse3d.languages.blender._pbr import COARSE_TO_FINE, MATERIALS, family_for, pbr_fordef test_coarse_families_all_resolve():diff --git a/harness/tests/blender_cadquery/test_prompt_block_lint.py b/harness/tests/blender_cadquery/test_prompt_block_lint.pydeleted file mode 100644index 091126ad..00000000--- a/harness/tests/blender_cadquery/test_prompt_block_lint.py+++ /dev/null@@ -1,43 +0,0 @@-"""Every Python block in the Blender/CadQuery prompts passes its own lint."""--from __future__ import annotations--import re-from pathlib import Path--from codeverse3d.languages.blender import lint_blender_source-from codeverse3d.languages.cadquery import lint_cadquery_source--PROMPTS = Path(__file__).resolve().parents[2] / "codeverse3d" / "prompts"-FENCE = re.compile(r"^```(?:py|python)\s*$(.*?)^```\s*$", re.M | re.S)--BLENDER_HEADER = (- "import bpy\nimport bmesh\nimport math\nimport random\nfrom mathutils import Vector, Matrix\n"-)-CADQUERY_HEADER = "import cadquery as cq\nimport math\nimport random\n"---def blocks(rel: str) -> list[tuple[int, str]]:- text = (PROMPTS / rel).read_text()- out = []- for m in FENCE.finditer(text):- out.append((text[: m.start()].count("\n") + 2, m.group(1)))- assert out, f"{rel}: no python blocks found"- return out---def test_prompt_blocks_lint_clean() -> None:- for rel in ("blender/contract.md",): # the blender cookbook is gone (D106 rule, every track)- for line, code in blocks(rel):- src = code if "import bpy" in code else BLENDER_HEADER + code- r = lint_blender_source(src, expect_names=False)- errs = [(f.data.get("line"), f.message) for f in r.findings if f.severity.value == "error"]- assert not errs, f"{rel} block at line {line}: {errs}"- for rel in ("cadquery/contract.md",): # the cadquery cookbook is gone (D106 rule, every track)- for line, code in blocks(rel):- src = code if "import cadquery" in code else CADQUERY_HEADER + code- if not re.search(r"^result\s*=", src, re.M):- src += "\nresult = cq.Assembly()\n"- r = lint_cadquery_source(src)- errs = [(f.data.get("line"), f.message) for f in r.findings if f.severity.value == "error"]- assert not errs, f"{rel} block at line {line}: {errs}"diff --git a/harness/tests/core/test_config_backends.py b/harness/tests/core/test_config_backends.pydeleted file mode 100644index 73c52304..00000000--- a/harness/tests/core/test_config_backends.py+++ /dev/null@@ -1,16 +0,0 @@-"""Settings.backends() — one source of backend-role defaults."""--from __future__ import annotations--import pytest--from codeverse3d.config import Settings-from codeverse3d.contracts.common import Backends---def test_backends_keyword_overrides_win_only_when_truthy_and_name_a_role():- b = Settings().backends(judge="gemini:custom", planner=None, generator="")- assert b.judge == "gemini:custom"- assert (b.planner, b.generator) == (Backends().planner, Backends().generator)- with pytest.raises(TypeError, match="unknown backend role"):- Settings().backends(judger="x")diff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.pyindex 80b068f1..43b0b7f6 100644--- a/harness/tests/core/test_config_env_aliases.py+++ b/harness/tests/core/test_config_env_aliases.py@@ -30,58 +30,8 @@ def test_every_switch_speaks_one_grammar(monkeypatch, caplog):assert env in caplog.text-def test_the_in_flight_cap_spellings_empty_zero_and_garbage(monkeypatch):- """Flat beats nested; empty is unset; 0 means unlimited; a cap is not a switch — garbage stops the run."""- from codeverse3d.config import Rate-- monkeypatch.delenv("C3D_RATE__MAX_IN_FLIGHT", raising=False)- monkeypatch.setenv("C3D_MAX_IN_FLIGHT", "16")- assert Settings().rate.max_in_flight == 16- monkeypatch.delenv("C3D_MAX_IN_FLIGHT", raising=False)- monkeypatch.setenv("C3D_RATE__MAX_IN_FLIGHT", "24")- assert Settings().rate.max_in_flight == 24- monkeypatch.setenv("C3D_MAX_IN_FLIGHT", "8")- assert Settings().rate.max_in_flight == 8- monkeypatch.delenv("C3D_RENDER__GPU", raising=False)- monkeypatch.setenv("C3D_RENDER_GPU", " ON ") # the documented flat spelling, case- and space-tolerant- assert Settings().render.gpu == "on"- monkeypatch.delenv("C3D_RATE__MAX_IN_FLIGHT", raising=False)- monkeypatch.setenv("C3D_MAX_IN_FLIGHT", "")- assert Settings().rate.max_in_flight == 96- assert Rate(max_in_flight=0).max_in_flight == 0, "0 stays legal: it means unlimited"- monkeypatch.setenv("C3D_MAX_IN_FLIGHT", "sixteen")- with pytest.raises(ValueError, match="max_in_flight"):- 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):- """INSTALL §8.3: config files < C3D_* env, per setting — it decides A/B arms."""- for name, raw in (("C3D_SKILLS", "0"), ("C3D_RUNS_DIR", "/from_env"), ("C3D_JUDGE__SAMPLES", "3")):- monkeypatch.setenv(name, raw)- s = Settings(skills=True, runs_dir="/from_yaml", judge={"samples": 2, "max_px": 512})- assert (s.skills, str(s.runs_dir), s.judge.samples) == (False, "/from_env", 3)- assert s.judge.max_px == 512, "a yaml sibling the environment does not name survives"-def test_runtime_js_dir_override_and_loud_failure(tmp_path, monkeypatch):"""C3D_RUNTIME_JS supports relocation and rejects a missing directory."""@@ -95,29 +45,3 @@ def test_runtime_js_dir_override_and_loud_failure(tmp_path, monkeypatch):Settings().runtime_js_dir()monkeypatch.delenv("C3D_RUNTIME_JS")assert Settings().runtime_js_dir().name == "runtime_js" # editable checkout resolves---def test_the_config_names_before_d78_are_still_read_under_the_new_ones(tmp_path, monkeypatch):- """The pre-D78 config file names are still read; a new file wins per setting."""- from codeverse3d import config as C-- home = tmp_path / "fakehome"- (home / ".config" / "codeverse").mkdir(parents=True)- (home / ".config" / "codeverse" / "config.yaml").write_text("limits:\n agent_timeout_s: 900\n max_parallel_builds: 3\n")- (home / ".config" / "3dcodeverse").mkdir(parents=True)- (home / ".config" / "3dcodeverse" / "config.yaml").write_text("limits:\n max_parallel_builds: 5\n")- proj = tmp_path / "proj"- proj.mkdir()- (proj / "codeverse.yaml").write_text("rate:\n max_in_flight: 8\n")- monkeypatch.setattr(C, "_USER_CONFIG", home / ".config" / "3dcodeverse" / "config.yaml")- monkeypatch.setattr(C, "_LEGACY_USER_CONFIG", home / ".config" / "codeverse" / "config.yaml")- monkeypatch.chdir(proj)- for var in ("C3D_MAX_IN_FLIGHT", "C3D_RATE__MAX_IN_FLIGHT", "C3D_LIMITS__AGENT_TIMEOUT_S", "C3D_LIMITS__MAX_PARALLEL_BUILDS"):- monkeypatch.delenv(var, raising=False)- C.get_settings.cache_clear()- try:- s = C.get_settings()- assert (s.limits.agent_timeout_s, s.limits.max_parallel_builds, s.rate.max_in_flight) == (900, 5, 8)- finally:- C.get_settings.cache_clear()-diff --git a/harness/tests/core/test_contract_additions.py b/harness/tests/core/test_contract_additions.pydeleted file mode 100644index 7d76ced7..00000000--- a/harness/tests/core/test_contract_additions.py+++ /dev/null@@ -1,39 +0,0 @@-"""Run options and old-record compatibility."""--from __future__ import annotations--from codeverse3d.contracts.artifacts import RenderSet-from codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.spec import RunOptions, Spec---def test_spec_options_do_not_change_the_plan_stage_hash():- from codeverse3d.orchestrator import hash_inputs- from codeverse3d.tracks.lifecycle import plan_stage_inputs-- plain = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")- opted = plain.model_copy(update={"options": RunOptions(candidates=4)})- assert hash_inputs(plan_stage_inputs(plain)) == hash_inputs(plan_stage_inputs(opted))---def test_records_written_before_the_2026_08_30_field_retirements_still_load():- """Stored runs carry keys since retired (or lack ones added since); every model here must keep loading them."""- from codeverse3d.contracts.agent import AgentJob- from codeverse3d.contracts.run import RoundRecord, SkillRead-- d = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair").model_dump(mode="json")- d.pop("options")- s2 = Spec(**d) # old spec.json without options still parses- assert s2.options.candidates is None-- rs = RenderSet.model_validate({"renderer": "blender", "turntable": "renders/turntable.mp4",- "contact_sheet": "renders/sheet.png"})- assert rs.contact_sheet == "renders/sheet.png" and not hasattr(rs, "turntable")- sk = SkillRead.model_validate({"name": "bpy_modifiers", "surfaced": True, "first_seen_turn": None})- assert sk.surfaced and not hasattr(sk, "first_seen_turn")- job = AgentJob.model_validate({"workspace": "/w", "prompt": "p",- "images": [{"path": "renders/sheet.png", "label": "sheet"}]})- assert job.prompt == "p" and not hasattr(job, "images")- rec = RoundRecord.model_validate({"index": 1, "kind": "refine",- "pairwise": {"a": "r00", "b": "r01", "winner": "a", "confidence": 0.9}})- assert rec.index == 1 and not hasattr(rec, "pairwise")diff --git a/harness/tests/core/test_contracts.py b/harness/tests/core/test_contracts.pyindex e7842d8c..5cd24cec 100644--- a/harness/tests/core/test_contracts.py+++ b/harness/tests/core/test_contracts.py@@ -7,24 +7,12 @@ import mathimport pytestfrom pydantic import ValidationError-from codeverse3d.contracts.common import Budgetfrom codeverse3d.contracts.plan import (ArticulatedPlan,- AssetPlan,BBox,CameraPlan,JointPlan,PartPlan,- ScenePlan,- StaticPlan,- ZonePlan,-)-from codeverse3d.contracts.spec import Spec-from codeverse3d.conventions import (- OBJECT_CLAY_VIEWS,- OBJECT_VIEWS,- OBJECT_VIEWS_QUICK,- slugify,)@@ -32,34 +20,6 @@ def _box(cx=0.0, cy=0.0, cz=0.5, ex=1.0, ey=1.0, ez=1.0) -> BBox:return BBox(center=(cx, cy, cz), extents=(ex, ey, ez))-def test_a_prompt_slugifies_to_a_run_name():- assert slugify("A mid-century wooden dining chair!") == "a_mid_century_wooden_dining_chair"---def test_view_presets_unique():- names = [v.name for v in OBJECT_VIEWS]- assert len(names) == len(set(names)) == 14- # the 14-view rig (D47): quick subset by name, poles present, underside reachable- assert {v.name for v in OBJECT_VIEWS_QUICK} <= set(names) and len(OBJECT_VIEWS_QUICK) == 4- assert "bottom" in names and "top" in names- assert min(v.elevation_deg for v in OBJECT_VIEWS) == -90.0- assert max(v.elevation_deg for v in OBJECT_VIEWS) == 90.0- # the clay rig's 'top' (el 88) shares the rig's name at another camera: never union by name- assert len(OBJECT_CLAY_VIEWS) == 4- clay_top = next(v for v in OBJECT_CLAY_VIEWS if v.name == "top")- assert clay_top.elevation_deg == 88.0---def test_static_plan_validates_attach_and_duplicates():- with pytest.raises(ValidationError):- StaticPlan(object_name="o", summary="s", overall_bbox=_box(),- parts=[PartPlan(name="Seat", role="r", description="d", bbox=_box()),- PartPlan(name="seat", role="r", description="d", bbox=_box())])- with pytest.raises(ValidationError):- StaticPlan(object_name="o", summary="s", overall_bbox=_box(),- parts=[PartPlan(name="Seat", role="r", description="d", bbox=_box(), attach_to="Ghost")])--def test_articulated_plan_requires_single_root_tree_and_sane_joints():parts = [PartPlan(name="Base", role="r", description="d", bbox=_box()),PartPlan(name="Door", role="r", description="d", bbox=_box(0.4, -0.5)),@@ -77,16 +37,6 @@ def test_articulated_plan_requires_single_root_tree_and_sane_joints():JointPlan(name="j", type="revolute", parent="A", child="B", axis=(0, 0, 1), pivot=(0, 0, 0), lower=0, upper=1, rest=2)-def test_scene_plan_zone_contents_must_be_assets():- z = ZonePlan(name="Pond", description="d", bbox=_box(), contents=["Lantern"])- cam = CameraPlan(name="c", position=(0, 1.6, 5), look_at=(0, 0, 0))- with pytest.raises(ValidationError):- ScenePlan(title="t", summary="s", setting="x", bounds=_box(), environment="e", zones=[z], cameras=[cam])- ok = ScenePlan(title="t", summary="s", setting="x", bounds=_box(), environment="e", zones=[z], cameras=[cam],- assets=[AssetPlan(name="Lantern", kind="threejs", description="d", approx_size_m=(0.3, 0.3, 1.2))])- assert ok.zones[0].contents == ["Lantern"]--def test_camera_plan_name_must_be_filename_safe():"""Camera names become render filenames (render_scene.mjs) — reject path tricks."""ok = CameraPlan(name="pier_low-2", position=(0, 1.6, 5), look_at=(0, 0, 0))@@ -98,46 +48,3 @@ def test_camera_plan_name_must_be_filename_safe():for bad in ({"fov": 170}, {"fov": 2}, {"look_at": (0, 1.6, 5)}):with pytest.raises(ValidationError):CameraPlan(**{"name": "cam", "position": (0, 1.6, 5), "look_at": (0, 0, 0), **bad})---def test_budget_and_recorded_specs_reject_retired_cost_keys():- with pytest.raises(ValidationError):- Budget(max_usd=1.0)- with pytest.raises(ValidationError):- Budget(max_minuts=5)- import json-- data = {"id": "x", "track": "static_object", "language": "blender", "prompt": "p",- "budget": {"max_rounds": 2, "max_minutes": 30.0, "max_usd": 2.5}}- with pytest.raises(ValidationError):- Spec.model_validate(data)- with pytest.raises(ValidationError):- Spec.model_validate_json(json.dumps(data))--[email protected]("status", ["passed", "plateau", "stopped"])-def test_retired_run_statuses_are_rejected(status):- from codeverse3d.contracts.run import RunStatus-- with pytest.raises(ValueError):- RunStatus(status)---def test_missing_round_snapshot_does_not_borrow_canonical_artifacts(tmp_ws):- from codeverse3d.contracts.run import RoundRecord- from codeverse3d.record.deliverable import keep_round_artifacts, round_outputs-- (tmp_ws.artifacts / "object.glb").write_bytes(b"current build")- rnd = RoundRecord(index=0, kind="baseline")- assert round_outputs(tmp_ws, rnd) is None- keep_round_artifacts(tmp_ws, 0)- (tmp_ws.artifacts / "object.glb").write_bytes(b"next build")- assert (round_outputs(tmp_ws, rnd) / "object.glb").read_bytes() == b"current build"--[email protected]("name", ["scene_v1", "shader_v1"])-def test_retired_rubrics_are_not_available(name):- from codeverse3d.judges.rubrics import RubricError, load_rubric-- with pytest.raises(RubricError, match="unknown rubric"):- load_rubric(name)diff --git a/harness/tests/core/test_doctor.py b/harness/tests/core/test_doctor.pyindex 499b097c..34579ac9 100644--- a/harness/tests/core/test_doctor.py+++ b/harness/tests/core/test_doctor.py@@ -5,35 +5,6 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-import pytest--from codeverse3d.doctor import check_gpu_probe, check_node---def test_the_gpu_probe_releases_the_browser_instead_of_closing_it(tmp_path: Path, monkeypatch):- """close() would kill the daemon's SHARED browser under every concurrent run; release() disconnects."""- mark = tmp_path / "mark"- (tmp_path / "gpu_launch.cjs").write_text(- f"const fs = require('fs'), mark = {json.dumps(str(mark))};\n"- "exports.launchBrowser = async () => ({gpu: true, renderer: 'fake', shared: true,\n"- " browser: {close: async () => fs.writeFileSync(mark, 'close')},\n"- " release: async () => fs.writeFileSync(mark, 'release')});\n")- monkeypatch.setenv("C3D_RUNTIME_JS", str(tmp_path))- assert check_gpu_probe(timeout_s=60) == [("chrome webgl", "OK", "GPU: fake")]- assert mark.read_text() == "release"---def test_a_torn_package_json_is_a_failed_row_not_a_crash(tmp_path: Path, monkeypatch):- """B9: one torn node_modules/*/package.json crashed the whole report."""- for pkg in ("three", "puppeteer"):- (tmp_path / "node_modules" / pkg).mkdir(parents=True)- (tmp_path / "node_modules" / pkg / "package.json").write_text('{"version": "0.18')- monkeypatch.setenv("C3D_RUNTIME_JS", str(tmp_path))- rows = {name: (status, detail) for name, status, detail in check_node()}- assert rows["three"][0] == "FAIL" and "unreadable" in rows["three"][1]- assert rows["puppeteer"][0] == "FAIL"-def _fake_probe(monkeypatch, tmp_path: Path, payload: dict) -> list:from codeverse3d import doctor@@ -55,82 +26,8 @@ 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)", "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 "310 ms" 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]assert soft["blender eevee"][1] == "WARN" and "software GL" in soft["blender eevee"][2]---def test_doctor_blender_render_probe_runs_for_real():- from codeverse3d.config import get_settings- from codeverse3d.doctor import check_blender_render-- if not get_settings().resolve_blender():- 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_every_shipped_overlay(monkeypatch):- """One ``skills overlay`` row per shipped variant, in name order: ``argon`` (empty) and ``argon_raw``- (D113: the three lib-free ``c3d-bpy-scene-*`` shadows, no routes) — a dict keyed by the row name- would keep only the last, so the rows are read as a list."""- 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 = check_skills()- finally:- get_settings.cache_clear()- assert next(status for name, status, _ in rows if name == "skills library") == "OK"- overlays = [(status, detail) for name, status, detail in rows if name == "skills overlay"]- assert [status for status, _ in overlays] == ["OK", "OK"], overlays- assert overlays[0][1].startswith("argon: 0 bundles, 0 invalid")- assert overlays[1][1].startswith("argon_raw: 3 bundles, 0 invalid") and "routes.toml: no rows" in overlays[1][1]diff --git a/harness/tests/core/test_legacy_env_prefix.py b/harness/tests/core/test_legacy_env_prefix.pydeleted file mode 100644index 167db667..00000000--- a/harness/tests/core/test_legacy_env_prefix.py+++ /dev/null@@ -1,22 +0,0 @@-"""`CV3D_` was the settings prefix until D78 (2026-09-22); a shell that still sets it keeps working."""--from __future__ import annotations--import os-import subprocess-import sys---def _run(env: dict[str, str]) -> subprocess.CompletedProcess[str]:- code = ("import os, codeverse3d; "- "print(os.environ.get('C3D_RUNS_DIR', '-'), os.environ.get('C3D_RENDER__GPU', '-'))")- clean = {k: v for k, v in os.environ.items() if not k.startswith(("CV3D_", "C3D_"))}- return subprocess.run([sys.executable, "-c", code], env={**clean, **env}, capture_output=True, text=True, check=True)---def test_an_old_prefix_is_read_as_the_new_one_warned_and_loses_to_the_new_name():- p = _run({"CV3D_RUNS_DIR": "/tmp/old", "CV3D_RENDER__GPU": "off"})- assert p.stdout.split() == ["/tmp/old", "off"]- assert "CV3D_RENDER__GPU" in p.stderr and "CV3D_RUNS_DIR" in p.stderr- p = _run({"CV3D_RUNS_DIR": "/tmp/old", "C3D_RUNS_DIR": "/tmp/new"})- assert p.stdout.split()[0] == "/tmp/new" and p.stderr == ""diff --git a/harness/tests/core/test_names.py b/harness/tests/core/test_names.pyindex 83f06832..e268d6cc 100644--- a/harness/tests/core/test_names.py+++ b/harness/tests/core/test_names.py@@ -1,6 +1,4 @@-"""The naming rule: one PascalCase rule (``conventions.PASCAL_RE``) that accepts all-caps-acronyms (owner, 2026-09-22), the stdlib-only wrapper copies pinned to it, and the-snake round trip every gate matches parts by."""+"""The naming rule: one PascalCase rule that accepts all-caps acronyms (owner, 2026-09-22) and the wrapper copies pinned to it."""from __future__ import annotations@@ -8,24 +6,12 @@ import astimport refrom pathlib import Path-from codeverse3d.contracts.common import Track-from codeverse3d.contracts.plan import StaticPlan-from codeverse3d.conventions import LINK_NAME_RE as URDF_LINK_RE-from codeverse3d.conventions import PASCAL_RE, part_key, split_instance, to_pascal, to_snake-from codeverse3d.languages.blender import lint_blender_source-from codeverse3d.languages.cadquery import lint_cadquery_source-from codeverse3d.texturing.materials import family_for-from codeverse3d.tracks.planner import normalise_names, plan_example+from codeverse3d.conventions import PASCAL_RE, split_instance, to_snakeWRAPPERS = Path(__file__).resolve().parents[2] / "codeverse3d" / "languages" / "wrappers"VALID = ["LED", "TV", "A", "TVStand", "LEDStrip", "USBPort", "HDMIPort1", "CPU_2", "SeatCushion", "Leg_0"]INVALID = ["led", "tvStand", "seat_cushion", "TV Stand", "Seat Cushion", "TV-Stand", "Seat-Cushion", "", "_Leg", "Leg_", "3D"]-#: acronym names: snake key, and what to_pascal rebuilds from that key (the acronym is lost)-SNAKE = {"LED": ("led", "Led"), "TV": ("tv", "Tv"), "A": ("a", "A"), "TVStand": ("tv_stand", "TvStand"),- "LEDStrip": ("led_strip", "LedStrip"), "USBPort": ("usb_port", "UsbPort"),- "HDMIPort1": ("hdmi_port1", "HdmiPort1"), "CPU_2": ("cpu_2", "Cpu2")}-def _wrapper_assign(file: str, name: str) -> ast.AST:tree = ast.parse((WRAPPERS / file).read_text())@@ -57,51 +43,8 @@ def test_the_naming_rule_and_its_stdlib_wrapper_copies():assert snake(n) == to_snake(n), n-def test_snake_round_trip_and_to_pascal():- for name, (snake, rebuilt) in SNAKE.items():- assert to_snake(name) == snake, name- assert to_pascal(snake) == rebuilt, name # rebuilding from the key loses the acronym- if "_" not in name: # ... but for a plan name never the key itself- assert to_snake(to_pascal(name)) == snake == to_snake(rebuilt), name- assert [to_pascal(n) for n in ("TVStand", "LED", "A", "HDMIPort1", "SeatCushion")] == ["TVStand", "LED", "A", "HDMIPort1", "SeatCushion"]- # an instance suffix / underscores / spaces / hyphens / lowercase still go through to_snake- # (an instance name is not a plan name: to_pascal folds its suffix, CPU_2 -> Cpu2 -> key cpu2,- # exactly as Leg_0 -> Leg0 always has)- assert [to_pascal(n) for n in ("CPU_2", "Leg_0", "tv stand", "LED strip", "seat-cushion", "tvStand", "")] == \- ["Cpu2", "Leg0", "TvStand", "LedStrip", "SeatCushion", "TvStand", "Part"]---def test_planner_normalisation_keeps_acronym_names():- d = plan_example(Track.STATIC_OBJECT)- d["parts"][0]["name"], d["parts"][1]["name"] = "TVStand", "led strip"- d["parts"][1]["attach_to"] = d["parts"][2]["attach_to"] = "TVStand"- plan = normalise_names(StaticPlan.model_validate(d))- assert [p.name for p in plan.parts[:2]] == ["TVStand", "LedStrip"] and plan.parts[1].attach_to == "TVStand"---def test_the_part_name_lints_accept_acronyms():- src = "import cadquery as cq\nresult = cq.Assembly()\n" + "".join(- f"result.add(cq.Workplane().box(1, 1, 1), name='{n}', color=cq.Color(1, 0, 0))\n" for n in ("TVStand", "LED", "CPU_2"))- assert not any("not PascalCase" in f.message for f in lint_cadquery_source(src).findings)- rep = lint_blender_source("import bpy\nobj = bpy.context.object\nobj.name = 'USBPort'\n")- assert any("named objects" in f.message and "USBPort" in f.message for f in rep.findings)- # N47o: a URDF link is the part's snake key, the PascalCase spelling accepted — one rule, and- # the Blender-run link wrapper's copy of it is the same pattern- assert all(URDF_LINK_RE.match(n) for n in ("TVStand", "LED", "CPU_2", "A", "door_handle", "DoorHandle"))- assert not any(URDF_LINK_RE.match(n) for n in ("Door.001", "door handle", "../evil", "9lives"))- safe = _wrapper_assign("run_bpy_links.py", "_SAFE_LINK")- assert f"^{ast.literal_eval(safe.value.args[0])}$" == URDF_LINK_RE.pattern # type: ignore[attr-defined]---def test_material_words_split_acronyms():- hit = family_for("PVCPipe")- assert hit is not None and hit == family_for("pvc pipe")--def test_one_instance_rule_for_every_reader():- """``conventions.split_instance`` is the rule the measure table, the contract match and- refine grouping read (four hand-written copies until 2026-09-23 — the refine grouping- read ``DonkeyCart_800006``, a scene asset's all-digit hex id, as instance 800006)."""+ """split_instance is the one rule all readers share (refine grouping once read DonkeyCart_800006 as instance 800006)."""from codeverse3d.orchestrator import _canon_target, _instance_basefrom codeverse3d.spatial.measure import instance_groups@@ -113,11 +56,3 @@ def test_one_instance_rule_for_every_reader():["Leg", "Shelf", "Shelf2", "Cart_800006", "Cart_801"]assert _instance_base("DonkeyCart_800006") == "DonkeyCart_800006" and _instance_base("") == "overall"assert _canon_target("leg_1", {"leg": "Leg"}) == "Leg_1"---def test_one_part_rule_strips_an_instance_suffix_even_for_a_single_copy():- """N4: a single ``Arm-2`` the contract gate accepts maps to its plan part too — ``conventions.part_key``."""- plan = {"leg", "seat", "arm", "handle", "link", "cpu_2"}- rows = {"Leg_0": "leg", "Arm-2": "arm", "Handle.001": "handle", "Link__2": "link", "Leg_0__1": "leg",- "Seat": "seat", "CPU_2": "cpu_2", "Shelf": None}- assert {n: part_key(n, plan) for n in rows} == rowsdiff --git a/harness/tests/core/test_plan_normalise.py b/harness/tests/core/test_plan_normalise.pyindex e14e15e9..88345f8e 100644--- a/harness/tests/core/test_plan_normalise.py+++ b/harness/tests/core/test_plan_normalise.py@@ -6,7 +6,6 @@ import copyimport mathimport pytest-from pydantic import ValidationErrorfrom codeverse3d.contracts.common import Trackfrom codeverse3d.contracts.plan import ArticulatedPlan@@ -66,126 +65,6 @@ def test_degree_shaped_limits_convert_together_and_a_two_turn_range_becomes_contassert any("looked like degrees" in n for n in p.normalisations) and any("> 2π → continuous" in n for n in p.normalisations)-def test_a_sub_part_outside_its_parent_grows_the_parent_bbox():- d = _raw()- parent = d["parts"][0]- c, e = parent["bbox"]["center"], parent["bbox"]["extents"]- sill = {"name": "ThresholdSill", "role": "sill", "description": "a 40 mm deep sill proud of the frame",- # 0.20 m proud of the frame: far outside any slack (max(SUBPART_SLACK_M, 10 % of the extent))- "bbox": {"center": [c[0], c[1] - e[1] / 2 - 0.20, c[2] - e[2] / 2 + 0.02], "extents": [e[0], 0.06, 0.04]}}- parent.setdefault("children", []).append(sill)- p = ArticulatedPlan.model_validate(d)- grown = next(x for x in p.parts if x.name == parent["name"])- assert grown.bbox.min[1] <= sill["bbox"]["center"][1] - 0.03 + 1e-9 # the parent now encloses the sill- assert grown.bbox.max[1] == pytest.approx(c[1] + e[1] / 2) # and did not grow where it did not need to- assert any("bbox grown on y" in n for n in p.normalisations)---def test_planner_text_in_normalisations_is_dropped():- """Planner prose cannot masquerade as harness repair history."""- from codeverse3d.contracts.plan import ArticulatedPlan-- raw = ArticulatedPlan._normalise_raw({"parts": [{"name": "A", "bbox": {"center": [0, 0, 0], "extents": [1, 1, 1]}}],- "joints": [{"name": "j", "parent": "A", "child": "A", "type": "revolute", "lower": 0, "upper": 1}],- "normalisations": ["rest pose set to 0.15 m (planner prose)"]})- assert raw["normalisations"] == []---def test_a_joint_naming_a_part_by_a_unique_fragment_is_resolved():- d = _raw()- d["parts"][1]["name"] = "ChestDrawer" # the plan's own name ...- d["joints"][0]["child"] = "Drawer" # ... referenced by one word of it- part = "ChestDrawer"- plan = ArticulatedPlan.model_validate(d)- assert _joint(plan, d["joints"][0]).child == part- assert any("resolved to the one part it names" in n for n in plan.normalisations)---def test_an_ambiguous_joint_reference_is_rejected_and_names_the_real_parts():- d = _raw()- d["parts"][1]["name"] = "ChestDrawer"- twin = dict(d["parts"][1])- twin["name"] = "SpareDrawer"- d["parts"].append(twin)- fragment = "Drawer"- d["joints"][0]["child"] = fragment- with pytest.raises(ValidationError) as e:- ArticulatedPlan.model_validate(d)- msg = str(e.value)- assert f"unknown link(s) {fragment}" in msg- assert "chest_drawer" in msg and "spare_drawer" in msg, "the planner must be told the real names"---def test_a_root_link_that_names_no_part_becomes_the_one_link_no_joint_moves():- d = _raw()- d["root_link"] = "040fbba3-b0f3-42e1-85b3-f61b0c034293"- plan = ArticulatedPlan.model_validate(d)- assert plan.root_link == "Cabinet"- assert any("no joint moves" in n and "Cabinet" in n for n in plan.normalisations)---def test_an_ambiguous_root_is_still_rejected():- d = _raw()- d["root_link"] = "nowhere"- d["parts"].append({"name": "Pedestal", "role": "base", "description": "a plinth", "material": "oak",- "bbox": {"center": [0, 0, -0.05], "extents": [0.5, 0.6, 0.1]}})- with pytest.raises(ValidationError, match="root_link nowhere is not a part"):- ArticulatedPlan.model_validate(d)---def test_swapped_limits_are_written_as_the_swap_they_are():- d = _raw()- j = d["joints"][0]- j["lower"], j["upper"] = 1.2, 0.0- j["rest"] = 0.5- p = ArticulatedPlan.model_validate(d)- fixed = next(x for x in p.joints if x.name == j["name"])- assert (fixed.lower, fixed.upper) == (0.0, 1.2)- assert any("swapped" in n for n in p.normalisations)---def test_a_rest_outside_the_limits_is_clamped_not_fatal():- d = _raw()- j = d["joints"][0]- j["lower"], j["upper"], j["rest"] = 0.0, 1.0, 2.5- p = ArticulatedPlan.model_validate(d)- fixed = next(x for x in p.joints if x.name == j["name"])- assert fixed.rest == pytest.approx(1.0)- assert any("clamped" in n for n in p.normalisations)---def test_a_zero_axis_still_fails_validation():- d = _raw()- d["joints"][0]["axis"] = [0, 0, 0]- with pytest.raises(ValidationError):- ArticulatedPlan.model_validate(d)---def _rename_part(d: dict, old: str, new: str) -> None:- for part in d["parts"]:- if part["name"] == old:- part["name"] = new- if part.get("attach_to") == old:- part["attach_to"] = new- for j in d["joints"]:- for side in ("parent", "child"):- if j.get(side) == old:- j[side] = new- if d.get("root_link") == old:- d["root_link"] = new---def test_a_root_link_naming_no_part_is_resolved_by_the_1b_word_rule():- """Word-boundary match, as the joint-fragment repair — never a bare substring."""- d = _raw()- real_root = d["root_link"]- _rename_part(d, real_root, "TrackedChassis")- d["root_link"] = "Chassis"- p = ArticulatedPlan.model_validate(d)- assert p.root_link == "TrackedChassis"- assert any("root_link 'Chassis'" in n and "TrackedChassis" in n for n in p.normalisations)--def test_a_joint_naming_a_sub_part_by_word_subset_promotes_it():d = _raw()parent = d["parts"][0]@@ -202,18 +81,3 @@ def test_a_joint_naming_a_sub_part_by_word_subset_promotes_it():j = next(x for x in p.joints if x.name == "CaseToGlazedDoor")assert j.child == "GlazedFrontDoor"assert any("resolved to sub-part GlazedFrontDoor" in n for n in p.normalisations)---def test_the_unknown_link_complaint_lists_the_sub_parts():- d = _raw()- parent = d["parts"][0]- parent.setdefault("children", []).append(- {"name": "PendulumBob", "role": "bob", "description": "a brass disc",- "bbox": {"center": list(parent["bbox"]["center"]), "extents": [0.1, 0.1, 0.02]},- "material": "brass"})- d["joints"].append({"name": "Mystery", "type": "revolute", "parent": parent["name"],- "child": "SomethingElse", "axis": [0, 1, 0], "pivot": [0, 0, 0],- "lower": 0.0, "upper": 1.0, "rest": 0.0, "motion": "?"})- with pytest.raises(ValidationError, match=r"Sub-parts that exist but are NOT links:.*PendulumBob"):- ArticulatedPlan.model_validate(d)-diff --git a/harness/tests/core/test_portability.py b/harness/tests/core/test_portability.pyindex fd86ffea..51941c1e 100644--- a/harness/tests/core/test_portability.py+++ b/harness/tests/core/test_portability.py@@ -13,8 +13,6 @@ from codeverse3d.spatial.node import (NODE_MIN,NODE_MIN_STR,NodeError,- node_version_error,- parse_node_version,require_node_version,)from codeverse3d.workspace import Workspace@@ -60,28 +58,6 @@ def test_write_example_refuses_to_write_nothing(tmp_path, monkeypatch) -> None: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)):- assert parse_node_version(text) == expected, text- assert node_version_error((20, 6, 0)) == node_version_error(None) == ""- msg = node_version_error((20, 5, 9))- assert "20.5.9" in msg and NODE_MIN_STR in msg and "C3D_BINARIES__NODE" in msg and "nvm" in msg--def test_run_node_enforces_the_version_floor(tmp_path, monkeypatch) -> None:import codeverse3d.spatial.node as node_moddiff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.pyindex 31f0906b..a07729d6 100644--- a/harness/tests/core/test_proc.py+++ b/harness/tests/core/test_proc.py@@ -3,9 +3,7 @@from __future__ import annotationsimport os-import signalimport sys-import threadingimport timefrom pathlib import Path@@ -13,37 +11,8 @@ import pytestfrom codeverse3d.proc import (STREAM_BUDGET_BYTES,- ManagedProcess,- append_jsonl_line,- iter_jsonl_lines,- read_jsonl_lenient,run_subprocess,- scrub_secrets,)-from tests.conftest import assert_pid_gone---def test_timeout_kills_the_whole_process_group(tmp_path: Path):- """A timed-out child AND its grandchildren die (killpg), and their output is still collected."""- r = run_subprocess(["bash", "-c", "echo hello; sleep 30 & echo $!; wait"], cwd=tmp_path, timeout_s=0.4)- assert r.timed_out and r.returncode != 0- assert r.stdout.splitlines()[0] == "hello"- assert_pid_gone(int(r.stdout.strip().splitlines()[1]), timeout_s=5.0)---def test_a_leader_that_exits_0_does_not_burn_the_drain_window(tmp_path: Path, monkeypatch):- """A clean exit takes same-group grandchildren down without burning the drain window."""- import codeverse3d.proc as proc_mod-- monkeypatch.setattr(proc_mod, "DRAIN_TIMEOUT_S", 3.0)- pid_file = tmp_path / "pid"- t0 = time.monotonic()- r = run_subprocess(["bash", "-c", f"sleep 300 & echo $! > {pid_file}; echo done"],- cwd=tmp_path, timeout_s=10)- assert r.returncode == 0 and "done" in r.stdout- assert time.monotonic() - t0 < 2.5, "the drain window was burned on a live group member"- assert "detached descendant" not in r.stderr- assert_pid_gone(int(pid_file.read_text()), timeout_s=5.0)def test_a_detached_descendant_holding_the_pipes_cannot_extend_the_timeout(tmp_path: Path, monkeypatch):@@ -62,63 +31,6 @@ def test_a_detached_descendant_holding_the_pipes_cannot_extend_the_timeout(tmp_passert elapsed < 8.0, f"run_subprocess returned only after {elapsed:.1f}s"-# --------------------------------------------------------------------------- atomic writes-def test_concurrent_writers_of_one_destination_all_succeed(tmp_path: Path):- """Barrier-synchronised writers (one pid, many threads) all publish one destination, no temp litter."""- from codeverse3d.proc import write_text_atomic-- out = tmp_path / "shared.txt"- n = 8- bar = threading.Barrier(n)- errors: list[BaseException] = []-- def writer() -> None:- try:- bar.wait()- write_text_atomic(out, "payload\n")- except BaseException as e: # noqa: BLE001 — the point of the test- errors.append(e)-- threads = [threading.Thread(target=writer) for _ in range(n)]- for t in threads:- t.start()- for t in threads:- t.join()-- assert not errors, errors- assert out.read_text() == "payload\n"- assert list(tmp_path.iterdir()) == [out] # no temp litter left behind---# --------------------------------------------------------------------------- tolerant reads-def test_jsonl_helpers_round_trip_and_skip_bad_lines(tmp_path: Path):- p = tmp_path / "log.jsonl"- assert list(iter_jsonl_lines(p)) == [] and read_jsonl_lenient(p) == []- lock = threading.Lock()- append_jsonl_line(p, {"k": "é", "p": tmp_path}, lock) # default=str for the Path- append_jsonl_line(p, [1, 2], lock)- with p.open("ab") as fh: # what a SIGKILL mid-append leaves behind- fh.write(b'\n{"k": "b\xff\n{"k": "tr')- assert [i for i, _ in iter_jsonl_lines(p)] == [1, 2, 4, 5] # 1-based, blank line 3 skipped- rows = read_jsonl_lenient(p)- assert rows == [{"k": "é", "p": str(tmp_path)}, [1, 2]]- assert read_jsonl_lenient(p, dicts_only=True) == rows[:1]---# --------------------------------------------------------------------------- scrub_secrets-def test_scrub_secrets_drops_credentials_and_keeps_what_generated_code_needs():- secrets = {- "GEMINI_API_KEYS": "k1,k2", "GEMINI_API_KEY": "k", "FOO_API_KEY": "x",- "MY_SERVICE_TOKEN": "t", "DB_PASSWORD": "p", "DEPLOY_PRIVATE_KEY": "s",- "AWS_SECRET_ACCESS_KEY": "a", "CLIENT_SECRET": "c", "X_AUTH_TOKEN": "z",- }- env = {"PATH": "/usr/bin", "HOME": "/home/u", "DISPLAY": ":0", "NODE_PATH": "/nm",- "MESA_LOADER_DRIVER_OVERRIDE": "d3d12", "GALLIUM_DRIVER": "llvmpipe",- "C3D_RENDER_GPU": "off", "PYTHONUNBUFFERED": "1",- "TOKENIZERS_PARALLELISM": "false"} # _TOKEN is a SUFFIX match, not a substring- assert scrub_secrets({**env, **secrets}) == env--# --------------------------------------------------------------------------- ManagedProcess lifecycle#: spawns a grandchild, writes its OWN pid (== the new session's pgid) to argv[1] and#: hangs — so the probe below is a real GROUP probe, not just "the leader died".@@ -130,26 +42,6 @@ _PID_THEN_SLEEP = ()-def _raise_ki(signum: int, frame: object) -> None:- raise KeyboardInterrupt--[email protected](60, method="thread") # thread method: the test drives SIGALRM itself-def test_keyboard_interrupt_kills_the_group(tmp_path: Path):- """KeyboardInterrupt kills the separate child process group and propagates."""- pid_file = tmp_path / "pid"- old = signal.signal(signal.SIGALRM, _raise_ki)- try:- signal.setitimer(signal.ITIMER_REAL, 0.8) # fires while run_subprocess blocks in wait()- with pytest.raises(KeyboardInterrupt):- run_subprocess([sys.executable, "-c", _PID_THEN_SLEEP, str(pid_file)],- cwd=tmp_path, timeout_s=120)- finally:- signal.setitimer(signal.ITIMER_REAL, 0.0)- signal.signal(signal.SIGALRM, old)- assert_pid_gone(int(pid_file.read_text()), group=True)--@pytest.mark.timeout(120)def test_huge_output_is_bounded_head_and_tail(tmp_path: Path):"""Large output is bounded while preserving its head, tail, and truncation marker; one bad byte@@ -173,53 +65,6 @@ def test_huge_output_is_bounded_head_and_tail(tmp_path: Path):assert "x" * 1000 in r.stdout[:cut] and "x" * 1000 in r.stdout[cut:]-def test_managed_process_reaps_on_exit_no_zombie(tmp_path: Path):- with ManagedProcess([sys.executable, "-c", "print('hi')"], cwd=tmp_path) as mp:- mp.wait(timeout=30)- pid = mp.pid- assert mp.stdout_text.strip() == "hi"- with pytest.raises(ChildProcessError):- os.waitpid(pid, os.WNOHANG) # __exit__ already reaped it — no zombie left---def test_a_stop_signal_kills_the_children_refuses_new_ones_and_cannot_hang(tmp_path):- """A run's sessions and builds run in worker threads; SIGTERM reaches the main thread- only, and used to leave their trees running (a SIGTERM'd make orphaned its agy session).- Now: the live child group dies, a worker cannot start another one (its retry, its next- build), and a worker stuck in a long call cannot hold the exit past STOP_GRACE_S."""- import subprocess-- marker = tmp_path / "refused"- script = tmp_path / "victim.py"- script.write_text(- "import threading, time\n"- "from codeverse3d import proc\n"- "proc.STOP_GRACE_S = 1.0\n"- "proc.install_stop_handlers()\n"- "def session():\n"- " with proc.ManagedProcess(['sleep', '120'], cwd='.') as mp:\n"- " print(mp.proc.pid, flush=True)\n"- " mp.proc.wait()\n"- " try:\n"- " proc.ManagedProcess(['sleep', '120'], cwd='.') # the retry after the kill\n"- " except proc.ProcessStopping:\n"- f" open({str(marker)!r}, 'w').write('refused')\n"- "threading.Thread(target=session).start()\n"- "threading.Thread(target=time.sleep, args=(120,)).start() # a model call that never ends\n"- "time.sleep(120)\n")- victim = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.PIPE, text=True)- child = int(victim.stdout.readline())- t0 = time.monotonic()- os.kill(victim.pid, signal.SIGTERM)- assert victim.wait(timeout=20) == 128 + signal.SIGTERM- assert time.monotonic() - t0 < 10, "a stuck worker thread held the exit"- deadline = time.monotonic() + 5- while time.monotonic() < deadline and _alive(child):- time.sleep(0.05)- assert not _alive(child), "the worker thread's sleep survived its parent's SIGTERM"- assert marker.read_text() == "refused", "a new child started after the stop"--def _alive(pid: int) -> bool:try:os.kill(pid, 0)diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.pyindex 89267c48..511789b0 100644--- a/harness/tests/core/test_run_layout.py+++ b/harness/tests/core/test_run_layout.py@@ -1,125 +1,18 @@-"""The three-bucket run layout (docs/RUN_LAYOUT.md): directories, aliases,+"""The run layout (docs/RUN_LAYOUT.md): directories,.gitignore and the additive record blocks. Pure filesystem + pydantic."""from __future__ import annotations-import json-import osfrom pathlib import Path-from codeverse3d.contracts.run import RunDeliverable, RunRecord, RunTelemetry-from codeverse3d.contracts.spec import Spec-from codeverse3d.workspace import EVIDENCE_DIR, LAYOUT_ALIASES, Workspace+from codeverse3d.workspace import Workspace-def test_create_makes_the_buckets_aliases_and_gitignore(tmp_path: Path):+def test_create_makes_the_buckets_and_gitignore(tmp_path: Path):ws = Workspace(tmp_path / "run").create()assert ws.deliverable.is_dir() and ws.telemetry.is_dir() and ws.artifacts.is_dir()- assert os.readlink(ws.root / EVIDENCE_DIR) == "artifacts" # evidence/ is the aliasignored = (ws.root / ".gitignore").read_text().splitlines()- assert {"artifacts/", "deliverable/", "telemetry/", "evidence", "trajectories/"} <= set(ignored)- for name, target in LAYOUT_ALIASES:- link = ws.root / name- assert link.is_symlink(), name- assert os.readlink(link) == target- ws.events_path.write_text('{"event": "run.start"}\n')- assert (ws.telemetry / "events.jsonl").read_text().strip().endswith("}")- # an atomic rewrite of the physical file must not disturb the alias- ws.write_json(ws.state_path, {"status": "max_rounds"})- assert json.loads((ws.telemetry / "run_state.json").read_text())["status"] == "max_rounds"- assert (ws.telemetry / "run_state.json").is_symlink()---def test_ensure_layout_is_idempotent_and_dry_runnable(tmp_path: Path):- ws = Workspace(tmp_path / "run")- planned = ws.ensure_layout(dry_run=True)- assert planned and not ws.deliverable.exists()- first = ws.ensure_layout()- assert set(first) == set(planned)- assert ws.ensure_layout() == {} # nothing left to do- assert ws.ensure_layout(dry_run=True) == {}---def test_ensure_layout_never_clobbers_real_data(tmp_path: Path):- ws = Workspace(tmp_path / "run")- (ws.root / "evidence").mkdir(parents=True)- (ws.root / "evidence" / "keep.txt").write_text("evidence")- actions = ws.ensure_layout()- assert actions["evidence"] == "kept"- assert (ws.root / "evidence" / "keep.txt").read_text() == "evidence"- assert not (ws.root / "evidence").is_symlink()---def test_record_blocks_are_additive(tmp_path: Path):- """Telemetry can be added at finalization; manifests use the current round field."""- spec = Spec(id="x", track="static_object", language="blender", prompt="a chair")- rec = RunRecord(spec=spec, workspace=str(tmp_path), status="max_rounds")- assert rec.telemetry is None- rec.telemetry = RunTelemetry()- again = RunRecord.model_validate_json(rec.model_dump_json())- assert again.telemetry is not None and again.telemetry.schema_version == 1- assert RunDeliverable.model_validate({"round": 1, "commit": "abc"}).round == 1- assert RunDeliverable.model_validate({"best_round": 1, "commit": "abc"}).round is None---# --------------------------------------------------------------------------- relocation-def _moved_run(tmp_path: Path):- """Create a record whose absolute sheet path predates a workspace move."""- import shutil-- from codeverse3d.contracts.artifacts import Judgment, RenderSet- from codeverse3d.contracts.common import Backends, Language, Track- from codeverse3d.contracts.run import RoundRecord, RunStatus-- a = tmp_path / "A" / "run1"- (a / "artifacts" / "renders" / "r01").mkdir(parents=True)- sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"- sheet_a.write_bytes(b"PNG")- spec = Spec(id="run1", track=Track.STATIC_OBJECT, language=Language.BLENDER,- prompt="a wooden chair", backends=Backends(generator="gemini-cli:gemini-3.8-flash"))- rec = RunRecord(spec=spec, workspace=str(a), status=RunStatus.MAX_ROUNDS,- rounds=[RoundRecord(index=0, kind="generate",- judgment=Judgment(rubric="r", scores={}, overall=0.6, passed=False),- renders=RenderSet(views=[], contact_sheet=str(sheet_a)))])- b = tmp_path / "B" / "run1"- b.parent.mkdir(parents=True)- shutil.move(str(a), str(b))- return a, b, sheet_a, rec---def _captured(render) -> str:- """rich's Console holds its own stream, so capsys never sees it; widen it too so the- panel cannot wrap the path under assertion."""- from codeverse3d.cli._common import console-- old_width, console.width = console.width, 400- try:- with console.capture() as cap:- render()- finally:- console.width = old_width- return cap.get()---def test_a_copied_run_reads_its_own_files_while_the_original_still_exists(tmp_path):- """V10f: a copied run's stored absolute paths rebase onto THIS root, even while the original lives."""- import shutil-- from codeverse3d.workspace import Workspace-- a = tmp_path / "A" / "run1"- (a / "artifacts" / "renders" / "r01").mkdir(parents=True)- sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"- sheet_a.write_bytes(b"ORIGINAL")- b = tmp_path / "B" / "run1"- b.parent.mkdir(parents=True)- shutil.copytree(a, b) # copy: the original stays alive- (b / "artifacts" / "renders" / "r01" / "sheet.png").write_bytes(b"COPY")- got = Workspace(b).rebase(str(sheet_a))- assert got == b / "artifacts" / "renders" / "r01" / "sheet.png"- assert got.read_bytes() == b"COPY", "the copy's own file must win over the live original"- # ...and a path already under THIS root is untouched, existing or not- assert Workspace(a).rebase(str(sheet_a)) == sheet_a+ assert {"artifacts/", "deliverable/", "telemetry/", "trajectories/"} <= set(ignored)def test_a_stale_index_lock_names_the_remedy(tmp_path, monkeypatch):@@ -178,14 +71,3 @@ def test_a_planted_git_hook_or_filter_never_runs_on_a_commit(tmp_path):(ws.src / "model.py").write_text("x = 2\n")ws.changed_files()assert not fired.exists(), f"a planted filter ran during changed_files(): {fired.read_text()!r}"---def test_show_itself_prints_the_relocated_sheet_not_the_stored_one(tmp_path):- """The actual ``show`` command also rebases its displayed contact sheet."""- from codeverse3d.cli.layout_cmd import print_evidence- from codeverse3d.workspace import Workspace-- a, b, _sheet, rec = _moved_run(tmp_path)- out = _captured(lambda: print_evidence(Workspace(b), rec))- assert str(b / "artifacts" / "renders" / "r01" / "sheet.png") in out- assert str(a) not in out, "`3dcode show` must not print a path under the old root"diff --git a/harness/tests/core/test_runlock.py b/harness/tests/core/test_runlock.pyindex 04ef5af8..abfddf54 100644--- a/harness/tests/core/test_runlock.py+++ b/harness/tests/core/test_runlock.py@@ -2,17 +2,14 @@from __future__ import annotations-import threadingimport timefrom pathlib import Pathimport pytestfrom codeverse3d.proc import (- LOCKS_DIR,RunLocked,exclusive,- flock_path,holder_of,)@@ -71,45 +68,3 @@ def test_a_second_process_is_refused_and_a_killed_holder_never_wedges_the_run(tmassert holder_of(run_root) is None, "a SIGKILLed holder cannot leave a record behind"with exclusive(run_root):pass---def test_a_second_thread_is_refused_and_the_first_keeps_the_lock(tmp_path: Path):- """A refused sibling thread cannot release the owning thread's lock."""- run_root = tmp_path / "runs" / "slug"- run_root.mkdir(parents=True)- entered, refused = threading.Event(), []- release = threading.Event()-- def t2() -> None:- try:- with exclusive(run_root, what="T2"):- refused.append("ENTERED WHILE T1 HELD IT")- except RunLocked as e:- refused.append(str(e))-- with exclusive(run_root, what="T1"):- with exclusive(run_root, what="T1 again"): # the SAME thread re-enters- pass- th = threading.Thread(target=t2)- th.start()- th.join(timeout=10)- entered.set()- assert refused and "refusing to enter" in refused[0], refused- # T2's refusal must not have released T1's lock: the run is still held- assert (holder_of(run_root) or {}).get("what") == "T1"- release.set()- assert entered.is_set()- with exclusive(run_root): # fully released after the owning thread exits- pass----def test_the_lock_file_lives_outside_the_run_directory(tmp_path: Path):- """A --force wipe rmtree's the run root; a lock inside it would be deleted mid-hold."""- run_root = tmp_path / "runs" / "slug"- run_root.mkdir(parents=True)- with exclusive(run_root):- lock = flock_path(run_root)- assert lock.is_file()- assert run_root not in lock.parents- assert lock.parent == run_root.parent / LOCKS_DIRdiff --git a/harness/tests/cost/test_audit_read.py b/harness/tests/cost/test_audit_read.pyindex 61a23d0d..d5a5c4d1 100644--- a/harness/tests/cost/test_audit_read.py+++ b/harness/tests/cost/test_audit_read.py@@ -8,7 +8,7 @@ from pathlib import Pathimport pytest-from codeverse3d.addons.costreport.audit import audit_runs, find_runs, read_run+from codeverse3d.addons.costreport.audit import audit_runs, read_runfrom codeverse3d.contracts.common import Usagefrom codeverse3d.cost.ledger import load_ledger, record_callfrom codeverse3d.cost.types import Stage@@ -21,42 +21,6 @@ def test_a_run_reads_as_its_ledger_rows_and_its_record_facts(fake_run: Path, tmpassert led.track == "static_object" and led.stop_reason == "max_rounds" and led.round_built == [None]assert led.minutes == pytest.approx((20.0 + 60.0) / 60), "the run's minutes, not its span"assert led.model_s == pytest.approx(47.0)- # a run without a ledger is left out of the audit- bare = tmp_path / "pre_ledger"- shutil.copytree(fake_run, bare)- shutil.rmtree(bare / "telemetry")- assert audit_runs([tmp_path]).n_runs == 1- # a record with no extra["stop_reason"] stops where its status says (it read blank, N60)- rec = json.loads((bare / "record.json").read_text())- rec["extra"].pop("stop_reason")- (bare / "record.json").write_text(json.dumps(rec))- assert read_run(bare).stop_reason == "max_rounds"---def test_find_runs_counts_each_run_once_and_never_one_inside_a_run(tmp_path: Path):- """N58: `record.find_run_dirs` — a sub-workspace or a directory nested in a run is part of that run,- and a cell another battery symlinks in is found (a bare rglob missed it)."""- bat = tmp_path / "bat"- for d in (bat / "runs" / "a", bat / "runs" / "a" / "_assets" / "x", bat / "runs" / "a" / "eval" / "inner",- tmp_path / "other" / "cells" / "c" / "run"):- d.mkdir(parents=True)- (d / "record.json").write_text("{}")- (tmp_path / "other" / "cells" / "c" / "cell.json").write_text("{}")- (bat / "cells").mkdir()- (bat / "cells" / "c").symlink_to(tmp_path / "other" / "cells" / "c")- assert find_runs(bat) == [bat / "cells" / "c", bat / "runs" / "a"]---def test_an_ab_batterys_control_and_variant_cells_stay_two_runs(fake_run: Path, tmp_path: Path):- """ab_plan lays a prompt's cells out as ``arms/<arm>/cells/<id>/<generator>``: naming a- cell by its last two segments gave the control and the variant ONE label."""- for arm in ("control", "variant"):- cell = tmp_path / "out" / "arms" / arm / "cells" / "chair" / "harness_gemini-cli"- shutil.copytree(fake_run, cell / "run")- (cell / "cell.json").write_text(json.dumps({"prompt_id": "chair", "arm": "harness:x", "kind": "harness"}))- audit = audit_runs([tmp_path / "out"])- assert sorted(r.run for r in audit.runs) == ["control__chair__harness_gemini-cli",- "variant__chair__harness_gemini-cli"]def test_a_losing_candidate_is_waste(fake_run: Path, tmp_path: Path):diff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.pyindex 82155331..4b032efa 100644--- a/harness/tests/cost/test_audit_report.py+++ b/harness/tests/cost/test_audit_report.py@@ -11,23 +11,6 @@ import pytestfrom codeverse3d.addons.costreport.audit import (audit_runs,)-from codeverse3d.addons.costreport.report import console, markdown---def test_a_run_that_booked_no_money_still_reports(tmp_path: Path):- """A $0 run (every session killed before it reported usage) must not divide by zero."""- ws = tmp_path / "free_run"- ws.mkdir()- (ws / "record.json").write_text(json.dumps({- "spec": {"track": "static_object", "language": "blender", "backends": {"generator": "gemini-cli:gemini-3.8-flash"}},- "status": "failed", "rounds": [], "total_usage": {}, "extra": {}}))- ledger = ws / "telemetry" / "cost.jsonl"- ledger.parent.mkdir()- ledger.write_text(json.dumps({"run": ws.name, "round": 0, "stage": "baseline", "role": "generator", "backend": "gemini-cli",- "provider": "gemini", "model": "gemini-3.8-flash", "cost_usd": 0.0}) + "\n")- audit = audit_runs([tmp_path])- assert audit.n_runs == 1 and audit.total_usd == 0- assert "0%" in console(audit) and "# Cost audit" in markdown(audit)def test_a_lower_scoring_round_is_not_waste_but_a_repair_that_never_built_is(fake_run: Path, tmp_path: Path):diff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.pyindex 1344fcca..16ccf945 100644--- a/harness/tests/cost/test_cli.py+++ b/harness/tests/cost/test_cli.py@@ -12,16 +12,6 @@ from codeverse3d.cli.main import apprunner = CliRunner()-def test_cost_show_recheck_reports_drift(fake_run: Path):- r = runner.invoke(app, ["cost", "show", str(fake_run), "--recheck"])- assert r.exit_code == 0 and "re-priced total" in r.output---def test_cost_show_on_an_empty_tree_fails_cleanly(tmp_path: Path):- r = runner.invoke(app, ["cost", "show", str(tmp_path)])- assert r.exit_code != 0 and "no run with a cost ledger" in r.output--def test_cost_prices_and_estimate():r = runner.invoke(app, ["cost", "prices", "--provider", "gemini"])assert r.exit_code == 0 and "gemini:gemini-3.8-flash" in r.stdout and "verified" in r.stdout@@ -42,8 +32,6 @@ def test_cost_takes_a_bare_run_path_a_slug_or_a_battery(fake_run: Path):r = runner.invoke(app, ["cost", str(fake_run)])assert r.exit_code == 0, r.outputassert "| fake_run | static_object |" in r.output- r = runner.invoke(app, ["cost", fake_run.name, "--runs-dir", str(fake_run.parent)])- assert r.exit_code == 0 and "| fake_run | static_object |" in r.outputr = runner.invoke(app, ["cost", "--runs-dir", str(fake_run.parent)])assert r.exit_code == 0 and "runs: 1" in r.output@@ -64,37 +52,3 @@ def test_the_ledger_is_the_money(fake_run: Path):assert "$0.0999" in r.output and "$0.1200" in r.output # the ledger's own dollars-def test_cost_reports_the_calls_per_key_when_the_ledger_recorded_them(fake_run: Path, tmp_path: Path):- base = {"run": fake_run.name, "round": 0, "stage": "baseline", "role": "generator", "backend": "gemini",- "provider": "gemini", "model": "gemini-3.8-flash", "input_tokens": 1_000, "output_tokens": 10,- "cost_usd": 0.001, "price_source": "exact"}- _live_ledger(fake_run, [dict(base, key="…k1", attempts=1), dict(base, key="…k1", attempts=3),- dict(base, key="…k2", attempts=1)])- r = runner.invoke(app, ["cost", str(fake_run), "--md", str(tmp_path / "c.md")])- assert r.exit_code == 0, r.output- assert "key (last 4 chars):" in r.output and "…k1" in r.output and "tries/call 2.00" in r.output- md = (tmp_path / "c.md").read_text()- assert "## Per API key" in md and "tries/call" in md---def test_cost_cache_reports_the_cold_head_of_every_session(fake_run: Path):- _live_ledger(fake_run, [- {"run": "x", "round": 0, "stage": "baseline", "label": "api-agent:baseline:t0",- "provider": "gemini", "model": "gemini-3.8-flash", "input_tokens": 12_000,- "cached_tokens": 0, "cost_usd": 0.009, "price_input": 0.75, "price_cached": 0.075},- {"run": "x", "round": 0, "stage": "baseline", "label": "api-agent:baseline:t1",- "provider": "gemini", "model": "gemini-3.8-flash", "input_tokens": 20_000,- "cached_tokens": 12_000, "cost_usd": 0.007, "price_input": 0.75, "price_cached": 0.075},- ])- r = runner.invoke(app, ["cost", "cache", str(fake_run)])- assert r.exit_code == 0, r.output- assert "r0:baseline" in r.output and "12,000" in r.output- assert "cold heads cost" in r.output---def test_cost_prices_flags_stale_and_approximate_rows():- r = runner.invoke(app, ["cost", "prices", "--stale"])- assert r.exit_code == 0- assert "flags" in r.stdout and ("flagged" in r.stdout or "none older than" in r.stdout)- r = runner.invoke(app, ["cost", "prices", "--days", "-1"])- assert r.exit_code == 0 and "stale>-1d" in r.stdout # nothing is younger than -1 daysdiff --git a/harness/tests/cost/test_context.py b/harness/tests/cost/test_context.pyindex 0b75e2ea..d443ebbf 100644--- a/harness/tests/cost/test_context.py+++ b/harness/tests/cost/test_context.py@@ -3,12 +3,8 @@from __future__ import annotationsfrom codeverse3d.cost.context import (- CallContext,attribute,- bound_run,- call_context,context_from_label,- current,)from codeverse3d.cost.types import Role, Stage@@ -24,46 +20,7 @@ def test_label_tells_stage_role_and_round():assert context_from_label("captioner").role is Role.CAPTIONERassert context_from_label("").stage is Noneassert context_from_label("baseline_repair1").stage is Stage.REPAIR # repair wins- assert attribute(label="detail_seat_edge").stage is Stage.REFINE # the static detail roundzl = attribute(label="zone-layout") # the ledger agrees with the guard's stage='plan'assert zl.stage is Stage.PLAN and zl.role is Role.PLANNER-def test_session_beats_a_generation_label_a_named_job_beats_the_session_explicit_beats_all():- # best-of-N: the session knows it is a candidate, a call inside it only says "baseline"- with call_context(round=3, stage=Stage.CANDIDATE, label="cand_c1"):- got = attribute(label="baseline")- assert got.stage is Stage.CANDIDATE and got.round == 3- assert got.label == "baseline" # the most specific label is kept- forced = attribute(CallContext(stage=Stage.REPAIR, round=9), label="baseline")- assert forced.stage is Stage.REPAIR and forced.round == 9- # a spatial tool that bills a model inside a refine session is not a refine call- with call_context(round=2, stage=Stage.REFINE, role=Role.GENERATOR, label="refine_seat"):- verdict = attribute(label="judge:static_object:r02:s0")- assert verdict.stage is Stage.JUDGE and verdict.role is Role.JUDGE and verdict.round == 2- cap = attribute(label="caption:best")- assert cap.stage is Stage.CAPTION and cap.role is Role.CAPTIONER- # a label that names nothing keeps the session's attribution- anon = attribute(label="summarise")- assert anon.stage is Stage.REFINE and anon.role is Role.GENERATOR---def test_a_run_bound_in_a_thread_is_never_published_to_the_others():- """The 2026-08-30 leak: a process-global binding republished one parallel run's name."""- import threading-- ready, seen = threading.Barrier(3), {}-- def one(name: str) -> None:- with bound_run(name):- ready.wait(timeout=5)- seen[name] = current().run-- threads = [threading.Thread(target=one, args=(n,)) for n in ("a", "b")]- for t in threads:- t.start()- ready.wait(timeout=5)- for t in threads:- t.join(timeout=5)- assert seen == {"a": "a", "b": "b"}- assert current().run == "" # ...and the main thread never inherited either of themdiff --git a/harness/tests/cost/test_guard.py b/harness/tests/cost/test_guard.pyindex 16aacae8..c7a78eb6 100644--- a/harness/tests/cost/test_guard.py+++ b/harness/tests/cost/test_guard.py@@ -8,7 +8,6 @@ from codeverse3d.cost import estimate_callfrom codeverse3d.cost.guard import image_tokens, text_tokens-# ------------------------------------------------------------------ guarddef test_estimate_from_text_and_images():est = estimate_call("gemini:gemini-3.1-pro-preview", prompt="x" * 4000, n_images=4, output_tokens=2000)assert est.input_tokens == 1000 + image_tokens(4)diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex 0c6d9cb9..f562ebea 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -1,4 +1,4 @@-"""Metering: every ChatModel.generate and every CodingAgent.run becomes a ledger row."""+"""Metering: every ChatModel.generate becomes a ledger row."""from __future__ import annotations@@ -6,11 +6,9 @@ from pathlib import Pathimport pytest-from codeverse3d.contracts.agent import AgentJob, AgentResultfrom codeverse3d.contracts.chat import ChatMessage, ChatRequest, ChatResponsefrom codeverse3d.contracts.common import Usagefrom codeverse3d.cost.instrument import (- MeteredAgent,MeteredChatModel,run_ledger,)@@ -44,41 +42,6 @@ class FakeChat:return ChatResponse(text="ok", usage=_usage())-class FakeAgent:- """A backend whose individual calls already reach the ledger."""-- kind = "self-metering"- model = "gemini:gemini-3.8-flash"-- def __init__(self, chat, turns: int = 3):- self.chat, self.turns, self.seen_turns = chat, turns, 0-- @property- def id(self) -> str:- return f"{self.kind}:{self.model}"-- def available(self) -> tuple[bool, str]:- return True, "ok"-- def run(self, job: AgentJob) -> AgentResult:- self.seen_turns = job.max_turns- total = Usage()- for t in range(self.turns):- r = self.chat.generate(ChatRequest(messages=[ChatMessage.user("x")],- label=f"api-agent:{job.label}:t{t}"))- total = total + r.usage- return AgentResult(ok=True, exit_reason="completed", usage=total, tool_calls=self.turns)---class CliAgent(FakeAgent):- kind = "gemini-cli" # a vendor CLI bills as ONE session row-- def run(self, job: AgentJob) -> AgentResult:- self.seen_turns = job.max_turns- return AgentResult(ok=True, exit_reason="completed", tool_calls=4,- usage=_usage(backend="gemini-cli", input_tokens=50_000, cached_tokens=40_000))--def test_a_metered_call_becomes_one_priced_row(tmp_path: Path):chat = FakeChat()with run_ledger(tmp_path, run="r1"):@@ -89,107 +52,7 @@ def test_a_metered_call_becomes_one_priced_row(tmp_path: Path):assert row.run == "r1" and row.stage is Stage.JUDGE and row.role is Role.JUDGE and row.round == 1assert row.input_tokens == 12_000 and row.cached_tokens == 8_000 and row.cache_hit is Trueassert row.price_source == "exact" and row.price_input == 0.75 and row.price_checked- assert row.latency_ms == 1234 and row.cost_usd > 0---def test_both_registries_hand_out_metered_backends(monkeypatch: pytest.MonkeyPatch):- from codeverse3d.agents import registry- from codeverse3d.models import registry as model_registry-- monkeypatch.setattr(registry, "_build_agent", lambda aid: CliAgent(FakeChat()))- assert isinstance(registry.get_coding_agent("gemini-cli:m"), MeteredAgent)- monkeypatch.setattr(model_registry, "build_chat_model", lambda mid: FakeChat())- model_registry.get_chat_model.cache_clear()- try:- assert isinstance(model_registry.get_chat_model("gemini:gemini-3.8-flash"), MeteredChatModel)- finally:- model_registry.get_chat_model.cache_clear()---def test_accounting_never_breaks_a_call(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- def boom(*a: object, **k: object) -> None:- raise RuntimeError("ledger on fire")-- monkeypatch.setattr("codeverse3d.cost.instrument.record_call", boom)- with run_ledger(tmp_path, run="r1"):- resp = MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")]))- assert resp.text == "ok"---def test_the_proxy_forwards_everything_else():- chat = FakeChat()- chat.pool = "the-key-pool" # type: ignore[attr-defined]- m = MeteredChatModel(chat)- assert m.id == "gemini:gemini-3.8-flash" and m.provider == "gemini"- assert m.pool == "the-key-pool"- agent = MeteredAgent(FakeAgent(chat))- assert agent.kind == "self-metering" and agent.available() == (True, "ok")---def test_post_hoc_work_never_creates_a_partial_ledger(tmp_path: Path):- """Post-hoc work never creates a misleading partial ledger."""- with run_ledger(tmp_path, run="old", create=False) as led:- assert led is None- MeteredChatModel(FakeChat()).generate(- ChatRequest(messages=[ChatMessage.user("x")], label="judge:static_object:r00:s0"))- assert not (tmp_path / "telemetry" / "cost.jsonl").exists()- # but a run that already keeps one is appended to- with run_ledger(tmp_path, run="old"):- MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))- with run_ledger(tmp_path, run="old", create=False) as led:- assert led is not None- MeteredChatModel(FakeChat()).generate(- ChatRequest(messages=[ChatMessage.user("x")], label="judge:static_object:r00:s0"))- assert len(load_ledger(tmp_path)) == 2---# ---------------------------------------------------- who meters the inside of a session-class SideEffectCliAgent(CliAgent):- """A subscription CLI during whose session something else bills a model."""-- def __init__(self, chat, side_effect):- super().__init__(chat)- self.side_effect = side_effect-- def run(self, job: AgentJob) -> AgentResult:- self.side_effect()- return super().run(job)---def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_path: Path):- """An unrelated inner model row never suppresses the CLI session."""- def inner_model_call() -> None:- MeteredChatModel(FakeChat()).generate(- ChatRequest(messages=[ChatMessage.user("x")], label="caption:best"))-- with run_ledger(tmp_path, run="r1"):- MeteredAgent(SideEffectCliAgent(FakeChat(), inner_model_call)).run(- AgentJob(workspace=str(tmp_path), prompt="p", label="baseline", round=0, kind="baseline"))- rows = load_ledger(tmp_path)- assert len(rows) == 2, [r.label for r in rows]- session = next(r for r in rows if r.source == "session")- assert session.backend == "gemini-cli" and session.input_tokens == 50_000- tool = next(r for r in rows if r.source != "session")- assert tool.stage is Stage.CAPTION # and it is NOT filed under the session's stage---# ------------------------------------------------------------------- nesting / parallelism-def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path):- """`bench.run_bench` runs N prompts in N threads; their rows must not mix."""- from concurrent.futures import ThreadPoolExecutor-- def one(name: str) -> None:- with run_ledger(tmp_path / name, run=name):- for _ in range(3):- MeteredChatModel(FakeChat()).generate(- ChatRequest(messages=[ChatMessage.user("x")], label="baseline"))-- names = [f"p{i}" for i in range(4)]- with ThreadPoolExecutor(max_workers=4) as pool:- list(pool.map(one, names))- for name in names:- rows = load_ledger(tmp_path / name)- assert len(rows) == 3 and {r.run for r in rows} == {name}+ assert row.cost_usd > 0class KeyedChat(FakeChat):@@ -224,7 +87,7 @@ def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: PatChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"},label="planner"))assert resp.parsed == {"ok": True}- rows = load_ledger(tmp_path) # "attempt" forensics are filtered here; "extra" is money+ rows = load_ledger(tmp_path) # "extra" is the discarded round-trip's moneybad, = [r for r in rows if r.source == "extra"]logical, = [r for r in rows if r.source == "live"]assert logical.outcome == "ok" and logical.attempts == 2 and logical.call_id@@ -232,45 +95,7 @@ def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: Patassert bad.call_id == logical.call_id and bad.cost_usd > 0total = summarise(rows).totalassert total.input_tokens == logical.input_tokens + bad.input_tokens- assert summarise(load_ledger(tmp_path, include_attempts=True)).total.input_tokens \- == total.input_tokens + 100, "include_attempts adds the winner's forensic row, once"- win, = [r for r in load_ledger(tmp_path, include_attempts=True) if r.source == "attempt"]- assert not win.discarded and win.attempt == 2---def test_a_late_hedge_loser_keeps_its_stage_role_and_round(tmp_path: Path):- """The loser lands after generate() returned, in a thread with empty contextvars."""- import threading-- from codeverse3d.cost.context import AttemptRecord, attempt_sink, call_context-- loser_usage = _usage(cost_usd=0.30)-- class Hedging:- provider, model = "gemini", "gemini-3.8-flash"- id = "gemini:gemini-3.8-flash"- late: threading.Thread | None = None-- def generate(self, req):- sink = attempt_sink() # captured once, like gemini._attempt_hook-- def loser_lands():- sink(AttemptRecord(attempt=2, key="k" * 20, outcome="ok", discarded=True,- usage=loser_usage, error=""))-- self.late = threading.Thread(target=loser_lands) # fresh thread = empty context- return ChatResponse(text="winner", usage=_usage(cost_usd=0.01))-- inner = Hedging()- with run_ledger(tmp_path, run="r1"):- with call_context(stage="candidate", role="generator", round=0):- MeteredChatModel(inner).generate(ChatRequest(messages=[ChatMessage.user("x")], label="baseline"))- assert inner.late is not None- inner.late.start()- inner.late.join()- loser, = [r for r in load_ledger(tmp_path) if r.source == "extra"]- assert loser.discarded and loser.stage is Stage.CANDIDATE- assert loser.role is Role.GENERATOR and loser.round == 0+ assert {r.source for r in rows} == {"live", "extra"}def test_a_failed_call_is_recorded_re_raised_and_carries_what_was_billed(tmp_path: Path):@@ -295,20 +120,3 @@ def test_a_failed_call_is_recorded_re_raised_and_carries_what_was_billed(tmp_patassert (row.cost_usd > 0) is (want["input_tokens"] > 0), "a billed failure is no longer a $0 row"[email protected]("kind,label,stage", [- ("zone", "zones_quay_water", Stage.ZONES), # N72: single-shot filed it under `other`- ("candidate", "baseline_c0", Stage.CANDIDATE),-])-def test_a_single_shot_task_is_booked_where_its_agent_session_would_be(tmp_path: Path, kind, label, stage):- from codeverse3d.tracks.generation import GenerationTask, generate_files- from codeverse3d.workspace import Workspace-- ws = Workspace(tmp_path / "run").create()- with run_ledger(tmp_path / "ss", run="r1"):- generate_files(ws, model=MeteredChatModel(FakeChat()),- task=GenerationTask(label=label, prompt="p", round=0, kind=kind))- with run_ledger(tmp_path / "ag", run="r1"):- MeteredAgent(CliAgent(FakeChat())).run(- AgentJob(workspace=str(ws.root), prompt="p", label=label, round=0, kind=kind))- (single,), (session,) = load_ledger(tmp_path / "ss"), load_ledger(tmp_path / "ag")- assert (single.stage, single.round) == (session.stage, session.round) == (stage, 0)diff --git a/harness/tests/cost/test_ledger.py b/harness/tests/cost/test_ledger.pyindex 601460af..594f12b0 100644--- a/harness/tests/cost/test_ledger.py+++ b/harness/tests/cost/test_ledger.py@@ -1,12 +1,10 @@-"""The append-only ledger: writing, reading, pricing provenance, aggregation."""-+"""The append-only ledger."""from __future__ import annotationsfrom pathlib import Pathfrom codeverse3d.contracts.common import Usage-from codeverse3d.cost import load_ledger, record_call-from codeverse3d.cost.ledger import existing_ledger_path, open_run_ledger+from codeverse3d.cost import record_calldef _usage(**kw: object) -> Usage:@@ -24,15 +22,6 @@ def test_keeps_the_billed_cost_but_can_reprice(tmp_path: Path):assert abs(repriced.cost_usd - 0.02475) < 1e-9 and repriced.recorded_usd == 0.123-def test_bad_line_does_not_lose_the_file(tmp_path: Path):- p = tmp_path / "l.jsonl"- record_call(_usage(), run="r", stage="plan", ledger=p)- with p.open("a") as fh:- fh.write("{not json\n")- record_call(_usage(), run="r", stage="judge", ledger=p)- assert len(load_ledger(p)) == 2--def test_provider_reported_cost_is_flagged(tmp_path: Path):"""A subscription CLI bills us a cost our table cannot reproduce: keep thedollar, mark it unauditable."""@@ -41,11 +30,3 @@ def test_provider_reported_cost_is_flagged(tmp_path: Path):assert row.cost_usd == 1.17 and row.price_source == "provider-reported"-def test_a_run_has_exactly_one_ledger_file(tmp_path: Path):- """``open_run_ledger`` writes only ``telemetry/cost.jsonl``, and that is the only name read."""- led = open_run_ledger(tmp_path)- assert existing_ledger_path(tmp_path) is None # nothing written yet- record_call(_usage(), run="r", stage="baseline", ledger=led)- assert existing_ledger_path(tmp_path) == tmp_path / "telemetry" / "cost.jsonl"- assert sorted(p.name for p in tmp_path.rglob("*.jsonl")) == ["cost.jsonl"]- assert len(load_ledger(tmp_path)) == 1diff --git a/harness/tests/cost/test_live.py b/harness/tests/cost/test_live.pyindex b8bc1f95..21316a08 100644--- a/harness/tests/cost/test_live.py+++ b/harness/tests/cost/test_live.py@@ -1,7 +1,4 @@-"""LIVE (needs gemini keys): the two measurements docs/COST.md quotes.-- python -m pytest tests/cost/test_live.py -q -m live-"""+"""LIVE (needs gemini keys): a metered run's ledger equals its record (docs/COST.md §12)."""from __future__ import annotations@@ -9,45 +6,9 @@ from pathlib import Pathimport pytest-from codeverse3d.contracts.chat import ChatMessage, ChatRequest-from codeverse3d.cost.guard import estimate_call-pytestmark = pytest.mark.live-REPO = Path(__file__).resolve().parents[2]---def _stable_text() -> str:- from codeverse3d.judges.prompt_builder import build_system_prompt- from codeverse3d.judges.rubrics import load_rubric-- return "\n".join([- build_system_prompt(load_rubric("static_object")),- (REPO / "codeverse3d/prompts/blender/contract.md").read_text(),- (REPO / "codeverse3d/prompts/blender/system.md").read_text(),- (REPO / "codeverse3d/prompts/system/harness_contract.md").read_text(),- *((REPO / "codeverse3d/skills" / name / "SKILL.md").read_text()- for name in ("c3d-part-contact", "c3d-blender-forms")),- ])---def _send(model, text: str):- return model.generate(ChatRequest(messages=[ChatMessage.user(text)], max_output_tokens=1100,- temperature=0.0, thinking="low", label="cost-test")).usage---def test_estimate_is_within_15_percent_of_the_bill():- """The pre-send estimate has to be good enough to route on."""- from codeverse3d.models import get_chat_model-- text = _stable_text()[:20_000]- est = estimate_call("gemini:gemini-3.8-flash", prompt=text, output_tokens=40)- usage = _send(get_chat_model("gemini:gemini-3.8-flash"),- text + "\n\nReply with ONE JSON object {\"ok\": true}.")- assert abs(est.input_tokens - usage.input_tokens) / usage.input_tokens < 0.15--# --------------------------------------------------------------- the metered run loopdef test_a_metered_run_reconciles_with_its_own_record(tmp_path: Path):"""LIVE end-to-end: a real (cheap) run's ledger must equal record.total_usage.diff --git a/harness/tests/cost/test_price_hygiene.py b/harness/tests/cost/test_price_hygiene.pyindex 854adbba..91db9c4f 100644--- a/harness/tests/cost/test_price_hygiene.py+++ b/harness/tests/cost/test_price_hygiene.py@@ -5,10 +5,8 @@ from __future__ import annotationsfrom codeverse3d.contracts.common import Usagefrom codeverse3d.models.pricing import (PRICES,- SOURCES,estimate_cost,price_provenance,- unit_prices,)#: model ids exposed by defaults, routes, CLI examples, and public backend contracts.@@ -30,17 +28,6 @@ SUPPORTED_MODEL_IDS = ()-def test_long_context_tier_is_applied():- small = Usage(input_tokens=100_000, output_tokens=1_000)- big = Usage(input_tokens=300_000, output_tokens=1_000)- assert unit_prices("gemini", "gemini-3.1-pro-preview", prompt_tokens=100_000)[0] == 2.0- assert unit_prices("gemini", "gemini-3.1-pro-preview", prompt_tokens=300_000)[0] == 4.0- assert estimate_cost("gemini", "gemini-3.1-pro-preview", big) > \- 3 * estimate_cost("gemini", "gemini-3.1-pro-preview", small)- # flash has no long-context tier- assert unit_prices("gemini", "gemini-3.8-flash", prompt_tokens=900_000)[0] == 0.75--def test_supported_model_ids_resolve_to_a_price():u = Usage(input_tokens=1_000, output_tokens=1_000)for model_id in SUPPORTED_MODEL_IDS:@@ -49,30 +36,6 @@ def test_supported_model_ids_resolve_to_a_price():assert estimate_cost(provider, model, u) > 0, model_id-def test_a_bracketed_context_variant_never_borrows_a_sibling_price():- """``[1m]`` is not a version suffix: a bracketed id needs its own exact row, and has none."""- assert price_provenance("anthropic", "claude-opus-5-5[1m]").price is None- assert price_provenance("anthropic", "claude-sonnet-5-5[1m]").price is None---# --------------------------------------------------------------- staleness maintenance-def test_every_price_row_was_checked_within_the_maintenance_window():- """When this fails, re-check the providers' pages and bump CHECKED — not the threshold."""- from datetime import date, datetime-- from codeverse3d.cli.cost_cmd import STALE_AFTER_DAYS- from codeverse3d.models.pricing import price_provenance-- stale = []+def test_every_price_row_declares_its_provenance():for prov, model in sorted(PRICES):- row = price_provenance(prov, model)- assert row.status in ("verified", "inferred", "unverified"), model- assert (PRICES[(prov, model)].source or prov) in SOURCES, model- try:- age = (date.today() - datetime.strptime(row.checked, "%Y-%m-%d").date()).days- except (TypeError, ValueError):- stale.append(f"{prov}:{model} (no checked date)")- continue- if age > STALE_AFTER_DAYS:- stale.append(f"{prov}:{model} ({age} days)")- assert not stale, f"price rows older than {STALE_AFTER_DAYS} days: {stale}"+ assert price_provenance(prov, model).status in ("verified", "inferred", "unverified"), modeldiff --git a/harness/tests/cost/test_tally.py b/harness/tests/cost/test_tally.pyindex 5febd6c4..d3e8241b 100644--- a/harness/tests/cost/test_tally.py+++ b/harness/tests/cost/test_tally.py@@ -3,19 +3,15 @@from __future__ import annotationsimport threading-import timefrom pathlib import Pathimport pytest-from codeverse3d.contracts.agent import AgentJob, AgentResult-from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ChatResponse+from codeverse3d.contracts.chat import ChatMessage, ChatRequestfrom codeverse3d.contracts.common import Usage-from codeverse3d.contracts.run import StepTime-from codeverse3d.cost.context import AttemptRecord, attempt_sink-from codeverse3d.cost.instrument import MeteredAgent, MeteredChatModel, run_ledger+from codeverse3d.cost.instrument import run_ledgerfrom codeverse3d.cost.ledger import load_ledger, record_call-from codeverse3d.cost.tally import Tally, tally, timed+from codeverse3d.cost.tally import Tally, tallyREQ = ChatRequest(messages=[ChatMessage.user("x")], label="judge:static_object:r00:s0")@@ -26,7 +22,6 @@ def test_a_tally_holds_exactly_the_ledger_rows_booked_inside_it(tmp_path: Path):record_call(u, stage="plan")with tally() as inner:record_call(u, stage="judge")- record_call(u, stage="judge", source="attempt") # forensics: its call's row carries itassert inner.usage.input_tokens == 1_000 and outer.usage.input_tokens == 2_000assert outer.usage.cost_usd == pytest.approx(sum(r.cost_usd for r in load_ledger(tmp_path)))@@ -55,74 +50,7 @@ def test_lost_time_adds_up_in_a_thread_and_takes_the_slowest_thread_side_by_sideassert t.lost_s() == pytest.approx(15.0)# A lost 100 of its 600 s; B took 550 without an error: the step would have ended at 550assert _side_by_side((600.0, 100.0), (550.0, 0.0)).lost_s() == pytest.approx(50.0)- # B took 600 anyway: A's errors cost the step nothing- assert _side_by_side((600.0, 100.0), (600.0, 0.0)).lost_s() == pytest.approx(0.0)# both sat out the same storm: the step lost it once, not twiceassert _side_by_side((600.0, 100.0), (560.0, 100.0)).lost_s() == pytest.approx(100.0)-def test_a_timed_step_is_one_row_with_its_wall_and_what_it_lost():- steps: list[StepTime] = []- with timed("judge", steps, round_index=2) as t:- t.add_time(5.0, 2.0)- time.sleep(0.03)- (row,) = steps- assert row.step == "judge" and row.round == 2 and row.wall_s >= 0.03- assert row.lost_s == pytest.approx(row.wall_s), "lost is clipped to the step's own clock"- with timed("skeleton", steps):- pass- assert len(steps) == 1, "a step that took no time leaves no row"- with pytest.raises(RuntimeError), timed("build", steps):- time.sleep(0.02)- raise RuntimeError("the time was still spent")- assert steps[-1].step == "build"---class SinkChat:- """A backend that reports its round-trips like ``GeminiModel`` does."""-- provider, model, id = "gemini", "gemini-3.8-flash", "gemini:gemini-3.8-flash"-- def __init__(self, trips: list[tuple[str, int, float]]):- self.trips = trips # (outcome, answered latency ms, seconds the round-trip holds)-- def generate(self, request: ChatRequest) -> ChatResponse:- sink = attempt_sink()- last = len(self.trips)- for i, (outcome, latency, hold) in enumerate(self.trips, 1):- time.sleep(hold)- sink(AttemptRecord(attempt=i, key="k", outcome=outcome, discarded=i != last,- usage=Usage(model=self.model, latency_ms=latency)))- return ChatResponse(text="ok", usage=Usage(model=self.model, input_tokens=10, latency_ms=self.trips[-1][1]))---def _lost(chat: object, tmp_path: Path) -> tuple[float, float]:- with run_ledger(tmp_path, run="r"), tally() as t:- MeteredChatModel(chat).generate(REQ)- (wall, lost), = t._time.values()- return wall, lost---def test_a_clean_call_loses_nothing_and_a_503_before_the_answer_is_lost(tmp_path: Path):- wall, lost = _lost(SinkChat([("ok", 50, 0.05)]), tmp_path)- assert lost == 0.0 and wall >= 0.05- wall, lost = _lost(SinkChat([("5xx", 0, 0.10), ("ok", 40, 0.04)]), tmp_path)- assert lost == pytest.approx(wall - 0.040, abs=0.02) and lost >= 0.09- # a reply that came back unusable is the model's own time, not the provider's- wall, lost = _lost(SinkChat([("skip", 60, 0.06), ("ok", 40, 0.04)]), tmp_path)- assert lost == 0.0---def test_an_agent_session_books_what_its_cli_lost_to_the_provider(tmp_path: Path):- class Cli:- kind, model, id = "gemini-cli", "gemini-3.8-flash", "gemini-cli:gemini-3.8-flash"-- def run(self, job: AgentJob) -> AgentResult:- time.sleep(0.02)- return AgentResult(ok=True, provider_wait_s=0.015, usage=Usage(backend="gemini-cli", input_tokens=5))-- with run_ledger(tmp_path, run="r"), tally() as t:- MeteredAgent(Cli()).run(AgentJob(workspace=str(tmp_path), prompt="p", label="baseline", round=0))- (wall, lost), = t._time.values()- assert wall >= 0.02 and lost == pytest.approx(0.015)- assert t.usage.input_tokens == 5, "the session row is booked into the tally like any ledger row"diff --git a/harness/tests/flywheel_cli/__init__.py b/harness/tests/flywheel_cli/__init__.pyindex e69de29b..8b137891 100644--- a/harness/tests/flywheel_cli/__init__.py+++ b/harness/tests/flywheel_cli/__init__.py@@ -0,0 +1 @@+diff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.pyindex 984bbe80..40c9b8d6 100644--- a/harness/tests/flywheel_cli/conftest.py+++ b/harness/tests/flywheel_cli/conftest.py@@ -1,6 +1,4 @@-"""Shared fixtures: a synthetic run (git repo with two commits, tiny PNGs, each round's-kept GLB under artifacts/rNN/, record.json with two judged rounds) — no models, Blender or-node required."""+"""Shared fixtures: a synthetic run (git repo, tiny PNGs, record.json with two judged rounds); no models needed."""from __future__ import annotationsdiff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.pyindex 89175ca7..bbf5e311 100644--- a/harness/tests/flywheel_cli/test_captions.py+++ b/harness/tests/flywheel_cli/test_captions.py@@ -8,9 +8,7 @@ import pytestfrom codeverse3d.addons.dataset.captions import (CaptionError,- Captions,caption_sample,- validate_captions,)from codeverse3d.contracts.chat import ImagePartfrom codeverse3d.record.record import load_record@@ -62,40 +60,3 @@ def test_caption_cmd_writes_the_captioner_row_into_the_run_ledger(fake_run, monkrows = [json.loads(ln) for ln in ledger.path.read_text().splitlines() if ln.strip()]assert any(row.get("label") == "captioner" for row in rows), rowsassert (ws.deliverable / "captions.json").is_file()---def test_caption_live_gemini(fake_run):- from codeverse3d.config import get_settings-- if not get_settings().gemini_api_keys:- pytest.skip("no gemini keys")- ws, rec = fake_run- caps = caption_sample(ws, rec, "gemini:gemini-3.8-flash")- assert len(caps.detailed) > 20 and "blender" in caps.instruction.lower()---GOOD_JS = dict(GOOD, instruction="Write a Three.js module that builds a desk lamp with a round base and conical shade.",- factory="Build the base cylinder, sweep the arm along an arc, add the cone shade, then merge the groups.")-SHADER = dict(GOOD, instruction="Write a GLSL fragment shader showing neon rain running down a window at night.",- factory="Layer a bokeh background pass, a grid-cell rain pass, then grade with a vignette.")--[email protected]("fields, language, problem", [- (GOOD, "blender", None),- (dict(GOOD, instruction="Please model a wooden chair with four legs for me."), "blender", "target language"),- (GOOD_JS, "threejs", None), # the required 'Three.js' phrase is not the forbidden API- (dict(GOOD_JS, factory="Build a THREE.Group holding THREE.Mesh boxes for every part."), "threejs", "THREE."),- (SHADER, "glsl_shader", None),- (dict(SHADER, instruction="Write an OpenGL Python program showing neon rain on a window."), "opengl_python", None),- (dict(SHADER, instruction="Write an OpenGL Python program showing neon rain on a window.",- factory="Uses moderngl FBOs for the feedback pass."), "opengl_python", "moderngl"),-])-def test_validate_captions(fields, language, problem):- from codeverse3d.contracts.common import Language-- probs = validate_captions(Captions(**fields), Language(language))- assert (probs == []) if problem is None else any(problem in p for p in probs), probs---# --------------------------------------------------------------------------- a run recorded before artifacts/rNN/diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.pyindex d1ff3668..428c2c67 100644--- a/harness/tests/flywheel_cli/test_cli.py+++ b/harness/tests/flywheel_cli/test_cli.py@@ -46,13 +46,6 @@ def stub_track(monkeypatch):return install-def test_help_and_version():- r = runner.invoke(app, ["--help"])- assert r.exit_code == 0 and "flywheel" in r.output and "doctor" in r.output- r = runner.invoke(app, ["--version"])- assert r.exit_code == 0 and "3dcode" in r.output--def test_make_no_run_creates_valid_workspace(tmp_path: Path):runs = tmp_path / "runs"r = runner.invoke(app, ["make", "a wooden dining chair", "--track", "static_object", "--language", "blender",@@ -77,27 +70,20 @@ def test_make_no_run_creates_valid_workspace(tmp_path: Path):assert r3.exit_code == 0-def test_tools_list_handles_an_optional_spatial_install():- r = runner.invoke(app, ["tools", "list"])- # spatial tools may or may not be installed yet; either a table or a clear message, never a traceback- assert r.exit_code in (0, 2), r.output- assert "Traceback" not in r.output--def test_doctor_json(monkeypatch):"""The CLI serialises doctor rows; the checks themselves are tested by install tests."""- import codeverse3d.cli.doctor as doctor_cli+ import codeverse3d.doctor as doctor_cliseen = {}- def fake_doctor(*, live, gpu, skills):- seen.update(live=live, gpu=gpu, skills=skills)+ def fake_doctor(*, live, gpu):+ seen.update(live=live, gpu=gpu)return [("python", "OK", "3.x"), ("node", "WARN", "missing"), ("mcp", "FAIL", "broken")]monkeypatch.setattr(doctor_cli, "run_doctor", fake_doctor)r = runner.invoke(app, ["doctor", "--no-gpu", "--json"])assert r.exit_code == 1, r.output- assert seen == {"live": False, "gpu": False, "skills": False}+ assert seen == {"live": False, "gpu": False}rows = json.loads(r.output[r.output.index("["):])assert rows == [{"check": "python", "status": "OK", "detail": "3.x"},@@ -143,8 +129,6 @@ def test_commands_over_a_runs_dir(runs_dir: Path, tmp_path: Path, monkeypatch):assert (out / "metadata.parquet").is_file() and (out / "samples-000.tar").is_file()r = runner.invoke(app, ["flywheel", "pairs", str(runs_dir), str(tmp_path / "p.jsonl")])assert r.exit_code == 0 and "pairs" in r.output- r = runner.invoke(app, ["flywheel", "index", str(runs_dir), str(tmp_path / "i.sqlite")])- assert r.exit_code == 0 and "indexed 3 runs" in r.output# no --model: Settings.default_captioner, not a literal the CLI kept (a configured one was ignored)seen: list[str] = []@@ -206,31 +190,6 @@ def test_commands_over_a_runs_dir(runs_dir: Path, tmp_path: Path, monkeypatch):assert "candidates" in r.output and "c1" in r.output and "pairwise" not in r.output-def test_calibration_rubric_map_includes_graphics(tmp_path: Path):- """A graphics round with no stored judgment is re-judged with the track's rubric, not static_object."""- from codeverse3d.addons.calibration import load_run_cases- from codeverse3d.contracts.artifacts import RenderSet, RenderView- from codeverse3d.contracts.common import Language, Track- from codeverse3d.contracts.run import RoundRecord-- run = tmp_path / "shader_run"- (run / "rounds").mkdir(parents=True)- spec = Spec(id="shader_run", track=Track.GRAPHICS, language=Language.GLSL_SHADER, prompt="neon rain on a window")- (run / "spec.json").write_text(spec.model_dump_json())- renders = RenderSet(views=[RenderView(name="frame_0", path=str(run / "artifacts" / "renders" / "r00" / "frame_0.png"))],- renderer="fake")- (run / "rounds" / "r00.json").write_text(RoundRecord(index=0, kind="baseline", renders=renders).model_dump_json())- assert [c.rubric for c in load_run_cases(run)] == ["shader"]---def test_make_invalid_combo_leaves_no_orphan_workspace(tmp_path: Path):- runs = tmp_path / "runs"- r = runner.invoke(app, ["make", "x", "--track", "scene", "--language", "blender",- "--runs-dir", str(runs), "--no-run", "--slug", "bad"])- assert r.exit_code == 1- assert not (runs / "bad").exists(), "invalid spec must not leave an orphan run dir"--def test_resume_refuses_a_finished_run_and_never_re_enters_it(made_run, stub_track):"""A finished run never re-enters the track unless forced; a raised cap is written to spec.jsonand seen by the resumed run; spec drift is a clean CLI error."""@@ -281,299 +240,6 @@ def test_resume_refuses_a_finished_run_and_never_re_enters_it(made_run, stub_traassert "Traceback" not in r.output-def test_render_graphics_regenerates_frames(tmp_path: Path, monkeypatch):- import codeverse3d.languages as langs- from codeverse3d.contracts.artifacts import BuildResult- from codeverse3d.contracts.common import Language- from tests.flywheel_cli.conftest import make_fake_run, tiny_png-- ws, rec = make_fake_run(tmp_path / "runs", "rain_glsl", prompt="neon rain", language=Language.GLSL_SHADER)- frames = ws.artifacts / "frames"- tiny_png(frames / "f00_t0.00.png")- tiny_png(frames / "f01_t1.00.png")- sheet = tiny_png(ws.artifacts / "frames_sheet.png", (0, 0, 200))-- class _RT:- def build(self, w, **kw):- return BuildResult(ok=True, language="glsl_shader", glb_path=None, duration_ms=8,- census={"renderer": "fake-gl"},- extra_paths={"frames": str(frames), "sheet": str(sheet)})-- monkeypatch.setattr(langs, "get_runtime", lambda language: _RT())- out = tmp_path / "out"- r = runner.invoke(app, ["render", "rain_glsl", "--runs-dir", str(tmp_path / "runs"), "--out", str(out)])- assert r.exit_code == 0, r.output- assert (out / "sheet.png").is_file() and len(list(out.glob("f*.png"))) == 2- assert "fake-gl" in r.output---def test_best_of_n_is_not_offered_on_a_scene(tmp_path: Path):- """F1: explicit --candidates N on a scene is refused, the default is 1, a stale spec runs one."""- from codeverse3d.config import get_settings- from codeverse3d.contracts.common import Track- from codeverse3d.tracks.scene import SceneTrack-- runs = tmp_path / "runs"- r = runner.invoke(app, ["make", "a kitchen", "--track", "scene", "--candidates", "2",- "--no-run", "--runs-dir", str(runs), "--slug", "scn2"])- assert r.exit_code == 1 and "--candidates" in r.output and not (runs / "scn2").exists()- r = runner.invoke(app, ["make", "a kitchen", "--track", "scene",- "--no-run", "--runs-dir", str(runs), "--slug", "scnq"])- assert r.exit_code == 0- spec = Spec.model_validate(json.loads((runs / "scnq" / "spec.json").read_text()))- assert spec.options.candidates == 1- r = runner.invoke(app, ["resume", "scnq", "--runs-dir", str(runs), "--candidates", "2"])- assert r.exit_code == 1 and "--candidates" in r.output- # a scene spec recorded before the fix (options.candidates=2) runs, and records, one- stale = spec.model_copy(update={"options": spec.options.model_copy(update={"candidates": 2})})- assert SceneTrack(n_candidates=2)._resolve_candidates(stale, get_settings()) == 1- assert spec.track is Track.SCENE---# --------------------------------------------------- render must not publish the wrong round-def _round_guard_ws(tmp_path: Path, *, tree: int, best: int | None = None):- """A workspace whose render tree sits at `tree` (an old record may still name a `best`)."""- import json as _json-- from codeverse3d.workspace import Workspace-- ws = Workspace(tmp_path / "wronground")- ws.create()- for i in range(tree + 1):- (ws.artifacts / "renders" / f"r{i:02d}").mkdir(parents=True, exist_ok=True)- if best is not None:- ws.record_path.write_text(_json.dumps({"best_round": best}))- return ws---def test_render_only_labels_the_working_tree_round(tmp_path: Path):- """A plain render is the working tree's round; a --round naming another one is refused."""- from codeverse3d.cli._common import CliError- from codeverse3d.cli.inspect_cmd import _render_round_or_refuse-- ws = _round_guard_ws(tmp_path, tree=4, best=3)- assert _render_round_or_refuse(ws, None) == 4, "an old record's best_round no longer matters"- with pytest.raises(CliError) as ei:- _render_round_or_refuse(ws, 3)- msg = str(ei.value)- assert "working tree, which is at round 4" in msg and "3dcode pick" in msg and ei.value.exit_code == 2- assert _render_round_or_refuse(ws, 4) == 4, "rendering the tree's own round is fine"- assert _render_round_or_refuse(_round_guard_ws(tmp_path / "b", tree=1), None) == 1--[email protected]("flag,value", [- ("--generator", "antigravity:gemini-3.8-flash"), ("--generator", "gemini-cli:gemini-3.8-flash"), ("--generator", "nocolon"), ("--generator", "single-shot:nope"),- ("--generator", "single-shot:gemini:"), ("--planner", "gemini"), ("--judge", "bogus:model"),- ("--captioner", "gemini:"),-], ids=lambda v: v.strip("-"))-def test_make_refuses_a_backend_id_it_cannot_build_before_the_run_exists(tmp_path: Path, flag: str, value: str):- """An unknown id used to surface after the PAID plan stage, as a traceback and an orphan run."""- r = runner.invoke(app, ["make", "a cup", flag, value, "--no-run", "--runs-dir", str(tmp_path / "runs"), "--slug", "b"])- assert r.exit_code == 2 and flag in r.output and "Traceback" not in r.output- assert not (tmp_path / "runs" / "b").exists()--[email protected]("args", [["--dim", "height=0"], ["--dim", "height=-1"], ["--dim", "height=nan"],- ["--dim", "height=inf"], ["--dim", "=1"]], ids=lambda a: a[-1])-def test_make_refuses_a_dimension_that_is_not_a_positive_length(tmp_path: Path, args: list[str]):- r = runner.invoke(app, ["make", "a cup", *args, "--no-run", "--runs-dir", str(tmp_path / "runs"), "--slug", "d"])- assert r.exit_code == 1 and "--dim" in r.output and not (tmp_path / "runs" / "d").exists()---def test_make_refuses_a_blank_prompt(tmp_path: Path):- r = runner.invoke(app, ["make", " ", "--no-run", "--runs-dir", str(tmp_path / "runs")])- assert r.exit_code == 2 and "prompt is empty" in r.output- assert not (tmp_path / "runs").exists() or not any((tmp_path / "runs").iterdir())--[email protected]("text", ["judge: [unclosed\n", "- a\n- list\n"], ids=["syntax", "list"])-def test_a_config_file_that_is_not_a_mapping_is_a_bad_configuration(tmp_path: Path, monkeypatch, text: str):- from codeverse3d import config-- (tmp_path / "3dcodeverse.yaml").write_text(text)- monkeypatch.chdir(tmp_path)- config.get_settings.cache_clear()- try:- r = runner.invoke(app, ["make", "a chair", "--no-run", "--runs-dir", str(tmp_path / "runs")])- finally:- config.get_settings.cache_clear()- assert r.exit_code == 2 and "bad configuration" in r.output and "3dcodeverse.yaml" in r.output---def test_render_refuses_a_mode_it_would_not_honour(tmp_path: Path):- """An unknown --mode escaped as a RenderError; on a scene or shader any mode rendered shaded, silently."""- runs = tmp_path / "runs"- for track, slug in (("static_object", "o"), ("scene", "s")):- assert runner.invoke(app, ["make", "x", "--track", track, "--no-run", "--runs-dir", str(runs), "--slug", slug]).exit_code == 0- r = runner.invoke(app, ["render", "o", "--mode", "bogus", "--runs-dir", str(runs)])- assert r.exit_code == 2 and "--mode must be one of" in r.output and r.exception is None or isinstance(r.exception, SystemExit)- r = runner.invoke(app, ["render", "s", "--mode", "wire", "--runs-dir", str(runs)])- assert r.exit_code == 2 and "object runs" in r.output---def test_judge_names_a_missing_record_or_missing_renders(tmp_path: Path, runs_dir: Path):- """No record.json / pruned per-view PNGs escaped as RecordError / FileNotFoundError."""- r = runner.invoke(app, ["make", "x", "--no-run", "--runs-dir", str(tmp_path / "r2"), "--slug", "nr"])- r = runner.invoke(app, ["judge", "nr", "--runs-dir", str(tmp_path / "r2")])- assert r.exit_code == 2 and "record.json" in r.output and isinstance(r.exception, SystemExit)- for p in (runs_dir / "wooden_chair_ab12cd34").rglob("view_*.png"):- p.unlink()- r = runner.invoke(app, ["judge", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir), "--model", "gemini:x"])- assert r.exit_code == 2 and "not on disk" in r.output and isinstance(r.exception, SystemExit)---def test_pairs_and_index_skip_an_unreadable_record(runs_dir: Path, tmp_path: Path):- """One corrupt record.json ended `flywheel pairs` / `index` for the whole tree (export already skipped it)."""- (runs_dir / "broken").mkdir()- (runs_dir / "broken" / "record.json").write_text("{not json")- (runs_dir / "broken" / "spec.json").write_text("{}")- r = runner.invoke(app, ["flywheel", "pairs", str(runs_dir), str(tmp_path / "p.jsonl")])- assert r.exit_code == 0, r.output- r = runner.invoke(app, ["flywheel", "index", str(runs_dir), str(tmp_path / "i.sqlite")])- assert r.exit_code == 0 and "indexed 3 runs" in r.output---def test_resume_reports_a_corrupt_run_state_cleanly(made_run):- runs, run_dir = made_run("--language", "threejs")- (run_dir / "run_state.json").write_text("garbage")- r = runner.invoke(app, ["resume", run_dir.name, "--runs-dir", str(runs)])- assert r.exit_code == 2 and "run_state.json" in r.output and "Traceback" not in r.output---def test_a_judge_unavailable_run_resumes_as_it_is(made_run, stub_track):- """The judge's provider being down is not the run's end: resume re-judges and goes on- (it was refused as finished, and --force re-bought every round)."""- from codeverse3d.contracts.run import RunStatus- from codeverse3d.orchestrator import RunState- from codeverse3d.workspace import Workspace-- runs, run_dir = made_run()- RunState(status=RunStatus.JUDGE_UNAVAILABLE, stop_reason="judge_unavailable").save(Workspace(run_dir))- entered = []- stub_track(lambda spec, resume, force: entered.append((resume, force)))- assert runner.invoke(app, ["resume", run_dir.name, "--runs-dir", str(runs)]).exit_code == 130- 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 v2" 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"])- assert r.exit_code == 2 and "--max-minutes" in r.output and not (tmp_path / "z" / "z").exists()- runs, run_dir = made_run()- r = runner.invoke(app, ["resume", run_dir.name, "--runs-dir", str(runs), "--max-minutes", "0"])- assert r.exit_code == 2 and "--max-minutes" in r.output- r = runner.invoke(app, ["make", "a cup", "--max-minutes", "inf", "--no-run", "--runs-dir", str(tmp_path / "i"), "--slug", "i"])- assert r.exit_code == 2 and "finite" in r.output and not (tmp_path / "i" / "i").exists()---def test_a_reference_that_is_not_an_image_is_refused_before_the_run_exists(tmp_path: Path):- bad = tmp_path / "ref.png"- bad.write_text("not an image")- r = runner.invoke(app, ["make", "a cup", "--image", str(bad), "--no-run", "--runs-dir", str(tmp_path / "runs"), "--slug", "i"])- assert r.exit_code == 1 and "not a readable image" in r.output and not (tmp_path / "runs" / "i").exists()---def test_an_option_that_would_be_dropped_is_refused(tmp_path: Path, runs_dir: Path):- """pick --judge without a pairwise verdict to buy, and render --width/--height on a graphics- run were accepted and silently did nothing."""- runs = tmp_path / "runs"- for extra in (["--judge", "gemini:gemini-3.8-flash"], ["--by", "pairwise", "--round", "0", "--judge", "gemini:x"]):- r = runner.invoke(app, ["pick", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir), *extra])- assert r.exit_code == 2 and "--judge is the pairwise judge" in r.output- assert runner.invoke(app, ["make", "a shader", "--track", "graphics", "--no-run", "--runs-dir", str(runs),- "--slug", "g"]).exit_code == 0- r = runner.invoke(app, ["render", "g", "--width", "64", "--runs-dir", str(runs)])- assert r.exit_code == 2 and "graphics run" in r.output---def test_resume_refuses_a_run_whose_clock_is_spent_even_with_force(made_run, stub_track):- """Live 2026-09-23: `resume --force` on a budget-stopped run archived its paid round, kept the- spent clock and stopped at once with 0 rounds. A spent clock needs a raised --max-minutes."""- from codeverse3d.contracts.run import RunStatus- from codeverse3d.orchestrator import RunState- from codeverse3d.workspace import Workspace-- runs, run_dir = made_run("--max-minutes", "20")- RunState(status=RunStatus.BUDGET, stop_reason="budget", extra={"budget_snapshot": {"active_s": 20.5 * 60}}).save(- Workspace(run_dir))- entered = []- stub_track(lambda spec, resume, force: entered.append(force))- for extra in ([], ["--force"], ["--rounds", "3"], ["--max-minutes", "20.2"]):- r = runner.invoke(app, ["resume", run_dir.name, "--runs-dir", str(runs), *extra])- assert r.exit_code == 1 and "clock is spent" in r.output, extra- assert entered == []- assert runner.invoke(app, ["resume", run_dir.name, "--runs-dir", str(runs), "--max-minutes", "40"]).exit_code == 130--def test_a_replay_judges_the_picked_round_on_the_runs_rubric_and_books_into_the_record(tmp_path: Path, monkeypatch):"""`3dcode judge` replays the run it reads. r0 0.55, r1 unjudged (a judge outage), r2 0.90, of astatic `--image` run:@@ -628,26 +294,3 @@ def test_a_replay_judges_the_picked_round_on_the_runs_rubric_and_books_into_the_assert prev2 is Noneassert load_record(ws).total_usage.cost_usd == pytest.approx(ledger_usage(load_ledger(ws.root)).cost_usd)assert load_record(ws).total_usage.cost_usd == pytest.approx(total + 3 * 0.05)---def test_render_of_a_scene_uses_the_in_run_cameras_and_times(tmp_path: Path, monkeypatch):- """N69: `3dcode render` on a scene renders the plan's cameras at SCENE_TIMES — what the in-run judge- saw (tracks/scene.ScenePipeline.render) — not the cameras createScene() authored."""- import codeverse3d.spatial.render_scene as RS- from codeverse3d.contracts.artifacts import RenderSet- from codeverse3d.contracts.plan import BBox, CameraPlan, ScenePlan, ZonePlan- from codeverse3d.tracks.scene import SCENE_TIMES- from codeverse3d.workspace import Workspace-- runs = tmp_path / "runs"- assert runner.invoke(app, ["make", "x", "--track", "scene", "--no-run", "--runs-dir", str(runs), "--slug", "s"]).exit_code == 0- ws = Workspace(runs / "s")- cam = CameraPlan(name="hero", position=(4, 2, 4), look_at=(0, 0, 0))- ws.write_json(ws.plan_path, ScenePlan(title="t", summary="s", setting="x", environment="e", bounds=BBox(center=(0, 0, 0), extents=(10, 4, 10)),- zones=[ZonePlan(name="z", description="d", bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)))],- cameras=[cam]))- seen: dict = {}- monkeypatch.setattr(RS, "render_scene", lambda ws, out_dir, **kw: seen.update(kw) or RenderSet(views=[], renderer="fake"))- r = runner.invoke(app, ["render", "s", "--runs-dir", str(runs)])- assert r.exit_code == 0, r.output- assert [c.name for c in seen["cameras"]] == ["hero"] and tuple(seen["times"]) == SCENE_TIMESdiff --git a/harness/tests/flywheel_cli/test_complexity_record.py b/harness/tests/flywheel_cli/test_complexity_record.pydeleted file mode 100644index 8c5e211b..00000000--- a/harness/tests/flywheel_cli/test_complexity_record.py+++ /dev/null@@ -1,67 +0,0 @@-"""The complexity block on a record.--``record.extra["complexity"]`` is what makes a verdict readable: it says how much-artifact the score was earned on. (The score-vs-complexity report over a corpus of-these is `eval/bench/complexity_report.py`, tested in `eval/tests`.)-"""--from __future__ import annotations--from datetime import UTC, datetime--import pytest--from codeverse3d.contracts.artifacts import Judgment, Measurement-from codeverse3d.contracts.common import Backends, Language, Track, Usage-from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan-from codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatus-from codeverse3d.contracts.spec import Spec-from codeverse3d.record.record import complexity_block, fill_derived, round_summary---def _measurement(index: float, parts: int = 8) -> Measurement:- return Measurement(- bbox_min=(0, 0, 0), bbox_max=(1, 1, 1), extents=(1, 1, 1), center=(0.5, 0.5, 0.5),- tri_count=1000, n_meshes=parts, n_islands=parts,- extra={"complexity": {"version": 1, "index": index, "band": "moderate", "part_count": parts,- "tri_count": 1000, "materials": 3, "silhouette": 4.0,- "feature_density": 500.0, "symmetry_groups": 1, "hollowness": 0.2,- "assembly_depth": 1, "components": {}, "extra": {}}},- )---def _round(index: int, score: float, cx: float | None) -> RoundRecord:- return RoundRecord(- index=index, kind="baseline" if index == 0 else "refine", commit="c" * 12,- measurement=_measurement(cx) if cx is not None else None,- judgment=Judgment(rubric="static_object", judge_backend="gemini:x",- scores={"geometry_detail": score}, overall=score, passed=score >= 0.72,- summary="s"),- usage=Usage(cost_usd=0.5),- )---def _record(rounds: list[RoundRecord]) -> RunRecord:- bbox = BBox(center=(0.0, 0.0, 0.0), extents=(0.1, 0.1, 0.1))- plan = StaticPlan(object_name="Thing", summary="a thing",- overall_bbox=BBox(center=(0.0, 0.5, 0.0), extents=(1.0, 1.0, 1.0)),- parts=[PartPlan(name=f"P{i}", role="body", description="d", bbox=bbox)- for i in range(4)])- return RunRecord(- spec=Spec(id="t", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a thing",- backends=Backends()),- plan=plan, workspace="/tmp/x", status=RunStatus.MAX_ROUNDS, rounds=rounds,- started_at=datetime.now(UTC),- )---def test_record_carries_the_last_rounds_complexity_and_the_trail() -> None:- rec = fill_derived(_record([_round(0, 0.80, 0.42), _round(1, 0.60, 0.55)]))- block = rec.extra["complexity"]- assert block["index"] == 0.55 # the build the run ENDS at, whatever it scored- assert block["plan_parts"] == 4- assert block["parts_per_plan_part"] == pytest.approx(2.0)- assert block["by_round"] == [0.42, 0.55]- assert [round_summary(r)["complexity"] for r in rec.rounds] == [0.42, 0.55]- # an unmeasured last round falls back to the last measured one- assert complexity_block(_record([_round(0, 0.6, 0.42), _round(1, 0.5, None)]))["index"] == 0.42diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.pyindex 3bdc91d3..2dc15c4d 100644--- a/harness/tests/flywheel_cli/test_flywheel.py+++ b/harness/tests/flywheel_cli/test_flywheel.py@@ -21,81 +21,9 @@ from codeverse3d.record.record import (# --------------------------------------------------------------------------- record-def test_finalize_and_load_record(fake_run):- ws, rec = fake_run- rec.environment = {}- path = finalize_record(ws, rec)- assert path == ws.record_path and path.is_file()- loaded = load_record(ws)- stored = json.loads(path.read_text())- assert not {"best_round", "baseline_score", "final_score"} & stored.keys() # the run names no best (2026-09-22)- assert loaded.environment["python"] and loaded.environment["codeverse3d"]- assert "three" in loaded.environment and "node" in loaded.environment- assert "rounds_summary" not in loaded.extra, "written, never read: gone 2026-09-22"- assert loaded.total_usage.cost_usd == pytest.approx(0.06), "the total is the ledger's"--# --------------------------------------------------------------------------- git helpers-def test_git_reads_at_a_commit(fake_run):- """read_tree_at reads a commit's tree (never a symlink as a file of its target); a sha the repository- no longer holds raises rather than diffing against an empty tree."""- ws, rec = fake_run- c0, c1 = rec.rounds[0].commit, rec.rounds[1].commit- t0 = git_history.read_tree_at(ws, c0)- t1 = git_history.read_tree_at(ws, c1)- assert set(t0) == {"src/model.py"}- assert set(t1) == {"src/model.py", "src/parts/leg.py"}- assert b"round 0" in t0["src/model.py"] and b"round 1" in t1["src/model.py"]- with pytest.raises(git_history.GitReadError):- git_history.read_tree_at(ws, "deadbeef")- for a, b in (("0" * 40, c1), (c1, "0" * 40)):- with pytest.raises(git_history.GitReadError):- git_history.diff_between(ws, a, b)- with pytest.raises(git_history.GitReadError):- git_history.changed_files_between(ws, c1, "0" * 40)-- (ws.src / "model.py").write_text("import bpy\n")- (ws.src / "link.py").symlink_to("model.py")- tree = git_history.read_tree_at(ws, ws.commit("with a symlink"))- assert "src/model.py" in tree- assert "src/link.py" not in tree, "a symlink is not a file the agent wrote"---def test_a_planted_smudge_filter_or_diff_driver_never_runs(fake_run, tmp_path):- """Programs git RUNS (a smudge filter, a diff driver / textconv) never run on the export read."""- ws, _rec = fake_run- fired = tmp_path / "fired"- payload = f"sh -c 'echo pwned >> {fired}; cat'"- (ws.src / "model.py").write_text("# real content\n")- commit = ws.commit("content")- (ws.root / ".git" / "info").mkdir(parents=True, exist_ok=True)- (ws.root / ".git" / "info" / "attributes").write_text("* filter=evil\n")- (ws.root / ".gitattributes").write_text("* filter=evil\n")- ws._git("config", "--local", "filter.evil.smudge", payload)- ws._git("config", "--local", "filter.evil.required", "false")- files = git_history.read_tree_at(ws, commit)- assert not fired.exists(), f"a planted smudge filter ran: {fired.read_text()!r}"- assert files["src/model.py"] == b"# real content\n" # the raw blob, unfiltered-- (ws.root / ".git" / "info" / "attributes").unlink()- (ws.root / ".gitattributes").unlink()- (ws.src / "blob.bin").write_bytes(b"\x00\x01before\n")- before = ws.commit("binary before")- (ws.src / "blob.bin").write_bytes(b"\x00\x01after\n")- after = ws.commit("binary after")- # planted AFTER the last commit: ws.commit() sanitises .git/config on the way past- (ws.root / ".gitattributes").write_text("*.bin diff=evil\n*.py diff=evil\n")- for key in ("textconv", "command"):- ws._git("config", "--local", f"diff.evil.{key}", payload)- ws._git("config", "--local", "diff.external", payload)- text, _total, _truncated = git_history.diff_between(ws, before, after)- files = git_history.changed_files_between(ws, before, after)- assert not fired.exists(), f"a planted diff driver ran: {fired.read_text()!r}"- assert files == ["src/blob.bin"] and "src/blob.bin" in text--# --------------------------------------------------------------------------- export + pack@@ -177,77 +105,72 @@ def test_export_pairs_and_a_core_only_install_over_a_runs_dir(runs_dir: Path, tmassert len(runs) == 3 and bad == ["broken"]-def test_export_of_one_run_with_captions_and_reexport(fake_run, tmp_path: Path):- ws, rec = fake_run- rec.extra["captions"] = {"detailed": "A chair.", "instruction": "Write a Blender Python script for a chair.",- "factory": "Build seat then legs.", "provenance": {"captioner": "gemini:x"}}- ws.write_json(ws.record_path, rec)- out = tmp_path / "ds"- export_samples(ws.root.parent, out)- rep = export_samples(ws.root.parent, out) # re-export overwrites, index stays at 1 row- assert rep.n_indexed == 1- row = json.loads((out / "metadata.jsonl").read_text().splitlines()[0])- assert row["captions"]["factory"] == "Build seat then legs."- assert json.loads(row["meta_json"])["has_captions"] is True---# --------------------------------------------------------------------------- finding: repair pairs (pairs.py:115)-def test_repair_pairs_match_structurally_not_by_kind(tmp_path: Path):- """Lifecycle labels the fixing round 'refine' — repair pairs must not need kind='repair'."""- from codeverse3d.addons.dataset.pairs import repair_pairs- from tests.flywheel_cli.conftest import make_fake_run+def _block_pyarrow(monkeypatch) -> None:+ """Make ``import pyarrow`` fail the way a core-only install does."""+ import builtins- ws, rec = make_fake_run(tmp_path / "runs", with_repair=True)- fixing = rec.rounds[-1]- assert fixing.kind == "repair" # fixture legacy label- fixing.kind = "refine" # what the tracks actually emit- pairs = repair_pairs(ws, rec)- assert len(pairs) == 1- p = pairs[0]- assert p["kind"] == "repair" and p["source"] == "round"- assert p["rejected"]["build_ok"] is False and p["chosen"]["build_ok"] is True- assert p["error"]["type"] == "SyntaxError"- assert "size=3.0" in p["chosen"]["files"]["src/model.py"]+ real_import = builtins.__import__+ def no_pyarrow(name, *a, **kw):+ if name == "pyarrow" or name.startswith("pyarrow."):+ raise ModuleNotFoundError("No module named 'pyarrow'")+ return real_import(name, *a, **kw)-def test_in_round_repair_pairs_from_generated_commit(tmp_path: Path):- """build_with_repair fixes inside one round: generated commit → final commit."""- import json as _json+ monkeypatch.setattr(builtins, "__import__", no_pyarrow)- from codeverse3d.addons.dataset.pairs import in_round_repair_pairs- from tests.flywheel_cli.conftest import make_fake_run- ws, rec = make_fake_run(tmp_path / "runs")- entry = ws.src / "model.py"- entry.write_text("import bpy\nbpy.ops.mesh.primitive_cube_add(size=\n") # as generated (broken)- gen = ws.commit("r01 refine: generated")- entry.write_text("import bpy\nbpy.ops.mesh.primitive_cube_add(size=2.0)\n") # after in-round repair- fin = ws.commit("r01 refine")- rnd = rec.rounds[1]- rnd.commit = fin- rnd.notes = "repair attempts: 1 (fixed)"- with ws.events_path.open("a") as fh:- fh.write(_json.dumps({"t": 1.0, "event": "build.done", "round": 1, "ok": False,- "error": "SyntaxError: unexpected EOF"}) + "\n")- fh.write(_json.dumps({"t": 2.0, "event": "build.done", "round": 1, "ok": True, "error": ""}) + "\n")- pairs = in_round_repair_pairs(ws, rec)- assert len(pairs) == 1- p = pairs[0]- assert p["source"] == "in_round" and p["rejected"]["commit"] == gen- assert "size=\n" in p["rejected"]["files"]["src/model.py"]- assert "size=2.0" in p["chosen"]["files"]["src/model.py"]- assert p["error"]["message"] == "SyntaxError: unexpected EOF"- # a round whose repair loop never fixed anything yields no pair- rnd.notes = "repair attempts: 2 (still failing)"- assert in_round_repair_pairs(ws, rec) == []---# --------------------------------------------------------------------------- finding: degraded judgments (pairs.py:75)def _degrade(judgment):return judgment.model_copy(update={"overall": 0.0, "passed": False, "summary": "judge_error: 429 on all samples","scores": {k: 0.0 for k in judgment.scores}})+def test_finalize_and_load_record(fake_run):+ ws, rec = fake_run+ rec.environment = {}+ path = finalize_record(ws, rec)+ assert path == ws.record_path and path.is_file()+ loaded = load_record(ws)+ stored = json.loads(path.read_text())+ assert not {"best_round", "baseline_score", "final_score"} & stored.keys() # the run names no best (2026-09-22)+ assert loaded.environment["python"] and loaded.environment["codeverse3d"]+ assert "three" in loaded.environment and "node" in loaded.environment+ assert "rounds_summary" not in loaded.extra, "written, never read: gone 2026-09-22"+ assert loaded.total_usage.cost_usd == pytest.approx(0.06), "the total is the ledger's"+++def test_a_planted_smudge_filter_or_diff_driver_never_runs(fake_run, tmp_path):+ """Programs git RUNS (a smudge filter, a diff driver / textconv) never run on the export read."""+ ws, _rec = fake_run+ fired = tmp_path / "fired"+ payload = f"sh -c 'echo pwned >> {fired}; cat'"+ (ws.src / "model.py").write_text("# real content\n")+ commit = ws.commit("content")+ (ws.root / ".git" / "info").mkdir(parents=True, exist_ok=True)+ (ws.root / ".git" / "info" / "attributes").write_text("* filter=evil\n")+ (ws.root / ".gitattributes").write_text("* filter=evil\n")+ ws._git("config", "--local", "filter.evil.smudge", payload)+ ws._git("config", "--local", "filter.evil.required", "false")+ files = git_history.read_tree_at(ws, commit)+ assert not fired.exists(), f"a planted smudge filter ran: {fired.read_text()!r}"+ assert files["src/model.py"] == b"# real content\n" # the raw blob, unfiltered++ (ws.root / ".git" / "info" / "attributes").unlink()+ (ws.root / ".gitattributes").unlink()+ (ws.src / "blob.bin").write_bytes(b"\x00\x01before\n")+ before = ws.commit("binary before")+ (ws.src / "blob.bin").write_bytes(b"\x00\x01after\n")+ after = ws.commit("binary after")+ # planted AFTER the last commit: ws.commit() sanitises .git/config on the way past+ (ws.root / ".gitattributes").write_text("*.bin diff=evil\n*.py diff=evil\n")+ for key in ("textconv", "command"):+ ws._git("config", "--local", f"diff.evil.{key}", payload)+ ws._git("config", "--local", "diff.external", payload)+ text, _total, _truncated = git_history.diff_between(ws, before, after)+ files = git_history.changed_files_between(ws, before, after)+ assert not fired.exists(), f"a planted diff driver ran: {fired.read_text()!r}"+ assert files == ["src/blob.bin"] and "src/blob.bin" in text++def test_degraded_round_is_not_a_zero_score(tmp_path: Path):from codeverse3d.addons.dataset.pairs import preference_pairsfrom codeverse3d.record.record import effective_judgment, effective_score, round_summary@@ -285,85 +208,3 @@ def test_a_run_with_only_degraded_verdicts_exports_unscored(tmp_path: Path):meta = json.loads(next(out.rglob("meta.json")).read_text())assert meta["score"] is None and meta["passed"] is None and meta["quality_tier"] == "D"assert meta["acceptance_results"] == {}---def test_a_run_reached_twice_is_found_once_at_its_physical_path(tmp_path):- """Batteries symlink each other's cells: export, index, pairs and the gallery counted them twice."""- from codeverse3d.record.record import find_run_dirs-- real = tmp_path / "zz_home" / "runs" / "chair"- real.mkdir(parents=True)- (real / "record.json").write_text("{}")- (tmp_path / "aa_borrower" / "runs").mkdir(parents=True)- (tmp_path / "aa_borrower" / "runs" / "chair").symlink_to(real) # sorts first- assert find_run_dirs(tmp_path) == [real], "descending: one hit, the physical one"- (real.parent / "alias").symlink_to(real)- assert find_run_dirs(real.parent) == [real], "direct children: the alias collapses too"---def test_empty_run_roots_distinguish_a_failed_battery_from_legitimate_empty_input(tmp_path):- from codeverse3d.record.record import iter_runs-- battery = tmp_path / "compare_empty"- (battery / "cells" / "cmp_med_chair").mkdir(parents=True)- with pytest.raises(FileNotFoundError, match=r"looks like a battery directory"):- list(iter_runs(battery))-- # Plain empty inputs are valid and stay quiet.- empty = tmp_path / "runs"- empty.mkdir()- assert list(iter_runs(empty)) == []-- noise = tmp_path / "noise"- (noise / "a" / "b" / "c").mkdir(parents=True)- assert list(iter_runs(noise)) == []---def test_parquet_keeps_the_complexity_columns_the_exporter_writes(tmp_path):- """The fixed Arrow schema preserves exported complexity columns."""- import pyarrow.parquet as pq-- from codeverse3d.addons.dataset.export import parquet_schema, write_parquet-- row = dict.fromkeys(parquet_schema().names)- row.update(id="x", key="k", complexity=7.5, complexity_band="high")- table = pq.read_table(write_parquet([row], tmp_path / "metadata.parquet"))- assert {"complexity", "complexity_band"} <= set(table.column_names)- got = table.to_pylist()[0]- assert got["complexity"] == 7.5 and got["complexity_band"] == "high"- # and the schema can never fall behind row_for_sample again- with pytest.raises(ValueError, match="missing column"):- write_parquet([{**row, "a_new_metric": 1.0}], tmp_path / "later.parquet")---def _block_pyarrow(monkeypatch) -> None:- """Make ``import pyarrow`` fail the way a core-only install does."""- import builtins-- real_import = builtins.__import__-- def no_pyarrow(name, *a, **kw):- if name == "pyarrow" or name.startswith("pyarrow."):- raise ModuleNotFoundError("No module named 'pyarrow'")- return real_import(name, *a, **kw)-- monkeypatch.setattr(builtins, "__import__", no_pyarrow)---def test_a_missing_runtime_js_does_not_lose_a_finished_runs_record(fake_run, monkeypatch):- """The version probe raised through finalize_record, so a shader run (no node needed) with a- bad C3D_RUNTIME_JS paid for every round and ended with no record.json (sweep 2026-09-23)."""- from codeverse3d import config- from codeverse3d.record import record as R-- ws, rec = fake_run- rec.environment = {}- monkeypatch.setenv("C3D_RUNTIME_JS", str(ws.root / "nowhere"))- config.get_settings.cache_clear()- R.environment_versions.cache_clear()- try:- finalize_record(ws, rec)- assert load_record(ws).environment["three"] == ""- finally:- config.get_settings.cache_clear()- R.environment_versions.cache_clear()diff --git a/harness/tests/flywheel_cli/test_manifest_pack.py b/harness/tests/flywheel_cli/test_manifest_pack.pyindex ae98fd53..722e5f40 100644--- a/harness/tests/flywheel_cli/test_manifest_pack.py+++ b/harness/tests/flywheel_cli/test_manifest_pack.py@@ -10,11 +10,9 @@ from pathlib import Pathimport pytestfrom codeverse3d.addons.dataset.export import (- ManifestError,export_samples,- load_manifest,)-from codeverse3d.addons.dataset.pack import PackError, pack_samples, verify_locators+from codeverse3d.addons.dataset.pack import pack_samples, verify_locatorsCHAIR_ID = "3dcodeverse/static_object/blender/wooden_chair_ab12cd34"@@ -35,50 +33,11 @@ def _tar_member_names(out: Path) -> list[str]:return names-# --------------------------------------------------------------------------- drop-duplicates → pack-def test_drop_duplicates_then_pack_ships_no_duplicate(runs_dir: Path, tmp_path: Path):- out = tmp_path / "ds"- # the codex run shares prompt + best-round code bytes with the chair → exact duplicate- rep = export_samples(runs_dir, out, drop_duplicates=True)- assert rep.n_exported == 3 and rep.n_indexed == 2 and rep.n_duplicates == 1- m = load_manifest(out)- assert {e.run.rel for e in m.entries} == {"wooden_chair_ab12cd34", "lamp_three"}- dup = [d for d in m.dropped if d.reason.startswith("duplicate_of:")]- assert len(dup) == 1 and dup[0].run.rel == "wooden_chair_codex"- assert dup[0].reason == f"duplicate_of:{CHAIR_ID}"- # the duplicate FOLDER stays on disk by design — it must still never ship- assert (out / "static_object" / "blender" / "wooden_chair_codex").is_dir()- prep = pack_samples(out)- assert prep.n_samples == 2 and verify_locators(out) == 2- names = _tar_member_names(out)- assert names and not any(n.startswith("wooden_chair_codex/") for n in names)- rows = [json.loads(ln) for ln in (out / "metadata.jsonl").read_text().splitlines()]- assert {r["key"] for r in rows} == {"wooden_chair_ab12cd34", "lamp_three"}- assert all(r["tar"] for r in rows)---# --------------------------------------------------------------------------- pack is manifest-only-def test_pack_without_a_manifest_is_a_hard_error(tmp_path: Path):- out = tmp_path / "ds"- (out / "static_object" / "blender" / "x").mkdir(parents=True) # samples alone don't count- with pytest.raises(PackError, match="no longer rescans"):- pack_samples(out)- with pytest.raises(ManifestError, match="dataset_manifest.json"):- load_manifest(out)--def _packed_state(out: Path) -> dict[str, bytes]:return {p.name: p.read_bytes()for p in [*out.glob("samples-*.tar"), out / "metadata.jsonl", out / "metadata.parquet"]}-def test_a_tampered_sample_file_fails_fast_and_names_it(exported_ds: Path):- (exported_ds / "static_object" / "blender" / "wooden_chair_ab12cd34" / "code.py").write_text("tampered")- with pytest.raises(PackError, match="code.py"):- pack_samples(exported_ds)- assert not list(exported_ds.glob("samples-*.tar")) and not list(exported_ds.glob("*.tmp"))--# --------------------------------------------------------------------------- phantom rows, failed and repeated packsdef test_a_planted_row_a_failed_publish_and_a_repack(exported_ds: Path, monkeypatch):"""A planted src/meta.json is not a row and not packed; every tar written then the index writediff --git a/harness/tests/flywheel_cli/test_quality_gallery.py b/harness/tests/flywheel_cli/test_quality_gallery.pyindex e783e254..48ca3a9b 100644--- a/harness/tests/flywheel_cli/test_quality_gallery.py+++ b/harness/tests/flywheel_cli/test_quality_gallery.py@@ -7,12 +7,6 @@ from pathlib import Pathfrom codeverse3d.addons.dataset.captions import caption_samplefrom codeverse3d.addons.dataset.export import export_samples, load_captions-from codeverse3d.addons.dataset.quality import (- find_duplicates,- mark_duplicates,- prompt_id,- quality_tier,-)from codeverse3d.record.record import load_recordfrom tests.flywheel_cli.test_captions import GOODfrom tests.orchestrator_tracks.fakes import FakeChatModel@@ -20,34 +14,6 @@ from tests.orchestrator_tracks.fakes import FakeChatModel# --------------------------------------------------------------------------- tiers + dedupe-def test_quality_tier_rule():- assert quality_tier(passed=True, gate_errors=0, score=0.9) == "A"- assert quality_tier(passed=True, gate_errors=3, score=0.9) == "B"- assert quality_tier(passed=False, gate_errors=0, score=0.61) == "C"- assert quality_tier(passed=None, gate_errors=0, score=0.6) == "C"- assert quality_tier(passed=False, gate_errors=0, score=0.59) == "D"- assert quality_tier(passed=None, gate_errors=5, score=None) == "D"---def test_only_raw_hash_duplicates_are_dropped_normalised_ones_are_only_marked():- """duplicate_of (the drop set) is keyed on the raw code_sha256; the fingerprint only marks."""- rows = [- {"id": "a", "key": "a", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "B", "score": 0.8},- {"id": "b", "key": "b", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8},- {"id": "c", "key": "c", "code_sha256": "S", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8},- {"id": "d", "key": "d", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "q", "quality_tier": "A", "score": 0.9},- {"id": "e", "key": "e", "code_sha256": "R", "code_fingerprint": "X", "prompt_hash": "p", "quality_tier": "A", "score": 0.8,- "has_captions": True},- {"id": "f", "key": "f", "code_sha256": "", "code_fingerprint": "", "prompt_hash": "p", "quality_tier": "A", "score": 0.9},- ]- groups = find_duplicates(rows)- assert len(groups) == 1 and groups[0].canonical == "e" and set(groups[0].duplicates) == {"a", "b"}- mark_duplicates(rows)- assert {r["id"]: r["duplicate_of"] for r in rows} == {"a": "e", "b": "e", "c": "", "d": "", "e": "", "f": ""}- assert {r["id"]: r["near_duplicate_of"] for r in rows} == {"a": "e", "b": "e", "c": "e", "d": "", "e": "", "f": ""}- assert prompt_id(" a chair ") == prompt_id("a chair") and len(prompt_id("x")) == 16--# --------------------------------------------------------------------------- export extrasdiff --git a/harness/tests/flywheel_cli/test_refine.py b/harness/tests/flywheel_cli/test_refine.pyindex bdc02f39..ca7ab9e8 100644--- a/harness/tests/flywheel_cli/test_refine.py+++ b/harness/tests/flywheel_cli/test_refine.py@@ -5,10 +5,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-import pytest--from codeverse3d.addons.dataset.pairs import MIN_PREFERENCE_DELTA-from codeverse3d.addons.dataset.refine import build_refine, outcome_of, transitions+from codeverse3d.addons.dataset.refine import build_refine, transitionsfrom codeverse3d.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse3d.record.record import load_recordfrom tests.flywheel_cli.conftest import make_fake_run@@ -63,35 +60,3 @@ def test_a_refine_round_carries_its_brief_its_diff_and_its_delta(tmp_path):assert n == 1 and not drops and not list(out.parent.glob("*.part"))row = json.loads(out.read_text().splitlines()[0])assert row["outcome"] == "improved" and "before_files" not in row # exclude_none keeps rows small--[email protected]("delta,label", [(0.05, "improved"), (0.04, "unchanged"), (-0.05, "regressed"),- (None, "unscored")])-def test_the_outcome_rule_is_the_one_pairs_uses(delta, label):- assert outcome_of(delta, MIN_PREFERENCE_DELTA) == label--[email protected]("break_it,reason", [- ("kind", None), ("commit", "no_commit"), ("build", "predecessor_build_failed"),- # RoundRecord.build is optional: a round that never reached the build stage carries- # None, and reading .ok on it took the whole export down with an AttributeError- ("no_build", "predecessor_build_failed"),- ("judgment", "predecessor_unjudged"),-])-def test_every_unexportable_round_is_counted_under_a_named_reason(tmp_path, break_it, reason):- ws = _corpus(tmp_path)- rec = load_record(ws)- if break_it == "kind":- rec.rounds[1].kind = "texture"- elif break_it == "commit":- rec.rounds[0].commit = ""- elif break_it == "build":- rec.rounds[0].build.ok = False- elif break_it == "no_build":- rec.rounds[0].build = None- else:- rec.rounds[0].judgment = None- ws.write_json(ws.record_path, rec)- rows, drops = _rows(tmp_path)- assert rows == []- assert drops == ({} if reason is None else {reason: 1}), f"{break_it}: {dict(drops)}"diff --git a/harness/tests/flywheel_cli/test_run_identity.py b/harness/tests/flywheel_cli/test_run_identity.pydeleted file mode 100644index a00901bb..00000000--- a/harness/tests/flywheel_cli/test_run_identity.py+++ /dev/null@@ -1,72 +0,0 @@-"""Run identity (RunId): the slug rule — 211 of 396 recorded run dirs are literally named ``run``."""--from __future__ import annotations--import sqlite3-from pathlib import Path--import pytest--from codeverse3d.addons.dataset.export import export_samples-from codeverse3d.addons.dataset.index import build_index as build_sqlite_index-from codeverse3d.addons.dataset.sample import SampleError-from codeverse3d.contracts.run import RunId-from codeverse3d.record.record import unique_files-from tests.flywheel_cli.conftest import make_fake_run---def test_the_slug_rule_and_the_battery_layouts():- for battery, rel, slug in [- ("runs", "wooden_chair_ab12cd34", "wooden_chair_ab12cd34"),- ("h2h_scene_v1", "h2h_b01_neon_alley.attempt1", "h2h_b01_neon_alley.attempt1"), # a retry keeps its suffix- ("articulated_flash", "runs/art_easy_laptop", "art_easy_laptop"), # runs/ is noise- ("compare_v1_full", "cells/cmp_easy_stool/harness_x/run", "cmp_easy_stool__harness_x"),- ]:- assert RunId(battery=battery, rel=rel).slug == slug, rel- # compare_backends: cell then arm- rid = RunId(battery="compare_v1_full", rel="cells/cmp_easy_stool/harness_x/run")- assert (rid.cell, rid.arm) == ("cmp_easy_stool", "harness_x")- # ab_plan: slug, arm, cell and the attempt suffix- rid = RunId(battery="plan_loop",- rel="C0/arms/control/cells/arch_hard_bay_window/"- "harness_api-agent_gemini_gemini-3.8-flash/run")- assert rid.slug == "C0__control__arch_hard_bay_window__harness_api-agent_gemini_gemini-3.8-flash"- assert rid.arm == "control" and rid.cell == "arch_hard_bay_window"- retry = RunId(battery="plan_loop",- rel="heldout/arms/control/cells/comp_hard_drafting_table/"- "harness_api-agent_gemini_gemini-3.8-flash.attempt1/run")- assert retry.slug.endswith("harness_api-agent_gemini_gemini-3.8-flash.attempt1")---def test_unique_files_skips_subruns_below_the_root_not_above_it(tmp_path: Path):- """A scan rooted inside ``_assets`` once returned [] — the skip read absolute parts."""- root = tmp_path / "scene" / "_assets" / "lamp"- (root / "_cand" / "c1").mkdir(parents=True)- (root / "record.json").write_text("{}")- (root / "_cand" / "c1" / "record.json").write_text("{}")- assert unique_files(root, "record.json") == [root / "record.json"]---# --------------------------------------------------------------------------- shared tree-def _colliding_root(tmp_path: Path) -> Path:- """Two rels that legitimately reduce to the SAME slug ``x``."""- root = tmp_path / "mixed"- make_fake_run(root / "runs", "x") # runs/x -> slug x- make_fake_run(root / "cells" / "x", "run") # cells/x/run -> slug x- return root---def test_slug_collisions_fail_before_export_or_index_publication(tmp_path: Path):- root = _colliding_root(tmp_path)- out = tmp_path / "ds"- with pytest.raises(SampleError, match="duplicate sample id") as export_error:- export_samples(root, out)- msg = str(export_error.value)- assert "cells/x/run" in msg and "runs/x" in msg, "both run dirs must be named"- assert list(out.rglob("meta.json")) == [], "nothing may be written on a collision"-- with pytest.raises(sqlite3.IntegrityError) as index_error:- build_sqlite_index(root, tmp_path / "collision.sqlite")- msg = str(index_error.value)- assert "duplicate run slug 'x'" in msg- assert "cells/x/run" in msg and "runs/x" in msgdiff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.pyindex 59952930..f68f26c0 100644--- a/harness/tests/flywheel_cli/test_run_layout_cli.py+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py@@ -4,17 +4,12 @@ export / gallery on BOTH layouts (old runs must keep working)."""from __future__ import annotationsimport json-import shutilfrom pathlib import Pathfrom typer.testing import CliRunnerfrom codeverse3d.addons import select-from codeverse3d.addons.dataset.export import export_samples-from codeverse3d.addons.gallery.index import entry_from_record-from codeverse3d.addons.gallery.page import build_staticfrom codeverse3d.cli.main import app-from codeverse3d.contracts.run import RunRecordfrom codeverse3d.cost.types import STAGE_ORDERfrom codeverse3d.record.deliverable import build_deliverable, deliverable_path, load_deliverablefrom codeverse3d.record.record import load_record, package_run@@ -23,34 +18,10 @@ from codeverse3d.record.telemetry import (ledger_rows,load_telemetry,)-from codeverse3d.workspace import LAYOUT_ALIASES, Workspace--from .conftest import make_fake_runrunner = CliRunner()-def strip_telemetry(ws: Workspace) -> Workspace:- """Remove optional packaging/telemetry; keep current per-round evidence."""- for name, _ in LAYOUT_ALIASES:- p = ws.root / name- if p.is_symlink():- p.unlink()- for d in (ws.deliverable, ws.telemetry):- shutil.rmtree(d, ignore_errors=True)- rec = json.loads(ws.record_path.read_text())- rec.pop("telemetry", None)- rec.pop("deliverable", None)- ws.record_path.write_text(json.dumps(rec, indent=2))- return ws---def unpackaged_run(tmp_path: Path, slug: str = "wooden_chair_ab12cd34") -> tuple[Workspace, RunRecord]:- ws, rec = make_fake_run(tmp_path / "runs", slug)- strip_telemetry(ws)- return ws, load_record(ws)--# --------------------------------------------------------------------------- packagingdef test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run):ws, rec = fake_run@@ -92,60 +63,6 @@ def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run)assert (ws.artifacts / "object.glb").read_bytes().startswith(b"glTF")-def test_telemetry_summarises_the_runs_own_ledger(fake_run):- ws, rec = fake_run- ledger = ws.root / "telemetry" / "cost.jsonl"- ledger.unlink()- assert ledger_rows(ws) == [] # a run with no ledger has no rows (nothing is reconstructed)- tele = build_telemetry(ws, rec, write=False)- assert tele.cost is not None and tele.cost.n_calls == 0 and tele.settings is not None- ledger.write_text(json.dumps({"stage": "plan", "role": "planner", "label": "plan", "cost_usd": 0.5,- "model": "gemini-3.8-flash", "n_calls": 1}) + "\n")- tele = build_telemetry(ws, rec)- assert tele.cost is not None and tele.cost.by_stage[0].stage == "plan"- assert {s.stage for s in tele.cost.by_stage} <= set(STAGE_ORDER)- assert not (ws.telemetry / "usage.jsonl").exists(), "one ledger, one name"- # a degraded verdict is unscored in the per-round cost table, never a 0.0- rec.rounds[1].judgment = rec.rounds[1].judgment.model_copy(update={"summary": "judge_error: outage"})- by_round = build_telemetry(ws, rec, write=False).cost.by_round- assert [r["score"] for r in by_round] == [rec.rounds[0].judgment.overall, None]---def test_the_settings_snapshot_records_the_temperature_the_track_planned_at(tmp_path):- """The planner row names the temperature the track planned at (graphics 0.5), never a default."""- from types import SimpleNamespace-- from codeverse3d.contracts.common import Language- from codeverse3d.record.telemetry import settings_snapshot- from codeverse3d.tracks.graphics import GraphicsTrack- from codeverse3d.tracks.static_object import StaticObjectTrack-- judge = SimpleNamespace(temperature=0.2, thinking="low", n_samples=3)- for language, track, want in ((Language.GLSL_SHADER, GraphicsTrack(), 0.5),- (Language.BLENDER, StaticObjectTrack(), 0.4)):- _ws, rec = make_fake_run(tmp_path / language.value, language=language)- assert next(r for r in settings_snapshot(rec).roles if r.role == "planner").temperature is None- rec.extra["sampling"] = track.sampling(judge)- roles = {r.role: r for r in settings_snapshot(rec).roles}- assert (roles["planner"].temperature, roles["planner"].source) == (want, "run"), language- assert (roles["judge"].temperature, roles["judge"].thinking, roles["judge"].n_samples) == (0.2, "low", 3)---def test_a_cards_links_are_the_picked_rounds_never_the_last_builds(tmp_path):- """The gallery linked artifacts/object.glb and artifacts/frames/ — the LAST build's — when the- picked round had no copy of its own (and frames/ always)."""- from .conftest import tiny_png-- ws, rec = make_fake_run(tmp_path / "runs", scores=(0.90, 0.50)) # r00 is picked, r01 built last- tiny_png(ws.artifacts / "frames" / "f00_t0.png") # the last build's frames- tiny_png(ws.renders_dir(0) / "frame_t00.00.png") # r00's own- links = {ln.label: ln.rel for ln in entry_from_record("runs", ws, rec).links}- assert links["glb"] == "artifacts/r00/object.glb" and links["frames/"] == "artifacts/renders/r00"- shutil.rmtree(ws.round_artifacts(0)) # r00 kept no build outputs- links = {ln.label: ln.rel for ln in entry_from_record("runs", ws, rec).links}- assert "glb" not in links--# --------------------------------------------------------------------------- showdef _show(slug: str, runs_dir: Path, *args: str):return runner.invoke(app, ["show", slug, "--runs-dir", str(runs_dir), *args])@@ -179,68 +96,20 @@ def test_show_sections_and_status_share_the_packaged_run(fake_run):assert out.index("STATUS") < out.index("DELIVERABLE")-def test_show_on_a_run_without_a_record_is_its_status(tmp_path: Path):- """Mid-run there is no record.json: `show` prints where the run stands and says what the other- sections wait for (it used to exit 1 and point at `3dcode status`); a named section still fails."""- from codeverse3d.contracts.common import Backends, Language, Track- from codeverse3d.contracts.spec import Spec- from codeverse3d.proc import EventLog- from codeverse3d.workspace import Workspace-- ws = Workspace(tmp_path / "runs" / "stool").create()- ws.write_json(ws.spec_path, Spec(id="stool", track=Track.STATIC_OBJECT, language=Language.BLENDER,- prompt="a small wooden stool", backends=Backends(generator="gemini-cli:x")))- EventLog(ws.events_path).emit("run.start")- r = _show("stool", ws.root.parent)- assert r.exit_code == 0, r.output- assert "a small wooden stool" in r.output and "run.start" in r.output and "need the record" in r.output- assert _show("stool", ws.root.parent, "--section", "cost").exit_code == 1---def test_show_works_on_an_unpackaged_run(tmp_path: Path):- ws, _ = unpackaged_run(tmp_path)- r = _show(ws.root.name, ws.root.parent)- assert r.exit_code == 0, r.output- assert "no deliverable/ yet" in r.output and "computed on the fly" in r.output- assert "COST & SETTINGS" in r.output and "models per role" in r.output- assert not ws.telemetry.exists() # show never writes---# --------------------------------------------------------------------------- export / gallery on both layouts-def test_export_and_gallery_on_both_layouts(tmp_path: Path):- runs = tmp_path / "runs"- ws_new, rec_new = make_fake_run(runs, "run_new")- package_run(ws_new, rec_new)- ws_new.write_json(ws_new.record_path, rec_new)- select.package(ws_new.root, 1)- ws_old, _ = make_fake_run(runs, "run_old")- strip_telemetry(ws_old)-- rep = export_samples(runs, tmp_path / "ds")- assert rep.n_exported == 2 and not rep.skipped, rep.skipped- metas = {p.parent.name: json.loads(p.read_text()) for p in (tmp_path / "ds").rglob("meta.json")}- assert metas["run_new"]["telemetry"]["total_usd"] == rec_new.total_usage.cost_usd- assert metas["run_new"]["telemetry"]["models"]["judge"]- assert metas["run_old"]["telemetry"] == {}- for meta in metas.values():- assert meta["code_source"] == "commit" and "renders/sheet.png" in meta["renders"]-- out_html = tmp_path / "g.html"- path, n, _ = build_static([runs], out_html)- assert n == 2 and "deliverable" in path.read_text()- new_item = entry_from_record("runs", ws_new, load_record(ws_new))- old_item = entry_from_record("runs", ws_old, load_record(ws_old))- assert new_item.cost_by_stage and old_item.cost_by_stage == {}- new_links = {ln.label: ln.rel for ln in new_item.links}- old_links = {ln.label: ln.rel for ln in old_item.links}- assert old_links["glb"] == "artifacts/r01/object.glb"- assert new_links["glb"] == "deliverable/object.glb"-- # a packaged run copied without its history exports from its deliverable snapshot- shutil.rmtree(ws_new.root / ".git")- shutil.rmtree(ws_old.root)- rep = export_samples(runs, tmp_path / "ds_nogit")- assert rep.n_exported == 1, rep.skipped- meta_path = next((tmp_path / "ds_nogit").rglob("meta.json"))- assert json.loads(meta_path.read_text())["code_source"] == "deliverable"- assert (meta_path.parent / "src" / "model.py").is_file()+def test_telemetry_summarises_the_runs_own_ledger(fake_run):+ ws, rec = fake_run+ ledger = ws.root / "telemetry" / "cost.jsonl"+ ledger.unlink()+ assert ledger_rows(ws) == [] # a run with no ledger has no rows (nothing is reconstructed)+ tele = build_telemetry(ws, rec, write=False)+ assert tele.cost is not None and tele.cost.n_calls == 0 and tele.settings is not None+ ledger.write_text(json.dumps({"stage": "plan", "role": "planner", "label": "plan", "cost_usd": 0.5,+ "model": "gemini-3.8-flash", "n_calls": 1}) + "\n")+ tele = build_telemetry(ws, rec)+ assert tele.cost is not None and tele.cost.by_stage[0].stage == "plan"+ assert {s.stage for s in tele.cost.by_stage} <= set(STAGE_ORDER)+ assert not (ws.telemetry / "usage.jsonl").exists(), "one ledger, one name"+ # a degraded verdict is unscored in the per-round cost table, never a 0.0+ rec.rounds[1].judgment = rec.rounds[1].judgment.model_copy(update={"summary": "judge_error: outage"})+ by_round = build_telemetry(ws, rec, write=False).cost.by_round+ assert [r["score"] for r in by_round] == [rec.rounds[0].judgment.overall, None]diff --git a/harness/tests/flywheel_cli/test_select.py b/harness/tests/flywheel_cli/test_select.pyindex 24d8bec2..5e9ba2e9 100644--- a/harness/tests/flywheel_cli/test_select.py+++ b/harness/tests/flywheel_cli/test_select.py@@ -62,42 +62,14 @@ def _run(root: Path, rounds: list[tuple[float | str | None, int]], *, status: Rureturn ws-# --------------------------------------------------------------------------- pick[email protected]("rounds,want", [- ([(0.50, 0), (0.70, 0), (0.60, 0)], 1), # the highest judged score- ([(0.70, 2), (0.70, 0)], 1), # a tie: fewer gate errors- ([(0.70, 1), (0.70, 1), (0.65, 0)], 0), # a full tie: the earlier round- ([(0.40, 0), ("degraded", 0), (None, 0)], 0), # a glitch or no verdict is never a score- ([(None, 0), ("degraded", 0)], None), # no judged round: nothing to pick by score-], ids=["score", "gate-errors", "earlier", "unjudged", "none-judged"])-def test_pick_takes_the_best_score_then_fewer_gate_errors_then_the_earlier_round(tmp_path, rounds, want):- assert select.pick(_run(tmp_path / "r", rounds).root) == want---def test_summarise_is_baseline_pick_delta_rounds_and_the_stop_reason(tmp_path):- ws = _run(tmp_path / "r", [(0.5, 0), (0.8, 0), (0.6, 0)], status=RunStatus.BUDGET)- s = select.summarise(ws.root)- assert (s.rounds, s.stop_reason, s.baseline_score, s.picked_round, s.picked_score, s.method) == (- 3, "budget", 0.5, 1, 0.8, "score")- assert s.delta == pytest.approx(0.3)- # once a round is handed over, that round is the run's pick — whichever way it was chosen- select.package(ws.root, 2, method="round")- s = select.summarise(ws.root)- assert (s.picked_round, s.picked_score, s.method) == (2, 0.6, "round") and s.delta == pytest.approx(0.1)- none = select.summarise(_run(tmp_path / "n", [(None, 0)]).root)- assert (none.picked_round, none.picked_score, none.baseline_score, none.delta) == (None, None, None, None)--def test_an_unjudged_run_shows_one_fallback_round_in_every_reader(tmp_path, monkeypatch):"""N55b: nothing judged → every reader shows ``select.fallback_round``, the latest round thatbuilt AND has renders — here r0 (r1 failed to build but kept renders, r2 built with norenders). Before, five readers gave four answers (2, None, r02's sheet, 1, 2)."""from codeverse3d.addons.calibration import load_run_cases- from codeverse3d.addons.dataset import index as dsifrom codeverse3d.addons.dataset.sample import exported_roundfrom codeverse3d.addons.gallery.index import entry_from_recordfrom codeverse3d.cli import _judge as J- from codeverse3d.contracts.run import RunIdfrom codeverse3d.record.record import load_recordws = _run(tmp_path / "u", [(None, 2), (None, 0), (None, 0)])@@ -112,8 +84,6 @@ def test_an_unjudged_run_shows_one_fallback_round_in_every_reader(tmp_path, monks = select.summarise(ws.root, record=rec)assert (s.picked_round, s.round) == (None, 0)assert exported_round(ws, rec).index == 0- row = dsi._run_row(ws, rec, RunId(battery="b", rel="u"))- assert (row[12], row[-6], row[-4]) == (0, 2, rec.rounds[0].commit) # picked_round, n_err, commitcard = entry_from_record("b", ws, rec)assert (card.picked_round, card.gate_errors, card.sheet) == (0, 2, "artifacts/renders/r00/sheet.png")assert [c.round_index for c in load_run_cases(ws.root) if c.is_picked] == [0]@@ -123,8 +93,6 @@ def test_an_unjudged_run_shows_one_fallback_round_in_every_reader(tmp_path, monkassert asked == [0] # `3dcode judge`'s default round--class _Pairwise:def __init__(self, winner: str, confidence: float, *, fail: bool = False):self.winner, self.confidence, self.fail, self.calls = winner, confidence, fail, []@@ -137,24 +105,6 @@ class _Pairwise:error="")-def test_pick_by_pairwise_asks_only_inside_the_margin_and_never_buys_a_verdict_twice(tmp_path):- ws = _run(tmp_path / "r", [(0.70, 0), (0.72, 0)])- judge = _Pairwise("b", 0.9)- assert select.pick(ws.root, by="pairwise", judge=judge) == 0 # r00 is B, and B won- assert judge.calls and "/r01/" in judge.calls[0][0] and judge.calls[0][2] == "static_object"- assert select.pick(ws.root, by="pairwise", judge=judge) == 0 and len(judge.calls) == 1 # cached, not re-bought- assert ws.judge_path(1, "_vs_r00_pairwise").is_file()- Path(judge.calls[0][0]).write_bytes(b"re-rendered") # new pictures are a new comparison- assert select.pick(ws.root, by="pairwise", judge=judge) == 0 and len(judge.calls) == 2- # an unsure verdict, an outage or a clear gap keep the top score- assert select.pick(_run(tmp_path / "u", [(0.70, 0), (0.72, 0)]).root, by="pairwise", judge=_Pairwise("b", 0.5)) == 1- assert select.pick(_run(tmp_path / "f", [(0.70, 0), (0.72, 0)]).root, by="pairwise",- judge=_Pairwise("b", 0.9, fail=True)) == 1- far = _Pairwise("b", 0.99)- assert select.pick(_run(tmp_path / "g", [(0.60, 0), (0.72, 0)]).root, by="pairwise", judge=far) == 1 and not far.calls- assert select.pick(ws.root) == 1 # by score it is still the top score--# --------------------------------------------------------------------------- packagedef test_a_scene_or_graphics_round_packages_from_its_own_commit_and_renders(tmp_path):"""A scene or graphics hand-over of round 0 of two is round 0's bytes, never the last's."""@@ -238,7 +188,17 @@ def test_make_hands_over_the_picked_round_unless_no_pick(tmp_path, monkeypatch):assert not (runs / "kept" / "selection.json").exists() and not (runs / "kept" / "deliverable" / "manifest.json").exists()-# --------------------------------------------------------------------------- a round's own outputs[email protected]("rounds,want", [+ ([(0.50, 0), (0.70, 0), (0.60, 0)], 1), # the highest judged score+ ([(0.70, 2), (0.70, 0)], 1), # a tie: fewer gate errors+ ([(0.70, 1), (0.70, 1), (0.65, 0)], 0), # a full tie: the earlier round+ ([(0.40, 0), ("degraded", 0), (None, 0)], 0), # a glitch or no verdict is never a score+ ([(None, 0), ("degraded", 0)], None), # no judged round: nothing to pick by score+], ids=["score", "gate-errors", "earlier", "unjudged", "none-judged"])+def test_pick_takes_the_best_score_then_fewer_gate_errors_then_the_earlier_round(tmp_path, rounds, want):+ assert select.pick(_run(tmp_path / "r", rounds).root) == want++def test_round_outputs_are_the_rounds_own_never_the_last_builds(tmp_path: Path):"""A reader asking for round N's GLB or complexity once got the last build's (B4, B6)."""ws = _run(tmp_path / "r", [(0.8, 0), (0.6, 0)])diff --git a/harness/tests/gallery/conftest.py b/harness/tests/gallery/conftest.pyindex 657c186b..da0c3563 100644--- a/harness/tests/gallery/conftest.py+++ b/harness/tests/gallery/conftest.py@@ -1,8 +1,4 @@-"""A synthetic multi-root run tree: two batteries, a good/failing/pending/corrupt run.--Reuses ``tests.flywheel_cli.conftest.make_fake_run`` so the gallery is exercised-against exactly the records the rest of the flywheel tests use.-"""+"""A synthetic multi-root run tree: two batteries, good/failing/pending/corrupt runs."""from __future__ import annotationsdiff --git a/harness/tests/gallery/test_cli.py b/harness/tests/gallery/test_cli.pyindex 38163fe1..ae726b6a 100644--- a/harness/tests/gallery/test_cli.py+++ b/harness/tests/gallery/test_cli.py@@ -2,7 +2,6 @@from __future__ import annotations-import osfrom pathlib import Pathimport pytest@@ -21,25 +20,11 @@ def test_build_writes_a_linked_page_and_embed_inlines_the_images(gallery_tree: dassert "gallery of 6 runs" in r.outputmarkup = out.read_text()assert "batch 9" in markup and "wooden_chair_ab12cd34" in markup- assert "data:image/jpeg" not in markup # link mode by defaultr = runner.invoke(app, ["gallery", "build", str(gallery_tree["runs"]), "--out", str(out), "--embed"])assert r.exit_code == 0, r.outputassert "data:image/jpeg;base64," in out.read_text()-def test_build_rejects_a_missing_root(tmp_path: Path):- r = runner.invoke(app, ["gallery", "build", str(tmp_path / "nope"), "--out", str(tmp_path / "x.html")])- assert r.exit_code != 0 and "not a directory" in r.output---def test_default_roots_from_cwd(gallery_tree: dict[str, Path], monkeypatch: pytest.MonkeyPatch):- monkeypatch.setattr("codeverse3d.cli._common.EVAL_ROOT", gallery_tree["root"] / "no_eval")- monkeypatch.chdir(gallery_tree["root"])- roots = resolve_roots(None)- assert [r.name for r in roots] == ["runs", "runs"]- assert str(roots[1]).endswith(os.path.join("eval", "bench", "out", "static_v9", "runs"))--def test_default_roots_find_the_eval_batteries_from_any_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):"""D77: the batteries live in <repo>/eval/bench/out/<b>/runs, found from any cwd."""repo = tmp_path / "repo"@@ -50,17 +35,3 @@ def test_default_roots_find_the_eval_batteries_from_any_cwd(tmp_path: Path, monkfor cwd in (repo / "harness", repo, repo / "eval"): # each battery listed once, from anywheremonkeypatch.chdir(cwd)assert [p.resolve() for p in resolve_roots(None)] == [battery.resolve()], cwd---def test_no_roots_anywhere_is_a_clear_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):- monkeypatch.chdir(tmp_path)- monkeypatch.setattr("codeverse3d.cli._common.EVAL_ROOT", tmp_path / "no_eval")- monkeypatch.setenv("C3D_RUNS_DIR", str(tmp_path / "absent"))- from codeverse3d.config import get_settings-- get_settings.cache_clear()- try:- r = runner.invoke(app, ["gallery", "build", "--out", str(tmp_path / "x.html")])- assert r.exit_code != 0 and "no run roots found" in r.output- finally:- get_settings.cache_clear()diff --git a/harness/tests/gallery/test_hardening.py b/harness/tests/gallery/test_hardening.pyindex 35766853..a8d6195e 100644--- a/harness/tests/gallery/test_hardening.py+++ b/harness/tests/gallery/test_hardening.py@@ -1,6 +1,4 @@-"""Serving LLM-authored HTML/SVG must be inert (CSP sandbox, honest content type),-and CSV cells must never reach a spreadsheet as formulas."""-+"""CSV cells must never reach a spreadsheet as formulas."""from __future__ import annotationsimport csv@@ -9,31 +7,9 @@ from pathlib import Pathfrom codeverse3d.addons.gallery.compare import CSV_COLUMNS, csv_safe, export_csvfrom codeverse3d.addons.gallery.index import build_index-from codeverse3d.addons.gallery.server import GalleryAppfrom tests.flywheel_cli.conftest import make_fake_run-# --------------------------------------------------------------------------- content types + CSP-def test_llm_html_and_svg_file_responses_are_sandboxed(gallery_tree: dict[str, Path]):- app = GalleryApp([gallery_tree["runs"]])- run = gallery_tree["runs"] / "wooden_chair_ab12cd34"- (run / "artifacts" / "page.html").write_text("<script>fetch('/api/index')</script>")- (run / "artifacts" / "figure.svg").write_text(- "<svg xmlns='http://www.w3.org/2000/svg'><script>1</script></svg>")- html = app.route("/file/runs/wooden_chair_ab12cd34/artifacts/page.html")- assert html.status == 200 and html.content_type == "text/html; charset=utf-8"- assert html.headers["Content-Security-Policy"] == "sandbox"- svg = app.route("/file/runs/wooden_chair_ab12cd34/artifacts/figure.svg")- assert svg.status == 200 and svg.content_type == "image/svg+xml"- assert svg.headers["Content-Security-Policy"] == "sandbox"- # images and code stay untouched — <img src=…> previews keep rendering- png = app.route("/file/runs/wooden_chair_ab12cd34/artifacts/renders/r01/sheet.png")- assert png.status == 200 and "Content-Security-Policy" not in png.headers- src = app.route("/file/runs/wooden_chair_ab12cd34/src/model.py")- assert src.status == 200 and "Content-Security-Policy" not in src.headers---# --------------------------------------------------------------------------- csv injectiondef test_csv_cells_never_reach_a_spreadsheet_as_formulas(tmp_path: Path):assert csv_safe("=HYPERLINK(1)") == "'=HYPERLINK(1)"assert csv_safe("+1") == "'+1" and csv_safe("-1") == "'-1" and csv_safe("@cmd") == "'@cmd"@@ -44,4 +20,3 @@ def test_csv_cells_never_reach_a_spreadsheet_as_formulas(tmp_path: Path):text = export_csv(build_index([runs]).entries())rows = list(csv.reader(io.StringIO(text)))assert rows[0] == list(CSV_COLUMNS) and len(rows) == 2- assert rows[1][CSV_COLUMNS.index("prompt")] == "'=2+5|cmd"diff --git a/harness/tests/gallery/test_index.py b/harness/tests/gallery/test_index.pyindex ad2dd31b..35e7f45b 100644--- a/harness/tests/gallery/test_index.py+++ b/harness/tests/gallery/test_index.py@@ -2,7 +2,6 @@from __future__ import annotations-import jsonfrom pathlib import Pathfrom codeverse3d.addons.gallery.index import build_index@@ -13,9 +12,6 @@ def test_filter_and_sort_and_summary(gallery_tree: dict[str, Path]):index = build_index([gallery_tree["runs"], gallery_tree["battery"]])entries = index.entries()assert [e.slug for e in sort_entries(entries, "score")][0] == "ctrl_med_toaster" # 0.9- assert [e.slug for e in sort_entries(entries, "name")] == sorted(e.slug for e in entries)- by_cost = sort_entries(entries, "cost")- assert by_cost[0].cost_usd >= by_cost[-1].cost_usdthreejs = [e for e in entries if match(e, {"lang": "threejs"})]assert [e.slug for e in threejs] == ["lamp_three"]assert [e.slug for e in entries if match(e, {"q": "TOASTER"})] == ["ctrl_med_toaster"]@@ -29,35 +25,3 @@ def test_filter_and_sort_and_summary(gallery_tree: dict[str, Path]):assert facets["battery"] == ["runs", "static_v9"]-# --------------------------------------------------------------------------- run identity-def test_nested_battery_runs_get_distinct_findable_slugs_and_eval_workspaces_are_not_runs(tmp_path: Path):- """Two compare-style runs whose dirs are both named ``run`` keep distinct, findable slugs; a cell's- ``eval/`` judge workspace (spec.json, no record.json) is not a run."""- from tests.flywheel_cli.conftest import make_fake_run-- root = tmp_path / "compare_v9"- make_fake_run(root / "cells" / "cmp_a_stool" / "armx", "run", prompt="a stool")- make_fake_run(root / "cells" / "cmp_b_lamp" / "armx", "run", prompt="a lamp")- eval_dir = root / "cells" / "cmp_a_stool" / "armx" / "eval"- eval_dir.mkdir()- (eval_dir / "spec.json").write_text(json.dumps({"prompt": "judge ws"}))- index = build_index([root])- (section,) = index.sections- assert sorted(e.slug for e in section.entries) == ["cmp_a_stool__armx", "cmp_b_lamp__armx"]- a = index.find("compare_v9", "cmp_a_stool__armx")- b = index.find("compare_v9", "cmp_b_lamp__armx")- assert a is not None and a.prompt == "a stool"- assert b is not None and b.prompt == "a lamp"- assert a.key != b.key---def test_duplicate_slugs_within_a_root_are_disambiguated(tmp_path: Path):- """Two rels that reduce to one slug follow the label#2 precedent — the viewer shows both."""- from tests.flywheel_cli.conftest import make_fake_run-- root = tmp_path / "mixed"- make_fake_run(root / "runs", "x", prompt="first")- make_fake_run(root / "cells" / "x", "run", prompt="second")- (section,) = build_index([root]).sections- assert [e.slug for e in section.entries] == ["x", "x#2"] # cells/x/run sorts first- assert {e.prompt for e in section.entries} == {"first", "second"}diff --git a/harness/tests/gallery/test_page.py b/harness/tests/gallery/test_page.pyindex 4a5f147a..b739ee7c 100644--- a/harness/tests/gallery/test_page.py+++ b/harness/tests/gallery/test_page.py@@ -4,66 +4,19 @@ server-side so a curl'd query string already shows the right runs."""from __future__ import annotationsimport re-from html.parser import HTMLParserfrom pathlib import Path-from codeverse3d.addons.gallery.index import build_indexfrom codeverse3d.addons.gallery.page import build_static, render_index, render_staticfrom codeverse3d.addons.gallery.urls import UrlMaker-VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",- "source", "track", "wbr"}--class _Checker(HTMLParser):- """Parses the document and collects every URL-bearing attribute + tag balance."""-- def __init__(self) -> None:- super().__init__(convert_charrefs=True)- self.urls: list[str] = []- self.stack: list[str] = []- self.unbalanced: list[str] = []- self.ids: list[str] = []- self.tags: list[str] = []-- def handle_starttag(self, tag, attrs):- self.tags.append(tag)- d = dict(attrs)- for key in ("src", "href", "action", "srcset", "poster", "data-src"):- if d.get(key):- self.urls.append(d[key])- if d.get("id"):- self.ids.append(d["id"])- if tag not in VOID:- self.stack.append(tag)-- def handle_endtag(self, tag):- if tag in VOID:- return- if self.stack and self.stack[-1] == tag:- self.stack.pop()- elif tag in self.stack:- while self.stack and self.stack.pop() != tag:- self.unbalanced.append(tag)- else:- self.unbalanced.append(tag)---def _parse(markup: str) -> _Checker:- c = _Checker()- c.feed(markup)- return c---def _assert_offline(markup: str) -> _Checker:- c = _parse(markup)- external = [u for u in c.urls if u.split(":", 1)[0].lower() in ("http", "https", "ftp")- or u.startswith("//")]+def _assert_offline(markup: str) -> list[str]:+ urls = re.findall(r"""(?:src|href|action|srcset|poster)=['"]([^'"]+)""", markup)+ external = [u for u in urls if u.split(":", 1)[0].lower() in ("http", "https", "ftp") or u.startswith("//")]assert not external, f"external references: {external[:5]}"for bad in ("cdn.", "googleapis.com", "unpkg", "jsdelivr", "@import url(http"):assert bad not in markup, bad- assert not c.unbalanced, f"unbalanced tags: {c.unbalanced[:5]}"- return c+ return urlsdef test_static_and_server_pages(gallery_tree: dict[str, Path], tmp_path: Path):@@ -73,14 +26,12 @@ def test_static_and_server_pages(gallery_tree: dict[str, Path], tmp_path: Path):path, n, index = build_static([gallery_tree["runs"], gallery_tree["battery"]], out, embed=True)assert path == out and n == 6 and out.is_file()markup = out.read_text()- checker = _assert_offline(markup)+ urls = _assert_offline(markup)assert markup.startswith("<!doctype html>")assert "data:image/jpeg;base64," in markup # --embed inlined the sheets- assert any(u.startswith("file://") for u in checker.urls) # links point at the run dirs- assert "gallery-data" in checker.ids and "s-cost" in checker.ids+ assert any(u.startswith("file://") for u in urls) # links point at the run dirs+ assert "id='gallery-data'" in markup or 'id="gallery-data"' in markupassert markup.count("<article class='card") == 6- for slug in ("wooden_chair_ab12cd34", "half_written", "not_started"):- assert slug in markupassert "broken:" in markup and "pending:" in markup # the two non-ok cards say whymarkup = render_index(index, UrlMaker(), flt={"lang": "threejs"}, sort="score")@@ -90,24 +41,9 @@ def test_static_and_server_pages(gallery_tree: dict[str, Path], tmp_path: Path):# ...but only the matching one is visible, and the summary counts only that oneassert len(re.findall(r"<article class='card [^']*is-hidden' data-run=", markup)) == 5assert ">1 <span class='faint'>of 6</span><" in markup- assert "<option value='threejs' selected>" in markupassert "vc-passed" not in markup and "PASS RATE" not in markup.upper() # no pass/fail since 2026-09-22markup = render_index(index, UrlMaker())- assert "/run/runs/wooden_chair_ab12cd34" in markup- assert "/file/runs/wooden_chair_ab12cd34/artifacts/renders/r01/sheet.png" in markup- assert "/code/runs/wooden_chair_ab12cd34/src" in markup- assert "/viewer/runs/wooden_chair_ab12cd34/artifacts/r01/object.glb" in markup # the picked round's+ assert "/run/runs/wooden_chair_ab12cd34" in markup and "/viewer/runs/wooden_chair_ab12cd34/artifacts/r01/object.glb" in markupstatic = render_static(index, embed=False)assert "/run/runs/" not in static and "/viewer/" not in static---def test_html_escaping_of_a_hostile_prompt(tmp_path: Path):- from tests.flywheel_cli.conftest import make_fake_run-- runs = tmp_path / "runs"- make_fake_run(runs, "xss", prompt="a chair <script>alert(1)</script> & \"quotes\"")- markup = render_index(build_index([runs]), UrlMaker())- assert "<script>alert(1)</script>" not in markup- assert "<script>alert(1)</script>" in markup- _assert_offline(markup)diff --git a/harness/tests/gallery/test_server.py b/harness/tests/gallery/test_server.pyindex 5db80777..3a653aac 100644--- a/harness/tests/gallery/test_server.py+++ b/harness/tests/gallery/test_server.py@@ -7,20 +7,13 @@ in a background thread and talks to it with ``http.client``.from __future__ import annotationsimport http.client-import jsonimport threadingfrom pathlib import Pathimport pytest-from codeverse3d.addons.gallery.server import (- DEFAULT_HOST,- GalleryApp,- GalleryError,- make_server,- resolve_host,-)-from codeverse3d.addons.gallery.urls import PathError, content_type, safe_join+from codeverse3d.addons.gallery.server import DEFAULT_HOST, GalleryApp, GalleryError, make_server+from codeverse3d.addons.gallery.urls import PathError, safe_join@pytest.fixture@@ -33,13 +26,7 @@ def test_routes(app: GalleryApp):r = app.route("/")assert r.status == 200 and r.content_type.startswith("text/html")assert b"3dcode gallery" in r.body- assert app.route("/index.html").status == 200- assert app.route("/healthz").body == b"ok"- api = json.loads(app.route("/api/runs", {"lang": "threejs"}).body)- assert api["total"] == 6 and api["n"] == 1 and api["runs"][0]["slug"] == "lamp_three"- summary = json.loads(app.route("/api/summary", {"battery": "runs"}).body)- assert summary["n"] == 2- assert app.route("/api/nope").status == 404+ assert app.route("/nope").status == 404# the detail of a broken / pending run does not crashr = app.route("/run/static_v9/half_written")@@ -67,21 +54,6 @@ def test_routes(app: GalleryApp):# unknown run / unknown routeassert app.route("/file/nope/nope/record.json").status == 404- assert app.route("/wat").status == 404- assert app.route("/file").status == 404-- # vendor and viewer- from codeverse3d.addons.gallery.viewer import viewer_available-- v = app.route("/viewer/runs/wooden_chair_ab12cd34/artifacts/object.glb")- if viewer_available():- assert v.status == 200 and b"importmap" in v.body- js = app.route("/vendor/three/build/three.module.js")- assert js.status == 200 and js.content_type.startswith("text/javascript")- assert app.route("/vendor/three/../../../etc/passwd").status == 404- assert app.route("/vendor/nope.js").status == 404- else: # runtime_js/node_modules not installed- assert v.status == 501def test_traversal_absolute_paths_and_symlinks_out_of_the_run_are_refused(app: GalleryApp, tmp_path: Path):@@ -103,49 +75,23 @@ def test_traversal_absolute_paths_and_symlinks_out_of_the_run_are_refused(app: Gassert r.status == 403 and b"classified" not in r.body-def test_content_type_table():- assert content_type("a.glb") == "model/gltf-binary"- assert content_type("a.frag") == "text/plain; charset=utf-8"- assert content_type("a.js") == "text/plain; charset=utf-8"- assert content_type("a.gif") == "image/gif"- assert content_type("a.unknownext") == "application/octet-stream"---# --------------------------------------------------------------------------- host guard-def test_host_guard():- assert resolve_host(None) == DEFAULT_HOST- assert resolve_host("") == DEFAULT_HOST- assert resolve_host("localhost") == "localhost"- assert resolve_host("0.0.0.0", explicit=True) == "0.0.0.0" # noqa: S104 - the point of the test- with pytest.raises(GalleryError):- resolve_host("0.0.0.0") # noqa: S104- with pytest.raises(GalleryError):- resolve_host("192.168.1.5")---# --------------------------------------------------------------------------- reload-def test_reload_picks_up_a_run_written_after_startup(gallery_tree: dict[str, Path]):- from tests.flywheel_cli.conftest import make_fake_run-- app = GalleryApp([gallery_tree["runs"]], reload=True)- assert len(app.index.entries()) == 2- make_fake_run(gallery_tree["runs"], "brand_new", prompt="a new stool")- app.route("/")- assert len(app.index.entries()) == 3- assert app.route("/run/runs/brand_new").status == 200---def test_unknown_compare_keys_cost_one_rescan_not_one_each(gallery_tree: dict[str, Path],- monkeypatch: pytest.MonkeyPatch):- import codeverse3d.addons.gallery.server as server-+def test_llm_html_and_svg_file_responses_are_sandboxed(gallery_tree: dict[str, Path]):app = GalleryApp([gallery_tree["runs"]])- real, scans = server.build_index, []- monkeypatch.setattr(server, "build_index", lambda roots: scans.append(1) or real(roots))- entries, missing = app.picked(["runs/nope_a", "runs/nope_b", "runs/wooden_chair_ab12cd34"])- assert len(scans) == 1 and missing == ["runs/nope_a", "runs/nope_b"] and len(entries) == 1- _, _, note = app._picked({"runs": ",".join(f"runs/nope_{i}" for i in range(20))})- assert len(scans) == 2 and note.startswith(f"showing the first {server.MAX_COMPARE} of 20 selected runs")+ run = gallery_tree["runs"] / "wooden_chair_ab12cd34"+ (run / "artifacts" / "page.html").write_text("<script>fetch('/api/index')</script>")+ (run / "artifacts" / "figure.svg").write_text(+ "<svg xmlns='http://www.w3.org/2000/svg'><script>1</script></svg>")+ html = app.route("/file/runs/wooden_chair_ab12cd34/artifacts/page.html")+ assert html.status == 200 and html.content_type == "text/html; charset=utf-8"+ assert html.headers["Content-Security-Policy"] == "sandbox"+ svg = app.route("/file/runs/wooden_chair_ab12cd34/artifacts/figure.svg")+ assert svg.status == 200 and svg.content_type == "image/svg+xml"+ assert svg.headers["Content-Security-Policy"] == "sandbox"+ # images and code stay untouched — <img src=…> previews keep rendering+ png = app.route("/file/runs/wooden_chair_ab12cd34/artifacts/renders/r01/sheet.png")+ assert png.status == 200 and "Content-Security-Policy" not in png.headers+ src = app.route("/file/runs/wooden_chair_ab12cd34/src/model.py")+ assert src.status == 200 and "Content-Security-Policy" not in src.headers# --------------------------------------------------------------------------- over a real socket@@ -170,8 +116,6 @@ def test_over_a_loopback_socket(app: GalleryApp):assert status == 200 and ctype == "image/png" and body[:8] == b"\x89PNG\r\n\x1a\n"status, ctype, _ = get("/file/runs/wooden_chair_ab12cd34/artifacts/object.glb")assert status == 200 and ctype == "model/gltf-binary"- status, ctype, body = get("/api/runs?tier=A")- assert status == 200 and ctype.startswith("application/json") and json.loads(body)["n"] >= 1status, _, body = get("/file/runs/wooden_chair_ab12cd34/..%2f..%2f..%2fetc%2fpasswd")assert status in (403, 404) and b"root:x:" not in bodyconn.request("HEAD", "/")diff --git a/harness/tests/gallery/test_triage.py b/harness/tests/gallery/test_triage.pyindex ad149d90..11ce6c34 100644--- a/harness/tests/gallery/test_triage.py+++ b/harness/tests/gallery/test_triage.py@@ -4,15 +4,12 @@ view, label humanisation, compare / CSV routing and the neighbour links."""from __future__ import annotationsfrom pathlib import Path-from urllib.parse import parse_qsfrom codeverse3d.addons.gallery.compare import (CSV_COLUMNS,)-from codeverse3d.addons.gallery.index import hero_viewfrom codeverse3d.addons.gallery.model import (VERDICTS,- humanize_view,summarize,)from codeverse3d.addons.gallery.page import render_index@@ -26,13 +23,8 @@ def test_breakdown_compare_and_csv_over_both_roots(gallery_tree: dict[str, Path]entries = app.index.entries()s = summarize(entries)assert s.n == 6- assert set(s.breakdown) == set(VERDICTS)- assert sum(s.breakdown.values()) == s.n- # the tree holds 4 judged runs and 2 with no usable record+ assert set(s.breakdown) == set(VERDICTS) and sum(s.breakdown.values()) == s.nassert s.breakdown == {"judged": 4, "unjudged": 0, "error": 2}- # every entry lands in exactly one bucket- assert sorted(e.verdict for e in entries) == sorted(- k for k, n in s.breakdown.items() for _ in range(n))by_slug = {e.slug: e for e in entries} # a corrupt record and a missing one are errorsassert by_slug["half_written"].verdict == by_slug["not_started"].verdict == "error"assert by_slug["half_written"].score is None@@ -44,8 +36,6 @@ def test_breakdown_compare_and_csv_over_both_roots(gallery_tree: dict[str, Path]assert page.count("<td class='head'>") == 2assert "wooden_chair_ab12cd34" in page and "ctrl_med_toaster" in pageassert "lamp_three" not in page- assert "Δ vs baseline" in page- assert "never starts, resumes or deletes" in page # the read-only stance is statedr = app.route("/compare", {"runs": "static_v9/half_written,static_v9/not_started"})assert r.status == 200 and b"half_written" in r.body # survives runs with no record@@ -63,12 +53,9 @@ def test_hero_view_empty_compare_and_neighbours_over_one_root(gallery_tree: dict# the card shows one hero view, not the contact sheetentry = app.index.find("runs", "wooden_chair_ab12cd34")assert entry.hero.endswith("view_front.png") # "front" is in HERO_PREFERENCE- assert entry.hero_label == "Front"- assert entry.n_views == 2- assert entry.sheet.endswith("sheet.png") and entry.card_image == entry.hero+ assert entry.n_views == 2 and entry.card_image == entry.heromarkup = render_index(app.index, UrlMaker())assert "view_front.png" in markup- assert "⊞ 2" in markup # the sheet is one disclosure awaypage = app.route("/compare").body.decode()assert "nothing to compare" in page and app.route("/compare").status == 200@@ -81,39 +68,3 @@ def test_hero_view_empty_compare_and_neighbours_over_one_root(gallery_tree: dictassert prev.slug == "wooden_chair_ab12cd34" and nxt is Nonepage = app.route("/run/runs/wooden_chair_ab12cd34").body.decode()assert "/run/runs/lamp_three" in page and "next →" in page- outside = app.index.find("runs", "lamp_three").model_copy(update={"battery": "nope"})- assert app.neighbours(outside) == (None, None)---def test_hero_falls_back_to_the_sheet_when_a_round_has_no_views(tmp_path: Path):- from tests.flywheel_cli.conftest import make_fake_run-- ws, rec = make_fake_run(tmp_path / "runs", "noviews")- for rnd in rec.rounds:- rnd.renders = None- assert hero_view(ws, rec, 1) == ("", "", 0) and hero_view(ws, rec, None) == ("", "", 0)---def test_view_names_are_humanised():- for raw, human in [- ("front_right_high", "Front Right High"),- ("front_right_34", "Front Right ¾"),- ("view_front_right_34.png", "Front Right ¾"),- ("t=2.5s", "t = 2.5 s"),- ("pose_rest", "Pose · rest"),- ("articulation_sheet", "Articulation poses"),- ("preview.gif", "Animated preview"),- ("", ""),- ]:- assert humanize_view(raw) == human, raw---def test_query_links_survive_a_duplicate_root_label(gallery_tree: dict[str, Path]):- """``build_index`` mints ``runs#2``; an unquoted ``#`` ends the URL in the browser."""- app = GalleryApp([gallery_tree["runs"], gallery_tree["runs"]])- key = "runs#2/wooden_chair_ab12cd34"- compare = app.route("/compare", {"runs": key}).body.decode()- href = compare.split("href='/export.csv?", 1)[1].split("'", 1)[0]- assert "#" not in href and parse_qs(href) == {"runs": [key]}- detail = app.route("/run/runs#2/wooden_chair_ab12cd34").body.decode()- assert "href='/?battery=runs%232'" in detaildiff --git a/harness/tests/graphics/test_frame_stats.py b/harness/tests/graphics/test_frame_stats.pyindex 9aeb2e44..6b172ce2 100644--- a/harness/tests/graphics/test_frame_stats.py+++ b/harness/tests/graphics/test_frame_stats.py@@ -18,10 +18,7 @@ def _gradient(t: float, w=160, h=90, moving=True):x = np.linspace(0, 1, w, dtype=np.float32)[None, :].repeat(h, 0)y = np.linspace(0, 1, h, dtype=np.float32)[:, None].repeat(w, 1)shift = 0.2 * t if moving else 0.0- r = 0.5 + 0.5 * np.sin(6.0 * (x + shift))- g = y- b = 0.5 + 0.5 * np.cos(4.0 * (y - shift))- return np.stack([r, g, b], -1)+ return np.stack([0.5 + 0.5 * np.sin(6.0 * (x + shift)), y, 0.5 + 0.5 * np.cos(4.0 * (y - shift))], -1)def _kinds(gate):@@ -60,8 +57,3 @@ def test_flicker_and_low_detail_warn(tmp_path):flat = [(t, _png(tmp_path / f"l{i}.png", np.full((90, 160, 3), 0.4 + 0.01 * t))) for i, t in enumerate((0.0, 1.0, 2.0))]g = frame_gate(sequence_stats(flat))assert _kinds(g)["low_detail"] == Severity.WARN and g.passed---def test_empty_sequence_is_an_error():- g = frame_gate(sequence_stats([]))- assert not g.passed and g.errors[0].data["kind"] == "no_frames"diff --git a/harness/tests/graphics/test_gl_host.py b/harness/tests/graphics/test_gl_host.pyindex 022a5442..466e25e2 100644--- a/harness/tests/graphics/test_gl_host.py+++ b/harness/tests/graphics/test_gl_host.py@@ -3,24 +3,16 @@from __future__ import annotationsimport json-from pathlib import Path-import numpy as npimport pytest-from PIL import Imagefrom codeverse3d.spatial import gl_renderfrom codeverse3d.spatial.gl_render import (- GlFrame,GlHost,- GlHostError,- gif_times,- write_contact_sheet,- write_gif,)FAKE_RUNNER = r'''-import json, os, sys, time+import json, os, sysfrom pathlib import Pathjob = json.loads(Path(sys.argv[sys.argv.index("--job") + 1]).read_text())out = Path(job["out_dir"]); out.mkdir(parents=True, exist_ok=True)@@ -28,10 +20,6 @@ mode = os.environ.get("FAKE_MODE", "ok")if os.environ.get("GALLIUM_DRIVER") == "d3d12" and mode in ("gpu_fail", "ok_cpu_only"):(out / "gl_result.json").write_text(json.dumps({"ok": False, "stage": "context", "error_type": "Error", "error_message": "no d3d12"}))sys.exit(3)-if mode == "crash":- sys.exit(139)-if mode == "hang":- time.sleep(30)frames = []for i, t in enumerate(sorted(set(job["times"]) | set(job.get("extra_times", [])))):p = out / "frames" / f"f{i:02d}_t{t:06.2f}.png"; p.parent.mkdir(exist_ok=True)@@ -64,43 +52,3 @@ def test_gpu_then_cpu_fallback_is_cached(tmp_path, fake_runner, monkeypatch):res2 = host.run_program(fake_runner, tmp_path / "o2", width=32, height=18, times=(0.0,))assert res2.ok and not res2.gpu # cached decision: no GPU retryassert (tmp_path / "o2" / gl_render.JOB_NAME).is_file() and json.loads((tmp_path / "o2" / gl_render.JOB_NAME).read_text())["mode"] == "program"---def test_relative_output_path_survives_runner_working_directory(tmp_path, fake_runner, monkeypatch):- monkeypatch.chdir(tmp_path)- result = GlHost(gpu="off").render_fragment_shader("src", Path("relative/render"),- width=32, height=18, times=(0.0,))- assert result.ok, result.stderr_tail- frame = Path(result.frames[0].path)- assert frame.is_file() and frame.is_relative_to(tmp_path / "relative/render")- assert not (tmp_path / "relative/render/relative").exists()---def test_gpu_on_failure_raises_and_crash_timeout_are_typed(tmp_path, fake_runner, monkeypatch):- monkeypatch.setenv("FAKE_MODE", "gpu_fail")- with pytest.raises(GlHostError):- GlHost(gpu="on", timeout_s=20).render_fragment_shader("src", tmp_path / "o", width=8, height=8, times=(0.0,))- monkeypatch.setenv("FAKE_MODE", "crash")- res = GlHost(gpu="off", timeout_s=20).render_fragment_shader("src", tmp_path / "c", width=8, height=8, times=(0.0,))- assert not res.ok and res.error_type == "RunnerCrash" and res.stage == "crash"- monkeypatch.setenv("FAKE_MODE", "hang")- res = GlHost(gpu="off", timeout_s=1.5).render_fragment_shader("src", tmp_path / "h", width=8, height=8, times=(0.0,))- assert not res.ok and res.timed_out and res.error_type == "RenderTimeout"---def test_sheet_gif_and_gif_times(tmp_path):- frames = []- for i, t in enumerate((0.0, 1.0, 2.5)):- p = tmp_path / f"f{i}.png"- Image.fromarray(np.full((18, 32, 3), 60 * i, dtype=np.uint8), "RGB").save(p)- frames.append(GlFrame(index=i, time=t, path=str(p)))- sheet = write_contact_sheet(frames, tmp_path / "sheet.png", cols=2, tile_w=64)- im = Image.open(sheet)- assert im.width > 128 and im.height > 2 * 36 # 2 columns × 2 rows of 64×36 tiles + labels- gif = write_gif(frames, tmp_path / "p.gif", width=32)- assert gif is not None and Image.open(gif).n_frames == 3- assert write_gif(frames[:1], tmp_path / "one.gif") is None- assert gif_times(8.0, 4) == [0.0, 2.0, 4.0, 6.0] and len(gif_times(0.1, 12)) == 12- with pytest.raises(ValueError):- write_contact_sheet([], tmp_path / "x.png")- assert Path(sheet).is_file()diff --git a/harness/tests/graphics/test_gl_runtime.py b/harness/tests/graphics/test_gl_runtime.pyindex ba5834c2..046fd545 100644--- a/harness/tests/graphics/test_gl_runtime.py+++ b/harness/tests/graphics/test_gl_runtime.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-import reimport numpy as npimport pytest@@ -12,7 +11,6 @@ from PIL import Imagefrom codeverse3d.contracts.plan import GraphicsPlan, PassPlanfrom codeverse3d.languages.glsl_shader import GlslShaderRuntimefrom codeverse3d.languages.opengl_python import OpenGLPythonRuntime-from codeverse3d.prompts import load_textfrom codeverse3d.spatial import gl_renderfrom codeverse3d.spatial.gl_render import GlHost, GlHostErrorfrom codeverse3d.spatial.registry import ToolContext, get_tool@@ -44,70 +42,25 @@ def _ws_with_plan(tmp_ws):def test_shader_skeleton_builds_and_writes_artifacts(tmp_ws, host):- """The glsl_shader stub (D107): the entry point, the plan as comments and ONE flat grey write —- no sky, sun or vignette to "keep the structure" of. It lints clean and builds the judged frames,- and the gate convicts it as `static` until the plan's passes replace the write."""+ """The glsl_shader stub (D107): entry point + plan comments + one flat write; builds the judged frames, gate says `static`."""ws = _ws_with_plan(tmp_ws)rt = GlslShaderRuntime(host=host)paths = rt.skeleton(ws, PLAN)assert {p.name for p in paths} == {"common.glsl", "shader.frag"}- src = (ws.src / "shader.frag").read_text()- assert "TODO pass 1: Sky" in src- for template in ("sunPos", "vignette", "haze", "mix(vec3"):- assert template not in src, templateassert rt.lint(ws).passedbr = rt.build(ws, **SMALL)assert br.ok, br.error_message- assert br.glb_path is None and br.language == "glsl_shader"- for key in ("frames", "sheet", "metrics"):- assert key in br.extra_paths+ assert br.glb_path is None and {"frames", "sheet", "metrics"} <= set(br.extra_paths)frames = sorted((ws.artifacts / "frames").glob("f*_t*.png"))assert len(frames) == 5 # t = 0, 1, 2.5, 4, 6 (duration 6)metrics = json.loads((ws.artifacts / "metrics.json").read_text())assert metrics["stats"]["mean_lum"] > 0.1 and not metrics["stats"]["any_nan"] and metrics["stats"]["static"]assert any(f["data"]["kind"] == "static" for f in metrics["gate"]["findings"])assert br.census["convention"] == "mainImage" and br.census["feedback"] is False- assert (ws.artifacts / "build.json").is_file()-def test_glsl_contract_example_builds(tmp_ws, host):- """The ONE executable interface example in glsl_shader/contract.md runs as src/shader.frag: lint- clean, five judged frames, no NaN, not static, no flicker — the only runnable prompt material the- language ships now that its cookbook and the seeded recipes are gone (D107)."""- text = load_text("glsl_shader/contract.md")- blocks = [b for b in re.findall(r"```glsl\n(.*?)```", text, re.S) if b.lstrip().startswith("void mainImage") and "..." not in b]- assert len(blocks) == 1, "the contract ships exactly one complete example"- assert len(blocks[0].strip().splitlines()) <= 12- ws = _ws_with_plan(tmp_ws)- ws.src.mkdir(parents=True, exist_ok=True)- (ws.src / "shader.frag").write_text(blocks[0])- rt = GlslShaderRuntime(host=host)- assert rt.lint(ws).passed- br = rt.build(ws, **SMALL)- assert br.ok, br.error_message- metrics = json.loads((ws.artifacts / "metrics.json").read_text())- assert len(list((ws.artifacts / "frames").glob("f*_t*.png"))) == 5- assert not metrics["stats"]["static"] and not metrics["stats"]["flicker"] and not metrics["stats"]["any_nan"]- assert metrics["gate"]["passed"]---def test_feedback_and_nan_detection(tmp_ws, host):- ws = _ws_with_plan(tmp_ws)- (ws.src / "shader.frag").write_text(- "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"- " vec3 prev = texture(u_prev, uv).rgb * 0.9;\n float d = smoothstep(0.05, 0.0, length(uv - vec2(0.5 + 0.3*sin(u_time), 0.5)));\n"- " float bad = uv.x > 0.9 ? sqrt(-1.0) : 0.0;\n fragColor = vec4(max(prev, vec3(d)) + bad, 1.0);\n}\n")- rt = GlslShaderRuntime(host=host)- br = rt.build(ws, **SMALL)- assert br.ok and br.census["feedback"] is True- metrics = json.loads((ws.artifacts / "metrics.json").read_text())- assert metrics["stats"]["any_nan"] is True- assert any(f["data"]["kind"] == "nan" for f in metrics["gate"]["findings"]) and not metrics["gate"]["passed"]--[email protected]("buffer_a", [False, True], ids=["image", "buffer_a"])-def test_feedback_starts_black_even_when_allocated_texture_memory_is_dirty(tmp_path, monkeypatch, buffer_a):- """Exercise real GL with nonzero allocation contents, not driver-provided zeros."""+def test_feedback_starts_black_even_when_allocated_texture_memory_is_dirty(tmp_path, monkeypatch):+ """Real GL with nonzero allocation contents, not driver-provided zeros: u_prev must still start black."""runner = tmp_path / "dirty_gl_runner.py"runner.write_text(f"""import importlib.util@@ -126,74 +79,32 @@ spec.loader.exec_module(module)sys.exit(module.main())""")monkeypatch.setattr(gl_render, "RUNNER", runner)- previous = """#version 330 core+ frag = """#version 330 coreuniform vec2 u_resolution;uniform sampler2D u_prev;out vec4 fragColor;void main() { fragColor = texture(u_prev, gl_FragCoord.xy / u_resolution); }"""- image = """#version 330 core-uniform vec2 u_resolution;-uniform sampler2D u_prev;-uniform sampler2D u_buffer_a;-out vec4 fragColor;-void main() {- vec2 uv=gl_FragCoord.xy/u_resolution;- vec4 a=texture(u_prev,uv), b=texture(u_buffer_a,uv);- bool black=all(equal(a,vec4(0,0,0,1))) && all(equal(b,vec4(0,0,0,1)));- fragColor=black?vec4(0,1,0,1):vec4(1,0,0,1);-}-""" if buffer_a else previoustry:- result = GlHost(timeout_s=90).render_fragment_shader(- image, tmp_path / "frames", width=8, height=8, times=(0.0,),- buffer_a_src=previous if buffer_a else None, feedback=True)+ result = GlHost(timeout_s=90).render_fragment_shader(frag, tmp_path / "frames", width=8, height=8, times=(0.0,), feedback=True)except GlHostError as exc:pytest.skip(f"OpenGL unavailable: {exc}")assert result.ok, result.error_message- pixels = np.asarray(Image.open(result.frames[0].path).convert("RGB"))- assert np.all(pixels == ([0, 255, 0] if buffer_a else [0, 0, 0])), pixels.tolist()+ assert np.all(np.asarray(Image.open(result.frames[0].path).convert("RGB")) == 0)def test_program_skeleton_builds_and_errors_map(tmp_ws, host):- """The opengl_python stub (D107): one t-dependent full-screen pass, no subject, camera or palette —- it lints clean, builds the judged frames, is neither static nor flickering, and a runtime error in- render() maps back to src/program.py:LINE."""+ """The opengl_python stub (D107) builds the judged frames; a runtime error in render() maps back to src/program.py:LINE."""ws = _ws_with_plan(tmp_ws)rt = OpenGLPythonRuntime(host=host)rt.skeleton(ws, PLAN)assert rt.lint(ws).passedsrc = (ws.src / "program.py").read_text()- for template in ("_cube", "_perspective", "_look_at", "u_mvp", "vec3 top", "0.25 + 0.75"):- assert template not in src, template # no placeholder look to "keep the structure" ofbr = rt.build(ws, **SMALL)assert br.ok, br.error_message- assert len(list((ws.artifacts / "frames").glob("*.png"))) == 5 and (ws.artifacts / "frames_sheet.png").is_file()- metrics = json.loads((ws.artifacts / "metrics.json").read_text())- assert not metrics["stats"]["static"] and not metrics["stats"]["flicker"] and metrics["stats"]["mean_lum"] > 0.1(ws.src / "program.py").write_text(src.replace("fbo.use()\n ctx.disable", "fbo.use()\n raise ValueError('boom')\n ctx.disable"))br = rt.build(ws, **SMALL)assert not br.ok and br.error_type == "ValueError" and br.error_file == "src/program.py" and br.error_line- assert "boom" in br.error_message---def test_opengl_contract_example_builds(tmp_ws, host):- """The ONE executable interface example in opengl_python/contract.md runs as src/program.py: lint- clean, five judged frames, not static — the only runnable prompt material the language ships now- that its cookbook is gone (D107)."""- text = load_text("opengl_python/contract.md")- blocks = [b for b in re.findall(r"```python\n(.*?)```", text, re.S) if "def setup(" in b and "import moderngl" in b]- assert len(blocks) == 1, "the contract ships exactly one complete example"- ws = _ws_with_plan(tmp_ws)- ws.src.mkdir(parents=True, exist_ok=True)- (ws.src / "program.py").write_text(blocks[0])- rt = OpenGLPythonRuntime(host=host)- assert rt.lint(ws).passed- br = rt.build(ws, **SMALL)- assert br.ok, br.error_message- metrics = json.loads((ws.artifacts / "metrics.json").read_text())- assert len(list((ws.artifacts / "frames").glob("*.png"))) == 5- assert not metrics["stats"]["static"] and not metrics["stats"]["flicker"] and not metrics["stats"]["any_nan"]def test_gl_tools_probe_and_frames(tmp_ws, host, monkeypatch):@@ -204,26 +115,21 @@ def test_gl_tools_probe_and_frames(tmp_ws, host, monkeypatch):obs = get_tool("gl_probe").call(ctx, {"t": 1.5})assert obs.ok and "PROBE OK" in obs.text and len(obs.images) == 1 and obs.numbers["n_frames"] == 1obs = get_tool("gl_frames").call(ctx, {"times": [0.0, 2.0], "width": 256, "height": 144})- assert obs.ok and "FRAMES OK" in obs.text and obs.images and obs.numbers["n_frames"] == 2 and obs.numbers["static"] # the stub is flat by design+ assert obs.ok and "FRAMES OK" in obs.text and obs.images and obs.numbers["n_frames"] == 2 and obs.numbers["static"](ws.src / "shader.frag").write_text("#version 330 core\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n")obs = get_tool("gl_probe").call(ctx, {})assert not obs.ok and "LINT FAILED" in obs.text and "#version" in obs.text-def test_gl_probe_compile_error_report(tmp_ws, host, monkeypatch):- """Pin: the gl_probe failure report names the error type and the agent's- (workspace-relative) file:line, from any cwd, without host paths."""+def test_feedback_and_nan_detection(tmp_ws, host):ws = _ws_with_plan(tmp_ws)- GlslShaderRuntime(host=host).skeleton(ws, PLAN)(ws.src / "shader.frag").write_text(- "// line 1\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"- " float v = twice(nope);\n fragColor = vec4(uv, v, 1.0);\n}\n")- monkeypatch.setattr("codeverse3d.languages.glsl_shader.GlslShaderRuntime.host", lambda self, timeout_s=None: host)- ctx = ToolContext(workspace=ws, language="glsl_shader", track="graphics")- obs = get_tool("gl_probe").call(ctx, {})- assert not obs.ok and obs.numbers["stage"] == "build"- first = obs.text.splitlines()[0]- assert first.startswith("BUILD FAILED: GlslCompileError") and "at src/shader.frag:4" in first- assert "nope" in obs.text and str(ws.root) not in obs.text- assert obs.text.count("nope") == 1 # the compile log is the message — the stderr tail is not repeated- assert obs.numbers["error_type"] == "GlslCompileError" and obs.numbers["error_line"] == 4+ "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"+ " vec3 prev = texture(u_prev, uv).rgb * 0.9;\n float d = smoothstep(0.05, 0.0, length(uv - vec2(0.5 + 0.3*sin(u_time), 0.5)));\n"+ " float bad = uv.x > 0.9 ? sqrt(-1.0) : 0.0;\n fragColor = vec4(max(prev, vec3(d)) + bad, 1.0);\n}\n")+ rt = GlslShaderRuntime(host=host)+ br = rt.build(ws, **SMALL)+ assert br.ok and br.census["feedback"] is True+ metrics = json.loads((ws.artifacts / "metrics.json").read_text())+ assert metrics["stats"]["any_nan"] is True+ assert any(f["data"]["kind"] == "nan" for f in metrics["gate"]["findings"]) and not metrics["gate"]["passed"]diff --git a/harness/tests/graphics/test_live.py b/harness/tests/graphics/test_live.pydeleted file mode 100644index 5aa4b72b..00000000--- a/harness/tests/graphics/test_live.py+++ /dev/null@@ -1,67 +0,0 @@-"""Live (network + Gemini keys): graphics planner → single-shot shader → real GL build → VLM judge."""--from __future__ import annotations--import pytest--from codeverse3d.config import get_settings-from codeverse3d.contracts.common import Backends, Budget, Language, Track-from codeverse3d.contracts.plan import GraphicsPlan-from codeverse3d.contracts.spec import Spec-from codeverse3d.judges.base import JudgeInput-from codeverse3d.judges.vlm_judge import VlmJudge-from codeverse3d.languages.glsl_shader import GlslShaderRuntime-from codeverse3d.tracks.generation import generate_files-from codeverse3d.tracks.graphics import (- GraphicsTrack,- frames_render_set,- graphics_prompt_context,-)-from codeverse3d.workspace import Workspace--pytestmark = pytest.mark.live-MODEL = "gemini:gemini-3.8-flash"--[email protected](scope="module")-def keys_ok():- if not get_settings().gemini_api_keys:- pytest.skip("no Gemini keys")---def test_live_plan_generate_build_judge(tmp_path, keys_ok):- from codeverse3d.models import get_chat_model- from codeverse3d.orchestrator import RunState- from codeverse3d.proc import EventLog- from codeverse3d.prompts import render-- spec = Spec(id="live_gfx", track=Track.GRAPHICS, language=Language.GLSL_SHADER,- prompt="a calm animated aurora borealis over snowy mountains with twinkling stars",- budget=Budget(max_rounds=1), backends=Backends(planner=MODEL, generator=f"single-shot:{MODEL}", judge=MODEL))- ws = Workspace(tmp_path / "live_gfx").create()- model = get_chat_model(MODEL)- from codeverse3d.tracks.planner import plan as run_planner- plan = run_planner(spec, MODEL, GraphicsPlan, ws, model=model)- assert isinstance(plan, GraphicsPlan) and plan.passes and plan.key_visuals and plan.motion- rt = GlslShaderRuntime()- rt.skeleton(ws, plan)- track = GraphicsTrack(runtime=rt)- ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState.load_or_new(ws, resume=False))- ctx.plan = plan- ctx.model = model- task = track.baseline_tasks(ctx)[0]- res = generate_files(ws, model=model, task=task)- assert res.ok and any(c.path.endswith("shader.frag") for c in res.files_changed)- lint = rt.lint(ws)- build = rt.build(ws, width=640, height=360)- assert lint.gate == "lint:glsl_shader"- if not build.ok:- pytest.skip(f"model wrote a shader that does not compile (repair loop not exercised here): {build.error_message[:200]}")- renders = frames_render_set(ws, build, 0)- assert len(renders.views) == 5 and renders.contact_sheet- judge = VlmJudge(rubric="shader", model_id=MODEL, n_samples=1)- j = judge.judge(JudgeInput(spec=spec, renders=renders, gates=[lint], acceptance=plan.acceptance, plan_summary=plan.summary,- round_index=0, extra_context=""))- assert 0.0 <= j.overall <= 1.0 and set(j.scores) >= {"brief_fidelity", "motion_quality"}- assert render("tracks/refine_graphics.j2", **graphics_prompt_context(- ctx, round_index=1, tasks=["x"], targets=["overall"], files=["src/shader.frag"], judge_summary="s", frame_notes="f", current_files={}))diff --git a/harness/tests/graphics/test_prompt_numbers.py b/harness/tests/graphics/test_prompt_numbers.pydeleted file mode 100644index 8c11e00e..00000000--- a/harness/tests/graphics/test_prompt_numbers.py+++ /dev/null@@ -1,22 +0,0 @@-"""The judge numbers ``generate_graphics.j2`` states are the rubric's (the gate thresholds it states are-pinned in ``prompts/_claims.toml``): change ``shader.yaml`` and this fails until the prompt agrees."""--from __future__ import annotations--from codeverse3d.judges.rubrics import load_rubric-from codeverse3d.prompts import load_text---def test_generate_graphics_states_the_rubrics_own_numbers() -> None:- text = load_text("tracks/generate_graphics.j2")- rubric = load_rubric("shader")- caps = {c.id: c.cap for c in rubric.caps}- penalties = {d.id: d.penalty for d in rubric.defects}- depth = next(c for c in rubric.criteria if c.id == "depth_and_detail")- assert f"`static`, cap {caps['static_frames']:g}" in text- assert f"`flicker`, cap {caps['flicker']:g}" in text- assert f"`stretched_aspect`, −{penalties['stretched_aspect']:.2f}" in text- assert f"`flat_fill` defect (−{penalties['flat_fill']:.2f})" in text- assert f"depth_and_detail ({depth.weight:.2f})" in text- # the anchor the prompt names is the one that describes "one field fills the frame"- assert "0.1 anchor" in text and "field" in depth.anchors["0.1"]diff --git a/harness/tests/graphics/test_round_metrics.py b/harness/tests/graphics/test_round_metrics.pyindex 7c444bff..64849709 100644--- a/harness/tests/graphics/test_round_metrics.py+++ b/harness/tests/graphics/test_round_metrics.py@@ -11,7 +11,6 @@ from codeverse3d.workspace import Workspacedef _metrics(ws: Workspace, lum: float) -> None:- ws.artifacts.mkdir(parents=True, exist_ok=True)(ws.artifacts / "metrics.json").write_text(json.dumps({"stats": SequenceStats(mean_lum=lum).model_dump(mode="json"),"gate": GateReport(gate="gl_frames", passed=True).model_dump(mode="json")}))@@ -25,13 +24,3 @@ def test_each_round_keeps_and_quotes_its_own_frame_metrics(tmp_path):frames_render_set(ws, build, i)assert "mean_lum=0.250" in frame_stats_text(ws, 0)assert "mean_lum=0.750" in frame_stats_text(ws, 1) and "mean_lum=0.750" in frame_stats_text(ws)---def test_a_round_recorded_before_the_copy_is_not_quoted_a_later_builds_metrics(tmp_path):- ws = Workspace(tmp_path / "run").create()- _metrics(ws, 0.75) # the last build's (round 1)- (ws.root / "rounds").mkdir()- for i in (0, 1):- (ws.root / "rounds" / f"r{i:02d}.json").write_text("{}")- assert "later build" in frame_stats_text(ws, 0) and "mean_lum" not in frame_stats_text(ws, 0)- assert "mean_lum=0.750" in frame_stats_text(ws, 1)diff --git a/harness/tests/graphics/test_stale_invalidation.py b/harness/tests/graphics/test_stale_invalidation.pyindex 239b2af0..4cba6543 100644--- a/harness/tests/graphics/test_stale_invalidation.py+++ b/harness/tests/graphics/test_stale_invalidation.py@@ -4,12 +4,9 @@ from __future__ import annotationsimport json-import pytest-import codeverse3d.spatial.tools # noqa: F401 — registers the gl_* toolsfrom codeverse3d.languages.glsl_shader import GlslShaderRuntimefrom codeverse3d.spatial.gl_render import GlResult-from codeverse3d.spatial.registry import ToolContext, get_toolfrom codeverse3d.workspace import Workspace@@ -22,41 +19,20 @@ class _FailingHost:def _seed_stale(ws: Workspace) -> None:- for name in ("frames_sheet.png", "preview.gif"):+ for name in ("frames_sheet.png", "preview.gif", "metrics.json", "gl_result.json"):(ws.artifacts / name).write_bytes(b"stale")- (ws.artifacts / "metrics.json").write_text('{"stale": true}')ws.write_json(ws.artifacts / "build.json", {"ok": True})frames = ws.artifacts / "frames"frames.mkdir(exist_ok=True)(frames / "f00_t000.00.png").write_bytes(b"stale frame")- (ws.artifacts / "gl_result.json").write_text("{}")[email protected]("frag, error_type", [- ("void mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(nope); }\n", "GlslCompileError"),- # the MissingEntryFile early return never reaches the host: the hoisted wipe must still clear- (None, "MissingEntryFile"),-])-def test_a_failed_build_invalidates_every_output_of_the_last_one(tmp_ws: Workspace, frag: str | None, error_type: str) -> None:- if frag is not None:- (tmp_ws.src / "shader.frag").write_text(frag)+def test_a_failed_build_invalidates_every_output_of_the_last_one(tmp_ws: Workspace) -> None:+ (tmp_ws.src / "shader.frag").write_text("void mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(nope); }\n")_seed_stale(tmp_ws)br = GlslShaderRuntime(host=_FailingHost()).build(tmp_ws, preview=False)- assert not br.ok and br.error_type == error_type+ assert not br.ok and br.error_type == "GlslCompileError"for name in ("frames_sheet.png", "preview.gif", "metrics.json", "gl_result.json"):assert not (tmp_ws.artifacts / name).exists(), nameassert not list((tmp_ws.artifacts / "frames").glob("*.png"))assert json.loads((tmp_ws.artifacts / "build.json").read_text())["ok"] is False---def test_gl_tool_lint_fail_records_the_failed_build_status(tmp_ws: Workspace) -> None:- """A lint refusal in the gl tools is the LATEST build status — the previous- round's build.json (ok: true) must not stay readable as current."""- (tmp_ws.src / "shader.frag").write_text(- "#version 330 core\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n")- tmp_ws.write_json(tmp_ws.artifacts / "build.json", {"ok": True})- ctx = ToolContext(workspace=tmp_ws, language="glsl_shader", track="graphics")- obs = get_tool("gl_probe").call(ctx, {})- assert not obs.ok and "LINT FAILED" in obs.text- last = json.loads((tmp_ws.artifacts / "build.json").read_text())- assert last["ok"] is False and last["error_type"] == "LintError"diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.pyindex 9fcf7d13..dadaa0eb 100644--- a/harness/tests/graphics/test_track.py+++ b/harness/tests/graphics/test_track.py@@ -1,47 +1,27 @@-"""Offline: the graphics track with fakes (no GL, no network) — judge replay and planner."""+"""Offline: the graphics track with fakes (no GL, no network) — judge replay."""from __future__ import annotations-from pathlib import Pathfrom typing import Anyimport numpy as np-import pytestfrom PIL import Imagefrom codeverse3d.config import Settingsfrom codeverse3d.contracts.artifacts import BuildResultfrom codeverse3d.contracts.common import Backends, Budget, Language, Track-from codeverse3d.contracts.plan import GraphicsPlan-from codeverse3d.contracts.spec import Constraints, Spec+from codeverse3d.contracts.spec import Specfrom codeverse3d.languages._gl_common import finish_build, judge_timesfrom codeverse3d.languages.glsl_shader import GlslShaderRuntimefrom codeverse3d.spatial.gl_render import GlFrame, GlResult, gif_timesfrom codeverse3d.tracks import plannerfrom codeverse3d.tracks.graphics import GraphicsTrack-from codeverse3d.tracks.planner import PlanningError, ensure_acceptancefrom codeverse3d.workspace import Workspacefrom tests.orchestrator_tracks.fakes import FakeAgent, FakeChatModel, FakeJudge, FakeServices-def make_spec(*, max_rounds: int = 3) -> Spec:- return Spec(id="g1", track=Track.GRAPHICS, language=Language.GLSL_SHADER, prompt="animated neon rain on a window with bokeh city lights",- constraints=Constraints(must_have=["bokeh lights"]),- budget=Budget(max_rounds=max_rounds, max_minutes=10, max_repair_attempts=2),- backends=Backends(planner="fake:planner", generator="fake:fake-model", judge="fake:judge"))---def _frame(path: Path, t: float) -> None:- x = np.linspace(0, 1, 64, dtype=np.float32)[None, :].repeat(36, 0)- shift = 0.3 * t- rgb = np.stack([0.5 + 0.5 * np.sin(6 * (x + shift)), x * 0.5 + 0.2, 0.6 - 0.4 * x], -1)- path.parent.mkdir(parents=True, exist_ok=True)- Image.fromarray((rgb * 255).astype(np.uint8), "RGB").save(path)--class FakeGlRuntime(GlslShaderRuntime):- """glsl_shader runtime without GL: writes synthetic frames through the real ``finish_build``- (the real runtime's layout, skeleton and lint)."""+ """glsl_shader runtime without GL: synthetic frames through the real ``finish_build``."""entry_globs = ("src/shader.frag", "src/common.glsl")@@ -49,74 +29,35 @@ class FakeGlRuntime(GlslShaderRuntime):frames = []for i, t in enumerate(judge_times(8.0) + gif_times(8.0, 4)):p = ws.artifacts / "frames" / f"f{i:02d}_t{t:06.2f}.png"- _frame(p, t)+ p.parent.mkdir(parents=True, exist_ok=True)+ x = np.linspace(0, 1, 64, dtype=np.float32)[None, :].repeat(36, 0)+ rgb = np.stack([0.5 + 0.5 * np.sin(6 * (x + 0.3 * t)), x * 0.5 + 0.2, 0.6 - 0.4 * x], -1)+ Image.fromarray((rgb * 255).astype(np.uint8), "RGB").save(p)frames.append(GlFrame(index=i, time=t, path=str(p), judge=i < 5))res = GlResult(ok=True, mode="shader", stage="render", renderer="fake-gl", frames=frames)return finish_build(ws, res, language="glsl_shader", census={"convention": "mainImage"})def _writer(job, ws):- body = "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"- body += f" // {job.label} r{job.round}\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}}\n"- return {"src/shader.frag": body}---def settings(tmp_path) -> Settings:- return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")---def _services(**kw):- return FakeServices(runtime_factory=lambda lang: FakeGlRuntime(), **kw)+ return {"src/shader.frag": "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n"+ f" // {job.label} r{job.round}\n fragColor = vec4(fragCoord / u_resolution.xy, 0.5, 1.0);\n}}\n"}-def plan_example() -> dict[str, Any]:- return planner.plan_example(Track.GRAPHICS)---def _plan(spec, ws, model, budget=None):- """The planner as the live path calls it (graphics dispatch happens on ``spec.track``)."""- return planner.plan(spec, "fake:planner", GraphicsPlan, ws, model=model, budget=budget)---def test_a_replayed_round_reads_the_payload_the_in_run_judge_read(tmp_path, settings):+def test_a_replayed_round_reads_the_payload_the_in_run_judge_read(tmp_path):"""``3dcode judge`` / calibration rebuild the payload the in-run judge read (``judges.base.round_input``)."""from codeverse3d.cli._judge import build_judge_inputfrom codeverse3d.record.record import load_record+ spec = Spec(id="g1", track=Track.GRAPHICS, language=Language.GLSL_SHADER, prompt="animated neon rain on a window",+ budget=Budget(max_rounds=1, max_minutes=10, max_repair_attempts=2),+ backends=Backends(planner="fake:planner", generator="fake:fake-model", judge="fake:judge"))ws = Workspace(tmp_path / "runs" / "replay")judge = FakeJudge(scores=(0.55, 0.72), targets=("SurfaceRipples",))- track = GraphicsTrack(services=_services(), judge=judge, agent=FakeAgent(_writer),- planner_model=FakeChatModel(lambda req: plan_example()), settings=settings, runtime=FakeGlRuntime())- rec = track.run(make_spec(max_rounds=1), ws)+ track = GraphicsTrack(services=FakeServices(runtime_factory=lambda lang: FakeGlRuntime()), judge=judge, agent=FakeAgent(_writer),+ planner_model=FakeChatModel(lambda req: planner.plan_example(Track.GRAPHICS)),+ settings=Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache"), runtime=FakeGlRuntime())+ rec = track.run(spec, ws)replay = build_judge_input(ws, load_record(ws), rec.rounds[-1])for field in ("plan_summary", "extra_context", "acceptance", "round_index"):assert getattr(replay, field) == getattr(judge.calls[-1], field), field- assert "Passes: PoolFloor (fullscreen)" in replay.plan_summary and "Motion: new drops land" in replay.plan_summary---def test_planner_reask_and_acceptance(tmp_ws):- spec = make_spec()- attempts = {"n": 0}-- def responder(req):- attempts["n"] += 1- if attempts["n"] == 1:- return {"title": "x", "summary": "y", "style": "z", "passes": []} # invalid: passes min_length=1- return plan_example()-- model = FakeChatModel(responder)- plan = _plan(spec, tmp_ws, model)- assert attempts["n"] == 2 and plan.title == "Tide pool ripples" and tmp_ws.plan_path.is_file()- assert "Fix EXACTLY these problems" in model.requests[1].messages[-1].text- ids = [a.id for a in plan.acceptance]- assert "must1" in ids and "a3" in ids # spec must_have appended, motion item already present in the example- # a plan without a motion acceptance item gets one; no 'ground contact' ever- p2 = ensure_acceptance(GraphicsPlan.model_validate({**plan_example(), "acceptance": []}), spec)- assert any(a.id.startswith("motion") for a in p2.acceptance) and not any("ground" in a.text.lower() for a in p2.acceptance)- always_bad = FakeChatModel(lambda req: {"title": "x"})- with pytest.raises(PlanningError):- _plan(spec, tmp_ws, always_bad)- sys_prompt = planner.build_system_prompt(spec, GraphicsPlan)- assert "ART-DIRECTOR" in sys_prompt and "TidePoolRipples" in sys_prompt- assert model.requests[0].temperature == 0.5 and model.requests[0].max_output_tokens == planner.PLAN_TOKENS_MAX+ assert "Passes: PoolFloor (fullscreen)" in replay.plan_summarydiff --git a/harness/tests/graphics/test_wrap_lint.py b/harness/tests/graphics/test_wrap_lint.pyindex 0f231c40..f55f4707 100644--- a/harness/tests/graphics/test_wrap_lint.py+++ b/harness/tests/graphics/test_wrap_lint.py@@ -2,62 +2,26 @@from __future__ import annotations-import pytest-from codeverse3d.contracts.artifacts import Severityfrom codeverse3d.languages.glsl_shader import (HEADER,compose,- detect_convention,first_error,lint_text,- lint_workspace,parse_glsl_log,- strip_comments,)from codeverse3d.languages.opengl_python import lint_source-from codeverse3d.languages.opengl_python import lint_workspace as lint_program_wsSHADER = "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n fragColor = vec4(uv, 0.5 + 0.5*sin(u_time), 1.0);\n}\n"COMMON = "float hash(float n) { return fract(sin(n) * 43758.5453); }\n"-def test_plain_main_convention_has_no_trailer_and_comments_ignored():- src = "// mainImage is mentioned here only in a comment; u_prev too\nvoid main() { fragColor = vec4(1.0); }\n"- c = compose(src)- assert c.convention == "main" and not c.uses_feedback- assert "mainImage(fragColor" not in c.source- assert detect_convention("void mainImage(out vec4 c, in vec2 f) {}") == "mainImage"- assert compose("void mainImage(out vec4 c, in vec2 f) { c = texture(u_prev, f); }").uses_feedback--[email protected](("tail", "convention"), [- ("void main() {\n mainImage(fragColor, gl_FragCoord.xy);\n}\n", "main"),- ("#ifdef STANDALONE\nvoid main() {\n mainImage(fragColor, gl_FragCoord.xy);\n}\n#endif\n", "mainImage"),-])-def test_an_authored_main_that_calls_main_image_gets_no_second_main(tail, convention):- """A Shadertoy port often keeps its own main() calling mainImage(); appending the trailer redefined- main (4/4 gpt-6-luna one-shot shaders, 2026-09-23). The author's main() wins, and it compiles —- unless it hides behind an #ifdef the harness never defines: then the trailer is the entry point."""- c = compose(SHADER + tail)- assert c.convention == convention # and it links: exactly one main() survives the preprocessor- import moderngl-- ctx = moderngl.create_standalone_context()- try:- ctx.program(vertex_shader="#version 330 core\nin vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }",- fragment_shader=c.source)- finally:- ctx.release()--def test_parse_glsl_log_dialects_map_to_files():c = compose(SHADER, COMMON)off = HEADER.count("\n") + 1 # common.glsl starts here (1 line) → shader.frag starts at off+1mesa = f"0:{off + 2}(12): error: `foo' undeclared\n0:{off}(3): warning: unused\n"nvidia = f"0({off + 2}) : error C1008: undefined variable \"foo\"\n"- angle = f"ERROR: 0:{off + 2}: 'foo' : undeclared identifier\n"- for log in (mesa, nvidia, angle):+ for log in (mesa, nvidia):msgs = parse_glsl_log(log, c.line_map)err = first_error(msgs)assert err is not None and err.file == "src/shader.frag" and err.file_line == 2, log@@ -75,36 +39,12 @@ def test_glsl_lint_rules():kinds = {f.data["kind"] for f in lint_text(bad) if f.severity == Severity.ERROR}assert {"version_line", "redeclared_uniform", "custom_uniform", "redeclared_output", "missing_input", "undeclared_sampler","float_modulo", "legacy_glsl"} <= kinds- # the comment on line 1 must not trigger anything; the #version is reported on line 2- ver = next(f for f in lint_text(bad) if f.data["kind"] == "version_line")- assert ver.data["line"] == 2+ assert next(f for f in lint_text(bad) if f.data["kind"] == "version_line").data["line"] == 2 # the comment on line 1 is ignoredassert not [f for f in lint_text(SHADER, COMMON) if f.severity == Severity.ERROR]- # common.glsl must not carry an entry point; no entry at all is an error- assert any(f.data["kind"] == "entry_in_common" for f in lint_text(SHADER, "void main(){}"))assert any(f.data["kind"] == "no_entry" for f in lint_text("vec3 f() { return vec3(0); }"))assert any(f.data["kind"] == "buffer_self_ref" for f in lint_text(SHADER, None, SHADER.replace("u_resolution", "u_buffer_a") + "\n"))-def test_mixed_comments_blank_only_the_comments():- """A `/*` inside a `//` comment opens nothing (the old two-pass stripper blanked real code)."""- src = ("// tweak /* the fog here\nfloat fogAmt(float d) { return d; }\nuniform float u_extra;\n// end */\n"- "/* a // inside a block */ float x() { return 1.0; }\n")- stripped = strip_comments(src)- assert stripped.count("\n") == src.count("\n") and "uniform float u_extra;" in stripped- assert "tweak" not in stripped and "inside" not in stripped- shader = src + SHADER- assert any(f.data["kind"] == "custom_uniform" for f in lint_text(shader))---def test_glsl_lint_workspace_missing_and_stray(tmp_ws):- rep = lint_workspace(tmp_ws)- assert not rep.passed and rep.findings[0].data["kind"] == "missing_entry"- (tmp_ws.src / "shader.frag").write_text(SHADER)- (tmp_ws.src / "extra.frag").write_text("// stray")- rep = lint_workspace(tmp_ws)- assert rep.passed and any(f.data["kind"] == "stray_file" for f in rep.findings)--PROGRAM_OK = """import mathimport modernglimport numpy as np@@ -126,13 +66,4 @@ def test_program_lint_rules():kinds = {f.data["kind"] for f in lint_source(bad)}assert {"window_lib", "forbidden_import", "own_context", "forbidden_call", "wall_clock", "bad_signature", "glsl_version","legacy_glsl", "unseeded_random"} <= kinds- assert any(f.data["kind"] == "syntax" for f in lint_source("def setup(:\n"))assert any(f.data["kind"] == "missing_entry" for f in lint_source("import moderngl\n"))---def test_program_lint_workspace(tmp_ws):- assert not lint_program_ws(tmp_ws).passed- (tmp_ws.src / "program.py").write_text(PROGRAM_OK)- (tmp_ws.src / "helpers.py").write_text("x = 1\n")- rep = lint_program_ws(tmp_ws)- assert rep.passed and any(f.data["kind"] == "stray_file" for f in rep.findings)diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.pyindex 9faf1c1a..aa5467da 100644--- a/harness/tests/install/test_docs.py+++ b/harness/tests/install/test_docs.py@@ -2,9 +2,7 @@from __future__ import annotations-import osimport re-import subprocessimport tomllibfrom pathlib import Pathfrom types import SimpleNamespace@@ -219,7 +217,7 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:from codeverse3d.proc import ProcResultsettings = SimpleNamespace(- gemini_api_keys=("fake",), anthropic_api_key="", openai_api_key="", skills=False,+ gemini_api_keys=("fake",), anthropic_api_key="", openai_api_key="",rate=SimpleNamespace(max_in_flight=1),binaries=SimpleNamespace(node="node", gemini_cli="gemini", claude_cli="claude",codex_cli="codex", agy_cli="agy"),@@ -240,9 +238,8 @@ def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:from codeverse3d.models.health import Healthmonkeypatch.setattr("codeverse3d.models.health.probe", lambda **kw: Health(model="gemini:m", n_ok=1, n_tried=1))- monkeypatch.setattr("codeverse3d.skills.registry.ROUTED_SKILLS", ("missing",))- rows = doctor_mod.run_doctor(live=True, gpu=True, skills=True)+ rows = doctor_mod.run_doctor(live=True, gpu=True)def no_runtime() -> Path:raise RuntimeError("runtime_js unavailable")@@ -318,45 +315,5 @@ def test_architecture_stage_graph_is_drawn_from_the_declarations():+ stage_graph())-def test_setup_verifies_the_interpreter_it_installed_into(tmp_path) -> None:- """The closing doctor uses ``--python``, not an unrelated executable on PATH."""- import sys-- fake = tmp_path / "bin"- fake.mkdir()- impostor = fake / "3dcodeverse"- impostor.write_text("#!/bin/sh\necho WRONG_INSTALL_ON_PATH\n")- impostor.chmod(0o755)- # the --python interpreter answers the doctor call itself (the real doctor is ~10 s of probes)- py = tmp_path / "python-shim"- py.write_text('#!/bin/sh\n[ "$1 $2" = "-m codeverse3d.cli.main" ] && { echo "DOCTOR_VIA_PYTHON $3"; exit 0; }\n'- f'exec {sys.executable} "$@"\n')- py.chmod(0o755)-- env = dict(os.environ, PATH=f"{fake}{os.pathsep}{os.environ['PATH']}")- proc = subprocess.run(- ["bash", str(SETUP), "--python", str(py), "--no-node", "--no-chrome", "--no-gpu", "--no-python", "--no-clis"],- capture_output=True, text=True, timeout=300, env=env)- assert "WRONG_INSTALL_ON_PATH" not in proc.stdout + proc.stderr, (- "setup.sh verified the 3dcodeverse first on PATH instead of the --python interpreter")- assert "DOCTOR_VIA_PYTHON doctor" in proc.stdout, proc.stdout + proc.stderr---def test_setup_names_the_remedy_when_the_interpreter_has_no_pip(tmp_path) -> None:- """A Python without pip fails with an actionable distro/venv remedy."""- import sys-- # a stand-in that answers the version probes but refuses `-m pip`, like a distro python3- nopip = tmp_path / "python-nopip"- nopip.write_text(- "#!/bin/sh\n"- 'for a in "$@"; do [ "$a" = "pip" ] && { echo "$0: No module named pip" >&2; exit 1; }; done\n'- f'exec {sys.executable} "$@"\n')- nopip.chmod(0o755)-- proc = subprocess.run(["bash", str(SETUP), "--python", str(nopip), "--no-node", "--no-chrome", "--no-clis", "--no-doctor"],- capture_output=True, text=True, timeout=300)- out = proc.stdout + proc.stderr- assert proc.returncode != 0, "a python that cannot pip must not look like a successful install"- assert "has no pip" in out, f"the bare ModuleNotFoundError is not an explanation:\n{out}"- assert "-m venv" in out and "python3-venv" in out, f"no actionable remedy in:\n{out}"++diff --git a/harness/tests/install/test_hermetic.py b/harness/tests/install/test_hermetic.pyindex bd2f2a5a..08961448 100644--- a/harness/tests/install/test_hermetic.py+++ b/harness/tests/install/test_hermetic.py@@ -1,21 +1,16 @@-"""Hermetic-suite and documented test-count guards."""+"""Hermetic-suite guard: credential-sensitive offline tests pass without API keys."""from __future__ import annotationsimport os-import reimport subprocessimport sysfrom pathlib import Path-import pytest--from tests.conftest import COLLECTED-HARNESS = Path(__file__).resolve().parents[2]KEY_ENVS = ("GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GENAI_API_KEY")-#: the one that PORT-2 caught (its texture-pass twin went with the texture pass); inside the offline (pure python) subset+#: the one that PORT-2 caught; inside the offline (pure python) subsetCREDENTIAL_FREE = ("tests/models/test_health.py::test_probe_model_treats_a_503_as_final",)@@ -30,32 +25,3 @@ def test_passes_with_no_api_keys_in_the_environment(tmp_path: Path) -> None:cwd=HARNESS, env=env, capture_output=True, text=True, timeout=300)assert r.returncode == 0, f"needs credentials:\n{r.stdout[-3000:]}\n{r.stderr[-2000:]}"---# --------------------------------------------------------------------------- PORT-8-INSTALL = HARNESS / "docs" / "INSTALL.md"-#: numbers the docs quote as test counts: "N passed", "N selected", "out of the N"-_COUNT = re.compile(r"(\d{3,6})\s+(?:passed|selected)|out of the (\d{3,6})")---#: below this, the run was narrowed (one file, -k, a single directory) and cannot bound-#: the suite. The full offline suite is ~1 900.-_FULL_RUN_FLOOR = 1000---def _collected() -> int:- """Return the collection ceiling, or skip when invoked on a narrow subset."""- n = COLLECTED.get("n", 0)- if n < _FULL_RUN_FLOOR:- pytest.skip(f"only {n} tests collected — a narrowed run cannot bound the suite")- return n---def test_quoted_test_counts_are_possible() -> None:- """Published counts cannot exceed what this suite can collect."""- ceiling = _collected()- quoted = [int(a or b) for a, b in _COUNT.findall(INSTALL.read_text())]-- assert quoted, f"no test counts found in {INSTALL} — did the wording change?"- too_big = [n for n in quoted if n > ceiling]- assert not too_big, f"{INSTALL.name} quotes {too_big}, but only {ceiling} tests exist"diff --git a/harness/tests/install/test_import_direction.py b/harness/tests/install/test_import_direction.pyindex b29d61a2..8144cf6e 100644--- a/harness/tests/install/test_import_direction.py+++ b/harness/tests/install/test_import_direction.py@@ -9,17 +9,16 @@ import pytestROOT = Path(__file__).resolve().parents[2] / "codeverse3d"+_UP = ("tracks", "addons", "cli", "orchestrator", "agents", "skills", "spatial", "languages", "reference",+ "judges", "models", "cost", "config")+#: leaf → the codeverse3d packages it must NOT importFORBIDDEN: dict[str, tuple[str, ...]] = {- "judges": ("tracks", "addons", "cli", "orchestrator", "agents", "skills", "texturing"),- "workspace.py": ("tracks", "addons", "cli", "orchestrator", "agents", "skills", "texturing",- "spatial", "languages", "reference", "judges", "models", "cost", "config"),- "contracts": ("tracks", "addons", "cli", "orchestrator", "agents", "workspace", "skills", "texturing",- "spatial", "languages", "reference", "judges", "models", "cost", "config", "proc"),- "proc.py": ("tracks", "addons", "cli", "orchestrator", "agents", "workspace", "skills", "texturing",- "spatial", "languages", "reference", "judges", "models", "cost", "config", "contracts"),- "conventions.py": ("tracks", "addons", "cli", "orchestrator", "agents", "workspace", "skills",- "texturing", "spatial", "languages", "reference", "judges", "models", "cost", "config"),+ "judges": ("tracks", "addons", "cli", "orchestrator", "agents", "skills"),+ "workspace.py": _UP,+ "contracts": (*_UP, "workspace", "proc"),+ "proc.py": (*_UP, "workspace", "contracts"),+ "conventions.py": (*_UP, "workspace"),}diff --git a/harness/tests/judges/test_calibration.py b/harness/tests/judges/test_calibration.pyindex 3f8ac808..3c00d949 100644--- a/harness/tests/judges/test_calibration.py+++ b/harness/tests/judges/test_calibration.py@@ -3,7 +3,7 @@ from pathlib import Pathimport pytest-from codeverse3d.addons.calibration import calibrate, load_run_cases+from codeverse3d.addons.calibration import calibratefrom codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severityfrom codeverse3d.contracts.run import RoundRecordfrom codeverse3d.judges.rubrics import load_rubric@@ -41,29 +41,6 @@ def _fake_run(root: Path, name: str) -> Path:return run-def test_load_cases_reads_the_plan_and_picks_the_fallback_round(tmp_path, caplog):- """No usable record.json: the plan comes from plan.json, typed, and its digest is the- in-run one — a Z-up object's size in the measurement frame (W×H×D). No picked round: the- stand-in is ``select.fallback_round`` (the latest built round with renders), as in every other- reader — even when an earlier round kept a GLB and it did not; its skipped geometry montage says so."""- from codeverse3d.addons.calibration import render_geometry_views-- run = _fake_run(tmp_path, "runA")- cases = load_run_cases(run)- assert [c.round_index for c in cases] == [0, 1] and cases[0].gate_errors == 1 and cases[1].gate_errors == 0- assert cases[0].rubric == "static_object" and len(cases[0].inp.acceptance) == 2- assert cases[1].is_picked and not cases[0].is_picked and cases[0].glb is None # no usable record: the last round- assert cases[0].inp.plan_summary == "Chair: a chair. Overall 0.50×0.90×0.50 m (W×H×D). Parts: Seat, Leg×4."- assert load_run_cases(run, rounds=[1])[0].round_index == 1-- (run / "artifacts" / "r00").mkdir(parents=True)- (run / "artifacts" / "r00" / "object.glb").write_bytes(b"glTF")- cases = load_run_cases(run)- assert cases[1].is_picked and not cases[0].is_picked and cases[0].glb.endswith("r00/object.glb")- assert render_geometry_views(cases[1], tmp_path / "out", "clay") is None- assert "kept no GLB" in caplog.text--def test_calibrate_offline(tmp_path):runs = [_fake_run(tmp_path, "runA"), _fake_run(tmp_path, "runB")]ids = ["A1", "A2"]@@ -82,10 +59,6 @@ def test_calibrate_offline(tmp_path):assert table.pearson_errors_vs_score == -1.0 and table.spearman_errors_vs_score == -1.0assert table.pearson_stored_vs_new is None # fake rounds carry no stored judgmentassert len(model.requests) == 8 and table.total_cost_usd == pytest.approx(0.008)- md = (tmp_path / "out" / "calibration_fake_fake-1.md").read_text()- assert "| runA | r00 | baseline | 1/1 |" in md and "pearson(gate errors, new score) = -1.000" in md- data = json.loads((tmp_path / "out" / "calibration_fake_fake-1.json").read_text())- assert data["rows"][0]["per_criterion_std"]empty = tmp_path / "empty"(empty / "rounds").mkdir(parents=True)(empty / "spec.json").write_text(make_spec(id="empty").model_dump_json())@@ -93,53 +66,6 @@ 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-- # compare_backends: <battery>/cells/<prompt>/<arm>/run- a = _run_label(Path("/bench/out/compare_v1/cells/chair/harness-gemini/run"))- b = _run_label(Path("/bench/out/compare_v1/cells/table/harness-gemini/run"))- # ab_plan: <out>/<arm>/cells/<item>/<slug>/run- c = _run_label(Path("/bench/out/ab/control/cells/chair/g37/run"))- d = _run_label(Path("/bench/out/ab/treatment/cells/chair/g37/run"))- e = _run_label(Path("/bench/out/ab/control/cells/table/g37/run"))- assert len({a, b, c, d, e}) == 5, (a, b, c, d, e)- # a plain harness run keeps its slug as the whole label- assert _run_label(Path("/home/u/proj/runs/chair_bl")) == "chair_bl"--def test_calibration_judges_what_the_in_run_judge_saw(tmp_path, monkeypatch):"""It rebuilt a thinner JudgeInput than `3dcode judge` (no previous verdict, trackcontext, stored clay views or GLB for the D48 slices), re-rendered clay views a rounddiff --git a/harness/tests/judges/test_caps.py b/harness/tests/judges/test_caps.pyindex 5168b464..24c91323 100644--- a/harness/tests/judges/test_caps.py+++ b/harness/tests/judges/test_caps.py@@ -35,43 +35,26 @@ E, W = Severity.ERROR, Severity.WARN@pytest.mark.parametrize(("rubric", "gates", "kw", "overall", "rules"), [(R, [_gate("build:blender", E, "Traceback ... NameError")], {}, 0.0, {"build_error"}),(R, [_gate("connectivity", E, "part Leg1 is 3cm above others", kind="floating")], {}, 0.6, {"floating_part"}),- (R, [_gate("connectivity", E, "Leg1 has no_contact with any part")], {}, 0.6, {"floating_part"}),(R, [_gate("connectivity", W, "floating sliver")], {}, 0.9, set()),- (R, [_gate("connectivity", E, "penetration Seat/Leg 12mm"), _gate("connectivity", E, "Arm floating", kind="floating")],- {}, 0.6, {"floating_part", "penetration_error"}),(R, [_gate("connectivity", E, "'Leg' and 'Seat' interpenetrate by ≈15 mm", target="Leg")], {}, 0.7, {"penetration_error"}),# N50: a typed finding caps by its kind — neither the part's name ("island") nor its message fires floating_part- (R, [_gate("connectivity", E, "'kitchen_island' and 'stool_leg' interpenetrate", target="kitchen_island",- kind="penetration")], {}, 0.7, {"penetration_error"}),- (A, [_gate("connectivity", E, "'Leg' and 'Seat' interpenetrate by ≈15 mm", target="Leg")], {"views": POSE}, 0.7,- {"penetration_error"}),(A, [_gate("joint_sweep", E, "link 'DrawerKnob' touches nothing connected to the root at pose rest ""(nearest 'Carcass' at 56.4 mm)", target="DrawerKnob")],{"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"}),# scene: 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")],{}, 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()),])def test_gate_caps(rubric, gates, kw, overall, rules):res = apply_caps(rubric, 0.9, gates, {}, [], **kw)@@ -80,20 +63,6 @@ def test_gate_caps(rubric, gates, kw, overall, rules):assert applied == rules if rules == set() else rules <= applied-def test_scene_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(@@ -105,13 +74,12 @@ CONTRACT_ERR = GateReport(gate="contract", passed=False, findings=[GateFinding((R, "interpenetration", [PASSED], True),(R, "floating_part", [_connectivity(False, ("error", "part 'Seat' is floating 12 mm above 'Leg'"))], False),(R, "interpenetration", [_connectivity(False, ("error", "'Leg' and 'Seat' interpenetrate by ≈15 mm"))], False),- (R, "floating_part", [], False), # a gate that did not run measured nothing(R, "wrong_object", [_connectivity(True)], False), # no gate measures 'wrong object'# 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),# 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."""@@ -130,57 +98,29 @@ def _placement(passed: bool, *findings: tuple[Severity, str, str, dict]) -> Gate@pytest.mark.parametrize(("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_veto_is_scoped_to_the_rules_kinds(defect, gates, absent):assert measured_absent(S, defect, gates) is absent-def test_scene_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}diff --git a/harness/tests/judges/test_defects.py b/harness/tests/judges/test_defects.pyindex 44f14751..e8c24f02 100644--- a/harness/tests/judges/test_defects.py+++ b/harness/tests/judges/test_defects.py@@ -7,13 +7,10 @@ import pytestfrom codeverse3d.contracts.artifacts import RenderSet, RenderViewfrom codeverse3d.judges.rubrics import (JudgeParseError,- RubricError,aggregate_samples,apply_caps,load_rubric,parse_judge_output,- rubric_from_dict,- wire_schema,)from codeverse3d.judges.vlm_judge import VlmJudgefrom tests.judges.conftest import FakeChatModel, good_reply@@ -30,29 +27,11 @@ def _reply(score=0.9, defects=None):def test_rubrics_declare_defects_with_costs():- for name in ("static_object", "articulated", "scene", "asset", "reference"):- r = load_rubric(name)- assert r.defects, name- assert all(d.penalty > 0 or d.cap is not None for d in r.defects)assert R.defect("floating_part").penalty == 0.10 and R.defect("floating_part").cap == 0.60assert R.defect("wrong_object").penalty == 0.0- assert {"no_articulation_visible", "wrong_motion_type", "pivot_misplaced", "pose_clips_body"} <= {d.id for d in A.defects}- with pytest.raises(KeyError):- R.defect("nope")-def test_duplicate_defect_ids_rejected():- bad = {"name": "x", "pass_threshold": 0.7, "criteria": [- {"id": "a", "weight": 1.0, "description": "d", "anchors": {"1.0": "", "0.7": "", "0.4": "", "0.1": ""}}],- "defects": [{"id": "f", "text": "t"}, {"id": "f", "text": "t2"}]}- with pytest.raises(RubricError):- rubric_from_dict(bad)---def test_wire_schema_has_fixed_defect_keys_and_parse_variants():- schema = wire_schema(R, IDS)- props = schema["$defs"]["Defects"]["properties"]- assert set(props) == {d.id for d in R.defects}+def test_defect_parse_variants():out = parse_judge_output(_reply(defects=["floating_part"]), R, IDS)assert out.defects["floating_part"] is True and out.defects["primitive_only"] is Falseassert out.defect_evidence["floating_part"] == "MONTAGE 1 top-left"@@ -102,27 +81,6 @@ def test_defect_vote_ties_are_absent(judge_input, cache_dir, caplog):assert raw["tie_broken"] == ["render_artifacts"]assert raw["scoring_version"] == 4 and raw["overridden"] == [] # 4: the kind-scoped veto (scene, 2026-10-14)- clean_first = FakeChatModel(by_label={":s0": [_reply(0.9)], ":s1": [_reply(0.9, ["render_artifacts"])]})- j2 = VlmJudge("static_object", chat_model=clean_first, n_samples=2, cache_dir=cache_dir).judge(judge_input)- raw2 = json.loads(j2.raw)- assert raw2["defect_votes"]["render_artifacts"] == [False, True]- assert raw2["defects"]["render_artifacts"] is False and j2.overall == pytest.approx(0.9)- assert raw2["tie_broken"] == ["render_artifacts"]---def test_acceptance_vote_ties_follow_the_representative_sample(judge_input, cache_dir):- """D36: an acceptance tie follows the representative sample."""- a_ok, a_no = _reply(0.9), _reply(0.9)- a_no["acceptance"]["A1"]["verified"] = False- j = VlmJudge("static_object", chat_model=FakeChatModel(by_label={":s0": [a_ok], ":s1": [a_no]}),- n_samples=2, cache_dir=cache_dir).judge(judge_input)- assert j.acceptance_results["A1"] is True and json.loads(j.raw)["tie_broken"] == ["A1"]- b_ok, b_no = _reply(0.9), _reply(0.9)- b_no["acceptance"]["A1"]["verified"] = False- j2 = VlmJudge("static_object", chat_model=FakeChatModel(by_label={":s0": [b_no], ":s1": [b_ok]}),- n_samples=2, cache_dir=cache_dir).judge(judge_input)- assert j2.acceptance_results["A1"] is False and json.loads(j2.raw)["tie_broken"] == ["A1"]-def test_missing_views_cap_for_articulated():rest = [RenderView(name=n, path="x") for n in ("front_right_high", "top")]diff --git a/harness/tests/judges/test_detail_anchors.py b/harness/tests/judges/test_detail_anchors.pydeleted file mode 100644index 8069c772..00000000--- a/harness/tests/judges/test_detail_anchors.py+++ /dev/null@@ -1,52 +0,0 @@-"""Guard rail (eval/docs/COMPLEXITY.md): the geometry-detail anchors stay countable and caps stay put."""--from __future__ import annotations--import pytest--from codeverse3d.contracts.plan import AcceptanceItem-from codeverse3d.judges.rubrics import _rule_hit, load_rubric---def test_detail_anchors_are_a_graded_countable_geometry_ladder() -> None:- """reference only: the other rubrics' system prompts are pinned by tests/prompts/manifest.json."""- r = load_rubric("reference")- c = r.criterion("detail")- levels = sorted((float(k) for k in c.anchors), reverse=True)- assert len(levels) >= 5 and levels[0] == 1.0 and levels[-1] == 0.1, levels- top = c.anchors["1.0"].lower()- assert any(w in top for w in ("five or more", "nearly every")), top- assert any(w in top for w in ("kind", "detail")), top- text = (c.description + " " + r.extra_instructions).lower()- assert "colour" in text and ("not" in text or "never" in text), "colour is not geometry"---def test_physical_plausibility_caps_are_untouched() -> None:- """The complexity wave may sharpen detail; it may never soften the gates."""- caps = {c.id: c for c in load_rubric("static_object").caps}- assert caps["build_error"].cap == 0.0- assert caps["floating_part"].cap == 0.6- assert caps["penetration_error"].cap == 0.7- assert caps["contract_violation"].cap == 0.75- assert caps["missing_must_acceptance"].cap == 0.6- defects = {d.id: d for d in load_rubric("static_object").defects}- assert defects["floating_part"].cap == 0.6 and defects["interpenetration"].cap == 0.7- assert defects["wrong_object"].cap == 0.25--[email protected]("rubric", ["static_object", "articulated", "scene"])-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")- assert rule.when == "acceptance" and rule.cap == 0.6 and rule.graded is True- items = [AcceptanceItem(id=f"M{i}", text=f"must {i}", priority="must") for i in range(10)]-- def cap_at(verified: int) -> float:- results = {a.id: i < verified for i, a in enumerate(items)}- hit = _rule_hit(rule, [], results, items, [], [])- assert hit is not None- return hit.cap-- assert cap_at(0) == pytest.approx(0.6)- assert cap_at(9) == pytest.approx(0.96)- assert _rule_hit(rule, [], {a.id: True for a in items}, items, [], []) is Nonediff --git a/harness/tests/judges/test_judge_slices.py b/harness/tests/judges/test_judge_slices.pyindex fe85a02e..27fd4483 100644--- a/harness/tests/judges/test_judge_slices.py+++ b/harness/tests/judges/test_judge_slices.py@@ -6,26 +6,20 @@ from pathlib import Pathimport trimesh-from codeverse3d.config import Settings, get_settingsfrom codeverse3d.contracts.artifacts import (- BuildResult,GateFinding,GateReport,RenderSet,Severity,)from codeverse3d.contracts.chat import ImagePart, TextPart-from codeverse3d.contracts.run import RoundRecord, RunRecordfrom codeverse3d.judges.base import JudgeInputfrom codeverse3d.judges.prompt_builder import (PROVENANCE_ELICITATION,build_judge_messages,- connectivity_error_pairs,- judge_prompt_hash,)from codeverse3d.judges.rubrics import load_rubricfrom codeverse3d.judges.vlm_judge import SLICE_LABELS, VlmJudge-from codeverse3d.workspace import Workspacefrom tests.judges.conftest import ACCEPTANCE, FakeChatModel, good_reply, make_renders, make_specR = load_rubric("static_object")@@ -81,31 +75,6 @@ def text_of(req) -> str:return "\n".join(p.text for m in req.messages for p in m.parts if isinstance(p, TextPart))-def test_knob_off_wrong_track_and_missing_glb_stay_baseline(tmp_path, cache_dir, monkeypatch):- renders = make_renders(tmp_path / "r")- glb = two_box_glb(tmp_path / "o.glb")- baseline = build_judge_messages(make_input(renders, dirty_gates(), None), R, cache_dir=cache_dir)-- # dirty gates but no glb_path (e.g. a pre-D48 record): baseline- req = judge_request(make_input(renders, dirty_gates(), None), cache_dir)- assert req.system == baseline[0] and PROVENANCE_ELICITATION not in req.system- assert [m.model_dump() for m in req.messages] == [m.model_dump() for m in baseline[1]]-- # dirty gates + glb on a NON-OBJECT track (stray glb_path on a scene input): baseline —- # the SLICE_TRACKS guard, tested directly at the VlmJudge layer- req = judge_request(make_input(renders, dirty_gates(), glb,- spec_kw={"track": "scene", "language": "scene_threejs"}), cache_dir)- assert req.system == baseline[0] and PROVENANCE_ELICITATION not in req.system- assert "cross-section" not in text_of(req)-- # dirty gates + glb, but the knob is off: baseline- monkeypatch.setattr("codeverse3d.judges.vlm_judge.get_settings",- lambda: Settings(judge={"slices": "off"}))- req = judge_request(make_input(renders, dirty_gates(), glb), cache_dir)- assert PROVENANCE_ELICITATION not in req.system and "cross-section" not in text_of(req)- get_settings.cache_clear()--# --------------------------------------------------------------------- clean = byte-identical, dirty = slices appendeddef test_slices_ride_only_on_a_connectivity_error(tmp_path, cache_dir):"""The invariant: glb present + knob on, but no gate ERROR → the exact pre-D48 payload. Any@@ -118,8 +87,6 @@ def test_slices_ride_only_on_a_connectivity_error(tmp_path, cache_dir):assert [m.model_dump() for m in req.messages] == [m.model_dump() for m in messages]assert PROVENANCE_ELICITATION not in req.systemassert "cross-section" not in text_of(req)- # and the protocol hash is untouched: the hash builds the default (elicitation-free) prompt- assert judge_prompt_hash(R) == VlmJudge("static_object", model_id="fake:fake-1").prompt_hashreq = judge_request(make_input(renders, dirty_gates(), glb), cache_dir)# placement: montage, 2 detail crops, THEN the two slices — never prepended@@ -127,13 +94,8 @@ def test_slices_ride_only_on_a_connectivity_error(tmp_path, cache_dir):assert lbls[-2:] == [SLICE_LABELS["front_back"], SLICE_LABELS["left_right"]]assert "DETAIL CROP" in lbls[-3] and len(lbls) == 5 # 1 montage + 2 crops + 2 slices- text = text_of(req)- assert "After the crops, 2 cross-section slice(s) show the interior" in text- assert "A gap between parts IN THE CUT PLANE is not evidence of disconnection" in text- assert "Judge floating_part and holes_or_inverted_faces from the shaded" in text- assert f"- slice 1: {SLICE_LABELS['front_back']}" in text+ assert "cross-section slice(s) show the interior" in text_of(req)assert req.system.count(PROVENANCE_ELICITATION) == 1- assert 'do not hide one to be kind. ' + PROVENANCE_ELICITATION in req.system# the slice pngs and their manifest landed in the judge cache, hatching the gate pairfrom codeverse3d.spatial.sections import SliceManifest@@ -142,54 +104,3 @@ def test_slices_ride_only_on_a_connectivity_error(tmp_path, cache_dir):man = SliceManifest.model_validate_json(manifests[0].read_text())assert man.error_pairs == [("A", "B")]assert all({p.a, p.b} == {"A", "B"} for s in man.rendered() for p in s.hatched_pairs)-- # the trigger is ANY connectivity ERROR, not only a penetration pair- floating = [GateReport(gate="connectivity", passed=False, findings=[- GateFinding(gate="connectivity", severity=Severity.ERROR, target="B",- message="part 'B' is floating", data={"kind": "floating"})])]- req = judge_request(make_input(renders, floating, glb), cache_dir)- assert req.system.count(PROVENANCE_ELICITATION) == 1- assert labels(req)[-2:] == [SLICE_LABELS["front_back"], SLICE_LABELS["left_right"]]---def test_error_pair_extraction_reads_target_and_other(tmp_path):- # target/other win over entering/container (the probe's direction is not the finding's)- assert connectivity_error_pairs(dirty_gates()) == [("A", "B")]- g = GateReport(gate="connectivity", passed=False, findings=[- GateFinding(gate="connectivity", severity=Severity.ERROR, target="",- message="x", data={"kind": "penetration", "entering": "Leg", "container": "Seat"}),- GateFinding(gate="connectivity", severity=Severity.ERROR, target="Mast",- message="floating", data={"kind": "floating"}), # no pair: not a penetration- GateFinding(gate="connectivity", severity=Severity.WARN, target="C",- message="weld", data={"kind": "penetration", "other": "D"}), # WARN: never- ])- assert connectivity_error_pairs([g]) == [("Leg", "Seat")]- assert connectivity_error_pairs([GateReport(gate="contract", passed=False, findings=[])]) == []---# --------------------------------------------------------------------- (d) 3dcode judge replay-def test_replay_reproduces_the_conditional_payload_from_stored_gates_and_glb(tmp_ws: Workspace, tmp_path, cache_dir):- from codeverse3d.cli._judge import build_judge_input-- tmp_ws.round_artifacts(0).mkdir(parents=True)- glb = two_box_glb(tmp_ws.round_artifacts(0) / "object.glb") # the round's own GLB (artifacts/r00/)- renders = make_renders(tmp_path / "renders")- rec = RunRecord(spec=make_spec(), workspace=str(tmp_ws.root))- rnd = RoundRecord(index=0, kind="baseline", gates=dirty_gates(), renders=renders,- build=BuildResult(ok=True, language="blender", glb_path=str(glb)))-- inp = build_judge_input(tmp_ws, rec, rnd)- assert inp.glb_path == str(glb)- req = judge_request(inp, cache_dir)- assert labels(req)[-2:] == [SLICE_LABELS["front_back"], SLICE_LABELS["left_right"]]- assert req.system.count(PROVENANCE_ELICITATION) == 1-- # a scene round's stored build never feeds the channel, whatever it exported- scene_rec = RunRecord(spec=make_spec(track="scene", language="scene_threejs"), workspace=str(tmp_ws.root))- assert build_judge_input(tmp_ws, scene_rec, rnd).glb_path is None-- # the canonical GLB is the LAST build's, never another round's; a deleted one disables the- # channel instead of crashing the replay- assert build_judge_input(tmp_ws, rec, rnd.model_copy(update={"index": 1})).glb_path is None- glb.unlink()- assert build_judge_input(tmp_ws, rec, rnd).glb_path is Nonediff --git a/harness/tests/judges/test_likeness.py b/harness/tests/judges/test_likeness.pydeleted file mode 100644index 9e2719fd..00000000--- a/harness/tests/judges/test_likeness.py+++ /dev/null@@ -1,31 +0,0 @@-"""LikenessJudge: the reference photos ride beside the frames; nothing is silhouette-matched."""--from __future__ import annotations--from codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.spec import ReferenceImage-from codeverse3d.judges.rubrics import load_rubric-from codeverse3d.judges.vlm_judge import LIKENESS_NOTE, LikenessJudge-from tests.judges.conftest import FakeChatModel, draw_chair, good_reply, image_parts, make_spec---def test_likeness_context_attaches_the_photos_and_the_note(judge_input, tmp_path, cache_dir):- ref = tmp_path / "aurora_green_spiral_sea.png"- draw_chair(ref)- judge_input.spec = make_spec(track=Track.GRAPHICS, language=Language.GLSL_SHADER,- references=[ReferenceImage(path=str(ref), role="likeness", note="aurora green spiral sea")])- model = FakeChatModel([good_reply(load_rubric("shader"), ["A1", "A2"], 0.8)])- j = LikenessJudge("fake:fake-1", rubric="shader", chat_model=model, cache_dir=cache_dir)- ctx = j.context(judge_input)- assert ctx.extra_images == [("REAL-WORLD REFERENCE 1/1 — aurora green spiral sea", str(ref))]- assert ctx.extra_text == LIKENESS_NOTE and "evenly spaced bars" in LIKENESS_NOTE- assert ctx.measured_scores == {}, "nothing is measured: a shader has no silhouette"- verdict = j.judge(judge_input)- assert verdict.overall > 0.7- req = model.requests[0]- labels = [p.label for p in image_parts(req)]- assert labels[0].startswith("REAL-WORLD REFERENCE 1/1"), labels- assert "REAL-WORLD REFERENCE PHOTOS are attached" in req.messages[0].parts[0].text- judge_input.spec = make_spec(track=Track.GRAPHICS, language=Language.GLSL_SHADER) # no photos: a plain judge- ctx = j.context(judge_input)- assert ctx.extra_images == [] and ctx.extra_text == ""diff --git a/harness/tests/judges/test_live.py b/harness/tests/judges/test_live.pydeleted file mode 100644index dd209b88..00000000--- a/harness/tests/judges/test_live.py+++ /dev/null@@ -1,127 +0,0 @@-"""Live judge tests (real Gemini calls; need keys). Run: pytest tests/judges -m live -s"""--from __future__ import annotations--import json-from pathlib import Path--import numpy as np-import pytest-import trimesh--from codeverse3d.config import get_settings-from codeverse3d.contracts.artifacts import RenderSet-from codeverse3d.contracts.plan import AcceptanceItem-from codeverse3d.judges.base import JudgeInput-from codeverse3d.judges.vlm_judge import VlmJudge-from tests.judges.conftest import make_measurement, make_renders, make_spec--pytestmark = pytest.mark.live-MODEL = "gemini:gemini-3.8-flash"---def _stool_glb(out: Path) -> Path:- seat = trimesh.creation.cylinder(radius=0.18, height=0.03, sections=48)- seat.apply_translation((0, 0, 0.45 - 0.015))- parts = {"Seat": seat}- for i in range(3):- a = np.deg2rad(90 + i * 120)- leg = trimesh.creation.cylinder(radius=0.018, height=0.43, sections=20)- leg.apply_translation((0.13 * np.cos(a), 0.13 * np.sin(a), 0.215))- parts[f"Leg{i + 1}"] = leg- scene = trimesh.Scene()- zup_to_yup = trimesh.transformations.rotation_matrix(-np.pi / 2, (1, 0, 0))- for name, m in parts.items():- m.apply_transform(zup_to_yup)- m.visual = trimesh.visual.ColorVisuals(m, face_colors=(160, 110, 60, 255))- scene.add_geometry(m, node_name=name, geom_name=name)- out.parent.mkdir(parents=True, exist_ok=True)- scene.export(out)- return out---def _renders_for_test(tmp: Path) -> tuple[RenderSet, object, str]:- """Real stool renders via spatial.render when possible, else PIL drawings."""- try:- from codeverse3d.conventions import OBJECT_VIEWS_QUICK- from codeverse3d.spatial.measure import measure_glb- from codeverse3d.spatial.render import render_glb-- glb = _stool_glb(tmp / "stool.glb")- rs = render_glb(glb, tmp / "renders", views=OBJECT_VIEWS_QUICK, sheet=True)- return rs, measure_glb(glb), "render_glb(trimesh stool)"- except Exception as e: # noqa: BLE001 - live test: fall back but SAY so- return make_renders(tmp / "renders"), make_measurement(), f"PIL chair drawings (render_glb unavailable: {type(e).__name__}: {str(e)[:120]})"---def test_live_vlm_judge_two_samples(tmp_path):- assert get_settings().gemini_api_keys, "no Gemini keys"- renders, meas, source = _renders_for_test(tmp_path)- prompt = ("A simple three-legged wooden stool, 45 cm tall, round seat 36 cm across." if "stool" in source- else "A simple wooden dining chair with four legs and a slatted backrest.")- spec = make_spec(prompt=prompt)- inp = JudgeInput(spec=spec, renders=renders, measurement=meas,- acceptance=[AcceptanceItem(id="A1", text="three legs reach the ground", how="visual", priority="must"),- AcceptanceItem(id="A2", text="seat is round", how="visual", priority="should")],- plan_summary="parts: Seat, Leg1, Leg2, Leg3")- judge = VlmJudge("static_object", model_id=MODEL, n_samples=2, cache_dir=tmp_path / "cache")- j = judge.judge(inp)- raw = json.loads(j.raw)- print(f"\nLIVE source={source}\noverall={j.overall} std={j.score_std} passed={j.passed} n={j.n_samples}"- f"\nscores={j.scores}\nacceptance={j.acceptance_results}\ncaps={raw.get('caps')}\nsample_errors={raw.get('sample_errors')}"- f"\nusage={j.usage}\nsummary={j.summary}\nplan={[i.instruction for i in j.improvement_plan]}")- assert not j.degraded, j.summary- assert j.n_samples == 2 and raw["sample_errors"] == [] # parsed first try- assert 0.0 < j.overall < 1.0- assert set(j.scores) == {c.id for c in judge.rubric.criteria}- assert set(raw["defects"]) == {d.id for d in judge.rubric.defects} # checklist answered- print(f"defects={[d for d, on in raw['defects'].items() if on]} penalty={raw['defect_penalty']}")---def test_live_judge_separates_crafted_from_crude(tmp_path):- """Dynamic range: a real stool render set vs a crude PIL chair drawing, same brief (stool)."""- renders, meas, source = _renders_for_test(tmp_path / "stool")- if "stool" not in source:- pytest.skip("needs real stool renders")- spec = make_spec(prompt="A simple three-legged wooden stool, 45 cm tall, round seat 36 cm across.")- judge = VlmJudge("static_object", model_id=MODEL, n_samples=1, cache_dir=tmp_path / "cache")- good = judge.judge(JudgeInput(spec=spec, renders=renders, measurement=meas, plan_summary="parts: Seat, Leg1, Leg2, Leg3"))- crude = judge.judge(JudgeInput(spec=spec, renders=make_renders(tmp_path / "crude"), measurement=make_measurement(),- plan_summary="parts: Seat, Leg1, Leg2, Leg3"))- gd, cd = json.loads(good.raw), json.loads(crude.raw)- print(f"\nLIVE stool overall={good.overall} uncapped={gd['overall_uncapped']} defects={[d for d, o in gd['defects'].items() if o]}"- f"\nLIVE crude overall={crude.overall} uncapped={cd['overall_uncapped']} defects={[d for d, o in cd['defects'].items() if o]}")- assert not good.degraded and not crude.degraded- assert good.overall - crude.overall >= 0.25- assert any(cd["defects"].values()) # the crude drawing trips the checklist---def test_live_pairwise_stool_vs_chair(tmp_path):- from codeverse3d.judges.pairwise import PairwiseJudge-- renders, _, source = _renders_for_test(tmp_path / "stool")- if "stool" not in source:- pytest.skip("needs real stool renders")- chair = make_renders(tmp_path / "chair")- spec = make_spec(prompt="A simple three-legged wooden stool, 45 cm tall, round seat.")- res = PairwiseJudge(MODEL, cache_dir=tmp_path / "cache").compare(spec, renders, chair)- print(f"\nLIVE pairwise winner={res.winner} conf={res.confidence} err={res.error!r}\nreasons={res.reasons}\nusage={res.usage}")- assert res.winner == "a"---def test_live_reference_judge(tmp_path):- from codeverse3d.contracts.spec import ReferenceImage- from codeverse3d.judges.vlm_judge import ReferenceJudge-- renders, meas, source = _renders_for_test(tmp_path / "stool")- if "stool" not in source:- pytest.skip("needs real stool renders")- front = next(v for v in renders.views if v.name == "front")- spec = make_spec(prompt="Reproduce the stool in the reference image.",- references=[ReferenceImage(path=front.path, role="target", note="the target stool")])- inp = JudgeInput(spec=spec, renders=renders, measurement=meas, plan_summary="parts: Seat, Leg1, Leg2, Leg3")- j = ReferenceJudge(MODEL, cache_dir=tmp_path / "cache").judge(inp)- raw = json.loads(j.raw)- print(f"\nLIVE reference overall={j.overall} passed={j.passed} scores={j.scores}\nsummary={j.summary}\nusage={j.usage}")- assert not j.degraded and raw["sample_errors"] == []- assert j.scores["silhouette_match"] >= 0.95 # reference is the render itselfdiff --git a/harness/tests/judges/test_montage.py b/harness/tests/judges/test_montage.pyindex c2453701..40bb3209 100644--- a/harness/tests/judges/test_montage.py+++ b/harness/tests/judges/test_montage.py@@ -1,14 +1,8 @@from pathlib import Path-import pytest-from codeverse3d.contracts.artifacts import RenderSet, RenderViewfrom codeverse3d.judges.prompt_builder import (- JudgeImageError,plan_montages,- rank_views,- render_montage,- shuffle_montages,)from tests.judges.conftest import draw_chair@@ -29,36 +23,6 @@ def _views(tmp: Path, names, *, mode="shaded", prefix="v"):return out-def test_rank_views_objects_and_scenes():- vs = [RenderView(name=n, path="x") for n in ("left", "top", "zzz", "front_right_high")]- assert [v.name for v in rank_views(vs, scene=False)] == ["front_right_high", "top", "left", "zzz"]- # scene rig: the scene's OWN cameras (any name that is not a harness rig name) come- # first — they are the pictures being graded; the overview rig follows in rank order- # and the eye-level rig last- sv = [RenderView(name=n, path="x") for n in ("overview_top", "Establishing", "eye_front", "BridgeView", "cam_b")]- assert [v.name for v in rank_views(sv, scene=True)] == ["Establishing", "BridgeView", "cam_b", "overview_top", "eye_front"]- # a re-judged stored pre-D47 8-view run ranks its legacy hero names first- legacy = ["front_right_34", "back_left_34", "front", "right", "back", "left", "top", "low_front_left"]- ranked = [v.name for v in rank_views([RenderView(name=n, path=f"/x/{n}.png") for n in legacy], scene=False)]- assert ranked[:2] == ["front_right_34", "back_left_34"], ranked---def test_plan_montages_full_rig_plus_clay_is_the_measured_cprod_plan(tmp_path):- """D47: 14 shaded + 4 clay -> 5 montages + 2 crops; montage 1 keeps the underside, one crop on ``bottom``."""- rs = RenderSet(views=_views(tmp_path, OBJ))- clay = RenderSet(views=_views(tmp_path, CLAY, mode="clay", prefix="c"))- ms = plan_montages(rs, geometry_views=clay) # defaults: max_montages=5, detail_crops=2- grids = [m for m in ms if not m.is_detail]- crops = [m for m in ms if m.is_detail]- assert len(ms) == 7 and len(grids) == 5 and len(crops) == 2- assert [m.kind for m in grids] == ["shaded", "geometry", "shaded", "shaded", "shaded"]- assert {v.name for v in grids[0].tiles} == {"front_right_high", "back_left_high", "top", "bottom"}- assert {v.name for v in grids[1].tiles} == set(CLAY) and all(v.mode == "clay" for v in grids[1].tiles)- assert [v.name for v in grids[2].tiles] == ["front", "right", "back", "left"]- assert crops[0].tiles[0].name == "front_right_high"- assert crops[1].tiles[0].name == "bottom"--def test_plan_montages_articulated_and_geometry(tmp_path):poses = _views(tmp_path, ["pose_rest", "pose_J@upper", "pose_K@upper"], prefix="p")sheet = _views(tmp_path, ["articulation_sheet"], prefix="s")@@ -73,25 +37,3 @@ def test_plan_montages_articulated_and_geometry(tmp_path):# more room: secondary shaded then the pose 2×2 (duplicate of the sheet, lowest priority)ms5 = plan_montages(rs, geometry_views=clay, max_montages=7, detail_crops=0)assert [m.kind for m in ms5] == ["shaded", "pose_sheet", "geometry", "shaded", "shaded", "shaded", "poses"]- # without a sheet the pose_* views form the pose montage- rs2 = RenderSet(views=_views(tmp_path, OBJ[:4]) + poses)- ms2 = plan_montages(rs2, detail_crops=0)- assert [m.kind for m in ms2] == ["shaded", "poses"] and len(ms2[1].tiles) == 3---def test_shuffle_keeps_sets_and_details_last(tmp_path):- rs = RenderSet(views=_views(tmp_path, OBJ))- ms = plan_montages(rs)- sh = shuffle_montages(ms, 7)- assert shuffle_montages(ms, 7) == sh and shuffle_montages(ms, None) == ms- assert [m.kind for m in sh[-2:]] == ["detail", "detail"]- assert {frozenset(v.name for v in m.tiles) for m in sh[:-2]} == {frozenset(v.name for v in m.tiles) for m in ms[:-2]}- seeds = {tuple((m.kind, tuple(v.name for v in m.tiles)) for m in shuffle_montages(ms, s)) for s in range(6)}- assert len(seeds) >= 3---def test_missing_tile_is_judge_image_error(tmp_path):- m = plan_montages(RenderSet(views=[RenderView(name="front", path="/nonexistent/x.png")]), detail_crops=0)[0]- with pytest.raises(JudgeImageError):- render_montage(m, cache_dir=tmp_path / "cache")-diff --git a/harness/tests/judges/test_output_schema.py b/harness/tests/judges/test_output_schema.pyindex 56a8d2f5..b0ed60e5 100644--- a/harness/tests/judges/test_output_schema.py+++ b/harness/tests/judges/test_output_schema.py@@ -4,7 +4,6 @@ from codeverse3d.judges.rubrics import (JudgeParseError,load_rubric,parse_judge_output,- wire_schema,)from tests.judges.conftest import good_reply@@ -12,16 +11,6 @@ R = load_rubric("static_object")IDS = ["A1", "must-2"]-def test_wire_schema_has_fixed_keys_and_no_overall():- s = wire_schema(R, IDS)- crit = s["$defs"]["Criteria"]- assert set(crit["required"]) == {c.id for c in R.criteria}- acc = s["$defs"]["Acceptance"]- assert set(acc["properties"]) == set(IDS)- assert "overall" not in s["properties"] and "passed" not in s["properties"] # law 3: scored in code- assert "acceptance" not in wire_schema(R, [])["properties"]--def test_parse_accepts_bare_values_defaults_missing_acceptance_and_rejects_bad_criteria():rep = good_reply(R, IDS)rep["acceptance"] = {"A1": True, "must-2": False}diff --git a/harness/tests/judges/test_pairwise.py b/harness/tests/judges/test_pairwise.pyindex d5196ab6..b4c2796d 100644--- a/harness/tests/judges/test_pairwise.py+++ b/harness/tests/judges/test_pairwise.py@@ -38,37 +38,3 @@ def test_the_swap_decides_the_winner_and_its_confidence(tmp_path, cache_dir):assert res.winner == "b" and res.confidence == 0.4-def test_tie_and_errors(tmp_path, cache_dir):- ra, rb = make_renders(tmp_path / "a", sheet=False), make_renders(tmp_path / "b", sheet=False)- model = FakeChatModel([_reply("tie", 0.6), _reply("tie", 0.6)])- res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)- assert res.winner == "tie" and res.confidence == 0.6- assert len(image_parts(model.requests[0])) == 2 # still one montage per side without a sheet- model2 = FakeChatModel(default=ModelError("down", retryable=True))- res2 = PairwiseJudge("fake:fake-1", chat_model=model2, cache_dir=cache_dir).compare(make_spec(), ra, rb)- assert res2.winner == "tie" and res2.confidence == 0.0 and "ModelError" in res2.error---def test_a_scene_pair_is_ranked_as_a_scene_from_the_views_the_judge_saw(tmp_path, cache_dir):- """A scene's own camera leads, and a view the verdict judge never saw (judge=False) is left out."""- from codeverse3d.contracts.artifacts import RenderSet, RenderView- from codeverse3d.contracts.common import Language, Track- from tests.judges.conftest import draw_chair-- def scene_renders(d):- d.mkdir(parents=True)- names = [("overview_front_right", True), ("overview_back_left", True), ("overview_top", True),- ("eye_front", True), ("unjudged_extra", False), ("Establishing", True)]- return RenderSet(views=[RenderView(name=n, path=str(draw_chair(d / f"{n}.png")), judge=j)- for n, j in names], renderer="fake")-- model = FakeChatModel(by_label={":fwd": [_reply("A")], ":swap": [_reply("B")]})- spec = make_spec(track=Track.SCENE, language=Language.SCENE_THREEJS)- PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(- spec, scene_renders(tmp_path / "a"), scene_renders(tmp_path / "b"))- labels = [p.label for p in image_parts(next(r for r in model.requests if r.label == "pairwise:fwd"))]- assert "top-left = Establishing" in labels[0]- assert not any("unjudged_extra" in lbl for lbl in labels)- # N66: the system prompt names no criteria of its own (it listed the object rubric's for every pair)- system = next(r for r in model.requests if r.label == "pairwise:fwd").system- assert "CRITERIA listed" in system and "proportions" not in systemdiff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.pyindex 992cab63..98557398 100644--- a/harness/tests/judges/test_prompt_builder.py+++ b/harness/tests/judges/test_prompt_builder.py@@ -5,20 +5,13 @@ from PIL import Imagefrom codeverse3d.contracts.artifacts import (GateFinding,GateReport,- ImprovementItem,- Judgment,- RenderSet,- RenderView,Severity,)from codeverse3d.contracts.chat import ImagePartfrom codeverse3d.judges.prompt_builder import (- TEXT_BUDGET_CHARS,build_judge_messages,- view_az_el,)from codeverse3d.judges.rubrics import load_rubric-from tests.judges.conftest import draw_chairR = load_rubric("static_object")@@ -42,64 +35,6 @@ def test_montage_images_are_cached_at_the_payload_size(judge_input, cache_dir):assert 900 <= im.size[0] <= 1024 and im.size[1] > im.size[0] # 2×2 grid + strip-def test_geometry_views_add_a_montage(tmp_path, judge_input, cache_dir):- """D47: the clay montage is labelled from the clay rig's own cameras (top at el 88, not 90)."""- from codeverse3d.conventions import OBJECT_CLAY_VIEWS-- clay = []- for v in OBJECT_CLAY_VIEWS:- p = draw_chair(tmp_path / f"clay_{v.name}.png", color=(180, 180, 180))- clay.append(RenderView(name=v.name, path=str(p), mode="clay"))- _, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir, geometry_views=RenderSet(views=clay))- labels = [p.label for p in _images(msgs)]- assert labels[0].startswith("MONTAGE 1/2 — SHADED views") and labels[1].startswith("MONTAGE 2/2 — GEOMETRY-ONLY views (clay")- assert "front_right_34 · az 35° el 22° · clay" in labels[1]- assert "top · az 0° el 88° · clay" in labels[1]- assert "top · az 0° el 90°" in labels[0]- text = _parts(msgs)[0].text- assert "GEOMETRY-ONLY montage shows the same object without materials" in text---def test_gates_previous_and_budget(judge_input, cache_dir):- judge_input.gates = [GateReport(gate="connectivity", passed=False, findings=[- GateFinding(gate="connectivity", severity=Severity.ERROR, target="LegBackLeft", message="floating 3 cm"),- GateFinding(gate="connectivity", severity=Severity.WARN, message="thin sliver on Seat")])]- judge_input.previous = Judgment(rubric="static_object", scores={}, overall=0.55, passed=False,- improvement_plan=[ImprovementItem(target="Seat", kind="geometry", instruction="thicken seat", priority=1)])- judge_input.round_index = 2- judge_input.extra_context = "x" * 50_000- _, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir)- text = _parts(msgs)[0].text- assert "errors (1)" in text and "[LegBackLeft]: floating 3 cm" in text- assert "warnings (1)" in text- assert "PREVIOUS VERDICT (round 1): overall 0.55" in text and "thicken seat" in text- assert len(text) <= TEXT_BUDGET_CHARS + 20---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"), cache_dir=cache_dir)- text = _parts(msgs)[0].text- assert "overview_*" in text and "console error" in text- # scene: 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():- v = RenderView(name="custom", path="x.png", camera_position=(0.0, 1.0, 1.0), look_at=(0, 0, 0))- az, el = view_az_el(v)- assert az == 0.0 and el == 45.0- assert view_az_el(RenderView(name="top", path="x")) == (0.0, 90.0)- # a geometry-mode tile answers from the clay rig's own cameras (el 88, not 90)- assert view_az_el(RenderView(name="top", path="x", mode="clay")) == (0.0, 88.0)- assert view_az_el(RenderView(name="front_right_34", path="x", mode="normals")) == (35.0, 22.0)- assert view_az_el(RenderView(name="zzz", path="x")) is None--# ===================================================================== the contact ledger (2026-08-30)#: a real p90 round's connectivity ledger (16 parts, 26 contacts, 23 overlaps, one open planned join)LEDGER_VIOLIN = {"parts": ["Chinrest", "Strings", "Tailpiece", "Bridge", "TuningPegs_3", "TuningPegs_2", "TuningPegs_1", "TuningPegs_0", "PegboxAndScroll", "Nut", "Fingerboard", "NeckRoot", "EndpinButton", "TopPlate", "RibStructure", "BackPlate"], "contact_gap_mm": 2.0, "contacts": [["Chinrest", "TopPlate", 0.0], ["Chinrest", "RibStructure", 0.0], ["Strings", "Tailpiece", 0.0], ["Strings", "Bridge", 0.8], ["Strings", "TuningPegs_2", 0.0], ["Strings", "TuningPegs_1", 0.6], ["Strings", "PegboxAndScroll", 0.0], ["Strings", "Nut", 0.0], ["Strings", "NeckRoot", 0.0], ["Tailpiece", "TopPlate", 0.0], ["Bridge", "TopPlate", 0.0], ["TuningPegs_3", "PegboxAndScroll", 0.0], ["TuningPegs_2", "PegboxAndScroll", 0.0], ["TuningPegs_1", "PegboxAndScroll", 0.0], ["TuningPegs_0", "PegboxAndScroll", 0.0], ["PegboxAndScroll", "Nut", 0.0], ["PegboxAndScroll", "Fingerboard", 0.0], ["PegboxAndScroll", "NeckRoot", 0.0], ["Nut", "Fingerboard", 0.0], ["Nut", "NeckRoot", 0.0], ["Fingerboard", "NeckRoot", 0.0], ["NeckRoot", "TopPlate", 0.0], ["NeckRoot", "RibStructure", 0.0], ["EndpinButton", "RibStructure", 0.0], ["TopPlate", "RibStructure", 0.0], ["RibStructure", "BackPlate", 0.0]], "overlaps": [["Chinrest", "TopPlate", 1.8, 0.08], ["Strings", "Tailpiece", 3.1, 0.02], ["Strings", "TuningPegs_2", 2.4, 0.02], ["Strings", "PegboxAndScroll", 5.1, 0.0], ["Strings", "Nut", 0.4, 0.02], ["Strings", "NeckRoot", 1.5, 0.02], ["Tailpiece", "TopPlate", 1.7, 0.23], ["Bridge", "TopPlate", 1.5, 0.36], ["TuningPegs_3", "PegboxAndScroll", 6.6, 0.17], ["TuningPegs_2", "PegboxAndScroll", 9.0, 0.33], ["TuningPegs_1", "PegboxAndScroll", 8.3, 0.27], ["TuningPegs_0", "PegboxAndScroll", 3.9, 0.19], ["PegboxAndScroll", "Nut", 2.5, 0.11], ["PegboxAndScroll", "Fingerboard", 2.7, 0.1], ["PegboxAndScroll", "NeckRoot", 4.1, 0.2], ["Nut", "Fingerboard", 1.0, 0.23], ["Nut", "NeckRoot", 1.0, 0.07], ["Fingerboard", "NeckRoot", 8.4, 0.55], ["NeckRoot", "TopPlate", 1.0, 0.0], ["NeckRoot", "RibStructure", 0.1, 0.0], ["EndpinButton", "RibStructure", 3.0, 0.0], ["TopPlate", "RibStructure", 1.6, 0.05], ["RibStructure", "BackPlate", 2.5, 0.07]], "ground_gap_mm": {"Chinrest": 33.0, "Strings": 43.0, "Tailpiece": 37.0, "Bridge": 37.5, "TuningPegs_3": 55.0, "TuningPegs_2": 45.0, "TuningPegs_1": 45.0, "TuningPegs_0": 55.0, "PegboxAndScroll": 33.0, "Nut": 51.0, "Fingerboard": 44.2, "NeckRoot": 21.3, "EndpinButton": 14.0, "TopPlate": 31.0, "RibStructure": 3.0, "BackPlate": 0.0}, "planned": [["RibStructure", "BackPlate", 0.0, "contact"], ["TopPlate", "RibStructure", 0.0, "contact"], ["EndpinButton", "RibStructure", 0.0, "contact"], ["NeckRoot", "RibStructure", 0.0, "contact"], ["Fingerboard", "NeckRoot", 0.0, "contact"], ["Nut", "Fingerboard", 0.0, "contact"], ["PegboxAndScroll", "NeckRoot", 0.0, "contact"], ["TuningPegs_3", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_2", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_1", "PegboxAndScroll", 0.0, "contact"], ["TuningPegs_0", "PegboxAndScroll", 0.0, "contact"], ["Bridge", "TopPlate", 0.0, "contact"], ["Tailpiece", "EndpinButton", 24.9, "open"], ["Strings", "Bridge", 0.8, "contact"], ["Chinrest", "TopPlate", 0.0, "contact"]], "planned_unresolved": []}@@ -139,26 +74,12 @@ def test_ledger_turns_penetration_warn_prose_into_one_measured_line():assert sum("interpenetrate" in f.message for f in rep.findings) == 13 # one WARN sentence per overlap over the weld linetext = gates_section([rep, CONTRACT_FAIL, GateReport(gate="budget", passed=True)])assert "interpenetrate" not in text- assert ("connectivity measured 23 mating overlaps (deepest weld 9.0 mm TuningPegs_2/PegboxAndScroll, through-ratio 0.33); "- "weld allowance 2 mm, ERROR line 10 mm; 23 weld(s) under it are NOT the interpenetration defect.") in text- # ≥ 0.5 of the way through: named as a measurement, left to the geometry montage- assert "Measured, not a defect claim: Fingerboard/NeckRoot reaches 55% of the way to its partner's mid-plane (8.4 mm)" in text- assert "errors (1):" in text and "- contract [Bridge]: 'Bridge' bbox extents off by 0.03 m" in text- assert "warnings (1), grouped by kind:" in text and "- contract ×1: [Nut] 'Nut' centre off by 4 mm" in text+ assert "connectivity measured 23 mating overlaps (deepest weld 9.0 mm TuningPegs_2/PegboxAndScroll" in text+ assert "errors (1):" in text and "warnings (1), grouped by kind:" in textassert "MEASURED STRUCTURE (connectivity gate, exact mesh-to-mesh distances): 16 parts, 26 contacts (gap ≤ 2 mm), 0 floating, 23 overlapping pairs." in text- assert "PLANNED JOINS (the plan's attach_to pairs, measured; contact = gap ≤ 2 mm): 14/15 in contact. OPEN: Tailpiece→EndpinButton 24.9 mm." in text- assert "Strings→Bridge 0.8," in text and "TuningPegs_3→PegboxAndScroll," in text- # a planned contact is not repeated in the adjacency; the unplanned ones are- assert "- other contacts, not in the plan (gap in mm where not 0): Chinrest: RibStructure · Strings: Tailpiece, TuningPegs_2, TuningPegs_1 0.6," in text- assert "TuningPegs_3: PegboxAndScroll" not in text- assert "- ground: lowest point 0.0 mm (BackPlate) — floor contact; parts within 10 mm of the floor: RibStructure 3.0 mm" in text- assert ("CONNECTIVITY PASSED: all 16 parts are in measured contact (26 contacts, gap <= 2 mm)." in text- and "Do NOT report any part as floating" in text)- # three overlaps reach 8 mm (the veto's line): no injunction against the interpenetration tick,- # the measurement is named and the picture decides — the prompt and rubrics._rule_gates_clean agree- assert "All 23 overlaps measured; 3 reach 8 mm or more (" in text- assert "mark interpenetration only if a part VISIBLY passes through another in a render" in text- assert "do NOT mark the interpenetration defect" not in text+ assert "14/15 in contact. OPEN: Tailpiece→EndpinButton 24.9 mm." in text+ assert "TuningPegs_3: PegboxAndScroll" not in text # a planned contact is not repeated in the adjacency+ assert "CONNECTIVITY PASSED: all 16 parts are in measured contact" in textassert text.index("errors (1)") < text.index("MEASURED STRUCTURE") < text.index("connectivity measured") < text.index("warnings (1)")@@ -233,33 +154,3 @@ def test_ledger_ground_line_and_single_part_and_grouped_warnings():assert "- connectivity ×2: [P0] part 'P0' contains 1 tiny disconnected island(s); [P1] part 'P1'" in textassert "- contract/center ×10: [C0] 'C0' centre off by 0 mm;" in text and "[C7] 'C7' centre off by 7 mm; … 2 more" in textassert "[C8]" not in text---def test_gates_section_without_a_ledger_is_byte_identical_to_the_pre_ledger_text():- """A replay of a pre-ledger round builds the exact text its stored verdict saw (captured at 4ddde32)."""- from codeverse3d.judges.prompt_builder import gates_section-- C = "connectivity"- def F(sev, msg, target=None, gate=C, data=None):- return GateFinding(gate=gate, severity=sev, target=target, message=msg, data=data or {})- assert gates_section([]) == 'GATE FINDINGS: (no gates run)'- passed = [GateReport(gate=C, passed=True, findings=[F(Severity.INFO, "all 9 parts are connected (12 contacts, gap ≤ 2 mm)")])]- assert gates_section(passed) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=pass\nno errors or warnings — parts are connected and contracts hold.\nCONNECTIVITY PASSED: every part is in measured contact with its neighbour (gap <= 2 mm). A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any part as floating, hovering or disconnected, and do not mark the floating-part defect present; if a joint looks visually ugly, say so under craftsmanship.'- mixed = [- GateReport(gate=C, passed=True, findings=[- F(Severity.WARN, "'Strings' and 'Tailpiece' interpenetrate by ≈2.5 mm (2% of surface samples inside, 30% where they meet)", "Strings",- data={"kind": "penetration", "other": "Tailpiece", "depth_m": 0.0025, "through_ratio": 0.1}),- F(Severity.WARN, "part 'Seat' contains 2 tiny disconnected island(s) (< 5% of the part size) — stray geometry", "Seat", data={"islands": 3, "tiny_islands": 2}),- F(Severity.INFO, "all 16 parts are connected (26 contacts, gap ≤ 2 mm)")]),- GateReport(gate="contract", passed=False, findings=[F(Severity.ERROR, "'Bridge' bbox extents off by 0.03 m", "Bridge", gate="contract"),- F(Severity.WARN, "'Nut' centre off by 4 mm", "Nut", gate="contract")]),- GateReport(gate="budget", passed=True)]- assert gates_section(mixed) == "GATE FINDINGS (deterministic; treat as facts): connectivity=pass, contract=FAIL, budget=pass\nerrors (1):\n- contract [Bridge]: 'Bridge' bbox extents off by 0.03 m\nwarnings (3):\n- connectivity [Strings]: 'Strings' and 'Tailpiece' interpenetrate by ≈2.5 mm (2% of surface samples inside, 30% where they meet)\n- connectivity [Seat]: part 'Seat' contains 2 tiny disconnected island(s) (< 5% of the part size) — stray geometry\n- contract [Nut]: 'Nut' centre off by 4 mm\nCONNECTIVITY PASSED: every part is in measured contact with its neighbour (gap <= 2 mm). A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any part as floating, hovering or disconnected, and do not mark the floating-part defect present; if a joint looks visually ugly, say so under craftsmanship."- failed = [GateReport(gate=C, passed=False, findings=[- F(Severity.ERROR, "part 'Seat' is floating: nearest supported part is 'Leg' at 12.0 mm", "Seat", data={"kind": "floating", "nearest": "Leg", "gap_m": 0.012}),- F(Severity.ERROR, "'Arm' and 'Post' interpenetrate by ≈14.0 mm (30% of surface samples inside, 80% where they meet) — 'Arm' reaches 120% of the way through 'Post' (10 mm)", "Arm",- data={"kind": "penetration", "other": "Post", "depth_m": 0.014, "through_ratio": 1.2})])]- assert gates_section(failed) == "GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (2):\n- connectivity [Seat]: part 'Seat' is floating: nearest supported part is 'Leg' at 12.0 mm\n- connectivity [Arm]: 'Arm' and 'Post' interpenetrate by ≈14.0 mm (30% of surface samples inside, 80% where they meet) — 'Arm' reaches 120% of the way through 'Post' (10 mm)"- many = [GateReport(gate=C, passed=False, findings=[F(Severity.ERROR, f"error {i}", f"P{i}") for i in range(14)] + [F(Severity.WARN, f"warn {i}", f"W{i}") for i in range(11)])]- assert gates_section(many) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (14):\n- connectivity [P0]: error 0\n- connectivity [P1]: error 1\n- connectivity [P2]: error 2\n- connectivity [P3]: error 3\n- connectivity [P4]: error 4\n- connectivity [P5]: error 5\n- connectivity [P6]: error 6\n- connectivity [P7]: error 7\n- connectivity [P8]: error 8\n- connectivity [P9]: error 9\n- connectivity [P10]: error 10\n- connectivity [P11]: error 11\n- … 2 more errors\nwarnings (11):\n- connectivity [W0]: warn 0\n- connectivity [W1]: warn 1\n- connectivity [W2]: warn 2\n- connectivity [W3]: warn 3\n- connectivity [W4]: warn 4\n- connectivity [W5]: warn 5\n- connectivity [W6]: warn 6\n- connectivity [W7]: warn 7\n- … 3 more warnings'- assert gates_section(many, max_errors=3, max_warns=2) == 'GATE FINDINGS (deterministic; treat as facts): connectivity=FAIL\nerrors (14):\n- connectivity [P0]: error 0\n- connectivity [P1]: error 1\n- connectivity [P2]: error 2\n- … 11 more errors\nwarnings (11):\n- connectivity [W0]: warn 0\n- connectivity [W1]: warn 1\n- … 9 more warnings'diff --git a/harness/tests/judges/test_reference.py b/harness/tests/judges/test_reference.pyindex 4d0dd5a4..c9f482ea 100644--- a/harness/tests/judges/test_reference.py+++ b/harness/tests/judges/test_reference.py@@ -2,7 +2,7 @@ import pytestfrom codeverse3d.contracts.spec import ReferenceImagefrom codeverse3d.judges.rubrics import load_rubric-from codeverse3d.judges.vlm_judge import ReferenceJudge, ReferenceJudgeError, iou_to_score+from codeverse3d.judges.vlm_judge import ReferenceJudge, iou_to_scorefrom tests.judges.conftest import FakeChatModel, draw_chair, good_reply, image_partsREF = load_rubric("reference")@@ -32,7 +32,3 @@ def test_reference_judge_measures_silhouette_and_adds_reference_images(judge_inpassert "silhouette_match" not in req.response_schema["$defs"]["Criteria"]["properties"]-def test_reference_judge_requires_reference(judge_input, cache_dir):- model = FakeChatModel([good_reply(REF, ["A1", "A2"], 0.8)])- with pytest.raises(ReferenceJudgeError):- ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=lambda a, b: {"iou": 1.0}, cache_dir=cache_dir).judge(judge_input)diff --git a/harness/tests/judges/test_rubrics.py b/harness/tests/judges/test_rubrics.pyindex 45ee76cf..2d1839fc 100644--- a/harness/tests/judges/test_rubrics.py+++ b/harness/tests/judges/test_rubrics.py@@ -16,19 +16,3 @@ def test_unknown_and_invalid_rubric():rubric_from_dict(bad)-def test_cap_rules_are_not_part_of_the_judge_prompt():- """D37: cap rules move ``content_hash`` but not ``judge_prompt_hash`` — they are scored in code."""- import yaml-- from codeverse3d.judges.prompt_builder import judge_prompt_hash- from codeverse3d.judges.rubrics import RUBRICS_DIR, rubric_from_dict-- r = load_rubric("static_object")- data = yaml.safe_load((RUBRICS_DIR / "static_object.yaml").read_text())- data["caps"] = []- stripped = rubric_from_dict(data)- assert stripped.content_hash() != r.content_hash(), "content_hash hashes what the YAML declares"- # …and only that: a schema default the YAML never wrote does not re-key recorded verdicts- assert r.content_hash() == rubric_from_dict(yaml.safe_load((RUBRICS_DIR / "static_object.yaml").read_text())).content_hash()- assert judge_prompt_hash(stripped) == judge_prompt_hash(r)- assert "interpenetration" in judge_prompt_hash.__globals__["build_system_prompt"](r), "the checklist defect IS rendered"diff --git a/harness/tests/judges/test_scene_judge.py b/harness/tests/judges/test_scene_judge.pyindex daaf5e18..531c83b7 100644--- a/harness/tests/judges/test_scene_judge.py+++ b/harness/tests/judges/test_scene_judge.py@@ -1,32 +1,19 @@-"""scene (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."""+"""scene judge: the rubric's own numbers, and the REAL placement gate report reaching the judge."""from __future__ import annotations-import mathfrom 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.artifacts import GateReport, RenderSet, RenderView, Severityfrom codeverse3d.contracts.chat import ImagePartfrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.judges.base import JudgeInputfrom codeverse3d.judges.prompt_builder import (- CONTACT_CROP_MIN_FRAC,- RIG_RULES,build_judge_messages,- gates_section,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_absentfrom codeverse3d.spatial.scene_placement import placement_findings@@ -38,48 +25,6 @@ S = load_rubric("scene")# --------------------------------------------------------------------------- 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)@@ -99,193 +44,6 @@ def _rig(root: Path | None = None, *, time_s: float = 0.0) -> list[RenderView]:]-# --------------------------------------------------------------------------- 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"), 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 rubricdef test_scene_numbers_are_pinned():"""What moved from v1 (eval/docs/EVAL.md §6, 2026-10-14) — and what stayed."""@@ -298,46 +56,20 @@ def test_scene_numbers_are_pinned():"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)+ # the veto lines are the gate's own tolerances (config.Placement), not numbers of their ownp = Placement()assert caps["floating_asset"].veto_warn_keys["gap_m"] == p.floating_indoor_m <= p.contact_massert caps["sunken_asset"].veto_warn_keys["sunk_m"] == p.sunk_massert 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.6assert {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 defectsassert {k: defects[k] for k in ("floating_asset", "sunken_asset", "interpenetration", "wrong_scale", "hard_edged_particles","missing_planned_element", "hero_misplaced", "diorama_look")} == {"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),"diorama_look": (0.05, None)}- # 2026-10-15 (owner's rule): the craft criteria and defects judge against the BRIEF's place, not one recipe;- # `diorama_look` names the template (a block on a plate ringed by a uniform backdrop, nothing beyond) and- # asks for the view; nothing in the rubric prescribes blended ground + paths, clusters, a foreground frame- # within a few metres, or fog + a two-hue key/fill for every scene- diorama = S.defect("diorama_look").text- assert "flat plate" in diorama and "uniform backdrop" in diorama and "nothing" in diorama and "Cite the view" in diorama- whole = (S.extra_instructions + " " + " ".join(d.text for d in S.defects) + " " + " ".join(- c.description + " " + " ".join(c.anchors.values()) for c in S.criteria)).lower()- for recipe in ("blended materials with paths", "in clusters", "rather than clusters", "within a few metres",- "warm key against a cooler fill", "fog/haze", "litter", "no haze", "boxes-and-cones"):- assert recipe not in whole, recipe- assert "brief's weather" in whole and "arranged as the place would arrange them" in whole- # 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- 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 YAMLfor name in ("static_object", "articulated", "reference"):assert all(not c.veto_warn_keys for c in load_rubric(name).caps), name@@ -407,12 +139,9 @@ def test_the_real_placement_report_reaches_the_judge_as_counts_and_contact_cropslabels = [p.label for p in msgs[0].parts if isinstance(p, ImagePart)]assert len(labels) == 2 + 1 + 3assert 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].textassert "scene_placement=FAIL" in text and "MEASURED PLACEMENT (scene_placement gate" in textassert "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 measuredassert measured_absent(S, "floating_asset", [rep]) is False and measured_absent(S, "sunken_asset", [rep]) is Truediff --git a/harness/tests/judges/test_vlm_judge.py b/harness/tests/judges/test_vlm_judge.pyindex d6ec7fcd..b6ba1863 100644--- a/harness/tests/judges/test_vlm_judge.py+++ b/harness/tests/judges/test_vlm_judge.py@@ -28,16 +28,8 @@ def test_full_path_single_sample(judge_input, cache_dir):assert raw["status"] == "ok" and raw["n_used"] == 1 and raw["rubric_hash"] == R.content_hash()assert "[verdict: overall 0.80 vs threshold 0.72 → PASS]" in j.summaryreq = model.requests[0]- assert req.response_schema is not None and "Criteria" in req.response_schema["$defs"]- assert req.label == "judge:static_object:r00:s0" and req.temperature == 0.2- assert len(image_parts(req)) == 3 # 2×2 montage + 2 detail crops- assert "Defects" in req.response_schema["$defs"]+ assert req.label == "judge:static_object:r00:s0" and len(image_parts(req)) == 3 # 2x2 montage + 2 detail cropsassert raw["defects"] == {d.id: False for d in R.defects} and raw["defect_penalty"] == 0.0- # D37: the judge protocol hash is recorded in every verdict, beside (not instead of) the rubric hash- from codeverse3d.judges.prompt_builder import judge_prompt_hash- assert raw["judge_prompt_hash"] == judge_prompt_hash(R) and len(raw["judge_prompt_hash"]) == 12- assert raw["judge_prompt_hash"] != raw["rubric_hash"]- assert _judge(FakeChatModel([]), cache_dir=cache_dir).prompt_hash == judge_prompt_hash(R)@pytest.mark.parametrize("fixed_order", [False, True])@@ -63,14 +55,6 @@ def test_floor_fails_even_if_mean_high(judge_input, cache_dir):assert "floors: intent_fidelity 0.20<0.30" in j.summary-def test_retry_on_parse_failure_then_success(judge_input, cache_dir):- model = FakeChatModel(["not json at all", good_reply(R, IDS, 0.8)])- j = _judge(model, cache_dir=cache_dir).judge(judge_input)- assert j.passed and len(model.requests) == 2- assert model.requests[1].temperature > model.requests[0].temperature # nudged- assert j.usage.cost_usd == pytest.approx(0.002) # failed attempt still charged--@pytest.mark.parametrize(("retryable", "calls"), [(True, 3), (False, 1)])def test_a_failing_model_degrades_the_verdict(judge_input, cache_dir, retryable, calls):model = FakeChatModel(default=ModelError("boom", retryable=retryable))@@ -83,53 +67,6 @@ def test_a_failing_model_degrades_the_verdict(judge_input, cache_dir, retryable,assert json.loads(j.raw)["judge_prompt_hash"] == judge_prompt_hash(R)-def test_base_judge_rejects_measured_rubric(judge_input, cache_dir):- with pytest.raises(ValueError, match="measured criteria"):- VlmJudge("reference", chat_model=FakeChatModel(), cache_dir=cache_dir).judge(judge_input)---# --------------------------------------------------------------- payload size (docs/COST.md §3)-def test_judge_payload_size_comes_from_the_settings_dial(monkeypatch):- """``Settings.judge`` sizes the verdict's images unless the caller states its own (docs/COST.md §3)."""- from codeverse3d.config import Settings, get_settings- from codeverse3d.judges.vlm_judge import VlmJudge-- s = Settings()- monkeypatch.setattr("codeverse3d.judges.vlm_judge.get_settings", lambda: s)- j = VlmJudge(rubric="static_object", model_id="fake:fake-1")- # nothing shrinks the payload (docs/COST.md §14, D47)- assert j.max_px == 1024 and j.detail_crops == 2 and j.max_montages == 5- # a caller that states a size still gets it — the dial is the default, not a cap- explicit = VlmJudge(rubric="static_object", model_id="fake:fake-1", max_px=768, detail_crops=1)- assert explicit.max_px == 768 and explicit.detail_crops == 1- s2 = Settings(judge={"detail_crops": 0, "max_px": 512})- monkeypatch.setattr("codeverse3d.judges.vlm_judge.get_settings", lambda: s2)- assert VlmJudge(rubric="static_object", model_id="fake:fake-1").detail_crops == 0- get_settings.cache_clear()---# ----------------------------------------------------------------------------- D37 judge protocol hash-def test_judge_prompt_hash_tracks_the_protocol_not_the_run(monkeypatch):- from codeverse3d.judges import prompt_builder as pb- from codeverse3d.judges.prompt_builder import judge_prompt_hash- from codeverse3d.judges.rubrics import wire_schema-- base = judge_prompt_hash(R)- assert judge_prompt_hash(R) == base # deterministic- # per-run content (acceptance ids) is NOT part of it: the schema is hashed with no ids- assert wire_schema(R, ["A1"]) != wire_schema(R, []) and judge_prompt_hash(R) == base- # the rubric is part of it (through the rendered rubric block)- other = load_rubric("shader")- assert judge_prompt_hash(other) != base- # an edit to the role prompt or the rig rules changes it — that is the whole point- monkeypatch.setattr(pb, "_ROLE", pb._ROLE + "\nScore generously.")- edited_role = judge_prompt_hash(R)- assert edited_role != base- monkeypatch.setattr(pb, "RIG_RULES", {**pb.RIG_RULES, "object": "All views show the same object."})- assert judge_prompt_hash(R) not in (base, edited_role)---# ---------------------------------------------------------------------- per-sample retry budgetdef test_a_sample_stops_when_its_budget_is_spent(judge_input, cache_dir, monkeypatch):import time as real_timefrom types import SimpleNamespace@@ -166,55 +103,10 @@ def test_a_sample_stops_when_its_budget_is_spent(judge_input, cache_dir, monkeypj = _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_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 (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 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=[])-- assert TRACK_MONTAGE_CAP == {"scene": 4, "graphics": 3}- j = VlmJudge("scene", 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", model_id="fake:fake-1")- assert jo._montages_for(inp(Track.STATIC_OBJECT, Language.BLENDER)) == 5- explicit = VlmJudge("scene", 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", 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", model_id="fake:fake-1")- assert j.thinking == "medium"- assert VlmJudge("scene", 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", 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"+def test_retry_on_parse_failure_then_success(judge_input, cache_dir):+ model = FakeChatModel(["not json at all", good_reply(R, IDS, 0.8)])+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)+ assert j.passed and len(model.requests) == 2 and j.usage.cost_usd == pytest.approx(0.002) # failed attempt still chargeddiff --git a/harness/tests/languages/test_ast_lint.py b/harness/tests/languages/test_ast_lint.pyindex 5cc34754..2670c3b7 100644--- a/harness/tests/languages/test_ast_lint.py+++ b/harness/tests/languages/test_ast_lint.py@@ -1,4 +1,4 @@-"""Shared AST-lint primitives + the per-language forbidden-import supersets (drift guard)."""+"""Shared AST-lint primitives: base-forbidden modules are errors in every language lint."""from __future__ import annotations@@ -7,19 +7,6 @@ import codeverse3d.languages.cadquery as cadquery_lintimport codeverse3d.languages.opengl_python as opengl_lintimport codeverse3d.languages.urdf as urdf_lintfrom codeverse3d.contracts.artifacts import Severity-from codeverse3d.languages._ast_lint import BASE_FORBIDDEN_IMPORTS---def test_language_forbidden_sets_are_supersets_of_base() -> None:- assert BASE_FORBIDDEN_IMPORTS <= blender_lint.FORBIDDEN_IMPORTS- assert BASE_FORBIDDEN_IMPORTS <= cadquery_lint.FORBIDDEN_IMPORTS- assert BASE_FORBIDDEN_IMPORTS <= opengl_lint.DANGEROUS_MODULES- assert "pathlib" in blender_lint.FORBIDDEN_IMPORTS- assert {"os", "sys", "OCP", "build123d"} <= cadquery_lint.FORBIDDEN_IMPORTS- assert {"os", "sys", "time", "datetime", "io", "tempfile", "signal"} <= opengl_lint.DANGEROUS_MODULES- # blender's documented allowance: os/sys stay importable (call rules catch abuse)- assert {"os", "sys"} <= blender_lint.ALLOWED_IMPORTS- assert not ({"os", "sys"} & (blender_lint.FORBIDDEN_IMPORTS | BASE_FORBIDDEN_IMPORTS))def test_base_modules_error_in_every_language_lint() -> None:@@ -43,28 +30,3 @@ def test_base_modules_error_in_every_language_lint() -> None:assert not [f for f in findings if "`os`" in f.message] # the blender language's policy: os/sys allowed-def test_every_python_lint_survives_a_parser_crash(monkeypatch):- """A parser crash (SystemError on 3.11, compare_v4_calm) is a lint ERROR, not a dead round."""- import ast-- from codeverse3d.languages.blender import lint_blender_source- from codeverse3d.languages.cadquery import lint_cadquery_source- from codeverse3d.languages.opengl_python import lint_source as lint_gl- from codeverse3d.languages.urdf import lint_model_text-- real = ast.parse-- def crash(src, *a, **k):- if "DEEP" in src:- raise SystemError("AST constructor recursion depth mismatch (before=54, after=62)")- return real(src, *a, **k)-- monkeypatch.setattr(ast, "parse", crash)- src = "import bpy\nDEEP = 1\n"- for name, run in (("blender", lambda: lint_blender_source(src).findings),- ("cadquery", lambda: lint_cadquery_source("import cadquery as cq\nDEEP = 1\n").findings),- ("opengl", lambda: lint_gl(src)),- ("urdf", lambda: lint_model_text(src, ["base"]))):- findings = run() # must not raise- errs = [f for f in findings if f.severity == Severity.ERROR]- assert errs and "deeper than the parser" in errs[0].message, (name, findings)diff --git a/harness/tests/languages/test_gl_common_entry.py b/harness/tests/languages/test_gl_common_entry.pydeleted file mode 100644index 41007fb3..00000000--- a/harness/tests/languages/test_gl_common_entry.py+++ /dev/null@@ -1,13 +0,0 @@-"""_gl_common.make_host (offline)."""--from __future__ import annotations--from codeverse3d.languages import _gl_common-from codeverse3d.spatial.gl_render import GlHost---def test_make_host_prefers_injected_host() -> None:- injected = GlHost(gpu="off", timeout_s=1.0)- assert _gl_common.make_host(injected, 99.0) is injected- built = _gl_common.make_host(None, 7.5)- assert isinstance(built, GlHost) and built is not injecteddiff --git a/harness/tests/languages/test_missing_entry.py b/harness/tests/languages/test_missing_entry.pyindex 73f3ea66..798bb939 100644--- a/harness/tests/languages/test_missing_entry.py+++ b/harness/tests/languages/test_missing_entry.py@@ -10,10 +10,9 @@ from codeverse3d.contracts.common import ENTRY_FILE, Languagefrom codeverse3d.languages.base import get_runtime[email protected]("language", list(Language))[email protected]("language", [Language.BLENDER, Language.SCENE_THREEJS, Language.URDF_BLENDER])def test_a_missing_entry_is_one_typed_repairable_failure(tmp_ws, language: Language) -> None:- """Regression: a scene with no scene.js was a `scene_probe` harness failure (never repaired)- and urdf a `LintError`; now all seven return MissingEntryFile, as build.json says too."""+ """Regression: a scene with no scene.js was a never-repaired harness failure; all runtimes now return MissingEntryFile."""res = get_runtime(language).build(tmp_ws)assert (res.ok, res.error_type, res.error_file, res.harness_failure) == \(False, "MissingEntryFile", ENTRY_FILE[language], False)diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.pyindex be9d9154..0702baa1 100644--- a/harness/tests/models/test_anthropic.py+++ b/harness/tests/models/test_anthropic.py@@ -6,25 +6,13 @@ import jsonfrom types import SimpleNamespace as NSfrom typing import Any-import httpx-import pytest-from codeverse3d.contracts.chat import (ChatMessage,ChatRequest,- ImagePart,)from codeverse3d.models.anthropic import (AnthropicModel,- build_kwargs,- classify_exception,- to_messages,)-from codeverse3d.models.base import ModelError-from codeverse3d.models.gemini import GeminiModel-from codeverse3d.models.openai import OpenAIModel--PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="def msg(blocks: list[Any], *, stop="end_turn", in_tok=100, out_tok=20, cache_read=0, cache_write=0):@@ -69,20 +57,6 @@ def make(script, model="claude-opus-5-5", **kw):return AnthropicModel(model, client=fc, sleep=lambda s: None, **kw), fc-def api_error(status: int, message: str = "err"):- import anthropic-- req = httpx.Request("POST", "https://api.anthropic.com/v1/messages")- resp = httpx.Response(status, request=req, json={"error": {"message": message}})- cls = {- 429: anthropic.RateLimitError,- 400: anthropic.BadRequestError,- 500: anthropic.InternalServerError,- 529: anthropic.OverloadedError,- }.get(status, anthropic.APIStatusError)- return cls(message, response=resp, body=None)--def test_text_thinking_adaptive_and_usage_cost():m, fc = make([msg([text("hi")], cache_read=30, cache_write=10)])r = m.generate(@@ -109,40 +83,6 @@ def test_text_thinking_adaptive_and_usage_cost():assert abs(u.cost_usd - (400 + 6 + 40 + 400 + 10) / 1e6) < 1e-12-def test_budget_thinking_for_older_models_and_temperature_rules():- kw = build_kwargs(- ChatRequest(- messages=[ChatMessage.user("x")],- thinking="high",- max_output_tokens=2000,- temperature=0.5,- ),- "claude-haiku-4-5",- )- assert (- kw["thinking"] == {"type": "enabled", "budget_tokens": 16000}- and kw["max_tokens"] >= 16000 + 2048- )- assert "temperature" not in kw- kw = build_kwargs(- ChatRequest(messages=[ChatMessage.user("x")], thinking="off", temperature=0.5),- "claude-haiku-4-5",- )- assert "thinking" not in kw and kw["temperature"] == 0.5- kw = build_kwargs(- ChatRequest(messages=[ChatMessage.user("x")], thinking="off"), "claude-opus-4-8"- )- assert kw["thinking"] == {"type": "disabled"}- for always_on in ("claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5"):- kw = build_kwargs(ChatRequest(messages=[ChatMessage.user("x")], thinking="off",- response_schema={"type": "object"}), always_on)- assert "thinking" not in kw and kw["output_config"] == {"effort": "low"}, always_on- assert "tool_choice" not in kw, always_on # forced tool use is a 400 on these- kw = build_kwargs(ChatRequest(messages=[ChatMessage.user("x")], thinking="high", temperature=0.5),- "claude-haiku-5-5")- assert kw["thinking"] == {"type": "adaptive"} and "temperature" not in kw--def test_structured_output_via_forced_submit_tool():schema = {"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"]}# haiku-5.5 can still turn thinking off and force a tool (opus-5.5 / sonnet-5.5 / fable cannot)@@ -157,80 +97,3 @@ def test_structured_output_via_forced_submit_tool():kw["tools"][0]["name"] == "submit"and kw["tools"][0]["input_schema"]["additionalProperties"] is False)- # with thinking on, a forced tool is refused: tool_choice is auto and the text is parsed- m, fc = make([msg([text('```json\n{"b": 2}\n```')])])- r = m.generate(- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"}, thinking="low")- )- assert r.parsed == {"b": 2}- kw = fc.calls[0]- assert "tool_choice" not in kw and "submit" in kw["system"]---def test_images_base64_message_merging_and_user_first():- msgs = to_messages(- [- ChatMessage.user(- "a", images=[ImagePart(data_b64=PNG_B64, mime="image/png", label="L")]- ),- ChatMessage.user("b"),- ]- )- assert len(msgs) == 1 and [b["type"] for b in msgs[0]["content"]] == [- "text",- "text",- "image",- "text",- ]- assert msgs[0]["content"][2]["source"]["media_type"] == "image/png"- msgs = to_messages([ChatMessage.assistant("hi")]) # assistant first gets a user prefix- assert msgs[0]["role"] == "user" and msgs[1]["role"] == "assistant"---def test_classify_connection_errors():- import anthropic-- req = httpx.Request("POST", "https://api.anthropic.com")- assert classify_exception(anthropic.APITimeoutError(request=req)).retryable- assert classify_exception(anthropic.APIConnectionError(request=req)).retryable- assert not classify_exception(RuntimeError("x")).retryable---def test_missing_key_is_loud(monkeypatch):- monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)- from codeverse3d.config import get_settings-- get_settings.cache_clear()- m = AnthropicModel("claude-opus-5-5")- if not get_settings().anthropic_api_key:- with pytest.raises(ModelError):- m.client()- get_settings.cache_clear()---def test_a_failed_reply_carries_what_it_was_billed():- """A refusal / bad-JSON / empty reply is billed on the error (D84)."""- for script, req in (- ([msg([], stop="refusal")], ChatRequest(messages=[ChatMessage.user("x")])),- (- [msg([text("not json")], stop="max_tokens")],- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"}),- ),- ([msg([], stop="end_turn")] * 6, ChatRequest(messages=[ChatMessage.user("x")])),- ):- m, _ = make(script)- with pytest.raises(ModelError) as e:- m.generate(req)- assert e.value.usage.input_tokens == 100 and e.value.usage.output_tokens == 20---[email protected]("make", [- lambda: AnthropicModel("claude-opus-5-5"),- lambda: OpenAIModel("gpt-x"),- lambda: GeminiModel("g", keys=["k"]),-], ids=["anthropic", "openai", "gemini"])-def test_every_api_adapter_reads_model_timeout_s(make, switch):- """N73: ``C3D_MODEL_TIMEOUT_S`` reached Gemini only; anthropic/openai sat on a 600 s literal."""- switch("C3D_MODEL_TIMEOUT_S", "2000")- assert make().timeout_s == 2000.0diff --git a/harness/tests/models/test_control_chars.py b/harness/tests/models/test_control_chars.pyindex 118b26a1..2e21b29e 100644--- a/harness/tests/models/test_control_chars.py+++ b/harness/tests/models/test_control_chars.py@@ -20,18 +20,6 @@ def test_the_plan_that_killed_a_cell_now_parses_clean():# a space, never deletion: "0.078" and "0.300" must not fuse into "0.0780.300"assert out["summary"] == "Overall envelope is 0.078 0.300 0.240 m"assert out["acceptance"][0]["text"] == "height is 0.240 m 0.005 m"- # what the plan meant to say, and the code a model writes, pass through untouched- for safe in ("def f():\n\tx = 1\r\n", "0.078 × 0.300 m ± 0.005 — café 日本語 🔧"):- assert strip_control_chars(safe) == safe---def test_the_subprocess_backstop_names_the_offender(tmp_path):- import pytest-- from codeverse3d.agents.cli_common import run_with_watchdog-- poisoned = "harness_instructions: envelope is 0.078 \x00 0.300 m"- with pytest.raises(ValueError, match=r"argv\[2\] contains a NUL at offset \d+"):- run_with_watchdog(["echo", "ok", poisoned], cwd=tmp_path, env=None, soft_timeout_s=5)+ assert strip_control_chars("def f():\n\tx = 1\r\n 0.078 × 0.300 m ± 0.005 日本語") == "def f():\n\tx = 1\r\n 0.078 × 0.300 m ± 0.005 日本語"diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.pyindex 82845818..60363433 100644--- a/harness/tests/models/test_gemini.py+++ b/harness/tests/models/test_gemini.py@@ -2,7 +2,6 @@from __future__ import annotations-import base64from typing import Anyimport pytest@@ -12,21 +11,14 @@ from google.genai import typesfrom codeverse3d.contracts.chat import (ChatMessage,ChatRequest,- ImagePart,- TextPart,)from codeverse3d.models.base import ModelErrorfrom codeverse3d.models.gemini import (GeminiModel,classify_exception,- to_contents,)from codeverse3d.models.retry import KeyPool, failure_outcome-from codeverse3d.tracks.planner import _truncated-PNG_1PX = base64.b64decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="-)def text_response(text: str, *, finish: str = "STOP", thoughts: int = 3@@ -154,105 +146,6 @@ def test_thinking_rejected_falls_back_without_thinking_config():assert r.text == "ok"assert log[0]["config"].thinking_config is not None and log[1]["config"].thinking_config is Noneassert any("thinking" in w for w in r.raw["warnings"])- # sticky for the next call- log.clear()- m._client_factory = lambda key: FakeClient([text_response("again")], key, log)- m.generate(ChatRequest(messages=[ChatMessage.user("y")]))- assert log[0]["config"].thinking_config is None---def test_images_inline_in_order(tmp_path):- p = tmp_path / "img.png"- p.write_bytes(PNG_1PX)- m, log, _ = make_model([text_response("red")])- msg = ChatMessage.user(- "look",- images=[- ImagePart(path=str(p), label="view1"),- ImagePart(data_b64=base64.b64encode(PNG_1PX).decode(), mime="image/png"),- ],- )- m.generate(ChatRequest(messages=[msg]))- parts = log[0]["contents"][0].parts- kinds = [("img" if pt.inline_data else "txt") for pt in parts]- assert kinds == ["txt", "txt", "img", "img"]- assert parts[2].inline_data.data == PNG_1PX and parts[2].inline_data.mime_type == "image/png"---def test_missing_image_is_loud():- m, _, _ = make_model([text_response("x")])- with pytest.raises(ModelError):- m.generate(- ChatRequest(- messages=[ChatMessage.user("look", images=[ImagePart(path="/nonexistent.png")])]- )- )---def test_empty_candidates_and_blocked_prompt():- empty = types.GenerateContentResponse(candidates=[], usage_metadata=None)- m, log, _ = make_model([empty, text_response("ok")])- assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"- blocked = types.GenerateContentResponse(- candidates=[],- prompt_feedback=types.GenerateContentResponsePromptFeedback(block_reason="SAFETY"),- )- m2, log2, _ = make_model([blocked, text_response("never")])- with pytest.raises(ModelError) as ei:- m2.generate(ChatRequest(messages=[ChatMessage.user("x")]))- assert not ei.value.retryable and len(log2) == 1---def test_classify_exception_transport():- import httpx-- assert classify_exception(httpx.ReadTimeout("t")).retryable- assert classify_exception(httpx.ConnectError("c")).retryable- assert not classify_exception(ValueError("v")).retryable- # one status table with the SDK adapters (N76): a 409 is retried and is an outage, a 400 is neither- from codeverse3d.tracks.generation import is_model_outage-- for code, retry in ((409, True), (408, True), (429, True), (529, True), (400, False), (404, False)):- err = classify_exception(_api_error(code, "x", "X"))- assert (err.retryable, is_model_outage(err)) == (retry, retry), code---def test_to_contents_merges_same_role_and_requires_content():- msgs = [- ChatMessage.user("a"),- ChatMessage(role="user", parts=[TextPart(text="b")]),- ChatMessage.assistant("c"),- ]- c = to_contents(msgs)- assert [x.role for x in c] == ["user", "model"] and len(c[0].parts) == 2- with pytest.raises(ModelError):- to_contents([ChatMessage(role="user", parts=[])])---def test_no_keys_is_loud():- with pytest.raises(ModelError):- GeminiModel("gemini-3.8-flash", keys=[])---def test_max_token_failures_are_not_retried():- cases = (- (- text_response('{"a": [1, 2', finish="MAX_TOKENS"),- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"}),- "max_output_tokens",- ),- (- text_response("", finish="MAX_TOKENS", thoughts=49),- ChatRequest(messages=[ChatMessage.user("x")], max_output_tokens=50),- "thinking",- ),- )- for response, request, message in cases:- model, log, _ = make_model([response, text_response("never")])- with pytest.raises(ModelError) as error:- model.generate(request)- assert not error.value.retryable and len(log) == 1- assert message in str(error.value)def test_a_charged_but_invalid_reply_carries_its_usage_on_the_error():@@ -266,93 +159,3 @@ def test_a_charged_but_invalid_reply_carries_its_usage_on_the_error():assert ei.value.usage.cost_usd > 0-def test_max_output_tokens_eaten_by_thinking_carries_the_thought_tokens():- """A MAX_TOKENS failure reports the thinking tokens it consumed."""- resp = types.GenerateContentResponse(- model_version="gemini-3.8-flash",- candidates=[- types.Candidate(- content=types.Content(role="model", parts=[]), finish_reason="MAX_TOKENS"- )- ],- usage_metadata=types.GenerateContentResponseUsageMetadata(- prompt_token_count=1000, candidates_token_count=0, thoughts_token_count=8000- ),- )- m, _log, _ = make_model([resp])- with pytest.raises(ModelError) as e:- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))- assert "exhausted by thinking" in str(e.value)- assert _truncated(e.value), "the planner's grow-the-budget retry must fire on exactly this case"- assert e.value.usage.thoughts_tokens == 8000 and e.value.usage.cost_usd > 0---# --------------------------------------------------------------------- streaming-def test_merge_stream_chunks_empty_stream_is_retryable():- from codeverse3d.models.gemini import _merge_stream_chunks-- with pytest.raises(ModelError) as e:- _merge_stream_chunks([])- assert e.value.retryable---def test_drain_stream_cuts_a_stream_past_its_attempt_budget():- """The attempt deadline also bounds a healthy but endless stream."""- from codeverse3d.models.gemini import _drain_stream-- ticks = iter([1.0, 10.0, 20.0])- chunk = types.GenerateContentResponse(candidates=[])- with pytest.raises(ModelError) as e:- _drain_stream(iter([chunk, chunk, chunk]), deadline=5.0, clock=lambda: next(ticks))- assert e.value.retryable and "attempt budget" in str(e.value)--[email protected](("raw", "streamed"), [(None, True), ("off", False)]) # spellings: test_config_env_aliases-def test_streaming_toggle(monkeypatch, switch, raw, streamed):- """``C3D_STREAM=off`` was silently ignored until 2026-09-22: only "0" was read."""- switch("C3D_STREAM", raw)- calls: list[int] = []- real = FakeModels.generate_content_stream- monkeypatch.setattr(FakeModels, "generate_content_stream", lambda self, **kw: (calls.append(1), real(self, **kw))[1])- m, _log, _ = make_model([text_response("hi")])- assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "hi"- assert bool(calls) is streamed--[email protected](("raw", "bound"), [(None, True), ("off", False)]) # spellings: test_config_env_aliases-def test_ipv4_transport_toggle(switch, raw, bound):- """``C3D_IPV4=off`` was silently ignored until 2026-09-22: only "0" restored dual-stack."""- import httpx-- from codeverse3d.models.gemini import _ipv4_client_args-- switch("C3D_IPV4", raw)- assert isinstance(_ipv4_client_args().get("transport"), httpx.HTTPTransport) is bound---def test_merge_stream_chunks_concatenates_text_and_keeps_final_usage():- """Stream merging concatenates text parts in order; usage comes from the final chunk."""- from codeverse3d.models.gemini import _merge_stream_chunks, extract_candidate-- c1 = types.GenerateContentResponse(- candidates=[- types.Candidate(- content=types.Content(role="model", parts=[types.Part.from_text(text="hel")])- )- ]- )- c2 = types.GenerateContentResponse(- candidates=[- types.Candidate(- content=types.Content(role="model", parts=[types.Part.from_text(text="lo")]),- finish_reason="STOP",- )- ],- usage_metadata=types.GenerateContentResponseUsageMetadata(- prompt_token_count=9, candidates_token_count=4- ),- )- merged = _merge_stream_chunks([c1, c2])- text, finish = extract_candidate(merged)- assert text == "hello" and finish == "STOP"- assert merged.usage_metadata.prompt_token_count == 9diff --git a/harness/tests/models/test_gemini_scheduling.py b/harness/tests/models/test_gemini_scheduling.pyindex 2558dd0c..f3481dcc 100644--- a/harness/tests/models/test_gemini_scheduling.py+++ b/harness/tests/models/test_gemini_scheduling.py@@ -18,27 +18,6 @@ def api_error(code: int, msg: str = "boom") -> genai_errors.APIError:return genai_errors.APIError(code, {"error": {"message": msg, "code": code}})-# ------------------------------------------------ retry budget + hedge (audit 2026-08-26 §5.1 / §5.2)-def test_max_wait_s_clips_the_retry_deadline_and_never_extends_it(monkeypatch):- """ChatRequest.max_wait_s clips the model's retry deadline, never raises it."""- import codeverse3d.models.gemini as gm- from codeverse3d.models.retry import RETRY_DEADLINE_S-- seen: list[float] = []- real = gm.rotate_with_retries-- def spy(pool, call, **kw):- seen.append(kw["max_total_s"])- return real(pool, call, **kw)-- monkeypatch.setattr(gm, "rotate_with_retries", spy)- m, _log, _ = make_model([text_response("a"), text_response("b"), text_response("c")])- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=30))- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5000))- assert seen == [RETRY_DEADLINE_S, 30.0, RETRY_DEADLINE_S]--def test_a_recovered_call_reports_its_attempts_and_a_failed_call_carries_its_count():hedged, log, _ = make_model([api_error(503), api_error(503), text_response("recovered")],@@ -58,21 +37,3 @@ def test_a_recovered_call_reports_its_attempts_and_a_failed_call_carries_its_couassert ei.value.attempts == 1, "the ledger's error row gets the count too"-# ------------------------------------------ per-attempt HTTP timeout (audit 2026-08-27)-def test_retry_budget_bounds_http_timeout_without_raising_an_explicit_ceiling():- from codeverse3d.models.parts import SDK_TIMEOUT_FLOOR_S-- m, log, _ = make_model(- [text_response("a"), text_response("b"), text_response("c")], timeout_s=300.0- )- m.generate(ChatRequest(messages=[ChatMessage.user("x")]))- assert (- log[0]["config"].http_options.timeout == 300_000- ) # plenty of budget: the full read timeout- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=60))- assert 55_000 <= log[1]["config"].http_options.timeout <= 60_000- m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5))- assert log[2]["config"].http_options.timeout == int(SDK_TIMEOUT_FLOOR_S * 1000)- small, small_log, _ = make_model([text_response("d")], timeout_s=8.0)- small.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5))- assert small_log[0]["config"].http_options.timeout == 8_000diff --git a/harness/tests/models/test_health.py b/harness/tests/models/test_health.pyindex a0f305ab..b4b20d16 100644--- a/harness/tests/models/test_health.py+++ b/harness/tests/models/test_health.py@@ -2,43 +2,6 @@from __future__ import annotations-from codeverse3d.models.health import DEFAULT_MIN_OK, Health---def test_health_threshold_requires_a_real_success_rate_and_names_the_reason():- for n_ok, n_tried, expected in (- (6, 6, True),- (3, 4, True),- (2, 4, False),- (4, 6, False),- (1, 4, False),- (0, 0, False),- ):- assert Health("m", n_ok=n_ok, n_tried=n_tried).ok is expected, (- f"{n_ok}/{n_tried}; threshold={DEFAULT_MIN_OK:.0%}"- )- # the doctor line carries the provider's reason- h = Health(- "gemini:gemini-3.8-flash",- n_ok=0,- n_tried=4,- reasons=("ModelError: Gemini API error 504: Deadline expired",),- )- text = str(h)- assert "0/4" in text and "504" in text, text---def test_the_probe_prompt_is_the_size_of_real_work():- """A five-token probe answers when a 12 k-token planner call does not."""- from codeverse3d.models.health import PROBE_TOKENS, _probe_prompt-- prompt = _probe_prompt()- approx_tokens = len(prompt) // 4- assert approx_tokens > 0.5 * PROBE_TOKENS, f"probe is only ~{approx_tokens} tokens"- assert "pong" in prompt, (- "the answer must still be one word, so the probe costs input not output"- )-def test_probe_never_raises_when_every_call_fails(monkeypatch):import codeverse3d.models.health as healthdiff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.pyindex 12f8110c..07b59924 100644--- a/harness/tests/models/test_keypool.py+++ b/harness/tests/models/test_keypool.py@@ -2,11 +2,9 @@from __future__ import annotations-import time-import pytest-from codeverse3d.models.retry import MAX_WAIT_S, KeyPool, KeyPoolExhausted+from codeverse3d.models.retry import KeyPool, KeyPoolExhaustedclass Clock:@@ -25,28 +23,6 @@ def make(keys=("k1", "k2", "k3"), **kw) -> tuple[KeyPool, Clock]:return KeyPool(list(keys), clock=c, sleep=c.sleep, **kw), c-def test_dedupes_and_rejects_empty():- pool, _ = make(keys=("a", "a", "", "b"))- assert pool.keys == ["a", "b"]- with pytest.raises(ValueError):- KeyPool([])---def test_all_cooling_blocks_until_cooldown_ends():- # a cooldown longer than the house cap is clipped to it: no single wait may- # exceed MAX_WAIT_S, patience comes from the number of attempts- pool, clock = make(keys=("a", "b"), cooldown_s=5)- for k in ("a", "b"):- pool.report(k, "429")- t0 = clock.t- assert pool.acquire(timeout_s=60) in ("a", "b")- assert MAX_WAIT_S - 1e-6 <= clock.t - t0 <= 5 + 1e-6- pool.report("a", "429")- pool.report("b", "429")- with pytest.raises(KeyPoolExhausted):- pool.acquire(timeout_s=1.0)--def test_dead_key_is_benched_for_an_hour_and_all_dead_raises_at_once():pool, clock = make(keys=("dead", "ok"), cooldown_s=30, dead_cooldown_s=3600)pool.report("dead", "dead")@@ -88,59 +64,8 @@ def test_try_acquire_never_waits_for_a_key_or_a_slot(tmp_path):assert pool.stats()["in_flight"] == 0, "a refused try_acquire holds nothing"-def test_the_in_flight_slot_wait_is_bounded_and_a_failed_acquire_gives_it_back(tmp_path):- pool = KeyPool(["a"], max_in_flight=1, slots_dir=tmp_path)- pool.acquire()- t0 = time.monotonic()- with pytest.raises(KeyPoolExhausted):- pool.acquire(timeout_s=0.05)- assert time.monotonic() - t0 < 2.0, "the slot wait must honour the timeout"- pool.release()- assert pool.acquire(timeout_s=0.5) == "a", "the slot came back; nothing leaked"- pool.release()- for _ in range(3): # KeyPoolExhausted must not leak a concurrency slot either- with pytest.raises(KeyPoolExhausted):- pool.acquire(exclude={"a"}, timeout_s=0.0)- assert pool.acquire(timeout_s=0.0) == "a" # the slot is still free---def test_a_capped_pool_names_its_slot_directory_and_a_session_key_takes_no_slot(tmp_path):- """The slots are machine-wide lock files, so a cap without a directory is refused rather- than silently becoming a per-process cap; a vendor CLI session picks a key (rotation and- cooldowns included) but holds no slot and has nothing to release."""- with pytest.raises(ValueError, match="slots_dir"):- KeyPool(["a"], max_in_flight=1)- pool = KeyPool(["a", "b"], max_in_flight=1, slots_dir=tmp_path)- assert pool.acquire(timeout_s=0.0) == "a"- assert pool.session_key(timeout_s=0.0) == "b", "the only slot is held, a session still gets a key"- pool.report("a", "429")- assert pool.session_key(timeout_s=0.0) == "b", "and it skips a cooling key like acquire does"- assert pool.stats()["in_flight"] == 1 and pool.slots.busy() == 1- pool.release()- assert pool.stats()["in_flight"] == 0 and pool.slots.busy() == 0---def test_the_rotation_starts_where_it_is_told_and_the_shared_pool_starts_anywhere(monkeypatch, tmp_path):- """Parallel ``3dcode make`` processes make the same calls in the same order: every pool- starting at key 0 put four runs' planner calls on one key (live, 2026-10-13)."""- from codeverse3d.config import get_settings- from codeverse3d.models import gemini-- pool, _ = make(start=4)- assert [pool.session_key() for _ in range(3)] == ["k2", "k3", "k1"]- monkeypatch.setattr(get_settings(), "cache_dir", tmp_path)- firsts = set()- for _ in range(40):- gemini._pools.clear()- firsts.add(gemini.shared_pool([f"s{j}" for j in range(12)], max_in_flight=0).session_key())- assert len(firsts) > 3- gemini._pools.clear()--def test_a_session_lease_keeps_one_session_per_key_across_pools_until_keys_run_out(tmp_path):- """Two pools stand in for two ``3dcode make`` processes: each session leases a key no- other live session holds; with every key leased the next one shares (lease ``None``);- closing a lease frees its key for the next session."""+ """Two pools = two processes: each leases a key no other live session holds; all leased -> shared (None)."""a, _ = make(keys=("k1", "k2"))b, _ = make(keys=("k1", "k2"))k1, l1 = a.lease_session_key(tmp_path)diff --git a/harness/tests/models/test_live_gemini.py b/harness/tests/models/test_live_gemini.pydeleted file mode 100644index e3d46fdc..00000000--- a/harness/tests/models/test_live_gemini.py+++ /dev/null@@ -1,82 +0,0 @@-"""Live Gemini checks (need keys + network): ``pytest -m live tests/models``."""--from __future__ import annotations--import pytest--from codeverse3d.contracts.chat import (- ChatMessage,- ChatRequest,- ImagePart,-)-from codeverse3d.contracts.plan import StaticPlan-from codeverse3d.models import get_chat_model--pytestmark = pytest.mark.live--MODEL = "gemini:gemini-3.8-flash"--[email protected](scope="module")-def model():- from codeverse3d.config import get_settings-- if not get_settings().gemini_api_keys:- pytest.skip("no gemini keys")- return get_chat_model(MODEL)---def test_text(model):- r = model.generate(- ChatRequest(- messages=[ChatMessage.user("Reply with exactly: pong")],- thinking="off",- max_output_tokens=200,- )- )- assert "pong" in r.text.lower()- assert r.usage.input_tokens > 0 and r.usage.output_tokens > 0 and r.usage.cost_usd > 0- assert r.finish_reason == "STOP"---def test_structured_static_plan(model):- r = model.generate(- ChatRequest(- messages=[- ChatMessage.user(- "Plan 'a simple wooden stool' (round seat, 4 legs, ring stretcher). Z-up, meters, stands on ground. PascalCase part names; attach_to names another part."- )- ],- system="You are a 3D planner. Output JSON matching the schema only.",- response_schema=StaticPlan.model_json_schema(),- temperature=0.4,- thinking="medium",- max_output_tokens=8000,- label="planner",- )- )- plan = StaticPlan.model_validate(r.parsed)- assert len(plan.parts) >= 3 and plan.overall_bbox.extents[2] > 0- assert r.usage.thoughts_tokens >= 0 and r.usage.cost_usd > 0---def test_vision(model, tmp_path):- from PIL import Image, ImageDraw-- img = Image.new("RGB", (128, 128), "white")- ImageDraw.Draw(img).ellipse((24, 24, 104, 104), fill="red")- p = tmp_path / "red.png"- img.save(p)- r = model.generate(- ChatRequest(- messages=[- ChatMessage.user(- "What colour is the shape? One word.",- images=[ImagePart(path=str(p), label="probe")],- )- ],- thinking="off",- max_output_tokens=200,- )- )- assert "red" in r.text.lower()diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.pyindex 4580f6b4..2a29e1f1 100644--- a/harness/tests/models/test_openai.py+++ b/harness/tests/models/test_openai.py@@ -6,20 +6,12 @@ from types import SimpleNamespace as NSfrom typing import Anyimport httpx-import pytest-from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart-from codeverse3d.models.base import ModelError+from codeverse3d.contracts.chat import ChatMessage, ChatRequestfrom codeverse3d.models.openai import (OpenAIModel,- build_kwargs,- classify_exception,- reasoning_effort,- to_messages,)-PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="-def completion(content: str | None,@@ -105,19 +97,6 @@ def test_text_reasoning_effort_usage_cost():assert abs(u.cost_usd - (160 + 2 + 300) / 1e6) < 1e-12-def test_reasoning_effort_mapping_and_temperature_for_non_reasoning():- assert reasoning_effort("gpt-6.1-sol", "off") == "low" # gpt-6 rejects "none" / "minimal"- assert reasoning_effort("gpt-6-astra", "off") == "low"- assert reasoning_effort("gpt-6.1-sol", "medium") == "medium"- assert reasoning_effort("gpt-x", "high") is None- kw = build_kwargs(- ChatRequest(messages=[ChatMessage.user("x")], temperature=0.1),- "gpt-x",- strict_schema=False,- )- assert kw["temperature"] == 0.1 and "reasoning_effort" not in kw--def test_json_schema_strict_then_fallback_to_non_strict():schema = {"type": "object",@@ -142,68 +121,3 @@ def test_json_schema_strict_then_fallback_to_non_strict():and set(first["schema"]["required"]) == {"a", "b"})assert second["strict"] is False and second["schema"]["required"] == ["a"]- # sticky: later calls go straight to strict=false- fc.script.append(completion('{"a": 2}'))- m.generate(ChatRequest(messages=[ChatMessage.user("y")], response_schema=schema))- assert fc.calls[2]["response_format"]["json_schema"]["strict"] is False---def test_images_data_urls():- msgs = to_messages(- [- ChatMessage.user(- "look", images=[ImagePart(data_b64=PNG_B64, mime="image/png", label="v")]- )- ],- "",- )- c = msgs[0]["content"]- assert [b["type"] for b in c] == ["text", "text", "image_url"]---def test_bad_json_and_empty_replies_are_retried_and_classify():- import openai-- m, fc = make([completion("garbage"), completion('{"ok": 1}')])- r = m.generate(- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})- )- assert r.parsed == {"ok": 1} and len(fc.calls) == 2- m, fc = make([completion(None), completion("ok")])- assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"- req = httpx.Request("POST", "https://api.openai.com")- assert classify_exception(openai.APITimeoutError(request=req)).retryable- assert not classify_exception(KeyError("k")).retryable---def test_base_url_from_settings(monkeypatch):- from codeverse3d.config import get_settings-- monkeypatch.setenv("C3D_OPENAI_BASE_URL", "http://localhost:8000/v1")- monkeypatch.delenv("OPENAI_API_KEY", raising=False)- get_settings.cache_clear()- try:- m = OpenAIModel("local-model")- c = m.client()- assert str(c.base_url).startswith("http://localhost:8000/v1")- finally:- get_settings.cache_clear()---def test_a_failed_reply_carries_what_it_was_billed():- """A bad-JSON or empty completion is billed on the error, reasoning split out (D84)."""- for script, req in (- (- [completion("not json", finish="length")],- ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"}),- ),- (- [completion(None, finish="content_filter")],- ChatRequest(messages=[ChatMessage.user("x")]),- ),- ):- m, _ = make(script)- with pytest.raises(ModelError) as e:- m.generate(req)- u = e.value.usage- assert u.input_tokens == 100 and u.output_tokens == 20 and u.thoughts_tokens == 10diff --git a/harness/tests/models/test_pricing.py b/harness/tests/models/test_pricing.pyindex fe29139e..ab662cb7 100644--- a/harness/tests/models/test_pricing.py+++ b/harness/tests/models/test_pricing.py@@ -10,14 +10,6 @@ from codeverse3d.contracts.common import Usagefrom codeverse3d.models.pricing import PRICES, estimate_cost, lookup_price, unit_prices-def test_gemini_cost_math():- u = Usage(- input_tokens=1_000_000, cached_tokens=400_000, output_tokens=100_000, thoughts_tokens=50_000- )- # 600k*0.75 + 400k*0.075 + 150k*3.75 (per 1M)- assert abs(estimate_cost("gemini", "gemini-3.8-flash", u) - (0.45 + 0.03 + 0.5625)) < 1e-9--def test_astra_prices_cached_input_reasoning_and_its_strict_long_prompt_tier():"""A live codex pilot ran gpt-6-astra unpriced (2026-09-23)."""usage = Usage(input_tokens=100_000, cached_tokens=80_000, output_tokens=4_000, thoughts_tokens=6_000)@@ -33,17 +25,8 @@ def test_astra_prices_cached_input_reasoning_and_its_strict_long_prompt_tier():("provider", "model", "row"),[("anthropic", "claude-opus-5-5-20260301", "claude-opus-5-5"),- ("anthropic", "claude-sonnet-5-5@20260301", "claude-sonnet-5-5"),- ("anthropic", "claude-haiku-4-5-20251001", "claude-haiku-4-5"),- ("openai", "gpt-6.1-sol-2026", "gpt-6.1-sol"),- ("openai", "gpt-6-sol", "gpt-6-sol"),("gemini", "gemini-3.8-flash-preview-09", "gemini-3.8-flash"),- ("gemini", "gemini-3.8-flash-latest", "gemini-3.8-flash"),- ("gemini", "gemini-2.5-flash-preview-05", "gemini-2.5-flash"),- # agy's effort-suffixed ids (every agy session was priced $0 until 2026-09-23)("gemini", "gemini-3.8-flash-medium", "gemini-3.8-flash"),- ("gemini", "gemini-3.8-flash-high", "gemini-3.8-flash"),- ("openai", "gpt-6-astra-2026-09-01", "gpt-6-astra"),],)def test_a_dated_or_tagged_id_prices_on_its_family_row(provider, model, row):@@ -54,12 +37,7 @@ def test_a_dated_or_tagged_id_prices_on_its_family_row(provider, model, row):("provider", "model"),[("openai", "gpt-55"),- ("openai", "gpt-5.7"), # ".7" is a different minor version, not a date tag- ("gemini", "gemini-3.8-flash-lite"),("anthropic", "claude-opus-5-5-turbo"),- ("anthropic", "claude-opus-5"), # an older generation is no longer priced- ("openai", "gpt-6.1-sol-mini"),- ("openai", "gpt-6-astra-mini"),],)def test_a_different_family_is_unpriced_and_warned(provider, model, caplog):diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.pyindex f258729a..8b75d25e 100644--- a/harness/tests/models/test_retry.py+++ b/harness/tests/models/test_retry.py@@ -21,13 +21,6 @@ from codeverse3d.models.retry import ()-def test_backoff_grows_and_caps():- d = [backoff_delay(i, base_delay=1.0, max_delay=8.0, jitter=False) for i in range(1, 7)]- assert d == [1.0, 2.0, 4.0, 8.0, 8.0, 8.0]- j = backoff_delay(3, base_delay=1.0, max_delay=8.0)- assert 2.0 <= j <= 4.0--# --------------------------------------------------------------------------- rotate_with_retriesdef _classify(exc: BaseException) -> ModelError:if isinstance(exc, ModelError):@@ -108,46 +101,6 @@ def test_rotate_every_key_dead_raises_without_benching():assert pool.stats()["dead"] == 0 # the request, not the keys, is suspect-# --------------------------------------------------------------------------- 503 storms[email protected](("hedge", "want_calls", "want_naps"), [(1, {9}, 7), (2, {9, 10}, 4)])-def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):- """A 503 storm gets a separate budget; hedging reduces its waits."""- lock = threading.Lock()- calls = {"n": 0}- naps: list[float] = []-- def call(key):- with lock:- calls["n"] += 1- n = calls["n"]- if n <= 8: # longer than max_attempts=3 could survive- raise RuntimeError("503 storm")- return "ok"-- out = _rotate503(- _pool(2),- call,- max_attempts=3,- base_delay=0.01,- storm_attempts=10,- storm_max_delay=0.05,- sleep=naps.append,- hedge=hedge,- )- assert out == "ok" and calls["n"] in want_calls- # the first 503 rotates to k2 for free (no nap); k2's 503 leaves no untried key in the- # 2-key pool, so that one is the storm- assert len(naps) == want_naps and all(d <= 0.05 for d in naps) # the cap is the cap---def test_storm_waits_never_exceed_the_house_limit_at_production_defaults(monkeypatch):- monkeypatch.setattr(random, "random", lambda: 1.0)- naps: list[float] = []- with pytest.raises(ModelError):- _rotate503(_pool(2), _boom(), max_attempts=2, storm_attempts=12, sleep=naps.append)- assert naps and max(naps) == MAX_WAIT_S--def test_one_call_cannot_retry_for_hours():"""The wall-clock deadline bounds even a long 503 storm."""clock = Clock()@@ -170,35 +123,7 @@ def test_one_call_cannot_retry_for_hours():)# bounded by the clock: the ONLY legal overshoot is the one floored attempt that was# already in flight when the deadline passed- assert clock.t <= RETRY_DEADLINE_S + SDK_TIMEOUT_FLOOR_S, (- f"one call burned {clock.t / 3600:.2f} h; the deadline is {RETRY_DEADLINE_S / 60:.0f} min"- )- assert clock.t < 5 * 3600, "this is the 5.1-hour regression"---def test_the_deadline_does_not_cut_a_call_that_is_making_progress():- """A slow-but-succeeding call must not be killed by the retry deadline."""- clock = Clock()- calls = {"n": 0}-- def call(_key):- calls["n"] += 1- clock.t += 280.0 # slow, but under the per-attempt timeout- if calls["n"] < 3:- raise RuntimeError("503 high demand")- return "ok"-- # hedge=1: serial fake clock and call counter (see the hedge tests for the raced form)- out = _rotate503(- _pool(2),- call,- max_attempts=6,- storm_attempts=60,- sleep=clock.sleep,- monotonic=clock,- hedge=1,- )- assert out == "ok" and calls["n"] == 3+ assert clock.t <= RETRY_DEADLINE_S + SDK_TIMEOUT_FLOOR_S, "the 5.1-hour regression"# --------------------------------------------------------------------------- hedging (audit 2026-08-26 §5.2)@@ -256,40 +181,45 @@ def test_after_the_first_503_the_next_attempt_is_hedged_and_the_first_success_wiassert st["5xx"] == 2 and st["in_flight"] == 0, "the loser's 503 is reported when it lands"-def test_the_worst_error_decides_a_hedged_attempt():- """A nonretryable hedge error outranks a sibling 503."""- pool = _pool(3)- stats: dict = {}[email protected](("hedge", "want_calls", "want_naps"), [(1, {9}, 7), (2, {9, 10}, 4)])+def test_503_storm_has_its_own_patience_budget(hedge, want_calls, want_naps):+ """A 503 storm gets a separate budget; hedging reduces its waits."""+ lock = threading.Lock()+ calls = {"n": 0}+ naps: list[float] = []def call(key):- if key == "k3":- raise ModelError("bad request", retryable=False, status=400)- raise ModelError("503 high demand", retryable=True, status=503)-- with pytest.raises(ModelError) as ei:- _rotate(pool, call, max_attempts=6, storm_attempts=10, stats=stats)- assert ei.value.status == 400 and stats == {"attempts": 3, "hedged": 1, "storm": 0}-+ with lock:+ calls["n"] += 1+ n = calls["n"]+ if n <= 8: # longer than max_attempts=3 could survive+ raise RuntimeError("503 storm")+ return "ok"-# --------------------------------------------------------------------------- deadline threading (2026-08-27)-def test_free_429_rotation_cannot_outlive_the_deadline():- """Free key rotation still consumes wall-clock budget."""- clock = Clock()- pool = _pool(10, cooldown_s=0.0, clock=clock, sleep=clock.sleep)- calls: list[str] = []+ out = _rotate503(+ _pool(2),+ call,+ max_attempts=3,+ base_delay=0.01,+ storm_attempts=10,+ storm_max_delay=0.05,+ sleep=naps.append,+ hedge=hedge,+ )+ assert out == "ok" and calls["n"] in want_calls+ # the first 503 rotates to k2 for free (no nap); k2's 503 leaves no untried key in the+ # 2-key pool, so that one is the storm+ assert len(naps) == want_naps and all(d <= 0.05 for d in naps) # the cap is the cap- def call(key):- calls.append(key)- raise ModelError("quota", retryable=True, status=429)- with pytest.raises(ModelError) as ei:- _rotate(pool, call, max_attempts=6, max_total_s=2.0, sleep=clock.sleep, monotonic=clock)- assert ei.value.status == 429- assert clock.t <= 2.5, f"free rotation outlived the deadline: {clock.t}"- assert len(calls) <= 5, "ten keys would all have been tried before"+def test_storm_waits_never_exceed_the_house_limit_at_production_defaults(monkeypatch):+ monkeypatch.setattr(random, "random", lambda: 1.0)+ naps: list[float] = []+ with pytest.raises(ModelError):+ _rotate503(_pool(2), _boom(), max_attempts=2, storm_attempts=12, sleep=naps.append)+ assert naps and max(naps) == MAX_WAIT_S-# --------------------------------------------------------------------------- on_attempt hook (2026-08-27)def test_on_attempt_hears_every_round_trip_and_a_late_hedge_loser():"""The attempt hook reports winners, failures, and late hedge losers."""pool = _pool(4)@@ -337,3 +267,66 @@ def test_a_broken_on_attempt_hook_never_breaks_the_call():assert _rotate(pool, lambda key: "ok", on_attempt=hook) == "ok"++def test_backoff_grows_and_caps():+ d = [backoff_delay(i, base_delay=1.0, max_delay=8.0, jitter=False) for i in range(1, 7)]+ assert d == [1.0, 2.0, 4.0, 8.0, 8.0, 8.0]+ j = backoff_delay(3, base_delay=1.0, max_delay=8.0)+ assert 2.0 <= j <= 4.0+++def test_the_deadline_does_not_cut_a_call_that_is_making_progress():+ """A slow-but-succeeding call must not be killed by the retry deadline."""+ clock = Clock()+ calls = {"n": 0}++ def call(_key):+ calls["n"] += 1+ clock.t += 280.0 # slow, but under the per-attempt timeout+ if calls["n"] < 3:+ raise RuntimeError("503 high demand")+ return "ok"++ # hedge=1: serial fake clock and call counter (see the hedge tests for the raced form)+ out = _rotate503(+ _pool(2),+ call,+ max_attempts=6,+ storm_attempts=60,+ sleep=clock.sleep,+ monotonic=clock,+ hedge=1,+ )+ assert out == "ok" and calls["n"] == 3+++def test_the_worst_error_decides_a_hedged_attempt():+ """A nonretryable hedge error outranks a sibling 503."""+ pool = _pool(3)+ stats: dict = {}++ def call(key):+ if key == "k3":+ raise ModelError("bad request", retryable=False, status=400)+ raise ModelError("503 high demand", retryable=True, status=503)++ with pytest.raises(ModelError) as ei:+ _rotate(pool, call, max_attempts=6, storm_attempts=10, stats=stats)+ assert ei.value.status == 400 and stats == {"attempts": 3, "hedged": 1, "storm": 0}+++def test_free_429_rotation_cannot_outlive_the_deadline():+ """Free key rotation still consumes wall-clock budget."""+ clock = Clock()+ pool = _pool(10, cooldown_s=0.0, clock=clock, sleep=clock.sleep)+ calls: list[str] = []++ def call(key):+ calls.append(key)+ raise ModelError("quota", retryable=True, status=429)++ with pytest.raises(ModelError) as ei:+ _rotate(pool, call, max_attempts=6, max_total_s=2.0, sleep=clock.sleep, monotonic=clock)+ assert ei.value.status == 429+ assert clock.t <= 2.5, f"free rotation outlived the deadline: {clock.t}"+ assert len(calls) <= 5, "ten keys would all have been tried before"diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.pyindex b426ab0f..9e84ce4a 100644--- a/harness/tests/models/test_schema_utils.py+++ b/harness/tests/models/test_schema_utils.py@@ -4,60 +4,16 @@ from __future__ import annotationsimport json-import pytest-from google.genai import typesfrom pydantic import BaseModelfrom codeverse3d.contracts.plan import ArticulatedPlan, ScenePlan, StaticPlanfrom codeverse3d.models.schema_utils import (- JsonParseError,inline_refs,- parse_json_lenient,to_gemini_schema,to_openai_strict_schema,)-def _walk(node, fn):- """Visit schema nodes only (values of a ``properties`` map are schemas, the map is not)."""- fn(node)- if isinstance(node, dict):- for k, v in node.items():- if k == "properties" and isinstance(v, dict):- for sub in v.values():- _walk(sub, fn)- else:- _walk(v, fn)- elif isinstance(node, list):- for v in node:- _walk(v, fn)---def test_gemini_schemas_are_clean_and_sdk_valid():- def check(node):- if not isinstance(node, dict):- return- for bad in (- "$ref",- "$defs",- "title",- "default",- "const",- "prefixItems",- "additionalProperties",- ):- assert bad not in node, (bad, node)- if "anyOf" in node:- assert all(value.get("type") != "null" for value in node["anyOf"])- if node.get("type") == "object" and "properties" in node:- assert node["propertyOrdering"] == list(node["properties"])-- for model in (StaticPlan, ArticulatedPlan, ScenePlan):- schema = to_gemini_schema(model.model_json_schema())- _walk(schema, check)- types.Schema.model_validate(schema)--def test_gemini_specifics():class M(BaseModel):vec: tuple[float, float, float]@@ -81,17 +37,6 @@ def test_gemini_specifics():assert g2["properties"]["n"] == {"enum": ["1", "2"], "type": "string"}-def test_inline_refs_and_recursion_guard():- s = {- "$defs": {"A": {"type": "string"}},- "properties": {"x": {"$ref": "#/$defs/A", "description": "d"}},- }- assert inline_refs(s) == {"properties": {"x": {"type": "string", "description": "d"}}}- rec = {"$defs": {"N": {"properties": {"child": {"$ref": "#/$defs/N"}}}}, "$ref": "#/$defs/N"}- with pytest.raises(ValueError):- inline_refs(rec)--def test_openai_strict_schemas_never_add_null():"""Wire contract == pydantic contract: a field accepts null on the wire iff thesource schema does (``x: T | None``) — never because it merely has a default /@@ -125,24 +70,6 @@ def _accepts_null(sub) -> bool:)-def test_parse_json_lenient_accepts_wrappers_and_rejects_non_json():- for text in (- '{"a": 1}',- 'Sure! ```json\n{"a": 1}\n```',- 'prefix text {"a": 1} trailing',- '{"a": 1,}',- '```\n{"a": 1}\n```',- '{"a": 1} and later {broken',- 'note {"a": 1} ps: see {figure 2}',- ):- assert parse_json_lenient(text) == {"a": 1}- assert parse_json_lenient("[1, 2]") == [1, 2]- for text in ("no json here", ""):- with pytest.raises(JsonParseError):- parse_json_lenient(text)- assert json.dumps(parse_json_lenient('{"n": {"x": [1]}}')) == '{"n": {"x": [1]}}'--def test_ask_structured_returns_the_triple_and_the_billed_usage_on_failure():"""The callers branch on the error string, so a provider that returns prose must notraise; a bad-JSON reply is charged like a good one: the caller's tally gets the usage."""diff --git a/harness/tests/models/test_slots.py b/harness/tests/models/test_slots.pyindex 1144a655..71ffbf4e 100644--- a/harness/tests/models/test_slots.py+++ b/harness/tests/models/test_slots.py@@ -1,22 +1,14 @@-"""The machine-wide in-flight slots (``retry.Slots``): flock'd lock files every process shares.--Real processes, real threads, real clocks — the owner asked for the file lock to be tested,-not assumed. Every test measures with ``time.monotonic`` (CLOCK_MONOTONIC is one clock for-the whole machine on Linux) and prints what it measured (``pytest -s`` shows it).-"""+"""The machine-wide in-flight slots (``retry.Slots``): flock'd lock files every process shares, tested with real processes."""from __future__ import annotationsimport jsonimport os-import signalimport subprocessimport sysimport timefrom pathlib import Path-from codeverse3d.models.retry import Slots-HARNESS = Path(__file__).resolve().parents[2]#: a child that takes a slot ``holds`` times for ``hold_s`` each, after a "go" on stdin,@@ -37,16 +29,6 @@ for _ in range(holds):print(json.dumps([t0, t1]), flush=True)"""-#: a child that takes a slot, says so, and then sleeps until it is killed-_HOLDER = """-import sys, time-from codeverse3d.models.retry import Slots-fd = Slots(int(sys.argv[2]), sys.argv[1]).take(10.0)-print("held", flush=True)-time.sleep(600)-"""--def _python(code: str, *args: object) -> subprocess.Popen:"""A child on THIS tree's codeverse3d (the editable install may point at another checkout)."""env = {**os.environ, "PYTHONPATH": str(HARNESS)}@@ -85,33 +67,9 @@ def test_n_plus_k_processes_never_have_more_than_n_in_flight(tmp_path: Path) ->for p in procs:p.kill()wall = max(t1 for _, t1 in intervals) - t_go- busy_s = sum(t1 - t0 for t0, t1 in intervals)peak = _peak(intervals)- print(f"\n(a) {n + k} processes x {holds} holds x {hold_s}s on {n} slots: peak {peak} in flight, "- f"mean {busy_s / wall:.2f}, wall {wall:.2f}s (floor {(n + k) * holds * hold_s / n:.2f}s)")assert len(intervals) == (n + k) * holdsassert peak == n, f"{peak} in flight at once on {n} slots"assert wall >= (n + k) * holds * hold_s / n - 0.05, "finished faster than 4 slots allow"-def test_a_process_killed_holding_a_slot_frees_it_at_once(tmp_path: Path) -> None:- """(b) SIGKILL runs no cleanup code; the kernel drops a dead process's flock anyway, so- a waiter gets the slot within one poll — no stale-lock timeout, no pid file to reap."""- slots = Slots(1, tmp_path)- child = _python(_HOLDER, tmp_path, 1)- try:- assert child.stdout.readline().strip() == "held", child.stderr.read()- assert slots.try_take() is None and slots.busy() == 1, "the child holds the only slot"- t_kill = time.monotonic()- os.kill(child.pid, signal.SIGKILL)- fd = slots.take(timeout_s=5.0)- freed_after = time.monotonic() - t_kill- finally:- child.kill()- child.wait(10)- Slots.give(fd)- print(f"\n(b) slot back {freed_after * 1000:.0f} ms after SIGKILL (poll {Slots.POLL_S * 1000:.0f} ms)")- assert child.returncode == -signal.SIGKILL- assert freed_after < 1.0--diff --git a/harness/tests/orchestrator_tracks/data/offrecord_runs.json b/harness/tests/orchestrator_tracks/data/offrecord_runs.jsonindex a95fe57a..d601f63a 100644--- a/harness/tests/orchestrator_tracks/data/offrecord_runs.json+++ b/harness/tests/orchestrator_tracks/data/offrecord_runs.json@@ -154,8 +154,7 @@"input_tokens": 10558,"output_tokens": 1868}- ],- "post_hoc_texture_passes": []+ ]},"tool_med_hand_drill": {"status": "budget",@@ -382,8 +381,7 @@"input_tokens": 10957,"output_tokens": 2020}- ],- "post_hoc_texture_passes": []+ ]},"furn_hard_rolltop_desk": {"status": "passed",@@ -514,20 +512,6 @@"input_tokens": 10750,"output_tokens": 1679}- ],- "post_hoc_texture_passes": [- {- "cost_usd": 0.294,- "shipped": false- },- {- "cost_usd": 0.0919,- "shipped": false- },- {- "cost_usd": 0.2703,- "shipped": true- }]}}diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.pyindex f4f54e19..d097d34b 100644--- a/harness/tests/orchestrator_tracks/fakes.py+++ b/harness/tests/orchestrator_tracks/fakes.py@@ -456,7 +456,7 @@ class FakeServices(Services):fix_hint=f"shrink {j.child} by 17 mm along the axis") for j in list(getattr(plan, "joints", []))[: self.sweep_errors]]return GateReport(gate="joint_sweep", passed=not findings, findings=findings), views- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, spatial_tools: bool) -> None:+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str) -> None:(ws.root / "AGENTS.md").write_text(contract_md)self.materialized.append(agent_kind)diff --git a/harness/tests/orchestrator_tracks/test_baseline_first.py b/harness/tests/orchestrator_tracks/test_baseline_first.pyindex a3196fd8..0b6d592f 100644--- a/harness/tests/orchestrator_tracks/test_baseline_first.py+++ b/harness/tests/orchestrator_tracks/test_baseline_first.py@@ -40,9 +40,9 @@ def _ctx(tmp_path, settings, language: Language, plan):return track, ctx[email protected]("language", [Language.THREEJS, Language.BLENDER, Language.CADQUERY])[email protected]("language", [Language.THREEJS, Language.CADQUERY]) # per-part files vs one filedef test_round0_is_one_session_owning_every_part_file_and_the_entry(tmp_path, settings, language):- """An 8-part plan was split into 3-5 serial scope sessions + an assemble session before D110."""+ """D110: one draft session, not 3-5 scope sessions + an assemble session."""track, ctx = _ctx(tmp_path, settings, language, _big_plan(10))(draft,) = track.baseline_tasks(ctx)files = ctx.runtime.expected_files(ctx.plan)@@ -107,8 +107,7 @@ def test_articulated_runs_one_draft_and_one_refine_session_end_to_end(tmp_path,def test_single_shot_refine_is_fenced_to_the_files_it_is_shown(tmp_path, settings):- """A single-shot call has no read tool and sees only the inlined files: told "the whole object"- it could rewrite a part file it was never shown, so it keeps the files its tasks name."""+ """A single-shot call sees only the inlined files, so it is fenced to the files its tasks name."""track, ctx = _ctx(tmp_path, settings, Language.THREEJS, _big_plan(8))ctx.agent_id = "single-shot:gemini:x"(refine,), _ = track.refine_tasks(ctx, _last(ctx.plan))@@ -120,9 +119,7 @@ def test_single_shot_refine_is_fenced_to_the_files_it_is_shown(tmp_path, settingdef test_refine_session_ends_before_the_run_clock_so_the_round_is_judged(tmp_path, settings):- """The baseline-first smoke's blender refine started at 25.8 of 60 min with a 30-min window: the- watchdog let the busy session run its 5-min grace on top, the run clock killed it at 60.0 min and- the round was dropped unbuilt and unjudged ($4.63). The window now ends reserve + grace early."""+ """Smoke: a refine at 25.8 of 60 min plus the 5-min grace was killed by the run clock, unjudged ($4.63); the window now ends reserve + grace early."""from codeverse3d.agents.cli_common import HARD_GRACE_Sfrom codeverse3d.tracks.static_object import REFINE_MIN_WINDOW_Sdiff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.pyindex 0006d13f..affebf28 100644--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py@@ -4,7 +4,6 @@ on the ledger, the one record of it)."""from __future__ import annotationsimport json-from pathlib import Pathimport pytest@@ -84,7 +83,6 @@ def test_a_paid_single_shot_response_is_persisted_when_the_budget_trips_and_the_with run_ledger(ws.root):res = generate_files(ws, model=model, task=task, budget=guard) # must NOT raiseassert res.ok and (ws.src / "object.js").is_file()- assert res.transcript_path and Path(res.transcript_path).is_file()assert sum(r.cost_usd for r in load_ledger(ws.root)) == pytest.approx(0.05) # booked, dollar for dollarassert not guard.ok() # the phase boundary (steps._run_phase) turns this into the stop# and once past the ceiling a single-shot buys no call at all@@ -137,12 +135,11 @@ def test_every_paid_planner_attempt_is_booked_once_whether_the_next_raises_or_neassert (paid.stage, paid.cost_usd, failed.outcome, failed.cost_usd) == ("plan", pytest.approx(0.01), "error", 0.0)# a plan that never validates: every paid attempt is booked exactly oncews = Workspace(tmp_path / "run2").create()- with run_ledger(ws.root), pytest.raises(PlanningError) as ei:+ with run_ledger(ws.root), pytest.raises(PlanningError):run_planner(make_spec(), "fake:planner", StaticPlan, ws,model=metered_chat_model(FakeChatModel(lambda req: {"object_name": "Chair"}, cost=0.01)), budget=guard)n = 1 + MAX_VALIDATION_REASKS # every paid attempt, each booked onceassert sum(r.cost_usd for r in load_ledger(ws.root)) == pytest.approx(0.01 * n)- assert ei.value.usage.cost_usd == pytest.approx(0.01 * n) # the error still reports the totaldef test_a_baseline_session_the_clock_stopped_after_it_wrote_code_is_salvaged(tmp_path, chair_plan, settings):diff --git a/harness/tests/orchestrator_tracks/test_cost_accounting.py b/harness/tests/orchestrator_tracks/test_cost_accounting.pyindex 6a6e09dc..42b0a3a5 100644--- a/harness/tests/orchestrator_tracks/test_cost_accounting.py+++ b/harness/tests/orchestrator_tracks/test_cost_accounting.py@@ -38,10 +38,7 @@ class _RecordedAgent:def replay(name: str, root: Path) -> float:- """Spend one recorded run's money through today's accounting path and return the ledger's- total: the ONE writer — ``MeteredAgent`` for a session, ``record_call`` (what- ``MeteredChatModel`` does per call) for the judge and texture money — inside- ``run_ledger(root)``, as ``BaseTrack.run`` opens it."""+ """Spend one recorded run through the ledger's one writer (MeteredAgent / record_call) and return its total."""fx = FIXTURES[name]guard = BudgetGuard(Budget(max_minutes=10_000))tasks: dict[tuple[str, int], list[dict]] = {}@@ -60,22 +57,19 @@ def replay(name: str, root: Path) -> float:for j in fx["judges"]: # the judge's MeteredChatModel writes one row per verdict callu = Usage(cost_usd=j["cost_usd"], input_tokens=j["input_tokens"], output_tokens=j["output_tokens"])record_call(u, round=j["round"], stage="judge", role="judge", label=j["rubric"])- for t in fx["post_hoc_texture_passes"]: # a texture pass joins the run's ledger- record_call(Usage(cost_usd=t["cost_usd"]), stage="texture", role="image", label="texture_pass")return sum(r.cost_usd for r in load_ledger(root))[email protected]("name", sorted(FIXTURES))[email protected]("name", ["tool_med_hand_drill", "furn_hard_rolltop_desk"]) # with and without retried sessionsdef test_every_recorded_dollar_reaches_the_ledger_once(name, tmp_path):fx = FIXTURES[name]total = replay(name, tmp_path)sessions = sum(s["cost_usd"] for s in fx["sessions"])judges = sum(j["cost_usd"] for j in fx["judges"])- texture = sum(t["cost_usd"] for t in fx["post_hoc_texture_passes"])# nothing is lost between the sessions and the ledger — retries included — and nothing twice- assert total == pytest.approx(sessions + judges + texture, abs=1e-6)+ assert total == pytest.approx(sessions + judges, abs=1e-6)rows = load_ledger(tmp_path) # telemetry/cost.jsonl, one writer, one row per call- assert len(rows) == len(fx["sessions"]) + len(fx["judges"]) + len(fx["post_hoc_texture_passes"])+ assert len(rows) == len(fx["sessions"]) + len(fx["judges"])# a retried session is its OWN row, labelled .a2retried = [s for s in fx["sessions"] if s["attempt"] > 1]assert sum(1 for r in rows if r.label.endswith(".a2")) == len(retried)diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex 4504a2f1..e9d9f118 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -248,10 +248,7 @@ def test_a_clock_that_trips_after_a_finished_zones_session_records_what_it_wrotedef test_stages_that_spend_the_clock_without_raising_still_get_a_salvaged_round(tmp_path, settings):- """Live 2026-09-23 (jetty_scene, $1.16): a 503 storm stretched the stages past the ceiling without- any of them raising (the zones degraded to single-shot and failed quietly), so the round loop's own- clock check stopped the run at `budget` with NO round: the salvage only ran when a stage RAISED- BudgetExceeded. Here the last stage (assemble) is the one that ends past the ceiling."""+ """Live 2026-09-23 (jetty_scene, $1.16): stages that overrun the clock without raising got NO salvaged round."""from tests.orchestrator_tracks.conftest import FAKE_CLOCKclass SlowAssemble(FakeServices):diff --git a/harness/tests/orchestrator_tracks/test_env_stage_honest.py b/harness/tests/orchestrator_tracks/test_env_stage_honest.pyindex 03c42e08..62c9602a 100644--- a/harness/tests/orchestrator_tracks/test_env_stage_honest.py+++ b/harness/tests/orchestrator_tracks/test_env_stage_honest.py@@ -1,11 +1,4 @@-"""D111: the scene env stage is ``ok`` only when the env module itself was written, else it is recovered.--Argon loop iteration 4 (scene_threejs, 2026-10-15): in 12 of 15 runs the env session wrote nothing,-was credited with the asset files written beside it and its stage read ``ok``; round 0 was unlit and-the single refine round wrote the whole environment from the skeleton. The stage now applies the-zone stage's own test (the file in ``files_changed`` or rewritten since the stage began) and runs-ONE single-shot recovery before the zones — for either scene language's env file.-"""+"""D111 (iteration 4): the env stage is ok only when the env module was written (12 of 15 runs were credited with other files), else one single-shot recovery."""from __future__ import annotations@@ -75,9 +68,8 @@ def test_a_session_credited_only_with_other_stages_files_fails_and_is_recovered(assert {"env.recover", "env.recovered"} <= set(_events(ctx))[email protected]("language", LANGUAGES)-def test_a_recovery_that_also_writes_nothing_leaves_the_stage_failed(tmp_path, settings, monkeypatch, language):- track, ctx = _ctx(tmp_path, settings, language)+def test_a_recovery_that_also_writes_nothing_leaves_the_stage_failed(tmp_path, settings, monkeypatch):+ track, ctx = _ctx(tmp_path, settings, Language.SCENE_BLENDER)def fake_generate_for(gen: Any, task: Any) -> GenerationResult:return GenerationResult(ok=False, label=task.label, notes="exit=timeout")@@ -133,9 +125,8 @@ def test_a_recovery_that_fails_its_check_gets_one_repair_with_the_error_and_the_assert [c["ok"] for c in checked] == [False, True][email protected]("language", LANGUAGES)-def test_a_recovery_that_fails_twice_leaves_the_placeholder_and_a_failed_stage(tmp_path, settings, monkeypatch, language):- track, ctx = _ctx(tmp_path, settings, language)+def test_a_recovery_that_fails_twice_leaves_the_placeholder_and_a_failed_stage(tmp_path, settings, monkeypatch):+ track, ctx = _ctx(tmp_path, settings, Language.SCENE_THREEJS)rel = env_file(ctx)def fake_generate_for(gen: Any, task: Any) -> GenerationResult:@@ -151,8 +142,7 @@ def test_a_recovery_that_fails_twice_leaves_the_placeholder_and_a_failed_stage(tdef test_the_recovery_never_commits_inside_another_sessions_window(tmp_path, settings, monkeypatch):- """Iteration 5, scene_blender r1_10: env.recover committed while an escalated asset session held the- workspace; that session's scope check then restored env.py to its own ``head_before``."""+ """Iteration 5, r1_10: env.recover committed inside an asset session's window; its scope check then reverted env.py."""import threadingfrom codeverse3d.agents.cli_common import begin_session, finish_sessiondiff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.pyindex eac08fe4..93479c7e 100644--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py@@ -59,15 +59,10 @@ class ScriptedJudge(FakeJudge):# --------------------------------------------------------------------- finding: finalise with a dirty tree at the last commitdef test_finalise_restores_the_last_round_when_an_aborted_round_dirtied_src(tmp_path, chair_plan, settings):- """A refine round that died after writing files leaves src/ back on the last judged round.-- finalise's own guarantee, so D112's two budget levers are off here: the launch window (4 min are- left, under min_session_s + judge_reserve_s) and the refine salvage (which would JUDGE these- edits — tests/orchestrator_tracks/test_transport_retry.py pins that path)."""+ """A refine that died after writing files leaves src/ on the last judged round (D112 launch window and salvage off)."""spec = make_spec(max_rounds=3)ws = Workspace(tmp_path / "runs" / "r")- # the baseline session's 6 minutes fit the 10-minute clock; the refine session's 6 more- # cross it AFTER its files hit the disk.+ # the refine session's 6 minutes cross the 10-minute clock AFTER its files hit the disktrack = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.55, 0.7), targets=("Seat",)), agent=FakeAgent(_writer, minutes=6.0),planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,runtime=FakeRuntime(Language.THREEJS), policy=_NO_RESERVE)@@ -130,9 +125,7 @@ def test_degraded_verdict_never_scores_and_run_stops_as_judge_unavailable(tmp_pa(["degraded", "degraded"], RunStatus.JUDGE_UNAVAILABLE, None),])def test_the_last_round_is_rejudged_before_the_run_ends(tmp_path, chair_plan, settings, verdicts, status, score):- """`--rounds 0`: the baseline IS the last round. Its failed verdict was never re-judged (the- re-judge lived in the refine branch) and the run stopped MAX_ROUNDS unscored; now it gets the- same one re-judge as any round, and a second failure says judge_unavailable (D80)."""+ """D80, `--rounds 0`: the baseline is the last round and gets the same one re-judge; a second failure is judge_unavailable."""ws = Workspace(tmp_path / "runs" / "r")judge = ScriptedJudge(verdicts)track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer),diff --git a/harness/tests/orchestrator_tracks/test_fix_generation.py b/harness/tests/orchestrator_tracks/test_fix_generation.pyindex 3d6818d4..ecea0c6a 100644--- a/harness/tests/orchestrator_tracks/test_fix_generation.py+++ b/harness/tests/orchestrator_tracks/test_fix_generation.py@@ -61,7 +61,7 @@ def test_generate_files_truncation_policy(tmp_path):# --------------------------------------------------------------------- finding: whole-workspace diff claimed sibling tasks' filesclass NonReportingAgent:- """An agent that writes its own file but reports no files_changed (fallback path)."""+ """An agent that writes its own file but reports no files_changed."""kind = "fake"model = "m"@@ -80,10 +80,10 @@ class NonReportingAgent:return AgentResult(ok=True, exit_reason="completed", files_changed=[], usage=Usage(backend="fake", cost_usd=0.001))-def test_run_agent_task_passes_files_hint_and_attributes_fallback_diff(tmp_path):+def test_run_agent_task_passes_files_hint_and_trusts_only_the_sessions_report(tmp_path):ws = Workspace(tmp_path / "ws").create()ws.commit("init")- # noise a fallback whole-tree diff used to claim as the task's own work+ # noise a whole-tree diff would claim as the task's own work(ws.root / "events.jsonl").write_text("{}\n")(ws.root / "notes.md").write_text("scratch\n")(ws.root / "artifacts").mkdir(exist_ok=True)@@ -92,4 +92,4 @@ def test_run_agent_task_passes_files_hint_and_attributes_fallback_diff(tmp_path)task = GenerationTask(label="refine_seat", prompt="p", files_hint=["src/parts/seat.js"], round=1, kind="refine")res = run_agent_task(ws, agent=agent, task=task)assert agent.jobs[0].files_hint == ["src/parts/seat.js"] # per-session attribution key- assert res.ok and [c.path for c in res.files_changed] == ["src/parts/seat.js"]+ assert not res.ok and res.files_changed == [] # the session reported nothing: nothing is crediteddiff --git a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py b/harness/tests/orchestrator_tracks/test_generation_planner_repair.pyindex d2677da3..50b672e2 100644--- a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py+++ b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py@@ -187,7 +187,6 @@ def test_build_with_repair_single_shot_sends_file_contents_and_stops_at_max(tmp_assert not out.ok and len(out.attempts) == 2 # max_repair_attempts=2 in make_specassert "--- src/model.py ---" in seen[0].messages[0].text and "import bpy" in seen[0].messages[0].textassert seen[1].temperature > seen[0].temperature # escalation on identical signature- assert out.usage.cost_usd == pytest.approx(0.004)def test_repair_rel_strips_a_prefix_not_a_character_set(tmp_ws):diff --git a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.pyindex 41ffb3d8..72b9b0cc 100644--- a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py+++ b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py@@ -38,7 +38,7 @@ def no_generate(monkeypatch):return calls[email protected]("repair_budget", [3, 0])[email protected]("repair_budget", [0])def test_a_harness_failure_that_persists_gives_up_without_a_repair(monkeypatch, no_generate, repair_budget):"""Bounded by MAX_HARNESS_REBUILDS, not by the repair budget (a max_repair_attempts=0 arm still rebuilds)."""stuck = (_build(ok=False, harness=True), GateReport(gate="lint", passed=True, findings=[]))diff --git a/harness/tests/orchestrator_tracks/test_integrations2.py b/harness/tests/orchestrator_tracks/test_integrations2.pyindex 262092e7..29a5a243 100644--- a/harness/tests/orchestrator_tracks/test_integrations2.py+++ b/harness/tests/orchestrator_tracks/test_integrations2.py@@ -1,4 +1,4 @@-"""Integration wiring into the tracks: runtime file layout, no texture pass inside a run."""+"""Integration wiring into the tracks: runtime file layout."""from __future__ import annotationsdiff --git a/harness/tests/orchestrator_tracks/test_refine_evidence.py b/harness/tests/orchestrator_tracks/test_refine_evidence.pyindex ffe590e9..cf3de7b4 100644--- a/harness/tests/orchestrator_tracks/test_refine_evidence.py+++ b/harness/tests/orchestrator_tracks/test_refine_evidence.py@@ -1,15 +1,7 @@-"""D112: the scene refine prompt carries the placement evidence itself, as facts.--Iteration 5, scene_threejs r1_07: the refine session read for its whole 15-minute window — 1.96 M input-tokens, most of them five pages of the 3 772-line ``artifacts/scene_probe.json`` — hunting the rows-behind "floating 0.05 m" in a scene its prompt calls outdoors, and was killed before its first write.-"""+"""D112 (iteration 5, r1_07): the refine prompt carries the placement rows itself; the session had burned 15 minutes paging scene_probe.json."""from __future__ import annotations-import pytest--from codeverse3d.contracts.common import Languagefrom codeverse3d.contracts.run import RoundRecordfrom codeverse3d.orchestrator import TaskGroup, build_refine_instructionsfrom codeverse3d.spatial.scene_placement import placement_findings@@ -17,9 +9,8 @@ from tests.orchestrator_tracks.test_env_stage_honest import LANGUAGES, _ctxfrom tests.scene_gates.test_placement import _row, _table[email protected]("language", LANGUAGES)-def test_the_refine_prompt_states_each_failed_row_its_gap_and_tolerance(tmp_path, settings, language: Language):- track, ctx = _ctx(tmp_path, settings, language)+def test_the_refine_prompt_states_each_failed_row_its_gap_and_tolerance(tmp_path, settings):+ track, ctx = _ctx(tmp_path, settings, LANGUAGES[0])ctx.tool_cards = "(tools)"gate = placement_findings(_table(*[_row(f"Boulder{i}", zone="FernHollow", gap=g) for i, g in enumerate((0.048, 0.046, 0.041))]),indoor=True)diff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.pyindex d6065e06..6b941494 100644--- a/harness/tests/orchestrator_tracks/test_round_economics.py+++ b/harness/tests/orchestrator_tracks/test_round_economics.py@@ -66,7 +66,7 @@ def test_hitting_the_cap_asks_for_a_landing_instead_of_killing_the_session(tmp_wassert len(agent.jobs) == 2 and turn_capped(_result_of(agent, 0)) and agent.jobs[0].max_turns == 28wrap = agent.jobs[1]assert wrap.max_turns == DEFAULT_WRAPUP_TURNS and "LAST session" in wrap.prompt and "do the work" in wrap.prompt- assert res.ok and res.turn_capped and res.sessions == 2+ assert res.ok# both sessions are paid for and each is a ledger row of its ownassert res.usage.cost_usd == pytest.approx(0.4)rows = load_ledger(tmp_ws.root)diff --git a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.pyindex aee7f8c4..20af38b5 100644--- a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py+++ b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py@@ -4,8 +4,6 @@ from __future__ import annotationsimport json-import pytest-from codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import ScenePlanfrom codeverse3d.contracts.spec import Constraints@@ -102,13 +100,11 @@ def test_hero_reentry_keeps_the_previous_sessions_src(tmp_ws, settings):assert res.ok and (tmp_ws.public / "assets" / f"{snake}.glb").is_file() # the kept src builds again[email protected]("kind", ["threejs", "blender_glb"])-def test_asset_check_soft_findings_share_one_rule_set(kind):- chk = SA.AssetCheck(ok=True, ran=True, size_m=(0.6, 0.4, 0.3), min_y=-0.1, tris=50_000, meshes=1, materials=1)- limit = SA.HERO_MAX_TRIS if kind == "blender_glb" else SA.ASSET_MAX_TRIS- SA._soft_findings(chk, (0.6, 0.4, 0.3), max_tris=limit)- assert not chk.ok and any("sinks" in e for e in chk.errors)- assert any(f"{limit} budget" in e for e in chk.errors)+def test_asset_check_soft_findings_share_one_rule_set():+ for limit in (SA.HERO_MAX_TRIS, SA.ASSET_MAX_TRIS): # hero GLB and threejs module+ chk = SA.AssetCheck(ok=True, ran=True, size_m=(0.6, 0.4, 0.3), min_y=-0.1, tris=50_000, meshes=1, materials=1)+ SA._soft_findings(chk, (0.6, 0.4, 0.3), max_tris=limit)+ assert not chk.ok and any("sinks" in e for e in chk.errors) and any(f"{limit} budget" in e for e in chk.errors)def test_a_fix_that_judges_worse_is_undone(tmp_ws, settings):@@ -204,15 +200,13 @@ def test_a_threejs_fix_with_only_soft_findings_is_kept_and_judged_again(tmp_ws,errors=["measured w=20.00 m but the plan says 8.00 m — rescale"])])monkeypatch.setattr(SA, "check_threejs_asset", lambda *a, **k: next(checks))monkeypatch.setattr(SA, "_judge_wanted", lambda *a, **k: True)- res = SA.build_threejs_asset(ctx, asset, judge=True)+ res = SA.build_module_asset(ctx, asset, judge=True)assert res.ok and res.fixed and (res.score_before, res.score) == (0.5, 0.7)assert (tmp_ws.root / boat).read_text() == "// asset_fishing_boat_fix\n", "the fix that imports is kept"def test_the_ladders_single_shot_call_waits_no_longer_than_the_asset_window(tmp_ws, settings):- """D108 capped a single-shot call at its task's window, but the ladder's single-shot step never passed- the window on: every asset and hero call ran on the 1 800 s retry ceiling — iteration 3's r1_13 waited- 1 800 s, then 1 641 s, on one hung hero and held the asset stage to 66 minutes (2026-10-15)."""+ """2026-10-15: the ladder's single-shot step never passed the D108 window on (r1_13 waited 1 800 s on one hung hero)."""from codeverse3d.models.retry import RETRY_DEADLINE_Sfrom codeverse3d.tracks.generation import single_shot_wait_sdiff --git a/harness/tests/orchestrator_tracks/test_zone_starvation.py b/harness/tests/orchestrator_tracks/test_zone_starvation.pyindex 3ca0ea34..14c3f316 100644--- a/harness/tests/orchestrator_tracks/test_zone_starvation.py+++ b/harness/tests/orchestrator_tracks/test_zone_starvation.py@@ -1,14 +1,5 @@-"""2026-10-15, iteration 2 of the argon loop: two Blender scenes shipped three EMPTY zones (0.18).--A runaway single-shot asset call held the asset stage for ~47 minutes; the zone stage then started-0.4 min before the scene track's soft cap and its agent session was clipped to the 180 s floor; it-read files until it was killed and wrote no zone; ``zones.done`` listed them failed and nothing acted;-refine spent its window on asset files. Three fixes, pinned here:--* a single-shot call is bounded by its task's own window (never below ``SINGLE_SHOT_MIN_WAIT_S``);-* the zone window comes from the HARD budget minus round 0's reserve, not the soft cap;-* every zone the session left unwritten gets one single-shot recovery before assembly.-"""+"""2026-10-15, iteration 2 (two scenes shipped three EMPTY zones, 0.18): a single-shot call is bounded by its task's window;+the zone window is the HARD budget minus round 0's reserve; every unwritten zone gets one single-shot recovery."""from __future__ import annotationsdiff --git a/harness/tests/prompts/conftest.py b/harness/tests/prompts/conftest.pyindex 9d00757b..4997c1d3 100644--- a/harness/tests/prompts/conftest.py+++ b/harness/tests/prompts/conftest.py@@ -26,36 +26,25 @@ STARTER_LIB = Path(__file__).resolve().parents[2] / "codeverse3d" / "languages"PROMPT_FILES = sorted(p.relative_to(PROMPTS_DIR).as_posix() for p in PROMPTS_DIR.rglob("*")if p.is_file() and p.suffix != ".py" and "__pycache__" not in p.parts)-def is_template(rel: str) -> bool:"""Rendered with a context (jinja): the ``.j2`` files and each language's ``system.md``.Every other file is quoted verbatim and must stay jinja-inert."""return rel.endswith(".j2") or (rel.endswith("/system.md") and not rel.startswith("system/"))-_FENCE = re.compile(r"```(\w[\w-]*)\n(.*?)```", re.DOTALL)#: fence-tag spellings that mean the same language_TAG_ALIASES = {"py": "python", "javascript": "js", "mjs": "js"}-def _tag(raw: str) -> str:return _TAG_ALIASES.get(raw, raw)-def read_prompt(rel: str) -> str:return (PROMPTS_DIR / rel).read_text()-def blocks(rel: str, lang: str) -> list[str]:"""All fenced blocks tagged ``lang`` in prompt file ``rel``, in order."""return [body for tag, body in _FENCE.findall(read_prompt(rel)) if _tag(tag) == lang]--def strip_imports_exports(js: str) -> str:- js = re.sub(r"^\s*import .*?;\s*$", "", js, flags=re.MULTILINE)- return re.sub(r"^export (default )?", "", js, flags=re.MULTILINE)--def labelled_files(rel: str, tag: str = "js") -> dict[str, str]:"""Blocks preceded by a `src/...` label line → {path: content} (contract examples)."""out: dict[str, str] = {}@@ -65,7 +54,6 @@ def labelled_files(rel: str, tag: str = "js") -> dict[str, str]:out[path] = bodyreturn out-# ----------------------------------------------------------------------- runnersdef run_node_module(tmp_path: Path, code: str, timeout: int = 120) -> str:"""Write ``code`` as an ES module and run it under the harness's ``three`` resolve hook."""@@ -78,7 +66,6 @@ def run_node_module(tmp_path: Path, code: str, timeout: int = 120) -> str:assert proc.rc == 0, f"node failed:\nSTDOUT:{proc.stdout[-3000:]}\nSTDERR:{proc.stderr[-3000:]}"return proc.stdout-def run_blender_script(tmp_path: Path, code: str, timeout: int = 240) -> str:"""Run python ``code`` inside Blender headless with an emptied factory scene."""blender = get_settings().resolve_blender()@@ -99,15 +86,3 @@ def run_blender_script(tmp_path: Path, code: str, timeout: int = 240) -> str:assert "BPY_SNIPPETS_OK" in out, f"blender snippets failed (rc={proc.returncode}):\n{out[-4000:]}"return out--def js_prelude(extra: str = "") -> str:- return (- "import * as THREE from 'three';\n"- "import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';\n"- "import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';\n"- "import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';\n"- "import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';\n"- "import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';\n"- "import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';\n"- "import { sunRig } from './lib/environment.js';\n" + extra # the rig the starter's env.js builds- )diff --git a/harness/tests/prompts/manifest.json b/harness/tests/prompts/manifest.jsonindex 081fcf67..032c6666 100644--- a/harness/tests/prompts/manifest.json+++ b/harness/tests/prompts/manifest.json@@ -18,11 +18,11 @@"job:refine@r01/prompt": {"bytes": 7267, "sha256": "a718673dc59d566a5af561d8543756e0326057613430e6dae0cb13eb23b8234e"},"job:refine@r01/scope": {"bytes": 379, "sha256": "d17ae76997ec9443d52089e32ec81ecac3ba2c93529b227533942e84598113d9"},"job:refine@r01/system": {"bytes": 3271, "sha256": "29f5a9b2e7b9a879be58963ce95ae6fbec7460dae6785d542b214d6b850e21f4"},- "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9845, "sha256": "5929e0acefb1af7df0c1efa5407df21d151aa8301c9866df852a59371e9617ac"},+ "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9819, "sha256": "0a7445d421267800ff75c73621b735d79a7ceb04ab107e640f52c145916b0201"},"judge:articulated:runs/run/artifacts/renders/r00/messages": {"bytes": 7266, "sha256": "44869437393997f2107fdf0a59b70d830557064fa5958abfbee786e535323a2c"},"judge:articulated:runs/run/artifacts/renders/r00/sampling": {"bytes": 11989, "sha256": "e93c46f5a7a740cd7cf30206976488736804f2b016f39424b2f0e41bfbea1c29"},"judge:articulated:runs/run/artifacts/renders/r00/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},- "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10748, "sha256": "80c901eab99e958a3131ad7c772547149c5bba6e25b3ca1070a01ae63bfc66d5"},+ "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10722, "sha256": "67b607398aa3997504db43be1092ecec063fc228f55af02dc66755ee602b993a"},"judge:articulated:runs/run/artifacts/renders/r01/messages": {"bytes": 7591, "sha256": "a2e7394b1d8515b0256e914ceb6b07eaf526a634104ea03829c559e5fd7ebf67"},"judge:articulated:runs/run/artifacts/renders/r01/sampling": {"bytes": 11989, "sha256": "e93c46f5a7a740cd7cf30206976488736804f2b016f39424b2f0e41bfbea1c29"},"judge:articulated:runs/run/artifacts/renders/r01/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},@@ -30,7 +30,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 125, "sha256": "5c725d8f66ce509d26245268d4c3525c99ce65ff9a56b94c708a74934ae2edf4"}},"stage_keys": {- "runs/run:plan": "1247d7fb9fd2",+ "runs/run:plan": "7ff91964f143","runs/run:skeleton": "7e94e98a2207"}},@@ -51,11 +51,11 @@"chat:planner:planner/messages": {"bytes": 1328, "sha256": "313c87553cf38df423dc9245a8af4cca5a41a844b489e13a5dc08e8c44eabba5"},"chat:planner:planner/sampling": {"bytes": 10001, "sha256": "0ff37a3ae43fdf878dd0911a9954d57e49365ad788c84818ea01d350310ab401"},"chat:planner:planner/system": {"bytes": 20030, "sha256": "45dccfcf72b4c6e46b7ceeaae8af0ebddf6f6e6b5970cda5fe900aa47682bf06"},- "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9565, "sha256": "34d67889b35ec52b188668fe4c2982cc1f24675d1974dd11711b584fab28ebae"},+ "judge:articulated:runs/run/artifacts/renders/r00/input": {"bytes": 9539, "sha256": "f0513f5660eed412e9e260200d50ba2cb4d5ea144d252fe7b6a86a4c94b0306d"},"judge:articulated:runs/run/artifacts/renders/r00/messages": {"bytes": 7120, "sha256": "7a0ef8d51456faa2c38867eea6c502fbe1a7aa30d6cd9f23b44701a2d11846bf"},"judge:articulated:runs/run/artifacts/renders/r00/sampling": {"bytes": 11989, "sha256": "e93c46f5a7a740cd7cf30206976488736804f2b016f39424b2f0e41bfbea1c29"},"judge:articulated:runs/run/artifacts/renders/r00/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},- "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10468, "sha256": "dd4d71680d8fae3259947cf894ba5ebfcaca9f5249df9f90d810b01ba56f69f5"},+ "judge:articulated:runs/run/artifacts/renders/r01/input": {"bytes": 10442, "sha256": "faeb5630c2e4ba0081b5ec45b166279deb1ad38548014ef829110a2c452d8d3d"},"judge:articulated:runs/run/artifacts/renders/r01/messages": {"bytes": 7445, "sha256": "2a654e5bb10f8a642367b40c8893a16dce24c4bc4f6941cfbba76ce348ad4f1c"},"judge:articulated:runs/run/artifacts/renders/r01/sampling": {"bytes": 11989, "sha256": "e93c46f5a7a740cd7cf30206976488736804f2b016f39424b2f0e41bfbea1c29"},"judge:articulated:runs/run/artifacts/renders/r01/system": {"bytes": 13129, "sha256": "b6c7c917b035224ca53b1a3e1fcd0c838b8ac20563e687cd6521d8cab4a78ed6"},@@ -63,7 +63,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 138, "sha256": "cb0610ba263bbb5cbeadf679a8213b52ece498906fabcdf2f8e5937d23c94c0b"}},"stage_keys": {- "runs/run:plan": "1247d7fb9fd2",+ "runs/run:plan": "7ff91964f143","runs/run:skeleton": "7e94e98a2207"}},@@ -81,15 +81,15 @@"job:baseline_c1@r00/prompt": {"bytes": 11347, "sha256": "5aca38cfae577e7e5e5974c2b6cd64e55ec35a1dfab33eaf62eff70652854df5"},"job:baseline_c1@r00/scope": {"bytes": 383, "sha256": "831265b54627f1f6c1bfadebefa4e898d6b543b253bf6be0685b5383bd39fb57"},"job:baseline_c1@r00/system": {"bytes": 3173, "sha256": "c3879a563e2a512b82358d0c3927dcbfe9347725e592035a9b64c5d1b34e6654"},- "judge:shader:runs/run/_cand/c0/artifacts/renders/r00/input": {"bytes": 4039, "sha256": "290042ab7a91ab3a8fc4130ce3d8be4517ffe6adbe651016103b06c55f5f9a06"},+ "judge:shader:runs/run/_cand/c0/artifacts/renders/r00/input": {"bytes": 4013, "sha256": "53102aacf0ecbb26bb489751b12f64205ca575c6ed6005650f9297108f4e2577"},"judge:shader:runs/run/_cand/c0/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/_cand/c0/artifacts/renders/r00/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/_cand/c0/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/_cand/c1/artifacts/renders/r00/input": {"bytes": 4039, "sha256": "f60bf5a2af22996a5e6bc6ec6bfbd9404b9786066be3b9683c6acccd002b03dd"},+ "judge:shader:runs/run/_cand/c1/artifacts/renders/r00/input": {"bytes": 4013, "sha256": "0cd59e323b50bd972a8187ab1752601a68a09be5b4cad5a8ff31272358edb36a"},"judge:shader:runs/run/_cand/c1/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/_cand/c1/artifacts/renders/r00/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/_cand/c1/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3985, "sha256": "f032a21cd4f5d9808da3e3279dfad3d98f5ef6014aa6665ec5aa86d082b03363"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3959, "sha256": "5a6cd939181903bcd28e49d83b7f86b407558242c1e86a91c82bd4fb147dd0ef"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -98,7 +98,7 @@"skills:runs/run:baseline@r00/routed": {"bytes": 56, "sha256": "400eb18b3e0ca869392d11f9fc95c12140d8234f3efe8f3c1ec66b5c43d1ffa6"}},"stage_keys": {- "runs/run:plan": "d1428ecadc7f",+ "runs/run:plan": "6b5b2d8775b3","runs/run:skeleton": "7ad4f988e9ca"}},@@ -117,15 +117,15 @@"job:refine@r02/prompt": {"bytes": 4828, "sha256": "f02f3a218edb95d79000fd339cc556045baccd5087231dd293db83195c927fa7"},"job:refine@r02/scope": {"bytes": 375, "sha256": "c4a7fdb0b390ec75d595006e11b9982113e60c49f5a62a978153167053bbcd33"},"job:refine@r02/system": {"bytes": 3173, "sha256": "c3879a563e2a512b82358d0c3927dcbfe9347725e592035a9b64c5d1b34e6654"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3985, "sha256": "d870900cac8f2619531f77b97eeacdaa18a2422cfdc3648394ad2f9bc80bb513"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3959, "sha256": "4dde2639e506ef0d2636bde47835d14b7f8702f43bdf5f4d7c6072ed65c6637c"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5038, "sha256": "86613ceff3c178c920863ab5c33e25efa6f3c8583b5acf1c0d756460a8d44598"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5012, "sha256": "2eadea804479eca53e39ff1fb2b505e71188e16cb38241b7e77dce40d5f97032"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 4123, "sha256": "a1f0c207406de6f415fdb8516b695aaedf7f06d25598f33932d2ad728f8c881f"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r02/input": {"bytes": 5034, "sha256": "e5ef544b5dc0b6f46cab4ab5944402afa53871a09efbaf69d7992aec865cdbed"},+ "judge:shader:runs/run/artifacts/renders/r02/input": {"bytes": 5008, "sha256": "260f183b612bd9ae84a5ad913e2fdd84788d144f9a24a14aba70d410caf861f6"},"judge:shader:runs/run/artifacts/renders/r02/messages": {"bytes": 4123, "sha256": "5b81b09f9d6a7e3225549454099d07143f5bb726c3ccff263b4afc7bfe13d88b"},"judge:shader:runs/run/artifacts/renders/r02/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r02/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -134,7 +134,7 @@"skills:runs/run:refine@r02/routed": {"bytes": 56, "sha256": "400eb18b3e0ca869392d11f9fc95c12140d8234f3efe8f3c1ec66b5c43d1ffa6"}},"stage_keys": {- "runs/run:plan": "d1428ecadc7f",+ "runs/run:plan": "6b5b2d8775b3","runs/run:skeleton": "7ad4f988e9ca"}},@@ -156,7 +156,7 @@"job:rebuild@r01/prompt": {"bytes": 11530, "sha256": "55b953a2ecd60c415cec8995694d1dc731bd0d8135bc594a1ba07d68b7f5f09f"},"job:rebuild@r01/scope": {"bytes": 379, "sha256": "471fba995682e47fe12099cb5881743a8aeae71a0243fa3598c72d69a5b31f98"},"job:rebuild@r01/system": {"bytes": 3173, "sha256": "c3879a563e2a512b82358d0c3927dcbfe9347725e592035a9b64c5d1b34e6654"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 3985, "sha256": "e367200e402b03487531c1963f3a52a62e69c5ae4a444cd79cf533f5a20b97b8"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 3959, "sha256": "df77c1b050ec2b6aacb408eeb09dc6b9ab0bd37e6aadea89a54db3ce9dffede3"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -164,7 +164,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 56, "sha256": "400eb18b3e0ca869392d11f9fc95c12140d8234f3efe8f3c1ec66b5c43d1ffa6"}},"stage_keys": {- "runs/run:plan": "d1428ecadc7f",+ "runs/run:plan": "6b5b2d8775b3","runs/run:skeleton": "7ad4f988e9ca"}},@@ -179,11 +179,11 @@"chat:planner:planner/messages": {"bytes": 348, "sha256": "f50fc3cdf3a426fc9c9b830b6e68d2cfe9fd9b7125550362b018f9c9b454b25c"},"chat:planner:planner/sampling": {"bytes": 3421, "sha256": "918170272cea656e8c542c54b777c57d1a4567a8cc36a0c1cd825cb81a01b9bb"},"chat:planner:planner/system": {"bytes": 11919, "sha256": "194d0e2a724c4799816033228af15cac568dd51c14ed85bff9c94ae5ba281866"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 4002, "sha256": "6bdd0dcae0cec619608a8c249e0aa9758412fc38b37451e82672fac1734ee746"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3976, "sha256": "6047e9f7c3985e1827f3ecc3263d87012c8a3c074b9bc33517e11e12751d2e58"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3727, "sha256": "d7deb2c4a1fa8e9b015a4e81439f9781e7618be6a01b013d18bb3acc4f6a32b9"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5055, "sha256": "873209f50a5429d7bdcf4421b197b8919edee65df20f60670c2f3f7957081dac"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5029, "sha256": "d3e2b3031ba4e6593d3c55af498869db17277952dcf5f320ac415bc04616aca7"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 4123, "sha256": "a1f0c207406de6f415fdb8516b695aaedf7f06d25598f33932d2ad728f8c881f"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -191,7 +191,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 68, "sha256": "cf6a7b5027626c144cf9f6ccc254f9bf6332217398c364638db88002139012ad"}},"stage_keys": {- "runs/run:plan": "d1428ecadc7f",+ "runs/run:plan": "6b5b2d8775b3","runs/run:skeleton": "7ad4f988e9ca"}},@@ -207,11 +207,11 @@"job:refine@r01/prompt": {"bytes": 4809, "sha256": "564c35401c05213d9906d0ecf84ead9e8c8a54ef51cae13eeb59fcb98e1b7275"},"job:refine@r01/scope": {"bytes": 354, "sha256": "81a4042ba077832530b2a9f64d3e1415da1b655b00caf1006ed51ee616a7b17b"},"job:refine@r01/system": {"bytes": 2729, "sha256": "d12d4891ce72156aa561bdfa0ed1fb20c5826412024b0be07b423949528e5df6"},- "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3989, "sha256": "a22f16438978b5696a35336dc39c53140d2ef0ba3d20f8edd278dfbf6102c0fa"},+ "judge:shader:runs/run/artifacts/renders/r00/input": {"bytes": 3963, "sha256": "5401be1bc487921af05b2dc05e8dc7c0fb7f2ee373d2741928c54417eee99b6e"},"judge:shader:runs/run/artifacts/renders/r00/messages": {"bytes": 3731, "sha256": "355b5a5eb7617171897155fe818a3975dea97d127ae8416f1352a67bb6a84a19"},"judge:shader:runs/run/artifacts/renders/r00/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r00/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},- "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5042, "sha256": "1c5de2d3c951c14714d0d911431c54742606fcf7d3ce3210725847f765c211fd"},+ "judge:shader:runs/run/artifacts/renders/r01/input": {"bytes": 5016, "sha256": "6e97c9effd603ac4a768006e2b4c63ce29506fe163aae8c36087f3f2f62390fc"},"judge:shader:runs/run/artifacts/renders/r01/messages": {"bytes": 4127, "sha256": "a4c4a41eea8d4af3df6646d2aa757c01a0ab663614361e61e76e84e21f9d5378"},"judge:shader:runs/run/artifacts/renders/r01/sampling": {"bytes": 11659, "sha256": "2f41a011f9775b7aaf1ec8c1594be4e9172d23f6eb6dfc4b262c6e6bf1097792"},"judge:shader:runs/run/artifacts/renders/r01/system": {"bytes": 11253, "sha256": "dcf75b56942831a1db5074023dfdad4b4750a3842eb4233dc2d41adacd1de67b"},@@ -219,7 +219,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 61, "sha256": "6cf132dce307379276e442875a061e8e0d099d50b70a8d18d4622abd9ce8ee8c"}},"stage_keys": {- "runs/run:plan": "f8b3f2dab137",+ "runs/run:plan": "2dae8a504e59","runs/run:skeleton": "52e9bc1e1abd"}},@@ -281,15 +281,15 @@"job:zones_quay_water@r00/prompt": {"bytes": 50923, "sha256": "0f6b6c68040e7d87ba4125f9dcd91823cfee0e47d6849aa41a3f1c4e0d3f4c25"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "d7cde9503b57c30d54062b7f12f1023f1510fad249cff287c3b771c306a065bf"},"job:zones_quay_water@r00/system": {"bytes": 6011, "sha256": "84a58b966fee66290cfdf85997e8ae0f25f840e457f4b331cac118873d2c5cef"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3716, "sha256": "fe258c1a4463f6af351f36b5ad19ff0b5bb9eeb66c923da13612dde6e8ccc3bc"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "8b1b52e0e3fd832fda14a7913d35cef8d5bda2cb02b8aea5a2935bbc1f7d5714"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "676859b5172ea33c86195b543b5c80e49dc907598dbdddb57a9734e58df9e8a1"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4716, "sha256": "98c77461082228940b414255328f36b407574528ce5a1adafe6a215ef66a8fd9"},+ "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "b546f93804fc3a29f245076f24cee36e64a1a7a5d45181f05eacc5bf59fc2dc0"},"judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "35679341c294b774ac1c228d9a2bc56f4792f8831dd1c216b513e4427e6cb0c1"},"judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4712, "sha256": "c1359d9418f423de52fe8de67878578f071f8c1941e1d1b277d7938b7e3404cc"},+ "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4686, "sha256": "5321b87318ce2cbdd7d3b6d6669d3283574a1e3034030803577f386c6e0d2d35"},"judge:scene:runs/run/artifacts/renders/r02/messages": {"bytes": 5298, "sha256": "0b15d27d13b64c082c86c2e4cea5d85a7f0b3e9daef93b5cb62f698d06570437"},"judge:scene:runs/run/artifacts/renders/r02/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r02/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -304,7 +304,7 @@"runs/run:assets": "47a6e0c9cb08","runs/run:env": "47a6e0c9cb08","runs/run:layouts": "47a6e0c9cb08",- "runs/run:plan": "8e0191e2d157",+ "runs/run:plan": "54e8de4267c4","runs/run:skeleton": "e42c2d2f88e0","runs/run:zones": "ffb8ffe86289"}@@ -342,11 +342,11 @@"job:zones_quay_water@r00/prompt": {"bytes": 38696, "sha256": "8524b350a4485277de24641c0a67881e56b7c25879100cee0210417af6403a62"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "d7cde9503b57c30d54062b7f12f1023f1510fad249cff287c3b771c306a065bf"},"job:zones_quay_water@r00/system": {"bytes": 7284, "sha256": "13fb6151a371cd11e8892f5b046bca581b917ccc1a267fef0aa4c189b26983f3"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3716, "sha256": "fe258c1a4463f6af351f36b5ad19ff0b5bb9eeb66c923da13612dde6e8ccc3bc"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "8b1b52e0e3fd832fda14a7913d35cef8d5bda2cb02b8aea5a2935bbc1f7d5714"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "676859b5172ea33c86195b543b5c80e49dc907598dbdddb57a9734e58df9e8a1"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4716, "sha256": "98c77461082228940b414255328f36b407574528ce5a1adafe6a215ef66a8fd9"},+ "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "b546f93804fc3a29f245076f24cee36e64a1a7a5d45181f05eacc5bf59fc2dc0"},"judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "35679341c294b774ac1c228d9a2bc56f4792f8831dd1c216b513e4427e6cb0c1"},"judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -360,7 +360,7 @@"runs/run:assets": "47a6e0c9cb08","runs/run:env": "47a6e0c9cb08","runs/run:layouts": "47a6e0c9cb08",- "runs/run:plan": "b72e02659933",+ "runs/run:plan": "a8963db58beb","runs/run:skeleton": "bb3344ab52c5","runs/run:zones": "7dd540d9edd0"}@@ -403,7 +403,7 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3733, "sha256": "2b7cec48dcea74e007c6358d8579fec0ec37ed1d189b8a042c0e13eee9fa1a0f"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3707, "sha256": "30b3e2a3c085d3231818fcaa188e1f93732151dd987f311121f2a5320110c27d"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "676859b5172ea33c86195b543b5c80e49dc907598dbdddb57a9734e58df9e8a1"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -417,7 +417,7 @@"runs/run:assets": "1fe4141b3b47","runs/run:env": "1fe4141b3b47","runs/run:layouts": "1fe4141b3b47",- "runs/run:plan": "8e0191e2d157",+ "runs/run:plan": "54e8de4267c4","runs/run:skeleton": "e42c2d2f88e0","runs/run:zones": "d83624cb1257"}@@ -435,7 +435,7 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26885, "sha256": "1dd3bb7f2490e9e655149e12cffeebcb43c6b91559b78bc942a4e38f741f7223"},+ "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -445,11 +445,11 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "context:runs/run/files": {"bytes": 56114, "sha256": "5f2b6a8aded7d754f30945bb62acdac9287caabef9fa56103e09962f6c669cda"},+ "context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},"job:asset_bollard@r00/prompt": {"bytes": 5182, "sha256": "eb2371d5d91daf0664ea4155eed95618b5798277e9b8e5cd118e48181aa499a3"},"job:asset_bollard@r00/scope": {"bytes": 357, "sha256": "450d659126efa73cdfe3371f18464e6ab40230af78367de6994d4712c9a8aaaf"},"job:asset_bollard@r00/system": {"bytes": 997, "sha256": "20d72b3bb074ab09ce4b2b6656b8bd0fcffef4fd3d437f2c171cb3efd96d475c"},- "job:env@r00/prompt": {"bytes": 47541, "sha256": "9b99f01eaaca7ad62a4e0ba8210f3c6c6d70fc095631a0c616dbbf067f597fb6"},+ "job:env@r00/prompt": {"bytes": 43448, "sha256": "1164ffe0334e8a194b523a848b0ab4001325df7919c87e8e8b6567f7dd25143e"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},"job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},"job:refine_quay@r01/prompt": {"bytes": 10092, "sha256": "7424fa604c576ccaa58bb104174f27b1ff6b38ea9682f3335170b1d821e73bd0"},@@ -464,18 +464,18 @@"job:refine_water@r02/prompt": {"bytes": 10096, "sha256": "99d6e0866d9bc4a9475f55db3e6b6efc7166bcb74b0bd80dd8157fa319086045"},"job:refine_water@r02/scope": {"bytes": 354, "sha256": "cbf41e8b42c1c64671a237a42d06bd8188616fd533a767c716e64758d211f737"},"job:refine_water@r02/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 53496, "sha256": "82b80505d5bb0ecc0ed5c7bc53f7d0bafdb8dc8102cb51c314e6628b3e7ffbcc"},+ "job:zones_quay_water@r00/prompt": {"bytes": 49403, "sha256": "49852823f06091b44f3e8a993529183dd622d60cf1c1cf9122442f51a8d3705e"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3716, "sha256": "f1aef1e33eb9c801d1b02bf7028d4a4738a56455427eaef288b8b4ad7016eeaf"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "5e7031f1c8d724681399e545e6adf0af8e6a8da6cae4364c7220a15b41f0744b"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4716, "sha256": "f86d30ec9fdd660eac0d9d4fdf9f445f523cc7d90c6bb8aa26ec5167e33fc351"},+ "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "ea728103072ad97014d8af107bb40109b9aef55ab30f817a017e3542b091682a"},"judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "c9a488e3385bb803ce084eda9a1ad2ed58c338201f1ad6d7f416cf0070f1a9f1"},"judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4712, "sha256": "dc6890544a07d3842f6c4577b6b3978211d9f32ec451b3b38a361bd43c0eddda"},+ "judge:scene:runs/run/artifacts/renders/r02/input": {"bytes": 4686, "sha256": "905a0f9912bb1052573d52017e5f838a18d429827cbcd52be7e6a7f6f40842f0"},"judge:scene:runs/run/artifacts/renders/r02/messages": {"bytes": 5298, "sha256": "d8e7af12d299bcc4d09f7b68a6cdf3de2816e89d0d785ff88153c9e3aa5ce8cd"},"judge:scene:runs/run/artifacts/renders/r02/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r02/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -490,7 +490,7 @@"runs/run:assets": "e3fcf2d29017","runs/run:env": "e3fcf2d29017","runs/run:layouts": "e3fcf2d29017",- "runs/run:plan": "28eda606da62",+ "runs/run:plan": "105b46262eac","runs/run:skeleton": "6bd35d0cf375","runs/run:zones": "0526c0ee5233"}@@ -520,7 +520,7 @@"chat:model:planner/system": {"bytes": 20977, "sha256": "0a3c2ea2bfb39981a166952054d1dcc10dffdf097d493e89b03e0b8586d2ee8e"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26885, "sha256": "1dd3bb7f2490e9e655149e12cffeebcb43c6b91559b78bc942a4e38f741f7223"},+ "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},"chat:planner:zone-layout#0/messages": {"bytes": 401, "sha256": "73206223434695497c74e5f8f5bc0a0f1b147a7dc38147645c6cf42b5372484b"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3391, "sha256": "fa6d28546a947ddc6ab8d0adb8af97a1605873109a47cf7f097f72d9788fd678"},@@ -531,25 +531,25 @@"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3361, "sha256": "9acfcedb047a4f1623c483cb99c1f8aa30fd1158e56f88d1c1518f138db1b34f"},"context:runs/run/_assets/crate/files": {"bytes": 32742, "sha256": "fee09c023ada7ce7895e070195596c0b5103ecc5dabf1cd86dbc5352775c90b2"},- "context:runs/run/files": {"bytes": 56114, "sha256": "5f2b6a8aded7d754f30945bb62acdac9287caabef9fa56103e09962f6c669cda"},+ "context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},"job:asset_crate@r00/prompt": {"bytes": 18032, "sha256": "27dfd5f4bedcc036f93c844230347401da2c4c4f8b1d300bfaece147b704c3fc"},"job:asset_crate@r00/scope": {"bytes": 430, "sha256": "3c4b45fd7cc847cc6a6a5f3b83784cddab99440be445d61f924f56b834cd1476"},"job:asset_crate@r00/system": {"bytes": 3716, "sha256": "6068eff7b8c36b4edcc5d64ead79bd3de7386e0bbaf4fb141210883fb34f8518"},- "job:env@r00/prompt": {"bytes": 47541, "sha256": "9b99f01eaaca7ad62a4e0ba8210f3c6c6d70fc095631a0c616dbbf067f597fb6"},+ "job:env@r00/prompt": {"bytes": 43448, "sha256": "1164ffe0334e8a194b523a848b0ab4001325df7919c87e8e8b6567f7dd25143e"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},"job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 53676, "sha256": "3b2b4db061b894aca9121f762690c234369d83ea0d960bb5172ad2f4a5684726"},+ "job:zones_quay_water@r00/prompt": {"bytes": 49583, "sha256": "89372b540939bb9cba1c787aecb7943bd7e4c2f1674546bde5f4d00172ddcf76"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/input": {"bytes": 3785, "sha256": "21bd05c59f26de033b992c9980f979b2bb36e4de54f47998ed8e0d9dd93dcb28"},+ "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/input": {"bytes": 3759, "sha256": "d3507d23f5a84d828cef7b6b6f9b2c5df3795a2c300ee7aaeb038af59267fc30"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/messages": {"bytes": 3099, "sha256": "eee511c765a105054417cb3fa37bf67c24bcf9022da44dc086385878a61d5f67"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/sampling": {"bytes": 8355, "sha256": "a80299c8dfc30739d05a0274526c361cb406c78a1ab5e923fcdf78d8c78ea73a"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate/system": {"bytes": 8834, "sha256": "8b52aa8a0e80ff6ba98f494c36013745f5dd07a4e1040d72ff7f55aeeb907ba5"},- "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/input": {"bytes": 3805, "sha256": "b87ed064f9857cfd4d2c6555cc545a0dd87de441a988ecd3411a9e582d2c2a3e"},+ "judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/input": {"bytes": 3779, "sha256": "91ec992fade8a7c1907c0888c2a65715a0ab1ec40ed8d2cd1037a976cf6e82e8"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/messages": {"bytes": 3099, "sha256": "eee511c765a105054417cb3fa37bf67c24bcf9022da44dc086385878a61d5f67"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/sampling": {"bytes": 8355, "sha256": "a80299c8dfc30739d05a0274526c361cb406c78a1ab5e923fcdf78d8c78ea73a"},"judge:asset:runs/run/_assets/crate/artifacts/renders/r00/assets/crate_fix/system": {"bytes": 8834, "sha256": "8b52aa8a0e80ff6ba98f494c36013745f5dd07a4e1040d72ff7f55aeeb907ba5"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3723, "sha256": "06066c33ccaef0d3151e448537ad71535fa1185a2c5b64794b15348d200e8b0e"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3697, "sha256": "dab5e24ca050491a18ba9f81e894fb7f1103e9d3a16bf93c708ac7fd6ab54944"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4937, "sha256": "407f918497c4e96ed25d4a9c5c968993644c2a43fadfcc1bc6a0c4f7e6a9d99f"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -562,7 +562,7 @@"runs/run:assets": "2e61537ff1c0","runs/run:env": "2e61537ff1c0","runs/run:layouts": "2e61537ff1c0",- "runs/run:plan": "28eda606da62",+ "runs/run:plan": "105b46262eac","runs/run:skeleton": "dba1ece541d0","runs/run:zones": "77a6039e286c"}@@ -577,15 +577,15 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26885, "sha256": "1dd3bb7f2490e9e655149e12cffeebcb43c6b91559b78bc942a4e38f741f7223"},- "context:runs/run/files": {"bytes": 56114, "sha256": "5f2b6a8aded7d754f30945bb62acdac9287caabef9fa56103e09962f6c669cda"},- "job:env@r00/prompt": {"bytes": 47541, "sha256": "9b99f01eaaca7ad62a4e0ba8210f3c6c6d70fc095631a0c616dbbf067f597fb6"},+ "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},+ "context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},+ "job:env@r00/prompt": {"bytes": 43448, "sha256": "1164ffe0334e8a194b523a848b0ab4001325df7919c87e8e8b6567f7dd25143e"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},"job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 52823, "sha256": "2a2e8d28955755da2036d29d9deb83a462d43e649e2e0845f0bab8cb746edf1c"},+ "job:zones_quay_water@r00/prompt": {"bytes": 48730, "sha256": "0c4385a64285a8527856475a914c1cc15e53ddcac9660ddc16f5cb35808f690d"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3716, "sha256": "639e646848634abcb37fb477595515720276cf73aff3a00f963fbbd747c6c5c7"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "ebaaf972b6033176defee1013c1eb8b83843caef8172efe2dba99ccfb339a33f"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -597,7 +597,7 @@"runs/run:assemble": "eb288074ac5b","runs/run:assets": "e3fcf2d29017","runs/run:env": "e3fcf2d29017",- "runs/run:plan": "28eda606da62",+ "runs/run:plan": "105b46262eac","runs/run:skeleton": "6bd35d0cf375","runs/run:zones": "799b540cc58b"}@@ -612,7 +612,7 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26885, "sha256": "1dd3bb7f2490e9e655149e12cffeebcb43c6b91559b78bc942a4e38f741f7223"},+ "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -622,26 +622,26 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "context:runs/run/files": {"bytes": 56114, "sha256": "5f2b6a8aded7d754f30945bb62acdac9287caabef9fa56103e09962f6c669cda"},- "job:env@r00/prompt": {"bytes": 47541, "sha256": "9b99f01eaaca7ad62a4e0ba8210f3c6c6d70fc095631a0c616dbbf067f597fb6"},+ "context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},+ "job:env@r00/prompt": {"bytes": 43448, "sha256": "1164ffe0334e8a194b523a848b0ab4001325df7919c87e8e8b6567f7dd25143e"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},"job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},"job:r00_baseline_repair1@r00/prompt": {"bytes": 3261, "sha256": "d6f7ee211ced016d303fba6017d6c0d86148b201135f6b9e659220f797bcc967"},"job:r00_baseline_repair1@r00/scope": {"bytes": 392, "sha256": "3321d34981a6a1b8621a35e4260c3378e9659f6371db48dbcfbd6a23e7d8547d"},- "job:r00_baseline_repair1@r00/system": {"bytes": 22966, "sha256": "3256222fb8ed89256633f06e4d5e772a25f523ae19e4d6664030233ce3a2b92f"},+ "job:r00_baseline_repair1@r00/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},"job:r00_baseline_repair2@r00/prompt": {"bytes": 3566, "sha256": "9095f72e1353c3ec863bff95f03c6de38ed4f19dc90420926eac8b9be360b7ec"},"job:r00_baseline_repair2@r00/scope": {"bytes": 394, "sha256": "7cb6a3e71ece9cc8d28cb865866a4877727e69d379c03d4a45a411b5414741d1"},- "job:r00_baseline_repair2@r00/system": {"bytes": 22966, "sha256": "3256222fb8ed89256633f06e4d5e772a25f523ae19e4d6664030233ce3a2b92f"},+ "job:r00_baseline_repair2@r00/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},"job:r01_refine_repair1@r01/prompt": {"bytes": 3261, "sha256": "d6f7ee211ced016d303fba6017d6c0d86148b201135f6b9e659220f797bcc967"},"job:r01_refine_repair1@r01/scope": {"bytes": 390, "sha256": "c69eaed8419cbb3ca77f53c7d3c95376ea17825ab53ecfb476b9c77c389a31d3"},- "job:r01_refine_repair1@r01/system": {"bytes": 22966, "sha256": "3256222fb8ed89256633f06e4d5e772a25f523ae19e4d6664030233ce3a2b92f"},+ "job:r01_refine_repair1@r01/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},"job:r01_refine_repair2@r01/prompt": {"bytes": 3566, "sha256": "9095f72e1353c3ec863bff95f03c6de38ed4f19dc90420926eac8b9be360b7ec"},"job:r01_refine_repair2@r01/scope": {"bytes": 392, "sha256": "68a7f7b764450f2c01bca83cc4ff4ccf70cc065902e80b97985922a7383ecd19"},- "job:r01_refine_repair2@r01/system": {"bytes": 22966, "sha256": "3256222fb8ed89256633f06e4d5e772a25f523ae19e4d6664030233ce3a2b92f"},+ "job:r01_refine_repair2@r01/system": {"bytes": 22749, "sha256": "5cd22054b3960b4e3e40aa9c3507bdaa4695eda55a300e3e631690560853f8bb"},"job:rebuild@r01/prompt": {"bytes": 10049, "sha256": "aa103063270f75b7b12d2f4e9d0795c02c69651ae119a3ee404e2e59391260a1"},"job:rebuild@r01/scope": {"bytes": 382, "sha256": "6ea60c37d5ea2360a24a236ed77174ca29ebdcb1ed8331da08e68fc494305dc9"},"job:rebuild@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 53496, "sha256": "82b80505d5bb0ecc0ed5c7bc53f7d0bafdb8dc8102cb51c314e6628b3e7ffbcc"},+ "job:zones_quay_water@r00/prompt": {"bytes": 49403, "sha256": "49852823f06091b44f3e8a993529183dd622d60cf1c1cf9122442f51a8d3705e"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},"skills:runs/run:baseline@r00/routed": {"bytes": 156, "sha256": "cae5ab46c39f9f4efb7ae3c4758b05d768025f93d525d5e13812b916a583fd30"},@@ -654,7 +654,7 @@"runs/run:assets": "e3fcf2d29017","runs/run:env": "e3fcf2d29017","runs/run:layouts": "e3fcf2d29017",- "runs/run:plan": "28eda606da62",+ "runs/run:plan": "105b46262eac","runs/run:skeleton": "6bd35d0cf375","runs/run:zones": "0526c0ee5233"}@@ -669,7 +669,7 @@"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26885, "sha256": "1dd3bb7f2490e9e655149e12cffeebcb43c6b91559b78bc942a4e38f741f7223"},+ "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -679,8 +679,8 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "context:runs/run/files": {"bytes": 56114, "sha256": "5f2b6a8aded7d754f30945bb62acdac9287caabef9fa56103e09962f6c669cda"},- "job:env@r00/prompt": {"bytes": 47541, "sha256": "9b99f01eaaca7ad62a4e0ba8210f3c6c6d70fc095631a0c616dbbf067f597fb6"},+ "context:runs/run/files": {"bytes": 55674, "sha256": "b13f8fe30cb373f4e8eae10b376ba430710b7c28fc71b830f63a35fefae4eb36"},+ "job:env@r00/prompt": {"bytes": 43448, "sha256": "1164ffe0334e8a194b523a848b0ab4001325df7919c87e8e8b6567f7dd25143e"},"job:env@r00/scope": {"bytes": 334, "sha256": "b94c09720c9e481759ea0408d7ef708c4d5a3e47b1c2b28a8d901a7c77d7c66b"},"job:env@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},"job:refine_quay@r01/prompt": {"bytes": 10092, "sha256": "7424fa604c576ccaa58bb104174f27b1ff6b38ea9682f3335170b1d821e73bd0"},@@ -689,14 +689,14 @@"job:refine_water@r01/prompt": {"bytes": 10097, "sha256": "2af3470e4b4cf5e411e22cc5402886696b2adc9eaf0460a7b934b5351ccb73e0"},"job:refine_water@r01/scope": {"bytes": 354, "sha256": "5c7aa29b996f768b637082248e69fbe65f7ed49d9f5abff27c464da564365b74"},"job:refine_water@r01/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "job:zones_quay_water@r00/prompt": {"bytes": 53496, "sha256": "82b80505d5bb0ecc0ed5c7bc53f7d0bafdb8dc8102cb51c314e6628b3e7ffbcc"},+ "job:zones_quay_water@r00/prompt": {"bytes": 49403, "sha256": "49852823f06091b44f3e8a993529183dd622d60cf1c1cf9122442f51a8d3705e"},"job:zones_quay_water@r00/scope": {"bytes": 379, "sha256": "5b1def419a1370ab2d9f2345bc4a5232ef3c793d4e4f1e01bd5ab9a3a8e88a7d"},"job:zones_quay_water@r00/system": {"bytes": 5614, "sha256": "b23b5fa6365b226f94f9cf4e9f3f7235628d22c1bee3ca22c6f44406ce518cdb"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3716, "sha256": "f1aef1e33eb9c801d1b02bf7028d4a4738a56455427eaef288b8b4ad7016eeaf"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3690, "sha256": "5e7031f1c8d724681399e545e6adf0af8e6a8da6cae4364c7220a15b41f0744b"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},- "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4716, "sha256": "f86d30ec9fdd660eac0d9d4fdf9f445f523cc7d90c6bb8aa26ec5167e33fc351"},+ "judge:scene:runs/run/artifacts/renders/r01/input": {"bytes": 4690, "sha256": "ea728103072ad97014d8af107bb40109b9aef55ab30f817a017e3542b091682a"},"judge:scene:runs/run/artifacts/renders/r01/messages": {"bytes": 5298, "sha256": "c9a488e3385bb803ce084eda9a1ad2ed58c338201f1ad6d7f416cf0070f1a9f1"},"judge:scene:runs/run/artifacts/renders/r01/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r01/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -710,7 +710,7 @@"runs/run:assets": "e3fcf2d29017","runs/run:env": "e3fcf2d29017","runs/run:layouts": "e3fcf2d29017",- "runs/run:plan": "6aa5a2da6b3e",+ "runs/run:plan": "23a48aef8e1b","runs/run:skeleton": "6bd35d0cf375","runs/run:zones": "0526c0ee5233"}@@ -729,21 +729,21 @@"chat:model:asset_fishing_boat:r00/messages": {"bytes": 3365, "sha256": "583f9c5888c4ff1567e3cbb2d9e3e8701e31169fd30f295d89dae16e046e55cc"},"chat:model:asset_fishing_boat:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},"chat:model:asset_fishing_boat:r00/system": {"bytes": 3483, "sha256": "79f9f153926a1b9edee34e0fbc13767ff419319c18575fc0ad2bb553d9e6f3ad"},- "chat:model:env:r00/messages": {"bytes": 50719, "sha256": "3b8afa7c088512b3bfc6445896fed38aacaa43edaf26c960e1865834cd332c94"},+ "chat:model:env:r00/messages": {"bytes": 46387, "sha256": "c4b540046974c278989f9361925e006c1825d93fdf544c8eab922676b7a72165"},"chat:model:env:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},"chat:model:env:r00/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},- "chat:model:refine_quay:r01/messages": {"bytes": 12743, "sha256": "6e2f8e2e31894a19a9b2f53eeaf49a912d8c275000d544fdbe8799914fbf8424"},+ "chat:model:refine_quay:r01/messages": {"bytes": 12521, "sha256": "7f839ae609b083385bc8a1c2d960e0d9c31842cac9e3c95f2c74d2afea73de17"},"chat:model:refine_quay:r01/sampling": {"bytes": 92, "sha256": "2a36044e5c117fc288123a5937c6e3cb5845f040b4de69f9c2440f623956c381"},"chat:model:refine_quay:r01/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},- "chat:model:refine_water:r01/messages": {"bytes": 12749, "sha256": "6d7aa7a9336bc7c56c169f3e59e64f8ea5ca1f703bdc22442d5a57ac48c19f61"},+ "chat:model:refine_water:r01/messages": {"bytes": 12527, "sha256": "c7684c66aed9311a614b682e72e5698a373e6b8ac81f7669eda75389f8157fa4"},"chat:model:refine_water:r01/sampling": {"bytes": 92, "sha256": "2a36044e5c117fc288123a5937c6e3cb5845f040b4de69f9c2440f623956c381"},"chat:model:refine_water:r01/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},- "chat:model:zones_quay_water:r00/messages": {"bytes": 56535, "sha256": "94637b6f2d5ffd44651f34af82ae45502fdd75bd8df1250c2a12ace6c2fa87d5"},+ "chat:model:zones_quay_water:r00/messages": {"bytes": 52203, "sha256": "83aabee30c7a9fee9aaaa749b37c1ff8fcaaefebd079834cfce1d03f9a1bb82c"},"chat:model:zones_quay_water:r00/sampling": {"bytes": 92, "sha256": "08e72af1b4fb249378c5a151e019ded70a1014eafa4d50f70927bb225f695678"},"chat:model:zones_quay_water:r00/system": {"bytes": 7632, "sha256": "2c187b396badbf62b604234f29d488679bf5a0446f67f0cfacb703509fc1e8ea"},"chat:planner:planner/messages": {"bytes": 204, "sha256": "b91c27cbf7a8071bf320a68a6113bd25896bf0422f92b9087fb155bad18dbdc1"},"chat:planner:planner/sampling": {"bytes": 8047, "sha256": "ac5eba7173d30fcdfc0682ff102fc65e9f4325a5a4f1fbdaca4b0dcd4547d4b1"},- "chat:planner:planner/system": {"bytes": 26885, "sha256": "1dd3bb7f2490e9e655149e12cffeebcb43c6b91559b78bc942a4e38f741f7223"},+ "chat:planner:planner/system": {"bytes": 26758, "sha256": "aab6253b3d1b9716c2e6e1786d07b89bd8efabb1f2476f5f9c10e18b3fe6ae8f"},"chat:planner:zone-layout#0/messages": {"bytes": 331, "sha256": "eeefd42e9d8d37a901af0ae126aebf39fb2e7861fabe6208d3a9408e1a3c1b37"},"chat:planner:zone-layout#0/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#0/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},@@ -753,7 +753,7 @@"chat:planner:zone-layout#2/messages": {"bytes": 485, "sha256": "67e917190ee227c5ed3415ab4b03c072af313d7040704e7de671e63c42e2ab52"},"chat:planner:zone-layout#2/sampling": {"bytes": 3397, "sha256": "160445a83ede28afc0191547fd42d9341e694ef70aaad380bebf60ead0a65c49"},"chat:planner:zone-layout#2/system": {"bytes": 3326, "sha256": "494acec302dd23fa2fc6ee1eb6d48e873d6cf0ad98bad413e27578cf062313d4"},- "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3733, "sha256": "ddb88a5a2eb5eb6ec089d4079b3a8609517bac917d2d51059562020b5250c1a5"},+ "judge:scene:runs/run/artifacts/renders/r00/input": {"bytes": 3707, "sha256": "8f701fd0fdbfc05436f36752f885dce6996d23adc4ecca76a446ebfb676fff5f"},"judge:scene:runs/run/artifacts/renders/r00/messages": {"bytes": 4930, "sha256": "562ef4bfc6b24c34604482cb73a02fb4b01da5c0e70685e3a1a4e1dda616a827"},"judge:scene:runs/run/artifacts/renders/r00/sampling": {"bytes": 14066, "sha256": "1f67b211de491259bed48f1499b8dbd9fa2037a903a637ba53befda40ade693d"},"judge:scene:runs/run/artifacts/renders/r00/system": {"bytes": 21572, "sha256": "eee5e34a58a91720755be68ed4d39cf127c634a484a4948e77c77ecce7e8cd16"},@@ -767,7 +767,7 @@"runs/run:assets": "212efeee2ac5","runs/run:env": "212efeee2ac5","runs/run:layouts": "212efeee2ac5",- "runs/run:plan": "28eda606da62",+ "runs/run:plan": "105b46262eac","runs/run:skeleton": "6bd35d0cf375","runs/run:zones": "b12775da7b08"}@@ -792,19 +792,19 @@"job:refine@r01/prompt": {"bytes": 7038, "sha256": "7567826ea7793e5f05f355c236b5984aa89abde8942f86b2a9e8a2e1881096c6"},"job:refine@r01/scope": {"bytes": 426, "sha256": "3a39df2f37665e52ae78549431ea567fa9591605332e152cd7d41d2b58914893"},"job:refine@r01/system": {"bytes": 2865, "sha256": "e8bdde0b2251c9f422c9a02c8c457543798280f5215e740312ffb73f1d0d867f"},- "judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/input": {"bytes": 5506, "sha256": "d02a6dd07a7c89ec86318d139d61f8642d01212c112170dd29a5107c020e701d"},+ "judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/input": {"bytes": 5480, "sha256": "d0f5d8618797710a5a8672d0e150fe844e47964c684f564870815881b8fccd22"},"judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/messages": {"bytes": 4246, "sha256": "029c3c03fe1f78f6f0d8b6b1b6bb4825d2851b55595a3c15c1a03f052b0b9771"},"judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/_cand/c0/artifacts/renders/r00/quick/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/input": {"bytes": 5506, "sha256": "737a9b37288d80c9b7a6c2ef0ce259ca210a69e16afd8adca2a180740555acc2"},+ "judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/input": {"bytes": 5480, "sha256": "634a91a0f2eb65344528e8d83e744d8eba81d77d1b8697885a023f546199bef5"},"judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/messages": {"bytes": 4246, "sha256": "029c3c03fe1f78f6f0d8b6b1b6bb4825d2851b55595a3c15c1a03f052b0b9771"},"judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/_cand/c1/artifacts/renders/r00/quick/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9069, "sha256": "bb74a30f22b7373eb8decd7c72a97787035333bb29c4b9abc11dfcc4ff71caac"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9043, "sha256": "dbaaabdbe8a66ecafe6caaf78c9d263dea54caa61f73b1c2a58356ac4eb232e8"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6699, "sha256": "7df542d34f969f456ab2fcd720b5ccf3a4547b1c57ed59a81df0a84a4d540b9a"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10282, "sha256": "fef8a89f93d63c2c547092f93b3ad64e53d2d34ef1a844456cc66868503b2365"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10256, "sha256": "039d3ffebaf48a6e6adb10eeb65db4d8be1c1902af599781104b174ea82108f8"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7124, "sha256": "a800f572433fa02006cc5a02c883359497949586963a0edeb799e047048d8f2c"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -814,7 +814,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 133, "sha256": "53e382eba5cd3e9e5438941f437cd2148cca27c331d46ccbb73fb8b1b092a9dc"}},"stage_keys": {- "runs/run:plan": "6f3091aaf16f",+ "runs/run:plan": "1fa4423b7ab2","runs/run:skeleton": "65d9bf7a6805"}},@@ -842,11 +842,11 @@"job:refine@r02/prompt": {"bytes": 7215, "sha256": "7d084dc936a0ca89af24a348321c9a88fd523c8353a034fe3bb37df511bcfe8e"},"job:refine@r02/scope": {"bytes": 350, "sha256": "4e7e7adc88c67e32725d4fbf7d2f95b24d0166d57881f69cf543ab1c6936ea35"},"job:refine@r02/system": {"bytes": 2205, "sha256": "2ca6cc8997115b5940dcef874355b65c82f25ee8000b964fe0ad96dce25ac0e8"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 9474, "sha256": "d668346739953b6399d84d1b68e79839aac99431c4ecdf2df7f57d5191797d72"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 9448, "sha256": "57f45cc8b04164a946635a087e7a5d925c8da6ba463e595f7f9723a3c8c49b4b"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 6808, "sha256": "afe220b9286ff63c1e78b62cf853ead93c525947a873c6eaea80d9094a9d483e"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10683, "sha256": "cc853b23b3fb38d3b5056a01e023b40e1573f306768180cc6bd82238773f7b8b"},+ "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10657, "sha256": "c43068c990f633b1a5cfe0136b3c6255f37d49b4724aadc45bcafe17f5280b36"},"judge:static_object:runs/run/artifacts/renders/r02/messages": {"bytes": 7233, "sha256": "d6a82300f22e09f4cc9f7d5a09ec89e5c6e9b300eab6b8899fc61648ac406c21"},"judge:static_object:runs/run/artifacts/renders/r02/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r02/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -855,7 +855,7 @@"skills:runs/run:refine@r02/routed": {"bytes": 134, "sha256": "f11f63910f028add64068034f65c2875924ea57ea94bc407859b8b1e1050c6b6"}},"stage_keys": {- "runs/run:plan": "5f878927a85a",+ "runs/run:plan": "dda15c4ec2ee","runs/run:skeleton": "1a2d68e2a2e3"}},@@ -877,15 +877,15 @@"job:refine@r02/prompt": {"bytes": 7174, "sha256": "3474b8ace6d7212c7430b362f161485f9243cdc6ef3118dc5d342c8720b85de5"},"job:refine@r02/scope": {"bytes": 428, "sha256": "57e2f2633c63ce908a2842199385fe002439dcc7d6f68ffac0261d5be22cb8e1"},"job:refine@r02/system": {"bytes": 3208, "sha256": "e24e99f321231e5587cae7f4fbbbcc50fbd254768f4f4c860c4dfa8f83804810"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9268, "sha256": "fc4f28df96ba174b164679ccfccd2b872f429d9aea3c27fdbc443b17a98603fb"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9242, "sha256": "24388c1c7e23be39af16276200ef38c874d6bd7a6f5efc2e8af4a639ac9ccaa9"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6756, "sha256": "447c252713a4d26c70c0b368c30217605f33543c3a329b6c32bee7099bdb1860"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10481, "sha256": "81c40cbc62148d817be68ae395caf69f59f50a475f3995f2c0e7463db43ce259"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10455, "sha256": "3b59af59898d972cffb2178b608d9ffba14af4b76f5eb7b96993e3536cb8b29e"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7181, "sha256": "0ee41f64bf25c8490c05f3478f11afde83f2d8fc7f4753553d7497f1ef83543a"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10477, "sha256": "6fd11fb0202546333870a439938f8887593174fe5483785e7893b24baf117fc7"},+ "judge:static_object:runs/run/artifacts/renders/r02/input": {"bytes": 10451, "sha256": "e47aeb8f1cb8ad461a97940370c9fdd54d95a077c9a84df047a51167c66a5f64"},"judge:static_object:runs/run/artifacts/renders/r02/messages": {"bytes": 7181, "sha256": "61b52dd59cc941e842e0e789faf595cd9ed24187eba10e7cc399e1ca792eb099"},"judge:static_object:runs/run/artifacts/renders/r02/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r02/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -894,7 +894,7 @@"skills:runs/run:refine@r02/routed": {"bytes": 133, "sha256": "518f7b7ba0343e508a61d4b00f2c7628ee771ef0cd1766d631194f988152e858"}},"stage_keys": {- "runs/run:plan": "31ab234e1554",+ "runs/run:plan": "b17889f442b9","runs/run:skeleton": "58657cfb09d9"}},@@ -913,11 +913,11 @@"job:refine@r01/prompt": {"bytes": 8861, "sha256": "40ce1992b720f3a98f57dedeab35b70590f3f9a49ef111a544a300896fa39a35"},"job:refine@r01/scope": {"bytes": 644, "sha256": "f5e0c8fc1e3c0527734f358ad11929cedc505d872e61bbbfa4926d2cf5f4a1d0"},"job:refine@r01/system": {"bytes": 3208, "sha256": "e24e99f321231e5587cae7f4fbbbcc50fbd254768f4f4c860c4dfa8f83804810"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 11173, "sha256": "e9772a34126dd442236ffc8abf3bc52e81aadefb65131915fa8689fcc661144a"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 11147, "sha256": "cea087f4cc7335c78c7dbe31cd08285d097c7627cb53151853c3d882639b6f8b"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 7002, "sha256": "90d9f0c3e869c20608b23834b3a93df8242b1dd3324fdfda3b91de9542337eb0"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11134, "sha256": "f825a8da4e119120216c23d2d3433cbf49ab7107bb97d58f7cd8359d7bd8eb45"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 12358, "sha256": "6f8bebf86689b3e4fc8b1b6c85abc6e6c616f562dcf001251f47aa0886e35610"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 12332, "sha256": "6879d4d19d95bb191dba70f85960b7fc5a2b385d850cdbc7b5f57a0f86a2e6e3"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7429, "sha256": "70fca81684fcce477eadc3e0d5c329b3dcc31dcc527958abf29e484a0d555a7c"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11134, "sha256": "f825a8da4e119120216c23d2d3433cbf49ab7107bb97d58f7cd8359d7bd8eb45"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -925,7 +925,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 104, "sha256": "754997d8db8e89f9b7b0379fceda29998c2e42d362fcaec169d7bd48fc097d3b"}},"stage_keys": {- "runs/run:plan": "31ab234e1554",+ "runs/run:plan": "b17889f442b9","runs/run:skeleton": "fb24414f9aea"}},@@ -944,11 +944,11 @@"job:refine@r01/prompt": {"bytes": 7012, "sha256": "9db3905eac671203349cd349d93748e1abadf89a9f584948cf3e64f0527abbcd"},"job:refine@r01/scope": {"bytes": 428, "sha256": "186e31cec33c5144bbc9713eb76374ef7608534682433c9a9288191efc417ec4"},"job:refine@r01/system": {"bytes": 3208, "sha256": "e24e99f321231e5587cae7f4fbbbcc50fbd254768f4f4c860c4dfa8f83804810"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9069, "sha256": "112ee7ab4e72d2441c6734f37e7300ab81c61e83b98589096ffc795f0fd8405b"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9043, "sha256": "e6f38103435ee5364a2bf61e2caedd75d4f4a7cf77c7d03d38d202bd8f73c1fa"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6699, "sha256": "6e3964ce3478de892b3c5dde9eb3154e9a54c2a669315a8e6f4b808c15dd930c"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10282, "sha256": "69e0340501fc86b997956c7cb421e8b6aae9b1e9eef6c86d385394677aadfc6f"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10256, "sha256": "211aff02135e7034dd64d7c3c0a812acfad49abb4b87b6a441ddbb355d9e9117"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7124, "sha256": "0e3a5d3ed25799eec213d2d7fd92ae5009e4d88d5a818eeaf0aef3de8d47b932"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -956,7 +956,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 133, "sha256": "537d8d98029fd6345c9d4a73eaf3615c7924c18a405b3ab633283694e23b1804"}},"stage_keys": {- "runs/run:plan": "31ab234e1554",+ "runs/run:plan": "b17889f442b9","runs/run:skeleton": "58657cfb09d9"}},@@ -977,11 +977,11 @@"chat:planner:planner/messages": {"bytes": 1354, "sha256": "5b1a589e27562a3668649aed4be4857a34804a2acdc140eb8fb3630d970f71a6"},"chat:planner:planner/sampling": {"bytes": 6272, "sha256": "04dbfbbd42d8b93a12571a1908beacc7eb471e6f2c0fc077371aa86e2a99fb40"},"chat:planner:planner/system": {"bytes": 18298, "sha256": "0483e07168e1b18aeb18cda38887e719a4c3993161c600c61da469ff2fccd4f4"},- "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9086, "sha256": "669af81897f573fef5c38a2c09f1d8e73203916481cb746baa067414a9943982"},+ "judge:static_object:runs/run/artifacts/renders/r00/input": {"bytes": 9060, "sha256": "9db5de7f375d60e4e56f9677affd8c4fbe4261f62d0111d1c021f08dcd5690bf"},"judge:static_object:runs/run/artifacts/renders/r00/messages": {"bytes": 6699, "sha256": "6e3964ce3478de892b3c5dde9eb3154e9a54c2a669315a8e6f4b808c15dd930c"},"judge:static_object:runs/run/artifacts/renders/r00/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r00/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},- "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10299, "sha256": "8162ff275ce387f5741d6aa215e3666ee6f519eb0c84a1b4ec9df2e7b01a96dd"},+ "judge:static_object:runs/run/artifacts/renders/r01/input": {"bytes": 10273, "sha256": "97bda1184c1cd78145113857ec2e8917f6f51bd969f028f9dac064b1ee9dd0bb"},"judge:static_object:runs/run/artifacts/renders/r01/messages": {"bytes": 7124, "sha256": "0e3a5d3ed25799eec213d2d7fd92ae5009e4d88d5a818eeaf0aef3de8d47b932"},"judge:static_object:runs/run/artifacts/renders/r01/sampling": {"bytes": 11368, "sha256": "d689cdebe9d63a438597fd51e16228f8d5fed5d5693c736223ce782f62a12242"},"judge:static_object:runs/run/artifacts/renders/r01/system": {"bytes": 15178, "sha256": "1becebca9df2996a380a8bedede59de191c58f5021c6f687a3dfd5abc673c4bc"},@@ -989,7 +989,7 @@"skills:runs/run:refine@r01/routed": {"bytes": 148, "sha256": "67ba73ea33f42a757e533e24b318438e321943eeb47470a930fbcfda97e72e93"}},"stage_keys": {- "runs/run:plan": "31ab234e1554",+ "runs/run:plan": "b17889f442b9","runs/run:skeleton": "58657cfb09d9"}}diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.pyindex 8d6f3739..057770dc 100644--- a/harness/tests/prompts/manifest.py+++ b/harness/tests/prompts/manifest.py@@ -1,34 +1,17 @@"""The prompt + judge-payload manifest: what every model is shown, hashed (permanent: owner, 2026-09-22).-Every track runs offline through the fakes of ``tests/orchestrator_tracks/fakes.py`` in the-scenarios of :data:`SCENARIOS`. Everything a model would receive is captured, normalised (the-scenario's tmp root becomes ``<TMP>``; timestamps, durations, clock-derived waits and image bytes-are dropped) and stored in ``manifest.json`` as ``kind → {sha256, bytes}``:--* ``job:<label>@rNN/{prompt,system,scope}`` — every coding-agent session (``FakeAgent.jobs``);-* ``chat:<role>:<label>/{system,messages,sampling}`` — every chat call: the ``planner`` (brief,- plan, re-asks, zone layouts) and the ``model`` (single-shot generation, the scene's single-shot- assets, a hero's own planner);-* ``judge:<rubric>:<renders dir>/{input,system,messages,sampling}`` — every verdict: the- ``JudgeInput`` the in-run judge reads (``FakeJudge.calls``) and the request the real- ``VlmJudge`` builds from it;-* ``context:<workspace>/files`` — what a session reads in its workspace, as materialised- (AGENTS/CLAUDE.md, the ignore file);-* ``skills:<workspace>:<kind>@rNN/routed`` — the skill bundles routed to a round;-* ``mcp_tools:<track>/<language>`` — the MCP tool list a session is offered;--and every cached stage's key under ``stage_keys``. A code-only change leaves all of it-byte-identical. A change that means to alter what a model sees re-blesses it in the same commit,-saying why::+Every track runs offline through the fakes of ``tests/orchestrator_tracks/fakes.py`` in the scenarios of+:data:`SCENARIOS`. Every agent job, chat call, judge request, workspace context file, routed skill bundle+and MCP tool list is captured, normalised (tmp root -> ``<TMP>``; timestamps, durations and image bytes+dropped) and stored in ``manifest.json`` as ``kind -> {sha256, bytes}``, with every cached stage's key under+``stage_keys``. A change that means to alter what a model sees re-blesses it in the same commit::python -m tests.prompts.manifest # compare this tree with manifest.jsonpython -m tests.prompts.manifest --bless # rewrite manifest.json from this treepython -m tests.prompts.manifest --dump DIR # every payload as a file: diff two trees' dumps-Not covered (the fakes cannot drive it): reference-image runs (reference and likeness judges, the-silhouette gate), replays (``3dcode judge``),-the budget-stop salvage (the clock is frozen), the node asset checker (a python stand-in answers)-and each vendor CLI's own framing of a session (only agy's workspace files are built).+Not covered (the fakes cannot drive it): reference-image runs, replays, the budget-stop salvage, the node+asset checker and each vendor CLI's own framing of a session."""from __future__ import annotations@@ -102,7 +85,7 @@ BRIEF = {"object_name": "DiningChair", "reference": "a Danish oak dining chair","mechanism": "the legs carry the seat", "visible_from_outside": ["seat", "legs", "backrest"],"signature_features": ["tapered legs", "curved backrest"], "materials": ["seat: oiled oak"]}CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".antigravityignore")-VOLATILE = frozenset({"duration_ms", "duration_s", "latency_ms", "max_wait_s", "timeout_s", "hard_deadline_s", "workspace", "data_b64"})+VOLATILE = frozenset({"duration_ms", "duration_s", "latency_ms", "max_wait_s", "timeout_s", "hard_deadline_s", "workspace"})SHADER = ("void mainImage(out vec4 fragColor, in vec2 fragCoord) {{\n vec2 uv = fragCoord / u_resolution.xy;\n"" // {tag}\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}}\n")PROGRAM = ("import moderngl # {tag}\n\n\ndef setup(ctx, width, height):\n return {{}}\n\n\n"@@ -117,12 +100,11 @@ def isolated(root: Path) -> Iterator[None]:part of its prompt), caches and ledgers under ``root``, and the node asset checker answered inpython (``_asset_check``)."""env, cwd = dict(os.environ), os.getcwd()- for k in [k for k in os.environ if k.startswith(("C3D_", "CV3D_"))]:+ for k in [k for k in os.environ if k.startswith("C3D_")]:del os.environ[k]os.environ["C3D_CACHE_DIR"] = str(root / "cache")with contextlib.ExitStack() as stack:for target, name, value in ((config, "_USER_CONFIG", root / "absent.yaml"),- (config, "_LEGACY_USER_CONFIG", root / "absent.yaml"),(BudgetGuard, "elapsed_minutes", lambda self: 0.0),(ledger, "_fallback", ledger.CostLedger(root / "process.jsonl")),(scene_assets, "check_threejs_asset", _asset_check),@@ -214,8 +196,8 @@ class ManifestServices(FakeServices):def tool_cards(self, track: str, language: str) -> str:return Services.tool_cards(self, track, language)- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, spatial_tools: bool) -> None:- Services.materialize(self, ws, agent_kind=agent_kind, contract_md=contract_md, spatial_tools=spatial_tools)+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str) -> None:+ Services.materialize(self, ws, agent_kind=agent_kind, contract_md=contract_md)self.materialized.append(agent_kind)self.contexts.append((ws.root, {n: (ws.root / n).read_text() for n in CONTEXT_FILES if (ws.root / n).is_file()}))@@ -497,7 +479,7 @@ def capture(rig: Rig) -> dict[str, str]:for job in rig.agent.jobs:items.append((f"job:{job.label}@r{job.round:02d}", {"prompt": norm(job.prompt), "system": norm(job.system_append),- "scope": _json(norm(job.model_dump(exclude={"prompt", "system_append", "env", "mcp_command"})))}))+ "scope": _json(norm(job.model_dump(exclude={"prompt", "system_append", "env"})))}))for role, model in (("planner", rig.planner), ("model", rig.model)):items += [(f"chat:{role}:{req.label}", chat_payloads(req, norm)) for req in model.requests]for judge in rig.services.judges:diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.pyindex ecd65d66..e9aa2af2 100644--- a/harness/tests/prompts/test_files.py+++ b/harness/tests/prompts/test_files.py@@ -22,21 +22,11 @@ def test_prompt_file_contract(rel: str) -> None:for seq in ("{{", "{%", "{#"):assert seq not in raw, f"{rel} contains {seq!r} which breaks jinja rendering"--def test_every_language_ships_a_system_prompt_and_a_contract_and_no_cookbook() -> None:- """A missing per-language file silently reads as "" through ``language_text`` — so the two files- every language needs are pinned present, and the cookbook pinned ABSENT for every language (D107,- owner 2026-10-15: a cookbook that came back would be prompt material a model copies verbatim)."""- from codeverse3d.prompts.catalog import language_text+def test_every_language_ships_a_system_prompt_and_a_contract() -> None:+ """A missing per-language file silently reads as "" through ``language_text``."""from codeverse3d.tracks.prompting import language_system_promptfor lang in Language:- text = language_system_prompt(lang)- assert text.strip(), f"{lang.value}: empty system prompt"+ assert language_system_prompt(lang).strip(), f"{lang.value}: empty system prompt"for name in ("system.md", "contract.md"):assert (PROMPTS_DIR / language_prompt(lang, name)).is_file(), (lang.value, name)- assert not (PROMPTS_DIR / language_prompt(lang, "cookbook.md")).is_file(), (lang.value, "ships a cookbook")- assert language_text(lang, "cookbook.md") == ""- assert language_prompt(Language.URDF_BLENDER, "contract.md") == "urdf/contract.md"- for role in ("asset", "repair"):- assert (PROMPTS_DIR / "system" / f"role_{role}.j2").is_file(), rolediff --git a/harness/tests/prompts/test_manifest.py b/harness/tests/prompts/test_manifest.pyindex 45f4208b..438abe03 100644--- a/harness/tests/prompts/test_manifest.py+++ b/harness/tests/prompts/test_manifest.py@@ -16,7 +16,6 @@ def scenario(request, tmp_path_factory) -> tuple[str, dict]:name = request.paramreturn name, M.digest(M.run_scenario(name, tmp_path_factory.mktemp(name.replace(".", "_"))))-@pytest.mark.parametrize(("section", "hint"), [("payloads", M.PAYLOAD_HINT), ("stage_keys", M.STAGE_HINT)],ids=["payloads", "stage_keys"])def test_the_run_matches_the_manifest(scenario, section: str, hint: str) -> None:@@ -26,6 +25,5 @@ def test_the_run_matches_the_manifest(scenario, section: str, hint: str) -> Nonelines = M.diff(got[section], stored[name][section])assert not lines, f"{name}: {section} changed\n" + "\n".join(lines) + "\n\n" + hint-def test_the_manifest_holds_exactly_the_scenarios() -> None:assert sorted(M.load()) == M.ALL, "bless after adding or removing a scenario"diff --git a/harness/tests/prompts/test_snippets_run.py b/harness/tests/prompts/test_snippets_run.pyindex 23218fc8..f3b8b8cf 100644--- a/harness/tests/prompts/test_snippets_run.py+++ b/harness/tests/prompts/test_snippets_run.py@@ -1,19 +1,9 @@-"""The contracts' promise: each language's ONE interface example RUNS (D107 — no language ships a-cookbook; the example in contract.md is the whole of a language's runnable prompt material).--* cadquery blocks run in-process (cadquery is a plain library).-* bpy blocks run in real headless Blender (marker: blender).-* js blocks run in real node against runtime_js/node_modules (marker: node).--The tests pin the INTERFACE the example demonstrates (it builds through the real runtime, exports-what the wrapper reads, sits on the ground), never its shape, part names or counts — the example is-a stub, not a worked object.-"""+"""The contracts' promise (D107): each language's ONE interface example in contract.md RUNS - cadquery in-process,+bpy in headless Blender (marker: blender), js in node (marker: node). The tests pin the INTERFACE the example+demonstrates, never its shape, part names or counts."""from __future__ import annotations-from pathlib import Path-import pytestfrom codeverse3d.config import get_settings@@ -26,25 +16,16 @@ from tests.prompts.conftest import (# --------------------------------------------------------------------- cadquery-def _exec_python_blocks(rel: str) -> dict:- pytest.importorskip("cadquery")- ns: dict = {}- bodies = blocks(rel, "python")- assert bodies, f"{rel} carries no python block: a language keeps ONE executable interface example"- for i, body in enumerate(bodies):- try:- exec(compile(body, f"{rel}:block{i}", "exec"), ns) # noqa: S102 - our own docs- except Exception as e: # pragma: no cover - failure path- pytest.fail(f"{rel} python block {i} failed: {type(e).__name__}: {e}")- return ns--def test_cadquery_contract_example_runs() -> None:"""The example defines ``result`` (what the wrapper exports), an Assembly with at least onenamed child, lowest point on the ground."""pytest.importorskip("cadquery") # the [cad] extra — absent on a [dev]-only install (CI)- ns = _exec_python_blocks("cadquery/contract.md")+ ns: dict = {}+ bodies = blocks("cadquery/contract.md", "python")+ assert bodies, "cadquery/contract.md keeps ONE executable interface example"+ for body in bodies:+ exec(compile(body, "cadquery/contract.md", "exec"), ns) # noqa: S102 - our own docsresult = ns["result"]assert result.children, "the example must add at least one named part"assert all(c.name for c in result.children)@@ -52,13 +33,10 @@ def test_cadquery_contract_example_runs() -> None:assert abs(bb.zmin) < 1e-6, f"not on the ground: zmin {bb.zmin}"assert bb.zmax > 0.01-# --------------------------------------------------------------------- blender@pytest.mark.blenderdef test_blender_contract_example_builds_and_exports(tmp_path) -> None:- """The example's labelled files (``src/model.py`` + any ``src/parts/*.py``) run in headless Blender- the way the wrapper runs them (``src/`` on ``sys.path``, ``model.py`` executed) and leave at least- one named mesh object that exports to a GLB with its lowest point on the ground (Y-up after export)."""+ """The example's labelled files (``src/model.py`` + any ``src/parts/*.py``) run in headless Blender the way..."""files = labelled_files("blender/contract.md", tag="python")assert "src/model.py" in files, f"blender/contract.md keeps ONE executable interface example: {sorted(files)}"for rel, body in files.items():@@ -82,7 +60,6 @@ def test_blender_contract_example_builds_and_exports(tmp_path) -> None:lo, hi = scene.boundsassert abs(lo[1]) < 1e-3 and hi[1] > 0.01, (lo, hi) # Y-up GLB, on the ground-def _build_urdf_example(tmp_path, tag: str, model_py: str, urdf: str):"""Run a doc example through the real urdf_blender build and the round's joint_sweep gate."""from codeverse3d.config import get_settings@@ -104,12 +81,9 @@ def _build_urdf_example(tmp_path, tag: str, model_py: str, urdf: str):assert not gate.findings, f"{tag}: {[f.message for f in gate.findings]}"return ws, res-@pytest.mark.blenderdef test_urdf_contract_example_builds_and_its_joint_moves_the_child(tmp_path) -> None:- """The contract's example (one python block + one URDF) must pass the harness build exactly as- written — FK consistency, no lint warnings, clean sweep — and its first movable joint must- move its child link between the limits (a lid hinged on an edge opens upward)."""+ """The contract's example (one python block + one URDF) must pass the harness build exactly as written — FK..."""import numpy as npfrom codeverse3d.spatial.joints_model import link_world_meshes, load_urdf@@ -125,7 +99,6 @@ def test_urdf_contract_example_builds_and_its_joint_moves_the_child(tmp_path) ->tops = {q: link_world_meshes(r, {joint.name: q})["lid"].bounds[1][2] for q in (0.0, 0.75, 1.5)}assert tops[1.5] > tops[0.75] > tops[0.0] + 0.05, f"lid does not open upward: {tops}"-# ------------------------------------------------------------------------ node@pytest.mark.nodedef test_threejs_contract_example_builds_glb(tmp_path) -> None:@@ -159,18 +132,12 @@ console.log('GLB_OK', meshes, buf.byteLength);assert "GLB_OK" in outassert (tmp_path / "object.glb").stat().st_size > 200-@pytest.mark.nodedef test_scene_contract_env_example_is_the_interface_and_nothing_else(tmp_path) -> None:- """The contract's one labelled file is ``src/env.js`` with the three exports the assembler reads and- no scene inside it (the complete day scene it used to carry — a sun rig, a grove of cones, the- +X+Z corner camera — was the most pasteable passage of the prompt corpus, 2026-10-15)."""+ """The contract's one labelled file is ``src/env.js`` with the three exports the assembler reads and no scene..."""files = labelled_files("scene_threejs/contract.md")assert set(files) == {"src/env.js"}body = files["src/env.js"]- assert len(body.strip().splitlines()) <= 12- for word in ("sunRig", "Fog(", "PlaneGeometry", "position: [", "Cone"):- assert word not in body, wordp = tmp_path / "src" / "env.js"p.parent.mkdir(parents=True, exist_ok=True)p.write_text(body)@@ -188,12 +155,9 @@ console.log('ENV_OK');out = run_node_module(tmp_path, runner)assert "ENV_OK" in out-# --------------------------------------------------------------------- scene_blenderdef _bpy_workspace(tmp_path, *, lib: bool = True):- """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 — in raw mode- (D113, ``lib`` False) a runtime whose settings ship no library."""+ """The scratch workspace the scene_blender snippets run in."""from codeverse3d.config import Settingsfrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import ScenePlan@@ -210,46 +174,20 @@ def _bpy_workspace(tmp_path, *, lib: bool = True):rt.skeleton(ws, plan)return ws, rt, plan--def test_the_bpy_plan_skeleton_builds_in_blender_as_written(tmp_path) -> None:- """The fresh skeleton (a stub env — a level plate and nothing that passes: no world, lamp or- atmosphere — and a TODO stub per zone) builds in Blender 5.2.2 before an author touches it: every- zone ok, no env error, a ground in the census and no fog or light until the author writes the- brief's (2026-10-15)."""- from codeverse3d.conventions import to_pascal-- ws, rt, plan = _bpy_workspace(tmp_path)- zones = {rt.zone_file(z.name).rsplit("/", 1)[-1][:-3] for z in plan.zones}- 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 run.facts.get("fog") is None and not run.facts.get("lights"), {k: run.facts.get(k) for k in ("fog", "lights")}---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. The contract's python- blocks are exactly these two labelled files: nothing else of the bpy prompt material is code."""- assert len(blocks("scene_blender/contract.md", "python")) == len(labelled_files("scene_blender/contract.md", tag="python"))+def _build_scene_blender_examples(tmp_path, rel: str, *, lib: bool) -> None:+ """The contract's two labelled files (src/env.py + src/zones/quay.py) 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 sbfrom 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")+ files = labelled_files(rel, tag="python")+ assert len(blocks(rel, "python")) == len(files) and set(files) == {"src/env.py", "src/zones/quay.py"}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)+ ws, rt, plan = _bpy_workspace(tmp_path, lib=lib)+ assert (ws.src / "lib").exists() is lib+ for path, body in files.items():+ (ws.root / path).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)@@ -260,44 +198,19 @@ def test_scene_blender_contract_examples_build_through_the_runtime(tmp_path) ->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")}+def test_scene_blender_contract_examples_build_through_the_runtime(tmp_path) -> None:+ _build_scene_blender_examples(tmp_path, "scene_blender/contract.md", lib=True)@pytest.mark.blender@pytest.mark.nodedef test_the_argon_raw_contract_examples_build_through_the_runtime_in_raw_mode(tmp_path) -> None:- """The ``argon_raw`` overlay's contract (D113) keeps the same two labelled files rewritten in raw bpy- / bmesh: in a raw workspace (no ``src/lib``) they lint clean under the raw lint, assemble, build with- the probe passing (a world, a lamp, a ground, an atmosphere) and seat what they place — the same- checks as the library-mode examples above."""- from codeverse3d.contracts.artifacts import Severity- from tests.scene_runtime.conftest import browser_available-- rel = "variants/argon_raw/scene_blender/contract.md"- assert len(blocks(rel, "python")) == len(labelled_files(rel, tag="python"))- if not browser_available():- pytest.skip("puppeteer/chrome required for the census probe")- ws, rt, plan = _bpy_workspace(tmp_path, lib=False)- assert not (ws.src / "lib").exists()- files = labelled_files(rel, tag="python")- assert set(files) == {"src/env.py", "src/zones/quay.py"}- for path, body in files.items():- assert "lib." not in body and "from lib" not in body, path- (ws.root / path).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")}-+ _build_scene_blender_examples(tmp_path, "variants/argon_raw/scene_blender/contract.md", lib=False)# --------------------------------------------------------------------- glsl_shaderdef test_glsl_shader_contract_example_builds_and_moves(tmp_ws) -> None:- """The contract's ONE complete ``mainImage`` (the block that defines it) is ``src/shader.frag``- as written: lint clean, the judged frames render through the real moderngl host, not static, no- NaN — before D107 nothing executed this language's prompt material except the cookbook's helpers."""+ """The contract's ONE complete ``mainImage`` (the block that defines it) is ``src/shader.frag`` as written."""pytest.importorskip("moderngl")import jsondiff --git a/harness/tests/prompts/test_snippets_static.py b/harness/tests/prompts/test_snippets_static.pydeleted file mode 100644index fba0417b..00000000--- a/harness/tests/prompts/test_snippets_static.py+++ /dev/null@@ -1,57 +0,0 @@-"""Static checks on fenced snippets the run tests cannot see: URDF frame recipe, GLSL-in-JS, the single-shot format."""--from __future__ import annotations--import re-import xml.etree.ElementTree as ET--import numpy as np-import pytest--from tests.prompts.conftest import blocks, read_prompt--XML_FILES = ["urdf/contract.md"]---def _is_template(body: str) -> bool:- """Fill-in skeletons carry symbolic origins (``PX PY PZ``) — not FK-checkable."""- return any(not _NUM.match(tok) for el in ET.fromstring(body).iter("origin") for tok in el.get("xyz", "0 0 0").split())---_NUM = re.compile(r"^-?\d+(\.\d+)?([eE]-?\d+)?$")--[email protected]("rel", XML_FILES)-def test_xml_examples_follow_the_enforced_frame_recipe(rel: str, tmp_path) -> None:- """The contract's URDF example passes the lint and the build's FK rule: visual origin = −(link frame world)."""- from codeverse3d.languages.urdf import lint_urdf_text- from codeverse3d.spatial.joints_model import fk, load_urdf-- checked = 0- for i, body in enumerate(blocks(rel, "xml")):- if _is_template(body):- continue- findings, _ = lint_urdf_text(body)- assert findings == [], f"{rel} block {i}: lint findings {[f.message for f in findings]}"- path = tmp_path / f"block{i}.urdf"- path.write_text(body)- robot = load_urdf(path, load_meshes=False)- T = fk(robot, {})- for name, link in robot.links.items():- assert np.allclose(T[name] @ link.visual_origin, np.eye(4), atol=1e-6), \- f"{rel} block {i}: link {name}: visual origin must be -(link frame world) = {(-T[name][:3, 3]).round(4).tolist()}"- checked += 1- assert checked > 0, f"{rel}: expected at least one FK-checkable xml block"---def test_singleshot_example_parses_with_harness_parser() -> None:- from codeverse3d.tracks import generation as gen-- text = read_prompt("system/singleshot_format.md")- example = blocks("system/singleshot_format.md", "text")[-1]- files = gen.parse_multifile(example)- assert set(files) == {"src/parts/seat.js", "src/object.js"}- assert "buildSeat" in files["src/parts/seat.js"]- assert "=== FILE" not in "".join(files.values())- # the format doc and the parser must agree on the markers- assert "=== FILE: " in text and "=== END FILE ===" in textdiff --git a/harness/tests/prompts/test_variants.py b/harness/tests/prompts/test_variants.pyindex 07da20b4..5cacc067 100644--- a/harness/tests/prompts/test_variants.py+++ b/harness/tests/prompts/test_variants.py@@ -2,43 +2,33 @@from __future__ import annotations-import jsonimport shutil-from collections.abc import Callablefrom pathlib import Path-from typing import Anyimport pytest-from jinja2 import FileSystemLoader, TemplateNotFound+from jinja2 import TemplateNotFoundfrom codeverse3d import promptsfrom codeverse3d.config import Settings, get_settings-from codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.spec import RunOptions+from codeverse3d.contracts.common import Languagefrom codeverse3d.prompts import variants as Vfrom 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+from tests.prompts.conftest import PROMPTS_DIRTV_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()-@pytest.fixture(autouse=True)def _no_process_variant(monkeypatch):"""No variant from this machine's environment, and no cached overlay from another test."""@@ -48,7 +38,6 @@ def _no_process_variant(monkeypatch):yield_clear()-@pytest.fixturedef overlay(tmp_path: Path, monkeypatch) -> Path:"""A tmp ``VARIANTS_DIR`` holding ``tv``: a system.md that shadows blender's, a template only the@@ -67,7 +56,6 @@ def overlay(tmp_path: Path, monkeypatch) -> Path:_clear()return root-# --------------------------------------------------------------------------- selectiondef test_resolution_order_including_the_served_model_lookup(overlay):"""settings.variant > variants[id as typed] > variants['<kind>:<served model>'] > base; plain lookups."""@@ -76,47 +64,15 @@ def test_resolution_order_including_the_served_model_lookup(overlay):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):+def test_variant_toml_is_type_checked(overlay):+ (overlay / "tv" / "variant.toml").write_text('[variant\nname = "tv"\n')+ with pytest.raises(ValueError, match="not valid TOML"):variant_info("tv")-# --------------------------------------------------------------------------- the prompt overlaydef test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):base_system = (PROMPTS_DIR / "blender" / "system.md").read_text()@@ -124,8 +80,6 @@ def test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):with activate("tv"):assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\n"assert prompts.load_text("blender/contract.md") == base_contract, "no overlay copy: the base file"- assert prompts.prompt_root("blender/system.md") == overlay / "tv" / "blender" / "system.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")@@ -141,325 +95,24 @@ def test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):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/system.md")- assert base != "# OVERLAY SYSTEM\n"- with activate("tv"):- assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\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/system.md") == base- with activate("tv"):- assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\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" / "system.md").write_text("# OVERLAY SYSTEM 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_an_empty_overlay_at_version_2():- """Iteration 1 (2026-10-15) shadowed the two zone briefs and boosted the Blender placement skill;- D106 withdrew both (the briefs carried a template; the boost amplified it) and iterations 2-4 ran- on the EMPTY overlay — iteration 4 was accepted as v2 (2026-10-16, ledger argon_scene): the gain- was harness code (D106-D108), so the overlay ships only its README and variant.toml."""- from codeverse3d.skills import variant_dir, variants_table-- info = variant_info("argon")- assert info.name == "argon" and info.version == 2 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", "variant.toml"]- assert sorted(p.name for p in variant_dir("argon").iterdir()) == ["README.md", "routes.toml"]- table = variants_table("argon")- assert table.variant == "argon" and not table.routes and not table.disabled and not table.boosts- 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+# --------------------------------------------------------------------------- the run-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."""+def test_knobs_apply_as_defaults_a_stated_field_wins_and_nothing_outlives_the_block(overlay, monkeypatch):+ """Regression: a variant's knobs leaked onto the process Settings and the next base run inherited them."""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+ s = Settings(skills_only="c3d-scene-water") # stated by the user: never touchedwith 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": 2, "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", 2, 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", 2, 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/reference/conftest.py b/harness/tests/reference/conftest.pyindex 292a4943..a861d4c7 100644--- a/harness/tests/reference/conftest.py+++ b/harness/tests/reference/conftest.py@@ -2,11 +2,8 @@from __future__ import annotations-from pathlib import Pathfrom typing import Any-import pytest-from codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.spec import Constraints, Spec@@ -16,14 +13,9 @@ def make_spec(**kw: Any) -> Spec:id="t1", track=Track.STATIC_OBJECT, language=Language.BLENDER,prompt="a hand-crank coffee grinder with a square wooden box body and a cast-iron cone hopper",constraints=Constraints(dimensions_m={"width": 0.14, "depth": 0.14, "height": 0.30},- must_have=["a crank handle", "a front drawer"]),+ ),)base.update(kw)return Spec(**base)-def cache_dir(tmp_path: Path) -> Path:- d = tmp_path / "cache"- d.mkdir()- return ddiff --git a/harness/tests/reference/test_judge_diff.py b/harness/tests/reference/test_judge_diff.pyindex 6ec7703b..6fbea513 100644--- a/harness/tests/reference/test_judge_diff.py+++ b/harness/tests/reference/test_judge_diff.py@@ -13,7 +13,6 @@ from tests.judges.conftest import (FakeChatModel,draw_chair,good_reply,- image_parts,make_measurement,make_renders,make_spec,@@ -33,10 +32,7 @@ def ref_input(tmp_path):note="my photo")])return JudgeInput(spec=spec, renders=make_renders(tmp_path / "renders"), measurement=make_measurement(),- acceptance=[AcceptanceItem(id="A1", text="four legs", how="measure", priority="must"),- AcceptanceItem(id="A2", text="slatted back", how="visual", priority="should")],- plan_summary="parts: Seat, Backrest, LegFrontLeft, LegFrontRight",- part_names=["Seat", "Backrest", "LegFrontLeft", "LegFrontRight"])+ acceptance=[AcceptanceItem(id="A1", text="four legs", how="measure", priority="must")])def _judge(model, **kw):@@ -44,34 +40,7 @@ def _judge(model, **kw):**kw)-def test_the_diff_reaches_the_scoring_call(ref_input, cache_dir):- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})- assert _judge(model, cache_dir=cache_dir).judge(ref_input).overall > 0- scoring = [r for r in model.requests if r.label.startswith("judge")][0]- text = scoring.messages[0].parts[0].text- assert "REFERENCE DIFF" in text and "reference shows 4 legs, render shows 2" in text- assert "already matching: the backrest slats are right" in text- assert image_parts(scoring)[0].label.startswith("REFERENCE 1/1 (target)")---def test_a_failing_diff_never_breaks_the_verdict(ref_input, cache_dir):- model = FakeChatModel(by_label={"reference_diff": [{"garbage": 1}],- "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})- j = _judge(model, cache_dir=cache_dir).judge(ref_input)- assert j.overall > 0 and j.rubric == "reference"--[email protected](("value", "diffed"), [("off", False), ("OFF", False), ("of", True)])-def test_diff_off_via_env(ref_input, cache_dir, switch, value, diffed):- """D44 (c): ``C3D_REFERENCE_DIFF=off`` switches the pass off; a typo keeps the default (on)."""- switch("C3D_REFERENCE_DIFF", value)- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]})- _judge(model, cache_dir=cache_dir).judge(ref_input)- assert any(r.label.startswith("reference_diff") for r in model.requests) is diffed---def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path, cache_dir):- """The brief wins: the measured criterion goes neutral."""+def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path):from codeverse3d.contracts.spec import Constraintsfrom codeverse3d.judges.vlm_judge import NEUTRAL_SCORE@@ -81,7 +50,7 @@ def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path, cache_dirinp = JudgeInput(spec=spec, renders=make_renders(tmp_path / "r"), measurement=make_measurement(),acceptance=[AcceptanceItem(id="A1", text="t", how="visual", priority="must")])model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1"], 0.8)]})- j = ReferenceJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir)+ j = ReferenceJudge("fake:fake-1", chat_model=model, cache_dir=tmp_path / "cache")verdict = j.judge(inp)assert verdict.scores["silhouette_match"] == NEUTRAL_SCOREtext = [r for r in model.requests if r.label.startswith("judge")][0].messages[0].parts[0].text@@ -89,31 +58,3 @@ def test_reference_that_contradicts_the_brief_scores_neutral(tmp_path, cache_dirassert "NEUTRAL" in text-def test_the_diff_call_names_every_part_of_an_articulated_plan(ref_input, cache_dir):- """The part list comes from the plan, not a regex over plan_summary (which dropped the last part)."""- from codeverse3d.contracts.plan import ArticulatedPlan- from codeverse3d.contracts.run import RoundRecord- from codeverse3d.contracts.spec import Track- from codeverse3d.judges.base import round_input- from codeverse3d.tracks.planner import plan_example-- plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))- names = [p.name for p in plan.parts]- inp = round_input(ref_input.spec, plan, RoundRecord(index=0, kind="baseline"), renders=ref_input.renders,- gates=[], previous=None, extra_context="", geometry_views=None, glb_path=None)- assert len(names) >= 2 and inp.part_names == names- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, [], 0.8)]})- _judge(model, cache_dir=cache_dir).judge(inp)- diff = [r for r in model.requests if r.label == "reference_diff"][0]- assert ", ".join(names) in "".join(getattr(pt, "text", "") for m in diff.messages for pt in m.parts)---def test_the_diff_call_is_charged_to_the_verdict(ref_input, cache_dir):- """An uncharged model call would hide from BudgetGuard and record.total_usage."""- model = FakeChatModel(by_label={"reference_diff": [DIFF], "judge": [good_reply(REF, ["A1", "A2"], 0.8)]},- cost=0.01)- with_diff = _judge(model, cache_dir=cache_dir).judge(ref_input)- model2 = FakeChatModel(by_label={"judge": [good_reply(REF, ["A1", "A2"], 0.8)]}, cost=0.01)- without = _judge(model2, cache_dir=cache_dir, diff=False).judge(ref_input)- assert with_diff.usage.cost_usd > without.usage.cost_usd- assert all(not r.label.startswith("reference_diff") for r in model2.requests) # diff=False: no diff calldiff --git a/harness/tests/reference/test_mismatch.py b/harness/tests/reference/test_mismatch.pyindex 08618f47..361eb179 100644--- a/harness/tests/reference/test_mismatch.py+++ b/harness/tests/reference/test_mismatch.py@@ -11,41 +11,12 @@ from codeverse3d.reference import comparefrom tests.orchestrator_tracks.fakes import FakeChatModelfrom tests.reference.conftest import make_spec-ANSWER = {- "mismatches": [- {"kind": "missing_feature", "target": "Hopper", "detail": "reference has a conical hopper; render is flat",- "severity": "critical"},- {"kind": "wrong_part_count", "target": "Flutes", "detail": "reference has 8 flutes, render has 0",- "severity": "major"},- {"kind": "wrong_proportion", "target": "overall", "detail": "reference body is taller", "severity": "minor"},- {"kind": "wrong_material", "target": "Body", "detail": "walnut vs grey", "severity": "minor"},- ],- "matches": ["the crank handle is present", "the drawer reads correctly"],-}-def _png(p: Path) -> Path:Image.new("RGB", (64, 64), (200, 200, 200)).save(p)return p-def test_compare_names_mismatches_and_builds_text(tmp_path: Path):- ref, ren = _png(tmp_path / "ref.png"), _png(tmp_path / "ren.png")- chat = FakeChatModel(by_label={"reference_diff": [ANSWER]})- d = compare(make_spec(), [ref], [ren], model=chat, part_names=["Hopper", "Body"],- measured={"iou": 0.42, "aspect_ratio_err": 0.13, "reliable": True, "view": "front"})- assert len(d.mismatches) == 4 and d.iou == 0.42 and d.view == "front"- text = d.as_text()- assert "IoU 0.420" in text and "8 flutes" in text- assert "already matching: the crank handle is present" in text- req = chat.requests[0]- labels = [p.label for p in req.messages[0].parts if getattr(p, "label", None)]- assert labels == ["REFERENCE 1", "RENDER 1 (ren)"]- assert "Hopper, Body" in req.messages[0].parts[0].text- assert "Ignore anything the brief overrides" in req.messages[0].parts[0].text- assert [m.severity for m in d.top(3)] == ["critical", "major", "minor"]--def test_a_failed_or_impossible_diff_is_soft(tmp_path: Path):ref, ren = _png(tmp_path / "ref.png"), _png(tmp_path / "ren.png")d = compare(make_spec(), [ref], [ren], model=FakeChatModel(by_label={"reference_diff": [ModelError("nope")]}))diff --git a/harness/tests/reference/test_proportions.py b/harness/tests/reference/test_proportions.pyindex a1ae7e2f..0ffd7932 100644--- a/harness/tests/reference/test_proportions.py+++ b/harness/tests/reference/test_proportions.py@@ -4,15 +4,12 @@ from __future__ import annotationsfrom pathlib import Path-import pytestfrom PIL import Image, ImageDrawfrom codeverse3d.reference import (ASPECT_TOL,conflict_note,dimension_conflict,- expected_aspect_range,- expected_front_aspect,)from tests.reference.conftest import make_spec@@ -25,26 +22,11 @@ def _box(path: Path, w: int, h: int) -> Path:return path-def test_expected_aspect_is_a_band_over_every_horizontal_extent():- """A brief never says which face a photo shows, so the expectation is a range."""- from codeverse3d.contracts.spec import Constraints-- assert expected_aspect_range(make_spec()) == (0.14 / 0.30, 0.14 / 0.30) # width == depth- chair = make_spec(constraints=Constraints(dimensions_m={"width": 0.45, "depth": 0.50, "height": 0.9}))- assert expected_aspect_range(chair) == pytest.approx((0.5, 0.5 / 0.9))- assert expected_front_aspect(chair) == pytest.approx(0.5278, abs=1e-3)- assert expected_aspect_range(make_spec(constraints=Constraints())) is None- # height alone says nothing about proportions- assert expected_aspect_range(make_spec(constraints=Constraints(dimensions_m={"height": 0.65}))) is None--CHAIR = {"width": 0.45, "depth": 0.50, "height": 0.9}def test_only_a_photo_beyond_the_tolerance_is_a_conflict(tmp_path: Path):- """The measured chair: band 0.50-0.56, photo 0.64 → 16 % outside, kept. The coffee grinder:- the brief says 0.47 w/h; the studio photo includes the crank arm and is ~0.70 → flagged. An- unreadable image is never a conflict."""+ """A photo beyond ASPECT_TOL of the brief is a conflict; an unreadable image never is."""from codeverse3d.contracts.spec import Constraintsspec = make_spec(constraints=Constraints(dimensions_m=CHAIR))@@ -54,8 +36,7 @@ def test_only_a_photo_beyond_the_tolerance_is_a_conflict(tmp_path: Path):info = dimension_conflict(make_spec(), _box(tmp_path / "crank.png", 210, 300))assert info["conflict"] and info["relative_error"] > 0.4note = conflict_note(info)- assert "BRIEF's dimensions are correct" in note and "part inventory" in note- assert "0.47-0.47" in note+ assert "BRIEF's dimensions are correct" in noteinfo = dimension_conflict(make_spec(), tmp_path / "missing.png")assert info["conflict"] is False and info["error"]diff --git a/harness/tests/reference/test_silhouette_best_view.py b/harness/tests/reference/test_silhouette_best_view.pyindex 809428b3..4056b186 100644--- a/harness/tests/reference/test_silhouette_best_view.py+++ b/harness/tests/reference/test_silhouette_best_view.py@@ -11,7 +11,7 @@ from codeverse3d.contracts.artifacts import RenderSet, RenderView, Severityfrom codeverse3d.contracts.spec import ReferenceImagefrom codeverse3d.judges.base import JudgeInputfrom codeverse3d.judges.vlm_judge import ReferenceJudge-from codeverse3d.spatial.silhouette import CANDIDATE_VIEWS, best_view_match, compare_silhouette+from codeverse3d.spatial.silhouette import best_view_match, compare_silhouettefrom codeverse3d.tracks.static_object import silhouette_gatefrom tests.judges.conftest import FakeChatModelfrom tests.reference.conftest import make_spec@@ -33,31 +33,15 @@ def _views(tmp: Path) -> list[RenderView]:for n, b in boxes.items()]-def test_best_view_skips_top_and_low_cameras_and_writes_the_diff(tmp_path: Path) -> None:- assert "top" not in CANDIDATE_VIEWS and "bottom" not in CANDIDATE_VIEWS- assert "front_right_low" not in CANDIDATE_VIEWS+def test_best_view_picks_the_matching_camera_and_writes_the_diff(tmp_path: Path) -> None:views = _views(tmp_path / "r")- views.append(RenderView(name="top", path=views[0].path, width=256, height=256))ref = _shape(tmp_path / "ref.png", (20, 95, 236, 165))res = best_view_match(views, ref, diff_png=tmp_path / "d.png")- assert "top" not in res["per_view"]assert (tmp_path / "d.png").is_file() and res["view"] == "right"- assert "error" in best_view_match([], ref)---def test_a_pre_d47_run_matches_its_own_cameras_through_one_alias_map(tmp_path: Path) -> None:- """N62: four lists each kept a different subset of the old ``*_34`` names; now- ``conventions.LEGACY_VIEW_ALIASES`` maps them, and the old low camera stays out as its twin does."""- views = _views(tmp_path / "r")- old = [RenderView(name=n, path=views[2].path, width=256, height=256) for n in ("front_right_34", "low_front_left")]- res = best_view_match(old, _shape(tmp_path / "ref.png", (20, 95, 236, 165)))- assert res["view"] == "front_right_34" and set(res["per_view"]) == {"front_right_34"}def test_the_gate_and_the_judge_read_one_measurement(tmp_path: Path) -> None:- """Audit 2026-09-24 N51: the gate compared the ``front`` render (IoU 0.26 → a WARN and a- refine round) while the judge scored the best-matching view (0.995). Both now read- ``silhouette.measure_reference``."""+ """N51: the gate and the judge score the same best-matching view (gate said IoU 0.26 on `front`, judge 0.995)."""views = _views(tmp_path / "r")ref = _shape(tmp_path / "ref.png", (20, 95, 236, 165))spec = make_spec(references=[ReferenceImage(path=str(ref), role="target")])diff --git a/harness/tests/reference/test_tool_compare_reference.py b/harness/tests/reference/test_tool_compare_reference.pydeleted file mode 100644index 5c9cf20a..00000000--- a/harness/tests/reference/test_tool_compare_reference.py+++ /dev/null@@ -1,69 +0,0 @@-"""The ``compare_reference`` spatial tool (side-by-side sheet + IoU, no model call)."""--from __future__ import annotations--import json-from pathlib import Path--import pytest-from PIL import Image, ImageDraw--import codeverse3d.spatial.tools # noqa: F401 (registers every tool)-from codeverse3d.contracts.artifacts import RenderSet, RenderView-from codeverse3d.spatial.registry import ToolContext, get_tool-from codeverse3d.workspace import Workspace-from tests.spatial_tools.conftest import build_stool---def _ref_png(path: Path) -> Path:- im = Image.new("RGB", (512, 512), (245, 245, 243))- ImageDraw.Draw(im).rectangle([150, 90, 360, 440], fill=(60, 40, 25))- im.save(path)- return path---def ctx(tmp_ws: Workspace, tmp_path: Path, monkeypatch) -> ToolContext:- (tmp_ws.artifacts / "object.glb").write_bytes(build_stool(tmp_path / "stool.glb").read_bytes())- ref = _ref_png(tmp_path / "ref.png")- tmp_ws.spec_path.write_text(json.dumps({- "id": "t", "track": "static_object", "language": "blender", "prompt": "a stool",- "references": [{"path": str(ref), "role": "target", "note": "my photo"}]}))-- def fake_render(_ctx, glb, *, views, mode="shaded", size=512, **kw):- out = []- for v in views:- p = tmp_path / f"{mode}_{v.name}.png"- im = Image.new("RGB", (size, size), (255, 255, 255))- ImageDraw.Draw(im).rectangle([size * 0.25, size * 0.2, size * 0.75, size * 0.9],- fill=(0, 0, 0) if mode == "silhouette" else (150, 90, 40))- im.save(p)- out.append(RenderView(name=v.name, path=str(p), width=size, height=size, mode=mode))- return RenderSet(views=out, renderer="fake")-- monkeypatch.setattr("codeverse3d.spatial.tools.cached_render_glb", fake_render)- return ToolContext(workspace=tmp_ws, language="blender", track="static_object")---def test_compare_reference_builds_a_side_by_side_sheet(ctx: ToolContext):- obs = get_tool("compare_reference").call(ctx, {"view": "front"})- assert obs.ok- assert obs.numbers["view"] == "front" and 0.0 <= obs.numbers["iou"] <= 1.0- assert len(obs.images) == 3 and all(Path(p).is_file() for p in obs.images)- with Image.open(obs.images[0]) as sheet: # 3 tiles side by side- assert sheet.width > sheet.height- assert "part inventory" in obs.text and "counts" in obs.text---def test_usage_errors_are_didactic(ctx: ToolContext):- obs = get_tool("compare_reference").call(ctx, {"view": "nope"})- assert not obs.ok and "unknown view" in obs.text- obs = get_tool("compare_reference").call(ctx, {"reference_index": 9})- assert not obs.ok and "out of range" in obs.text---def test_no_references_says_so(tmp_ws: Workspace, tmp_path: Path):- (tmp_ws.artifacts / "object.glb").write_bytes(build_stool(tmp_path / "s.glb").read_bytes())- tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "a stool"}))- obs = get_tool("compare_reference").call(ToolContext(workspace=tmp_ws, language="blender"), {})- assert not obs.ok and "no reference images" in obs.textdiff --git a/harness/tests/scene_blender/fixtures.py b/harness/tests/scene_blender/fixtures.pyindex 25606fb0..e11a07bc 100644--- a/harness/tests/scene_blender/fixtures.py+++ b/harness/tests/scene_blender/fixtures.py@@ -1,10 +1,5 @@-"""A hand-written scene_blender workspace with one of everything the census GLB must carry.--Blender frame (Z up, -Y front). ``yard`` places four crates as collection instances — seated,-floating 1.5 m, sunk 0.6 m, and one tagged ``placement = 'free'`` — plus a parented cart (a mesh-with a child mesh: one placement row). ``meadow`` scatters grass blades with geometry nodes (an-instance cloud). ``broken`` raises on a known line. ``CRATE_TRIS`` etc. are what bpy must count.-"""+"""A hand-written scene_blender workspace (Blender frame: Z up): ``yard`` places four crates as collection instances+(seated, floating, sunk, free) and a parented cart, ``meadow`` scatters grass with geometry nodes, ``broken`` raises."""from __future__ import annotationsdiff --git a/harness/tests/scene_blender/test_build.py b/harness/tests/scene_blender/test_build.pyindex 7d63c9af..b24d136e 100644--- a/harness/tests/scene_blender/test_build.py+++ b/harness/tests/scene_blender/test_build.py@@ -76,25 +76,6 @@ def test_placement_rows_for_sunk_floating_and_free(built) -> None:assert [r["name"] for r in rows.values() if r["name"].startswith("GrassPatch")] == ["GrassPatch"]-def test_the_zone_mark_survives_the_census_glb(built) -> None:- """D111: the census GLB's zone nodes carry ``extras[ZONE_ROOT_KEY]`` → three.js ``userData``, so only- the zones' children are rows; the env's roots (``Ground``) are scenery, measured as nothing."""- _, res = built- table = res.census["placement"]- assert table["assets"] and {r["zone"] for r in table["assets"]} <= {"Yard", "Meadow"}- assert "Ground" in table["scenery"]["names"]---def test_bpy_facts_reach_the_census(built) -> None:- ws, res = built- c = res.census- assert c["totals"]["lights"] == 1 and c["light_types"] == {"SUN": 1}- assert c["environment"] is True- assert c["bpy"]["drivers_invalid"] == [] and c["bpy"]["handlers"] == []- assert (ws.artifacts / "scene.blend").stat().st_size > 0 and (ws.artifacts / "census.glb").stat().st_size > 0- assert [g.gate for g in res.gates] == ["scene_probe"]--def _only_unlit(res) -> None:"""The skeleton's build: everything built, and the one ERROR is the placeholder env's ``unlit``."""errors = [f for g in res.gates for f in g.errors]@@ -116,16 +97,10 @@ def test_the_skeleton_builds_and_passes(tmp_ws) -> None:res = rt.build(tmp_ws)_only_unlit(res)c = res.census- # the stub env ships a plate and nothing that passes: no world, no atmosphere, no lamp until the author- # writes the brief's (a placeholder that passed was kept by every author, 2026-10-15)- assert c["fog"] is None and c["background"] is None and not c["bpy"]["glb"]["volumes_skipped"]+ assert c["fog"] is None and c["background"] is None and c["light_types"] == {}assert {g["name"] for g in c["groups"]} >= {"Quay", "Water", "Ground"}- assert c["light_types"] == {} and c["bpy"]["drivers_invalid"] == []- # the zone stubs place NOTHING (D106: they name the plan's contents and decide no position — the- # grid of placeholders inside the bbox was the seed of the block-on-a-plate look), so the fresh- # skeleton's placement table is empty and anything an author then places is measured on its ownplaced = [r for r in c["placement"]["assets"] if r["zone"] in ("Quay", "Water") and not r["exempt"]]- assert placed == [], placed+ assert placed == [], placed # D106: the zone stubs place nothingprobe = json.loads((tmp_ws.artifacts / "scene_probe.json").read_text())# the plan's cameras, named as scene_threejs's assembler names themassert [cam["name"] for cam in probe["boot"]["cameras"]] == [to_snake(c.name) for c in plan.cameras[:6]]@@ -150,31 +125,6 @@ def test_the_skeleton_renders_through_the_runtime(tmp_ws, switch) -> None:assert metrics["language"] == "scene_blender" and {c["name"] for c in metrics["camera_checks"]} >= set(names)-def test_assemble_leaves_a_failing_zone_out(tmp_ws) -> None:- write_fixture(tmp_ws)- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- asm = _rt().assemble(tmp_ws, plan)- assert asm.zones_included == ["meadow", "yard"] and set(asm.zones_failed) == {"broken"}- assert '"broken"' not in (tmp_ws.src / "scene.py").read_text()- assert _rt().build(tmp_ws).ok---def test_a_python_driver_fails_the_build_census(tmp_ws) -> None:- """D10 behind the lint: a driver whose expression the lint cannot read (built from a variable)- still fails the build."""- write_fixture(tmp_ws, broken=False)- yard = tmp_ws.src / "zones" / "yard.py"- yard.write_text(yard.read_text().replace(- " return ctx.collection\n",- " expr = 'noise.noise(' + '(frame, 0, 0))'\n"- " d = cart.driver_add('location', 2).driver\n"- " d.expression = expr\n"- " return ctx.collection\n"))- assert _rt().lint(tmp_ws).passed- res = _rt().build(tmp_ws)- assert not res.ok and res.error_type == "python_driver" and "Cart_0" in res.error_message--def test_a_hero_glb_is_imported_into_ctx_assets(tmp_ws) -> None:write_fixture(tmp_ws, broken=False)write_box_glb(tmp_ws.public / "assets" / "windmill.glb", size=(2.0, 4.0, 2.0))@@ -194,28 +144,3 @@ def test_a_hero_glb_is_imported_into_ctx_assets(tmp_ws) -> None:row = _rows(res)["Windmill_0"]assert row["zone"] == "Yard" and row["supported"] # a 4 m box centred on z = 2 stands on the ground--def test_probe_measures_without_touching_build_json(tmp_ws) -> None:- write_fixture(tmp_ws, broken=False)- rt = _rt()- assert rt.build(tmp_ws).ok- before = (tmp_ws.artifacts / "build.json").read_text()- res = rt.probe(tmp_ws)- assert res.ok and res.gate.passed and res.census["placement"]["assets"]- assert (tmp_ws.artifacts / "build.json").read_text() == before---def test_what_the_render_driver_reads(built) -> None:- """The .blend and census the render driver (DESIGN phase 2) is built on: cameras in plan order- with their aim, the frame clock, a census in bpy wording with no hero entry for the census GLB."""- import subprocess-- ws, res = built- assert res.census["language"] == "scene_blender" and res.census["glb_assets"] == []- code = ("import bpy, json; s = bpy.context.scene; "- "print('C3D', json.dumps([list(s['c3d_cameras']), [list(bpy.data.objects[n]['c3d_look_at']) for n in s['c3d_cameras']], "- "s.render.fps, s.frame_start, s.frame_end]))")- out = subprocess.run([get_settings().resolve_blender(), "-b", "--factory-startup", str(ws.artifacts / "scene.blend"),- "--python-expr", code], capture_output=True, text=True, timeout=120).stdout- cams, looks, fps, first, last = json.loads(next(line[4:] for line in out.splitlines() if line.startswith("C3D ")))- assert cams == ["overview"] and looks == [[0.0, 0.0, 0.0]] and (fps, first, last) == (30, 1, 46)diff --git a/harness/tests/scene_blender/test_env_check.py b/harness/tests/scene_blender/test_env_check.pyindex 20ed337c..840a6abe 100644--- a/harness/tests/scene_blender/test_env_check.py+++ b/harness/tests/scene_blender/test_env_check.py@@ -9,7 +9,6 @@ import pytestfrom codeverse3d.config import get_settingsfrom codeverse3d.contracts.common import Languagefrom codeverse3d.languages import get_runtime-from codeverse3d.languages.scene_blender import LIB_DIR, lib_interfacefrom codeverse3d.workspace import Workspacefrom tests.scene_blender.fixtures import ENV@@ -32,17 +31,6 @@ def _ws(tmp_path, env: str) -> Workspace:return ws-def test_the_lib_interface_lists_signatures_as_written(tmp_path):- ws = _ws(tmp_path, ENV)- (ws.src / "lib").mkdir()- for p in LIB_DIR.glob("*.py"):- (ws.src / "lib" / p.name).write_text(p.read_text())- rows = lib_interface(ws).splitlines()- assert rows and all(r.startswith("lib/") for r in rows)- assert not any(r.startswith("lib/__init__.py") for r in rows)- assert any(r.startswith("lib/sky.py (lib.sky): ") and "(" in r for r in rows)--@needs_blender@pytest.mark.blenderdef test_a_good_env_passes_and_each_broken_one_says_why(tmp_path):@@ -68,17 +56,3 @@ def test_a_raise_inside_a_lib_helper_is_quoted_at_the_env_line_that_called_it():assert env_frame(tb) == "src/env.py:287 `sky_batch.box(`"assert env_frame(tb.replace("/src/env.py", "/src/lib/env.py")) == "" # a lib module is not the env--@needs_blender-def test_check_env_leads_with_the_env_line_when_a_lib_helper_raised(tmp_path):- env = ENV.replace("import bpy\n", "import bpy\nfrom lib.turn import spin\n", 1).replace(- " return {}\n", " spin((0.0, 0.0, 1.0))\n return {}\n")- ws = _ws(tmp_path, env)- (ws.src / "lib").mkdir()- (ws.src / "lib" / "__init__.py").write_text("")- (ws.src / "lib" / "turn.py").write_text("import math\n\n\ndef spin(rotation):\n return math.cos(rotation)\n")- error = get_runtime(Language.SCENE_BLENDER).check_env(ws)- line = next(i for i, text in enumerate(env.splitlines(), 1) if "spin((0.0" in text)- assert error.startswith(f"src/env.py:{line} `spin((0.0, 0.0, 1.0))` (raised in src/lib/turn.py:5)"), error- assert "TypeError" in errordiff --git a/harness/tests/scene_blender/test_layout.py b/harness/tests/scene_blender/test_layout.pyindex 82096609..f83d24a1 100644--- a/harness/tests/scene_blender/test_layout.py+++ b/harness/tests/scene_blender/test_layout.py@@ -1,33 +1,16 @@-"""scene_blender without Blender: the runtime row, the file table, the frame, the skeleton's text-and the offline census gate (D2 / D10)."""+"""scene_blender without Blender: the runtime row, the skeleton and the offline census gate (D2 / D10)."""from __future__ import annotations-import astimport re-import pytest-from codeverse3d.contracts.artifacts import Severity-from codeverse3d.contracts.common import ENTRY_FILE, TRACK_LANGUAGES, Language, Track-from codeverse3d.contracts.plan import AssetPlan, ScenePlan+from codeverse3d.contracts.common import Track+from codeverse3d.contracts.plan import ScenePlanfrom codeverse3d.conventions import (DRAWS_WARN_SCENE,MAX_DRAWS_SCENE,MAX_TRIS_SCENE,- glb_basis,- to_authoring_frame,-)-from codeverse3d.languages import get_runtime-from codeverse3d.languages.base import SceneRuntime-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_factsfrom codeverse3d.tracks.planner import plan_example@@ -37,100 +20,6 @@ def _plan() -> ScenePlan:return ScenePlan.model_validate(plan_example(Track.SCENE))-def test_scene_blender_is_a_scene_language_with_a_runtime() -> None:- assert Language.SCENE_BLENDER in TRACK_LANGUAGES[Track.SCENE]- rt = get_runtime(Language.SCENE_BLENDER)- assert isinstance(rt, SceneRuntime) and rt.language is Language.SCENE_BLENDER- assert ENTRY_FILE[Language.SCENE_BLENDER] == "src/scene.py" == rt.entry_globs[0]---def test_the_file_table() -> None:- rt = get_runtime(Language.SCENE_BLENDER)- plan = _plan()- boat = next(a for a in plan.assets if a.name == "FishingBoat")- assert rt.zone_file("Quay Front") == "src/zones/quay_front.py"- assert rt.asset_file(boat.model_copy(update={"kind": "bpy"})) == "src/assets/fishing_boat.py"- assert rt.asset_file(boat.model_copy(update={"kind": "blender_glb"})) == "public/assets/fishing_boat.glb"- assert rt.files_for(plan, "Quay") == ["src/zones/quay.py"]- 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:- """D5: ``AssetPlan.kind`` gains ``bpy``; the old kinds still load."""- for kind in ("threejs", "bpy", "blender_glb"):- assert AssetPlan(name="Crate", kind=kind, description="a crate", approx_size_m=(1, 1, 1)).kind == kind---def test_glb_basis_inverts_to_authoring_frame() -> None:- """The census-GLB writer's basis (conventions, handed to Blender on argv) is the inverse of the- plan → Blender conversion the skeleton and assembler print: one frame, stated once."""- for v in ((1.0, 2.0, 3.0), (-4.5, 0.0, 7.25)):- b = to_authoring_frame(v, "scene_blender")- back = tuple(sum(r[i] * b[i] for i in range(3)) for r in glb_basis("scene_blender"))- assert back == pytest.approx(v)- assert glb_basis("scene_threejs") == ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))---def test_the_frame_clock() -> None:- assert (frame_of(0.0), frame_of(1.5)) == (1, 46)---def test_the_assembled_entry_is_data_in_the_blender_frame() -> None:- plan = _plan()- text = render_scene_py(["quay"], ["bollard"], ["windmill"], plan.cameras[:1])- ns: dict = {}- exec(compile(ast.parse(text), "scene.py", "exec"), ns) # data only: nothing to call- assert ns["ZONES"] == {"quay": "Quay"} and ns["ASSETS"] == {"bollard": "Bollard"} and ns["HEROES"] == {"windmill": "Windmill"}- cam, src = ns["CAMERAS"][0], plan.cameras[0]- assert cam["location"] == pytest.approx(to_authoring_frame(src.position, "scene_blender"), abs=1e-3)- assert cam["look_at"] == pytest.approx(to_authoring_frame(src.look_at, "scene_blender"), abs=1e-3)- assert cam["fov"] == src.fov---def test_the_skeleton_writes_the_layout(tmp_ws) -> None:- plan = _plan()- paths = {p.relative_to(tmp_ws.root).as_posix() for p in write_skeleton(tmp_ws, plan)}- want = {"src/scene.py", "src/env.py"} | {f"src/zones/{z}.py" for z in ("quay", "water")}- want |= {f"src/assets/{a}.py" for a in ("fishing_boat", "bollard")}- assert want <= paths- for p in paths:- compile((tmp_ws.root / p).read_text(), p, "exec")- # the zone stub names its planned contents (the census measures them as present) and decides- # no position: the grid of place() calls inside the bbox was the seed of the block-on-a-plate- # look (D106)- for z, contents in (("quay", ("Bollard", "Crate")), ("water", ("FishingBoat",))):- text = (tmp_ws.src / "zones" / f"{z}.py").read_text()- assert all(f"- {c}: ctx.assets['" in text for c in contents), text- assert "place(ctx" not in text and "keep them inside" not in text and "ctx.height_at" in text- # 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- env = (tmp_ws.src / "env.py").read_text()- assert "from lib import materials, terrain" in env # the placeholder plate uses the toolbox- assert "sky.sun_world(" not in env and "sky.haze(" not in env and "lighting.sun(" not in env # no light or atmosphere decided (2026-10-15)- assert "lib.scatter.instance" in (tmp_ws.src / "zones" / "quay.py").read_text() # named as one way- 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 gatedef _census(**bpy) -> dict:base = {"totals": {"meshes": 10, "instances": 10, "draws": MAX_DRAWS_SCENE + 1, "triangles": 10, "lights": 0},@@ -140,12 +29,6 @@ def _census(**bpy) -> dict:return merge_facts(base, facts)-def test_bpy_facts_replace_what_the_glb_cannot_carry() -> None:- c = _census()- assert c["totals"]["lights"] == 1 and c["fog"] == {"type": "VolumeBox"} and c["background"].startswith("sky:")- assert c["bpy"]["unique_tris"] == 10 and "fog" not in c["bpy"]--def test_offline_draws_are_not_gated_unique_triangles_are() -> None:"""D2: the census GLB's draw count describes the writer, not the scene — no draw findingoffline however high; the unique-triangle ceiling is an ERROR instead."""@@ -169,13 +52,6 @@ def test_python_drivers_and_handlers_fail_the_census() -> None:assert ("python_driver", Severity.ERROR) in kinds and ("app_handler", Severity.ERROR) in kinds-def test_offline_lamp_check_counts_the_world() -> None:- lit = _census_findings(_census(lights=0), offline=True)- dark = _census_findings(_census(lights=0, background=None), offline=True)- assert not [f for f in lit if "lamps" in f.message]- assert [f for f in dark if "lamps" in f.message][0].target == "src/env.py"--def test_an_unlit_scene_fails_the_build_in_both_languages() -> None:"""D112 (argon loop iteration 5, scene_blender r1_10): the placeholder env — no lamp, no world —passed the build as a WARN and every round-0 frame was black after the full render and judge spend.@@ -192,28 +68,6 @@ def test_an_unlit_scene_fails_the_build_in_both_languages() -> None:assert [f.severity for f in _census_findings({**three, "background": "#88aacc"}) if "no lights" in f.message] == [Severity.WARN]-def test_each_scene_language_plans_its_own_asset_kinds() -> None:- """D5: ``bpy`` joins the kinds a plan may hold; the schema a planner is handed stays- 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, 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:from codeverse3d.config import get_settingsdiff --git a/harness/tests/scene_blender/test_library.py b/harness/tests/scene_blender/test_library.pyindex fcc53131..1f5c2c80 100644--- a/harness/tests/scene_blender/test_library.py+++ b/harness/tests/scene_blender/test_library.py@@ -1,9 +1,6 @@-"""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+"""The bpy starter library (D51): the effects catalog prints every signature as the lib declares it (a+parameter printed positional that the lib takes by keyword only is a TypeError in every scene that trusts+the row), and ONE Blender build proves every factory seats what it makes, names nothing twice and staysunder its triangle ceiling."""from __future__ import annotations@@ -20,9 +17,8 @@ from codeverse3d.config import get_settingsfrom codeverse3d.contracts.common import Languagefrom codeverse3d.contracts.plan import CameraPlanfrom codeverse3d.languages import get_runtime-from codeverse3d.languages.scene_blender import LIB_DIR, lib_files, render_scene_py, write_example+from codeverse3d.languages.scene_blender import lib_files, render_scene_py, write_examplefrom codeverse3d.prompts.catalog import language_text-from codeverse3d.skills import skills_dirfrom tests.scene_runtime.conftest import needs_browserMODULES: dict[str, Path] = {p.stem: p for p in lib_files()}@@ -56,14 +52,6 @@ def _boundary(fn: ast.FunctionDef) -> tuple[list[str], list[str], bool]: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@@ -81,87 +69,42 @@ def _printed(span: str) -> ast.FunctionDef | 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."""+def _faults(printed: ast.FunctionDef, lib: ast.FunctionDef) -> list[str]:+ """How a printed signature misleads a caller of ``lib``: a parameter printed positional that the lib+ takes by keyword only, a ``*`` anywhere but at the lib's boundary (or missing), a name the lib lacks.+ ``…`` stands for "and the rest"; the lib spells a shadowing ``rng`` as ``rng_``."""a = printed.argsnames = [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+ abbreviated = bool(names) and names[0] == _MORElpos, 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 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:+ if a.kwonlyargs and not lkw:out.append("a `*` is printed but the lib has no keyword-only parameters")- elif star and not abbreviated:+ elif a.kwonlyargs 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:+ elif 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.kwonlyargsif 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."""+ """Regression: 15 catalog rows printed a REQUIRED keyword-only parameter as positional; a zone written+ from the row raised ``TypeError`` and was dropped from the build."""faults: list[str] = []checked = 0for row in [line for line in CATALOG.splitlines() if line.startswith("| ") and "`lib/" in line]:@@ -175,117 +118,20 @@ def test_the_catalog_prints_every_signature_with_the_libs_keyword_only_boundary(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)]+ faults += [f"lib/{stem}.py `{span}`: {f}" for f in _faults(printed, lib)]assert checked > 100, checkedassert 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_bpy_skills_never_print_a_keyword_only_parameter_positionally() -> None:- """The weaker rule for prose the catalog does not own (the skills; the cookbook that once joined- them is gone, 2026-10-15): 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 = {str(md.relative_to(skills_dir().parent)): md.read_text() for md in sorted(skills_dir().glob("c3d-bpy-scene-*/**/*.md"))}- assert len(texts) >= 3, sorted(texts) # 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 catalog and the skills cite-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_skills_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."""+LIB_CHECK = '''"""lib_check: a representative call per library module, each its own placement row."""from lib import architecture, figure, lighting, materials, mesh, motion, place, scatter, sky, terrain, vegetation, waterfrom mathutils import Matrix-SEED = 3-def build(ctx):- rng = ctx.rng(SEED)+ rng = ctx.rng(3)h = ctx.height_atrock = materials.mineral_surface("CheckRock", "6F6A60", stone=True)wood = materials.woodgrain(materials.material("CheckWood", "6B4A2B"))@@ -293,137 +139,83 @@ def build(ctx):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")]+ coat = materials.material("CheckCoat", "8A3A3A")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 = mesh.Batch("Prims_0") # primitives, a transformed view, a bevel; seated, spun by a driverb.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")+ r = mesh.Batch("Rocks_0") # terrain recipes stand on hterrain.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")):+ for i, kind in enumerate(("broadleaf", "oak", "cypress", "pine")): # the four tree kindst = mesh.Batch(f"Tree{kind.title()}_0")x = 10.0 + 6.0 * ivegetation.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 = Truepatch.hide_viewport = Truevegetation.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)- # architecturehouse = mesh.Batch("CheckHouse_0") # the example already has a House_0: names are globalarchitecture.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)+ {"wall": lime, "timber": wood, "door": coat, "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)+ sign = architecture.text_mesh("Sign_0", ctx.collection, "LIB", (20.0, 42.0, h(20.0, 42.0)), 0.6, coat)place.seat(sign, h)# a glazed room shell (the env's recipe) stood on the ground, so the gate measures it as ONE rowcabin = 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"]- # waterfall = 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 dressingfolk = 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)+ figure.figure(folk, coat, coat, (-12.0, 44.0, h(-12.0, 44.0)), heading=place.heading((-12.0, 44.0), (0.0, 0.0)), pose=0.5)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"]+ crate = ctx.assets["crate"] # an instance, a stack, the self-checks, a keyframed driftone = 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 floatingtop = scatter.instance(ctx.collection, crate, "StackedCrate_0", -14.0, 44.0, height_at=h, rot_z=yaw, scale=1.0)@@ -431,30 +223,20 @@ def build(ctx):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) == 2scatter.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)) == 4assert 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,+ "Plants_0": 3_000, "CheckHouse_0": 14_000, "Bridge_0": 1_500, "Lantern_0": 800, "Sign_0": 2_000, "Fall_0": 2_500,"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"}+SEATED = {"Prims_0", "Rope_0", "Rocks_0", "TreeBroadleaf_0", "TreeOak_0", "TreeCypress_0", "TreePine_0", "Plants_0",+ "CheckHouse_0", "Bridge_0", "Sign_0", "Fall_0", "Fountain_0", "Visitors_0", "LibCrate_0", "StackedCrate_0",+ "CheckCrate_0", "CheckCrate_1", "RoomShell"}EXEMPT = {"Meadow_0": "instanced", "Lantern_0": "free", "Fountain_0Spray_0": "free", "AuroraSky_0": "free", "Stars_0": "free"}@@ -521,98 +303,3 @@ def test_one_blender_build_seats_what_every_factory_makes(tmp_ws) -> None:assert not over, overassert 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.pyindex 4a58e1f7..30d27fb8 100644--- a/harness/tests/scene_blender/test_lint.py+++ b/harness/tests/scene_blender/test_lint.py@@ -5,19 +5,13 @@ from __future__ import annotationsimport pytestfrom codeverse3d.contracts.artifacts import LintKind, Severity-from codeverse3d.contracts.common import Track-from codeverse3d.contracts.plan import ScenePlanfrom codeverse3d.languages._ast_lint import BASE_FORBIDDEN_IMPORTSfrom 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_exampleHEAD = "import bpy\n\n\ndef build(ctx):\n"@@ -42,44 +36,22 @@ def _worst(source: str, **kw) -> Severity | None:TABLE = [# D10: a Python driver never evaluates under --factory-startup (it reads 0) -> ERROR('d = ob.driver_add("location", 2).driver\nd.expression = "noise.noise((frame, 0, 0))"', Severity.ERROR),- ('d = ob.driver_add("location", 2).driver\nd.expression = "bpy.data.objects[0].location.x"', Severity.ERROR),- ('d = ob.driver_add("location", 2).driver\nd.expression = "frame ** 2"', Severity.ERROR),- ('d = ob.driver_add("location", 2).driver\nd.use_self = True', Severity.ERROR),('d = ob.driver_add("location", 2).driver\nd.expression = "sin(frame * 0.2) * 2 if frame > 3 else 0"', None),- ("bpy.app.handlers.frame_change_pre.append(lambda s: None)", Severity.ERROR),# harness-owned: rendering, files, cameras, frames, scene render settings("bpy.ops.render.render(write_still=True)", Severity.ERROR),- ('bpy.ops.wm.save_as_mainfile(filepath="x.blend")', Severity.ERROR),- ('bpy.ops.import_scene.gltf(filepath="x.glb")', Severity.ERROR),- ('cam = bpy.data.cameras.new("C")', Severity.ERROR),('ctx.scene.render.engine = "CYCLES"', Severity.ERROR),- ("ctx.scene.cycles.samples = 64", Severity.ERROR),- ('ctx.scene.view_settings.view_transform = "AgX"', Severity.ERROR),- ("ctx.scene.frame_end = 100", Severity.ERROR),- ("ctx.scene.frame_set(10)", Severity.ERROR),- ("ctx.scene.camera = None", Severity.ERROR),- ('open("x.txt", "w")', Severity.ERROR),# the world is env.py's('ctx.scene.world = bpy.data.worlds.new("W")', Severity.ERROR),# renamed / removed API- ('sky.sky_type = "NISHITA"', Severity.ERROR),('bsdf.inputs["Specular"].default_value = 0.5', Severity.ERROR),- ("me.calc_normals()", Severity.ERROR),# determinism: ctx.rng(seed) is the only randomness("import random\nx = random.uniform(0, 1)", Severity.ERROR),- ("import random\nr = random.Random()", Severity.ERROR),- ("import numpy as np\nx = np.random.rand(3)", Severity.ERROR),- ("rng = ctx.rng(7)\nx = rng.uniform(0, 1)", None),("import random\nr = random.Random(3)\nx = r.uniform(0, 1)", None),- ("import numpy as np\ng = np.random.default_rng(3)", None),# build time and zone ownership("for i in range(50):\n bpy.ops.mesh.primitive_cube_add(size=1, location=(i, 0, 0))", Severity.WARN),("ctx.scene.collection.objects.link(ob)", Severity.WARN),# the agent's own settings on its own data are NOT harness-owned- ("mod.render_levels = 2", None),- ('mat.cycles.displacement_method = "BOTH"', None),("ctx.collection.objects.link(ob)", None),- ('ob["placement"] = "free"', None),]@@ -88,28 +60,12 @@ def test_the_scene_lint_table(body: str, worst: Severity | None) -> None:assert _worst(_zone(body)) is worst, _hits(_zone(body))[email protected]("mod", ["os", "sys", "time", "datetime", "pathlib", "subprocess", "socket"])[email protected]("mod", ["os", "time"])def test_clock_file_and_process_imports_are_forbidden(mod: str) -> None:assert _worst(f"import {mod}\n" + _zone("pass")) is Severity.ERRORassert BASE_FORBIDDEN_IMPORTS <= FORBIDDEN_IMPORTS-def test_the_world_and_lamps_belong_to_env() -> None:- env = ("import bpy\n\n\ndef height_at(x, y):\n return 0.0\n\n\ndef build_env(ctx):\n"- ' ctx.scene.world = bpy.data.worlds.new("Sky")\n'- ' ctx.collection.objects.link(bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN")))\n'- " return {}\n")- assert _worst(env, role="env", target="src/env.py") is None- assert _worst(env.replace("def build_env", "def make_env"), role="env", target="src/env.py") is Severity.ERROR---def test_module_exports_are_the_layout() -> None:- assert _worst("import bpy\n\n\ndef make(ctx):\n return ctx.collection\n") is Severity.ERROR # zone: build- asset = "import bpy\n\n\ndef build_crate(ctx, variant=0):\n return ctx.collection\n"- assert _worst(asset, role="asset", target="src/assets/crate.py") is None- assert _worst(asset, role="asset", target="src/assets/barrel.py") is Severity.ERROR--def test_simple_driver_is_blenders_subset() -> None:"""Verified against Blender 5.0.1 ``driver.is_simple_expression`` (DESIGN probes/drv.py)."""for ok in ("sin(frame*0.2)*2", "frame*2 if frame > 3 else 1", "clamp(frame / 40, 0, 1)", "lerp(0, 2, 0.5)", "pi", "not frame"):@@ -118,30 +74,6 @@ def test_simple_driver_is_blenders_subset() -> None:assert not simple_driver(bad), bad-def test_the_library_is_not_the_agents_code(tmp_ws) -> None:- """``src/lib/`` is harness-owned (D51): syntax only, never the policy."""- (tmp_ws.src / "lib").mkdir(parents=True)- (tmp_ws.src / "lib" / "sky.py").write_text("import os\nX = os.getcwd()\n")- (tmp_ws.src / "scene.py").write_text("ZONES = {}\nASSETS = {}\nHEROES = {}\nCAMERAS = []\n")- assert lint(tmp_ws).passed- (tmp_ws.src / "lib" / "sky.py").write_text("def broken(:\n")- assert not lint(tmp_ws).passed---def test_the_skeleton_lints_clean(tmp_ws) -> None:- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- write_skeleton(tmp_ws, plan)- rep = lint(tmp_ws)- 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--@pytest.mark.parametrize("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@@ -155,7 +87,3 @@ def test_the_library_passes_the_agent_lint_itself(path) -> None: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_nonfinite.py b/harness/tests/scene_blender/test_nonfinite.pyindex 1bf623f5..8208bdae 100644--- a/harness/tests/scene_blender/test_nonfinite.py+++ b/harness/tests/scene_blender/test_nonfinite.py@@ -1,12 +1,7 @@-"""D114: a NaN / inf the model's bpy code leaves in a transform or a vertex is the MODEL's build error.--Observed 2026-10-17 (a scene_blender run, round 2): an object with a NaN transform reached the census-GLB as ``"matrix":[NaN,…]``, the probe host's ``JSON.parse`` rejected it, the repair loop read that as-a harness failure and re-ran the build twice — the model was never told and the round scored nothing.-Pinned here: the detector (``wrappers/_finite.py``, pure), the census writer refusing to write one,-and — in real Blender — a zone that sets ``location.x = nan`` failing the wrapper with the object, the-channel and the zone file named, a ``BuildResult`` the repair loop hands to the model (no-``harness_retry``). The generated-image half of D114 (``scene.blend`` keeps in-memory pixels) is here too."""+"""D114: a NaN / inf the model's bpy code leaves in a transform or a vertex is the MODEL's build error (it once+reached the census GLB as ``NaN``, the probe's ``JSON.parse`` failed and the repair loop blamed the harness):+the census writer refuses to write one, a real Blender zone with ``location.x = nan`` fails naming object,+channel and file, and generated image pixels are packed into ``scene.blend``."""from __future__ import annotations@@ -56,64 +51,6 @@ def _obj(name: str, *, location=(0.0, 0.0, 0.0), rotation=(0.0, 0.0, 0.0), scalematrix_parent_inverse=np.eye(4).tolist(), parent=parent)-# --------------------------------------------------------------------------- the detector-def test_the_detector_names_the_channel_and_walks_up_to_the_parent_that_holds_it(monkeypatch) -> None:- f = _load("_finite", monkeypatch)- assert f.finite([[1.0, 2.0], [3.0, 4.0]]) and f.finite(np.eye(4)) and f.finite([])- assert not f.finite([0.0, NAN]) and not f.finite(np.array([[1.0, INF]]))- assert f.bad_rows(np.array([[0.0, 0.0, 0.0], [NAN, 0.0, 0.0], [1.0, INF, NAN]])) == 2- assert f.bad_rows(np.empty((0, 3))) == 0-- pillar = _obj("Pillar", location=(NAN, 0.0, 1.25))- assert f.own_channels(pillar) == ["location=(nan, 0, 1.25)"]- assert f.own_channels(_obj("Spun", rotation=(0.0, 0.0, INF))) == ["rotation_euler=(0, 0, inf)"]- # the rotation channel the object's mode USES (a NaN in an unused one is not what moved it)- assert f.own_channels(_obj("Q", mode="QUATERNION", quaternion=(NAN, 0.0, 0.0, 0.0), rotation=(NAN, 0, 0))) == [- "rotation_quaternion=(nan, 0, 0, 0)"]- assert f.own_channels(_obj("Flat", scale=(1.0, NAN, 1.0))) == ["scale=(1, nan, 1)"]- # a child of a NaN parent: the parent is the culprit, the child is named as what it broke- root = _obj("ArchRoot", rotation=(0.0, 0.0, NAN))- arch = _obj("Arch", parent=root)- culprit, channels = f.transform_culprit(arch)- assert culprit is root and channels == ["rotation_euler=(0, 0, nan)"]- # every channel finite on the way up: the evaluated matrix itself (a constraint, a driver)- culprit, channels = f.transform_culprit(_obj("Tracked"))- assert culprit.name == "Tracked" and channels == [f.EVALUATED_NOTE]---def test_the_report_is_a_model_error_naming_objects_files_and_channels(monkeypatch) -> None:- f = _load("_finite", monkeypatch)- files = {"Pillar": "src/zones/ruins.py", "ArchRoot": "src/zones/ruins.py", "Rock": "src/assets/rock.py"}- bad = f.Offenders(origin=lambda o: files.get(o.name, ""))- assert not bad- bad.vertices(SimpleNamespace(name="Rock"), 3, 120)- rep = bad.report()- assert rep["error_type"] == f.GEOMETRY_ERROR == "NonFiniteGeometry"- assert rep["error_file"] == "src/assets/rock.py" and rep["error_line"] is None- bad.transform(_obj("Pillar", location=(NAN, 0.0, 0.0)))- bad.transform(_obj("Arch", parent=_obj("ArchRoot", rotation=(0.0, NAN, 0.0))))- bad.transform(_obj("Pillar", location=(NAN, 0.0, 0.0))) # the same object twice: one row- bad.instances(SimpleNamespace(name="Meadow"), "'Blade'", 4, 500)- rep = bad.report()- assert rep["error_type"] == f.TRANSFORM_ERROR == "NonFiniteTransform"- assert [(r["object"], r["kind"], r["file"]) for r in rep["nonfinite"]] == [- ("Rock", "vertices", "src/assets/rock.py"), ("Pillar", "transform", "src/zones/ruins.py"),- ("ArchRoot", "transform", "src/zones/ruins.py"), ("Meadow", "instances", "")]- msg = rep["error_message"]- assert msg.startswith("4 object(s) carry non-finite (NaN/inf) values")- assert "'Pillar' [src/zones/ruins.py]: location=(nan, 0, 0)" in msg- assert "'ArchRoot' [src/zones/ruins.py]: rotation_euler=(0, nan, 0) (makes 'Arch' non-finite)" in msg- assert "3 of 120 evaluated vertices" in msg and "4 of 500 instances of 'Blade'" in msg- assert "division by zero" in msg- json.dumps(rep, allow_nan=False) # the report itself is JSON- # a placed asset: the instance's own NaN names it plainly; a NaN in the SOURCE says how it got there- placed = f.Offenders()- placed.transform(_obj("Rock_0", location=(1.0, NAN, 0.0)), _obj("RockBody"), via="(instanced by 'Rock_0')")- placed.transform(_obj("Rock_1"), _obj("RockCore", scale=(NAN, 1.0, 1.0)), via="(instanced by 'Rock_1')")- assert [r["detail"] for r in placed.report()["nonfinite"]] == [- "location=(1, nan, 0)", "scale=(nan, 1, 1) (makes 'Rock_1' non-finite) (instanced by 'Rock_1')"]--def test_the_census_writer_never_writes_a_nan(monkeypatch) -> None:g = _load("_census_glb", monkeypatch)w = g._Writer(np.eye(3))@@ -123,10 +60,6 @@ def test_the_census_writer_never_writes_a_nan(monkeypatch) -> None:broken[0, 3] = NANassert w.node_matrix(broken, _obj("Pillar", location=(NAN, 0.0, 0.0))) is Noneassert [r["object"] for r in w.bad.report()["nonfinite"]] == ["Pillar"]- # a non-finite custom property is not JSON either: dropped, the rest kept- props = {"placement": "free", "height": NAN, "_hidden": 1, "weight": 2.5}- holder = type("Props", (), {"keys": lambda self: props.keys(), "__getitem__": lambda self, k: props[k]})()- assert g.extras_of(holder) == {"placement": "free", "weight": 2.5}# the last line of defence: the JSON chunk refuses NaN outrightw.nodes.append({"name": "x", "matrix": [NAN] * 16})with pytest.raises(ValueError):@@ -218,7 +151,7 @@ def _image_pixels(blend: Path, image: str) -> list[float]:@pytest.mark.blender@needs_blender-def test_a_nan_in_a_zone_is_the_models_build_error_and_reaches_a_repair(tmp_path, monkeypatch) -> None:+def test_a_nan_in_a_zone_is_the_models_build_error(tmp_path) -> None:rt = get_runtime(Language.SCENE_BLENDER)ws = _workspace(tmp_path)res = rt.build(ws) # the wrapper fails, so no probe runs: no headless Chrome needed@@ -233,24 +166,6 @@ def test_a_nan_in_a_zone_is_the_models_build_error_and_reaches_a_repair(tmp_pathassert not (ws.artifacts / "census.glb").exists(), "nothing written: never a NaN in the GLB's JSON"assert set(report["zones_ok"]) == {"ruins", "meadow"}- # the repair loop: a model repair, never a harness rebuild — and the report names the culprit- events: list[str] = []- tasks: list[str] = []- builds = iter([(res, GateReport(gate="lint", passed=True, findings=[]))])- monkeypatch.setattr(R, "build_once", lambda ctx: next(builds, (res.model_copy(update={"error_message": "fixed?"}),- GateReport(gate="lint", passed=True, findings=[]))))- monkeypatch.setattr(R, "make_repair_task", lambda ctx, build, lint, **k: tasks.append(- R.format_error_report(build, lint)) or SimpleNamespace(label=k["label"]))- monkeypatch.setattr(C, "generate", lambda ws, **kw: SimpleNamespace(ok=True, files_changed=["src/zones/ruins.py"],- usage=Usage(), notes="", transient=False))- ctx = SimpleNamespace(spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=1)),- events=SimpleNamespace(emit=lambda name, **k: events.append(name)),- ws=ws, agent_id="x", agent=None, model=None, settings=None, budget=None)- out = R.build_with_repair(ctx, round_index=2, label="r02", max_attempts=1)- assert "build.harness_retry" not in events and "repair.attempt" in events and len(out.attempts) == 1- assert tasks[0].startswith("BUILD FAILED — NonFiniteTransform at src/zones/ruins.py")- assert "'Pillar'" in tasks[0] and "location=(nan" in tasks[0]-@pytest.mark.blender@needs_blender@@ -268,58 +183,37 @@ def test_the_scene_blend_keeps_generated_pixels_for_the_judged_frames(tmp_path)assert all(math.isfinite(v) for v in px)-FIELD = '''import bpy---def build(ctx):- e = bpy.data.objects.new("Rock_0", None)- e.instance_type = "COLLECTION"- e.instance_collection = ctx.assets["rock"]- e.location = (float("nan"), 5.0, 0.0)- ctx.collection.objects.link(e)- # a geometry-nodes scatter: the depsgraph lists its instances AS the host object- pts = bpy.data.meshes.new("Pts")- pts.from_pydata([(0, 0, 0), (float("nan"), 0, 0), (2, 0, 0)], [], [])- host = bpy.data.objects.new("Field", pts)- ctx.collection.objects.link(host)- me = bpy.data.meshes.new("BladeMesh")- me.from_pydata([(0, 0, 0), (0.1, 0, 0), (0, 0, 0.5)], [], [(0, 1, 2)])- blade = bpy.data.objects.new("Blade", me)- blade.hide_render = True- ctx.collection.objects.link(blade)- ng = bpy.data.node_groups.new("Scatter", "GeometryNodeTree")- ng.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")- ng.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")- gi, go = ng.nodes.new("NodeGroupInput"), ng.nodes.new("NodeGroupOutput")- m2p, iop = ng.nodes.new("GeometryNodeMeshToPoints"), ng.nodes.new("GeometryNodeInstanceOnPoints")- info = ng.nodes.new("GeometryNodeObjectInfo")- info.inputs[0].default_value = blade- ng.links.new(gi.outputs[0], m2p.inputs[0])- ng.links.new(m2p.outputs[0], iop.inputs["Points"])- ng.links.new(info.outputs["Geometry"], iop.inputs["Instance"])- ng.links.new(iop.outputs[0], go.inputs[0])- host.modifiers.new("Scatter", "NODES").node_group = ng- return ctx.collection-'''--@pytest.mark.blender@needs_blender-def test_instances_report_the_geometry_and_the_placement_together(tmp_path) -> None:- """An instanced mesh with a NaN vertex does not hide a NaN in what places it (one repair, not two),- and a geometry-nodes scatter names the mesh it scatters, not its own host twice."""+def test_a_nan_in_a_zone_is_the_models_build_error_and_reaches_a_repair(tmp_path, monkeypatch) -> None:rt = get_runtime(Language.SCENE_BLENDER)- ruins = RUINS.replace(' pillar.location.x = float("nan")\n', "").replace(' root.rotation_euler.z = float("nan")\n', "")- rock = ROCK.replace("(0, 0, 1)]", '(0, 0, float("nan"))]')- ws = _workspace(tmp_path, ruins=ruins, meadow=FIELD, rock=rock)- run = rt.run_wrapper(ws, ws.artifacts)- assert not run.result.ok and not run.result.harness_failure, (run.result.error_type, run.result.error_message)- rows = {(r["object"], r["kind"]): r for r in run.report["nonfinite"]}- assert rows[("RockBody", "vertices")]["file"] == "src/assets/rock.py"- assert rows[("Rock_0", "transform")]["file"] == "src/zones/meadow.py"- assert "location=(nan, 5, 0)" in rows[("Rock_0", "transform")]["detail"]- field = rows[("Field", "instances")]- assert field["file"] == "src/zones/meadow.py"- assert field["detail"].startswith("1 of 3 instances of mesh 'BladeMesh' it scatters"), field["detail"]- assert run.report["error_type"] == "NonFiniteTransform"- assert not (ws.artifacts / "census.glb").exists()+ ws = _workspace(tmp_path)+ res = rt.build(ws) # the wrapper fails, so no probe runs: no headless Chrome needed+ assert not res.ok and not res.harness_failure, (res.error_type, res.error_message)+ assert res.error_type == "NonFiniteTransform" and res.error_file == "src/zones/ruins.py"+ assert "'Pillar' [src/zones/ruins.py]: location=(nan, 0, 0)" in res.error_message+ assert "'ArchRoot' [src/zones/ruins.py]: rotation_euler=(0, 0, nan) (makes 'Arch' non-finite)" in res.error_message+ report = json.loads((ws.artifacts / "bpy_build.json").read_text())+ assert report["error_type"] == "NonFiniteTransform" and not report["ok"]+ assert {(r["object"], r["file"]) for r in report["nonfinite"]} == {("Pillar", "src/zones/ruins.py"),+ ("ArchRoot", "src/zones/ruins.py")}+ assert not (ws.artifacts / "census.glb").exists(), "nothing written: never a NaN in the GLB's JSON"+ assert set(report["zones_ok"]) == {"ruins", "meadow"}++ # the repair loop: a model repair, never a harness rebuild — and the report names the culprit+ events: list[str] = []+ tasks: list[str] = []+ builds = iter([(res, GateReport(gate="lint", passed=True, findings=[]))])+ monkeypatch.setattr(R, "build_once", lambda ctx: next(builds, (res.model_copy(update={"error_message": "fixed?"}),+ GateReport(gate="lint", passed=True, findings=[]))))+ monkeypatch.setattr(R, "make_repair_task", lambda ctx, build, lint, **k: tasks.append(+ R.format_error_report(build, lint)) or SimpleNamespace(label=k["label"]))+ monkeypatch.setattr(C, "generate", lambda ws, **kw: SimpleNamespace(ok=True, files_changed=["src/zones/ruins.py"],+ usage=Usage(), notes="", transient=False))+ ctx = SimpleNamespace(spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=1)),+ events=SimpleNamespace(emit=lambda name, **k: events.append(name)),+ ws=ws, agent_id="x", agent=None, model=None, settings=None, budget=None)+ out = R.build_with_repair(ctx, round_index=2, label="r02", max_attempts=1)+ assert "build.harness_retry" not in events and "repair.attempt" in events and len(out.attempts) == 1+ assert tasks[0].startswith("BUILD FAILED — NonFiniteTransform at src/zones/ruins.py")+ assert "'Pillar'" in tasks[0] and "location=(nan" in tasks[0]diff --git a/harness/tests/scene_blender/test_prompts.py b/harness/tests/scene_blender/test_prompts.pyindex 386471fe..c700517c 100644--- a/harness/tests/scene_blender/test_prompts.py+++ b/harness/tests/scene_blender/test_prompts.py@@ -1,12 +1,7 @@-"""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)."""+"""scene_blender track plumbing (offline): the asset stage's ``bpy`` check, the stage transport retry."""from __future__ import annotations-import astimport jsonfrom types import SimpleNamespace@@ -14,43 +9,18 @@ import pytestfrom codeverse3d.contracts.agent import AgentResultfrom codeverse3d.contracts.common import Language, Track, Usage-from codeverse3d.contracts.plan import ScenePlan, ZoneLayout-from codeverse3d.languages.scene_blender import LIB_DIRfrom codeverse3d.proc import EventLog-from codeverse3d.prompts import PROMPTS_DIR, render-from codeverse3d.prompts.catalog import language_text-from codeverse3d.skills import skills_dirfrom 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 language_system_promptfrom codeverse3d.tracks.scene import (- ENV_FILES,- SCENE_TEMPLATES,SceneTrack,- _guess_target,- env_file,- plan_bbox_line,- 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_blockfrom codeverse3d.workspace import Workspacefrom tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (FakeAgent,- FakeChatModel,FakeJudge,FakeRuntime,FakeServices,@@ -69,61 +39,6 @@ def settings(tmp_path):return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")-# --------------------------------------------------------------------------- the files-def test_the_language_ships_its_three_prompt_files_and_the_system_prompt_knows_about_tools() -> None:- """system / contract / asset — and no cookbook (owner, 2026-10-15; tests/prompts/test_files.py pins- its absence): the Blender 5.2 facts (D104) that lived in it are the contract's."""- for name in ("system.md", "contract.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- text = language_text(BPY, "contract.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 _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:- for attempt in (head + "\n pass", head): # a bare header (maybe with a trailing comment), or a one-liner with its body- try:- node = ast.parse(attempt).body[0]- break- except SyntaxError:- continue- else:- 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 plandef _bpy_ctx(tmp_ws, settings, *, agent=None, agent_id="fake:x", services=None):plan_obj = small_scene(BPY)@@ -133,153 +48,6 @@ def _bpy_ctx(tmp_ws, settings, *, agent=None, agent_id="fake:x", services=None):return ctx, plan_obj-def test_the_bpy_skeleton_is_an_interface_stub_without_a_landform(tmp_ws, settings) -> None:- """The env stub hands the plan over as data and a PLACEHOLDER that builds; the landform is the- author's (the stub used to be a level pad of the bounds' half-span + 15 m with fbm hills beyond,- a mossy ground, a fog box and — for an interior — a room shell with one ceiling light: 30/30- iteration-0 scenes kept its shape). A zone stub is the interface and a TODO naming the plan's- contents — no grid of positions, no "keep them inside the bbox" (owner, 2026-10-15)."""- from codeverse3d.languages.scene_blender import lint, write_skeleton-- ctx, plan_obj = _bpy_ctx(tmp_ws, settings)- write_skeleton(tmp_ws, plan_obj)- env = (tmp_ws.src / "env.py").read_text()- for landform in ("FLAT_RADIUS", "make_height_at", "room_shell(", "area_light(", "4A5A3A", "noise_scale", "40.0)"):- assert landform not in env, landform- assert "def height_at(x, y):" in env and "def build_env(ctx):" in env and "PLACEHOLDER" in env- assert "not the edge of the world" in env and "OPTIONAL toolbox" in env and "no_fog" in env- span = max(plan_obj.bounds.extents[0], plan_obj.bounds.extents[2])- assert f"GROUND_SIZE = {span * 3.0:.1f}" in env and "INTERIOR = False" in env- quay = (tmp_ws.src / "zones" / "quay.py").read_text()- assert "def build(ctx):" in quay and "return ctx.collection" in quay and "TODO" in quay- assert "place(" not in quay and "from lib" not in quay and "inside the bbox" not in quay- assert "continue past the bbox" in quay and "scene_placement" in quay- for content in plan_obj.zones[0].contents:- assert f"- {content}:" in quay, content- bollard = (tmp_ws.src / "assets" / "bollard.py").read_text()- assert "def build_bollard(ctx, variant=0):" in bollard and "PLACEHOLDER" in bollard and "optional" in bollard- assert "one mesh per material" not in bollard- rep = lint(tmp_ws)- assert rep.passed and not [f for f in rep.findings if f.severity.value != "info"], [(f.target, f.message) for f in rep.findings]- # an interior plan: the room box is DATA; nothing instantiates an enclosure or a ceiling light- inside = Workspace(tmp_ws.root.parent / "inside")- write_skeleton(inside, plan_obj.model_copy(update={"interior": True, "glazed": True}))- env = (inside.src / "env.py").read_text()- assert "INTERIOR = True" in env and "GLAZED = True" in env and "room_shell(" not in env and "CeilingLight" not in env---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 (38, 4, -30) as (38, 30, 4)."""- 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))- 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" not in env and "copy these numbers" not in env # no recipes travel in the brief (2026-10-15)- zone = render(t.zone, **st._ctx(ctx, 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 (38.0, 30.0, 4.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, 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 "# role: env" not 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_a_multi_zone_session_reads_the_shared_tail_once(tmp_ws, settings) -> None:- """Two zones in one session: a per-zone head for each (bbox, contents, layout, neighbours) and the- shared tail — cameras, assets, the contract, the measured list, the output rules — ONCE, after the- last head. A two-zone prompt used to carry the contract and the catalog twice, with "HOW TO- FINISH" landing between zone 1 and zone 2 (the copyability review of 2026-10-15)."""- ctx, plan_obj = _bpy_ctx(tmp_ws, settings)- st = SceneTrack(services=ctx.services)- task = st._zone_task(ctx, list(plan_obj.zones))- prompt = task.prompt- for z in plan_obj.zones:- assert f"# Zone `{z.name}` of" in prompt and f"write `src/zones/{z.name.lower()}.py`" in prompt- assert prompt.count("## Contract") == 1 and prompt.count("## Output") == 1 and prompt.count("## Assets available") == 1- assert prompt.index("# Zone `Water` of") < prompt.index("## Contract") # every head before the one tail- assert prompt.rstrip().endswith("OUT") or "## Output" in prompt[-2000:]- single = st._zone_task(ctx, [plan_obj.zones[0]]).prompt- assert single.count("## Contract") == 1 and "## Output" in single---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")@@ -287,16 +55,9 @@ def test_check_bpy_asset_without_a_blender_runtime_and_its_throw_away_workspace(ctx.runtime.skeleton(tmp_ws, plan_obj)unavailable = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard") # FakeRuntime has no run_wrapperassert 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+ assert 'ASSETS = {\n "bollard": "Bollard",\n}' in (scratch.root / "src" / "scene.py").read_text()# the wrapper's isolated-stage report maps to the check: a raise is fatal with its line, a clean build is measuredclass _Run:@@ -321,81 +82,11 @@ def test_check_bpy_asset_without_a_blender_runtime_and_its_throw_away_workspace(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]- # a NaN the census refused (D114): the build FINISHED — the module's error as reported, file first, not cut at 300- nan_msg = "2 object(s) carry non-finite (NaN/inf) values " + "x" * 400- ctx.runtime = _Runtime({"errors": [], "error_type": "NonFiniteGeometry", "error_message": nan_msg,- "error_file": "src/assets/bollard.py", "nonfinite": [{"object": "Bollard", "kind": "vertices"}]},- ok=False, error_type="NonFiniteGeometry")- nan = SA.check_bpy_asset(ctx, "src/assets/bollard.py", "bollard")- assert nan.fatal and nan.errors == [f"src/assets/bollard.py: NonFiniteGeometry: {nan_msg}"]- # 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_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"--class _TransientOnceAgent(FakeAgent):"""The first session with ``label`` dies of a provider failure (typed transient); the rest work."""@@ -417,17 +108,15 @@ def _zone_writer(job, ws):"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:+def test_an_env_session_killed_by_the_provider_is_retried_once(tmp_path, settings) -> None:"""The round loop's transport-retry rule, applied to a stage session (env / zones): ONE re-run underthe ``.a2`` label when the session died transient and the budget allows; a non-transient failureis 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+ # no assets: the asset stage runs beside the env stage, a different story from this oneplan_obj = small_scene(BPY).model_copy(update={"assets": []})for zone in plan_obj.zones:zone.contents = []- agent = _TransientOnceAgent(_zone_writer, "env", transient=transient)+ agent = _TransientOnceAgent(_zone_writer, "env", transient=True)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))@@ -436,14 +125,8 @@ def test_an_env_session_killed_by_the_provider_is_retried_once(tmp_path, settingevents = [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 serveskinds = [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-+ 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@pytest.mark.blenderdef test_check_bpy_asset_measures_a_module_in_blender(tmp_ws, settings) -> None:@@ -481,20 +164,3 @@ def test_check_bpy_asset_measures_a_module_in_blender(tmp_ws, settings) -> None: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_blender/test_raw_mode.py b/harness/tests/scene_blender/test_raw_mode.pyindex 7daab705..7cc05efa 100644--- a/harness/tests/scene_blender/test_raw_mode.py+++ b/harness/tests/scene_blender/test_raw_mode.py@@ -1,19 +1,11 @@-"""scene_blender raw mode (D113, ``Settings.scene_lib`` off, the ``argon_raw`` variant): no harness bpy-library ships, so every mesh, material, light, world and motion of the scene is the model's.--Pinned here: the raw skeleton (no ``src/lib``, no stub that imports or names it, the plan-less-example refused), the lint (a ``lib`` import is an ERROR in raw mode only), the runtime reading the-knob at call time, the ``argon_raw`` overlay (it resolves, its knob reaches the settings a run uses,-no file of it names the library, every overlaid stage template renders with the scene track's-context) and — in real Blender — the raw placeholder env and an empty zone building through the-wrapper. The default (library) mode is pinned byte-identical by the prompt manifest and the-existing scene_blender tests."""+"""scene_blender raw mode (D113, ``Settings.scene_lib`` off, the ``argon_raw`` variant): the raw skeleton, the lint+(a ``lib`` import is an ERROR in raw mode only), the knob read at call time, the overlay's knob, and the raw stubs+building in real Blender."""from __future__ import annotationsimport astimport re-from pathlib import Pathimport pytest@@ -26,16 +18,12 @@ from codeverse3d.languages.scene_blender import (lint_scene_source,write_skeleton,)-from codeverse3d.prompts import renderfrom codeverse3d.prompts.variants import (- VARIANTS_DIR,activate,knobs_applied,- run_knob,variant_info,)-from codeverse3d.skills import variant_dir-from codeverse3d.tracks.planner import build_system_prompt, plan_example+from codeverse3d.tracks.planner import plan_examplefrom codeverse3d.workspace import WorkspaceBPY = Language.SCENE_BLENDER@@ -43,11 +31,6 @@ RAW = "argon_raw"#: what names the harness library in text a model reads: the workspace path, a dotted helper call#: (``lib.place.seat``), an import of the package, a module file (``lib/vegetation.py``)LIB_MENTION = re.compile(r"src/lib|\blib\.[a-z_]+|\bfrom lib\b|\bimport lib\b|\blib/[a-z_]+\.py")-#: the stage templates the overlay shadows (the planner's included)-OVERLAID_TEMPLATES = ("tracks/scene_env_bpy.j2", "tracks/scene_zone_bpy.j2", "tracks/scene_refine_bpy.j2",- "tracks/scene_asset_bpy.j2", "tracks/plan_scene_bpy.j2")--def _plan() -> ScenePlan:return ScenePlan.model_validate(plan_example(Track.SCENE, BPY))@@ -69,40 +52,8 @@ def test_the_raw_skeleton_ships_no_library_and_no_stub_imports_or_names_it(tmp_wassert not _lib_imports(text), (p.name, _lib_imports(text))assert not LIB_MENTION.search(text), (p.name, LIB_MENTION.search(text))assert "toolbox" not in text, p.name- env = (tmp_ws.src / "env.py").read_text()- assert "def height_at(x, y):" in env and "def build_env(ctx):" in env and '"Ground"' in env- assert "worlds.new" not in env and "lights.new" not in env, "the placeholder builds ONE plate and nothing else"rep = lint(tmp_ws, lib=False)assert rep.passed and not [f for f in rep.findings if f.severity.value != "info"], [(f.target, f.message) for f in rep.findings]- # the interior placeholder too: the plan's data, no library helper named- inside = Workspace(tmp_ws.root.parent / "inside")- write_skeleton(inside, plan.model_copy(update={"interior": True, "glazed": True}), lib=False)- env = (inside.src / "env.py").read_text()- assert "INTERIOR = True" in env and "GLAZED = True" in env and not LIB_MENTION.search(env) and "room_shell" not in env---def test_the_plan_less_example_is_refused_in_raw_mode(tmp_ws) -> None:- """The example scene is built on the library: a raw run starts from a plan's stubs or not at all."""- with pytest.raises(ValueError, match="raw mode"):- write_skeleton(tmp_ws, None, lib=False)- assert not tmp_ws.src.exists() or not any(tmp_ws.src.rglob("*.py"))---def test_the_runtime_reads_the_knob_at_call_time(tmp_ws, monkeypatch) -> None:- """The run's knob is the ACTIVE variant's (``run_knob``, per thread): a runtime built before or inside- the run follows it, and the default comes back after."""- monkeypatch.delenv("C3D_SCENE_LIB", raising=False)- settings = Settings()- rt = SceneBlenderRuntime(settings=settings)- assert rt.ships_lib is True- with activate(RAW), knobs_applied(settings, variant_info(RAW)) as applied:- assert applied == {"scene_lib": False} and rt.ships_lib is False- assert settings.scene_lib is True, "a per-run knob is never written onto the shared settings"- rt.skeleton(tmp_ws, _plan())- assert not (tmp_ws.src / "lib").exists() and rt.lib_interface(tmp_ws) == ""- (tmp_ws.src / "zones" / "quay.py").write_text("from lib.materials import material\n\n\ndef build(ctx):\n return ctx.collection\n")- assert not rt.lint(tmp_ws).passed- assert rt.ships_lib is True and rt.lint(tmp_ws).passed, "library mode: the import is allowed again"# --------------------------------------------------------------------------- the lint@@ -119,26 +70,6 @@ def test_a_lib_import_is_an_error_in_raw_mode_and_not_in_library_mode() -> None:assert not lint_scene_source("from env import linked\n", target="src/zones/quay.py", role="helper", lib=False)-# --------------------------------------------------------------------------- the variant-def test_the_argon_raw_variant_resolves_and_its_knob_is_a_default_a_statement_beats(monkeypatch) -> None:- info = variant_info(RAW)- assert info.version == 1 and info.generators == ("agy:gemini-4-argon",) and info.knobs == {"scene_lib": False}- monkeypatch.delenv("C3D_SCENE_LIB", raising=False)- s = Settings()- with activate(RAW), knobs_applied(s, info) as applied:- assert applied == {"scene_lib": False} and run_knob("scene_lib", s) is False- assert s.scene_lib is True and "scene_lib" not in s.model_fields_set and run_knob("scene_lib", s) is True- with activate(""):- assert run_knob("scene_lib", s) is True, "the base run: the field's default"- monkeypatch.setenv("C3D_SCENE_LIB", "1") # the user's own statement wins over the knob- s = Settings()- with activate(RAW), knobs_applied(s, info) as applied:- assert applied == {} and run_knob("scene_lib", s) is True- monkeypatch.setenv("C3D_SCENE_LIB", "0") # ... and so does raw mode stated without the variant- with activate(""):- assert run_knob("scene_lib", Settings()) is False--def test_parallel_runs_of_one_process_never_flip_each_others_mode(tmp_path, monkeypatch) -> None:"""The bench runs ``--parallel N`` runs as threads of ONE process sharing the settings singleton. Araw run ending while a library run is still going (and the reverse) changes neither's answer, and@@ -174,130 +105,6 @@ def test_parallel_runs_of_one_process_never_flip_each_others_mode(tmp_path, monkget_settings.cache_clear()-def test_a_run_context_with_the_real_runtime_decides_once(tmp_ws, tmp_path, monkeypatch) -> None:- """The run's real ``SceneBlenderRuntime`` is the one answer: the track's ``ships_lib`` asks it, the- skeleton stage's cache key carries raw mode (a resume that changed the mode writes the skeleton- again — and removes the other mode's library), and the lint rejects ``lib`` — under the variant, in- a fan-out worker thread like the zone sessions."""- from codeverse3d.proc import fan_out- from codeverse3d.tracks import scene_assets as SA- from codeverse3d.tracks.lifecycle import SKELETON- from tests.orchestrator_tracks.conftest import make_spec-- monkeypatch.delenv("C3D_SCENE_LIB", raising=False)- settings = Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")- spec, plan = make_spec(Track.SCENE, BPY), _plan()- ctx = _ctx_bpy(tmp_ws, settings, spec, plan)- lib_key = SKELETON.key(ctx)- assert "scene_lib" not in lib_key and SA.ships_lib(ctx) is True- ctx.runtime.skeleton(tmp_ws, plan)- assert (tmp_ws.src / "lib").is_dir()- with activate(RAW):- def worker(_: int) -> tuple[bool, dict]:- return SA.ships_lib(ctx), SKELETON.key(ctx)-- (ships, key), = fan_out([0], worker, max_workers=1, label="t", item_name=str)- assert ships is False and key == {**lib_key, "scene_lib": False}- ctx.runtime.skeleton(tmp_ws, plan)- assert not (tmp_ws.src / "lib").exists(), "the library run's src/lib does not outlive a switch to raw"- (tmp_ws.src / "zones" / "quay.py").write_text("from lib.materials import material\n\n\ndef build(ctx):\n return ctx.collection\n")- assert not ctx.runtime.lint(tmp_ws).passed- # a rig's stated Settings(scene_lib=False) with the real runtime: the runtime still answers for both- raw_ctx = _ctx_bpy(tmp_ws, Settings(scene_lib=False), spec, plan)- assert SA.ships_lib(raw_ctx) is raw_ctx.runtime.ships_lib---def _ctx_bpy(ws: Workspace, settings: Settings, spec, plan):- from dataclasses import replace-- from tests.orchestrator_tracks.test_prompts_assets import _ctx-- return replace(_ctx(ws, settings, spec, plan, agent_id="fake:x"), runtime=SceneBlenderRuntime())---def test_a_variant_toml_knob_scene_lib_is_type_checked(tmp_path, monkeypatch) -> None:- from codeverse3d.prompts import variants as V-- (tmp_path / "tv").mkdir()- (tmp_path / "tv" / "variant.toml").write_text('[variant]\nname = "tv"\n[knobs]\nscene_lib = 0\n')- monkeypatch.setattr(V, "VARIANTS_DIR", tmp_path)- with pytest.raises(ValueError, match="scene_lib must be a bool"):- variant_info("tv")---def test_no_file_of_the_overlay_names_the_library() -> None:- """Prompts AND skills: every file a model can read under ``argon_raw`` (the READMEs, which no model- reads, are left out) — no ``src/lib``, no ``lib.<module>`` call, no import of it, no module file."""- files = {p.relative_to(root).as_posix(): p for root in (VARIANTS_DIR / RAW, variant_dir(RAW)) for p in sorted(root.rglob("*"))- if p.is_file() and p.name != "README.md" and "__pycache__" not in p.parts}- names = set(files)- assert {"scene_blender/contract.md", "tracks/scene_env_bpy.j2", "c3d-bpy-scene-placement/SKILL.md"} <= names, sorted(names)- for rel, p in files.items():- hits = sorted({m.group(0) for m in LIB_MENTION.finditer(p.read_text(encoding="utf-8"))})- assert not hits, (rel, hits)---def test_every_overlaid_template_renders_with_the_scene_track_context(tmp_ws, tmp_path) -> None:- """The env / zone / refine / asset briefs through the scene track's own context builders, and the- planner's system prompt — under the variant, so the overlay's copies render (a jinja block the- track does not feed would raise under StrictUndefined or drop a section)."""- from codeverse3d.tracks import scene_assets as SA- from codeverse3d.tracks.scene import SceneTrack, plan_bbox_line, scene_templates- from codeverse3d.tracks.zone_layout import layout_block- from tests.orchestrator_tracks.conftest import make_spec- from tests.orchestrator_tracks.fakes import small_scene- from tests.orchestrator_tracks.test_prompts_assets import _ctx-- plan = small_scene(BPY)- spec = make_spec(Track.SCENE, BPY)- settings = Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")- ctx = _ctx(tmp_ws, settings, spec, plan, agent_id="fake:x")- with activate(RAW), knobs_applied(ctx.settings, variant_info(RAW)):- ctx.extra["asset_api"] = SA.asset_api_summary(plan, {}, language=BPY, lib=SA.ships_lib(ctx))- st = SceneTrack(services=ctx.services)- t = scene_templates(BPY)- quay = plan.zones[0]- prompts = {- "env": render(t.env, **st._ctx(ctx, lib_interface="", env_check_error="", env_previous="")),- "zone": render(t.zone, **st._ctx(ctx, 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))),- "refine": render(t.refine, **st._ctx(ctx, round_index=1, tasks=["t"], targets=["Quay"], files=["src/env.py"],- edit_only_these=False, judge_summary="j", current_files={})),- "asset": SA._asset_prompt(ctx, plan.assets[0], "src/assets/bollard.py", language=BPY),- "plan": build_system_prompt(spec, ScenePlan),- }- for name, text in prompts.items():- assert text.strip(), name- assert not LIB_MENTION.search(text), (name, LIB_MENTION.search(text))- assert "No harness library ships" in prompts["env"] and "No harness library ships" in prompts["zone"]- assert "write `src/env.py`" in prompts["env"] and "def build(ctx)" in prompts["zone"]- assert "NO LIBRARY" in prompts["plan"] and "SHIPPED BPY LIBRARY" not in prompts["plan"]- assert "instance_type = 'COLLECTION'" in prompts["zone"], "the asset API names the Empty, not a library call"- assert "Reference rows" not in prompts["asset"], "no catalog row reaches a raw asset sheet"- assert {Path(r).name for r in OVERLAID_TEMPLATES} <= {p.name for p in (VARIANTS_DIR / RAW / "tracks").glob("*.j2")}---def test_a_run_under_argon_raw_sees_the_overlay_and_the_knob(tmp_path) -> None:- """The whole run, offline (the manifest's scenario): the knob reaches the settings the scene track- reads (the asset API's raw wording), the planner and every session read the overlay, and the- routed bpy bundles are the overlay's lib-free copies."""- from tests.prompts.manifest import run_scenario-- payloads = run_scenario("scene.scene_blender.agent.variant_argon_raw", tmp_path).payloads- readable = {k: v for k, v in payloads.items() if not k.endswith("/scope")} # scope: the read-only list, not text- for key, text in readable.items():- assert not LIB_MENTION.search(text), (key, LIB_MENTION.search(text))- assert "No harness library ships" in payloads["job:env@r00/prompt"]- assert "instance_type = 'COLLECTION'" in payloads["job:zones_quay_water@r00/prompt"]- assert "NO LIBRARY" in payloads["chat:planner:planner/system"]- assert "c3d-bpy-scene-placement" in payloads["skills:runs/run:zone@r00/routed"]- assert get_settings().scene_lib is True, "the knob does not outlive the run"--# --------------------------------------------------------------------------- in Blender@pytest.mark.blenderdef test_the_raw_placeholder_env_and_an_empty_zone_build_in_blender(tmp_path) -> None:diff --git a/harness/tests/scene_gates/test_draw_budget.py b/harness/tests/scene_gates/test_draw_budget.pyindex 17936863..3c24e738 100644--- a/harness/tests/scene_gates/test_draw_budget.py+++ b/harness/tests/scene_gates/test_draw_budget.py@@ -33,7 +33,7 @@ def test_the_probe_gates_the_census_draw_count(draws: int, severity: Severity |(f,) = hitsassert f.severity == severity and report.passed is (severity != Severity.ERROR)assert f.data["draws"] == draws and f.data["limit"] == limit- for text in (f"{draws:,}", f"{limit:,}", "Market", "InstancedMesh", "mergeGeometries", "lib/merge.js", "lib/instancing.js"):+ for text in (f"{draws:,}", f"{limit:,}", "Market", "InstancedMesh", "mergeGeometries", "lib/merge.js"):assert text in f.message, textdiff --git a/harness/tests/scene_gates/test_frame_metrics.py b/harness/tests/scene_gates/test_frame_metrics.pyindex b7cfa62d..3f3f20c1 100644--- a/harness/tests/scene_gates/test_frame_metrics.py+++ b/harness/tests/scene_gates/test_frame_metrics.py@@ -32,8 +32,7 @@ def test_camera_in_geometry_and_near_hit():_chk("Close", nearest_hit_m=0.3)))assert [(k, s) for k, s, _ in _kinds(rep)] == [("camera_in_geometry", Severity.ERROR)] * 2assert "Tower" in rep.findings[0].message and "0.5 m" in rep.findings[0].fix_hint- # one camera, one gate (audit 2026-09-24 N11): the build's scene_probe used to judge the first- # camera again (WARN at 0.3 m / 85 % dark) beside these ERRORs (0.5 m / 35 %) in the same round+ # one camera, one gate (audit 2026-09-24 N11): the scene_probe must not judge the first camera againfrom codeverse3d.spatial.probes import probe_reportcam0 = _chk("Buried", camera_in_geometry=True, inside_mesh_bbox=["Tower"], nearest_hit_m=0.1, dark_frac=0.9)@@ -108,9 +107,7 @@ def test_content_small_roles():def test_no_hint_prescribes_one_camera_or_light_construction():- """2026-10-15 (owner's rule): a fix hint states the measured requirement and leaves the construction- open. The old hints were the diorama shot — stand at 1.2x the content span, 6-20 m up, lookAt the- bounds centre, fill the bounds — and the library's rig as THE light; every refine round read them."""+ """2026-10-15 (owner's rule): a fix hint states the measured requirement, never a camera or light construction."""rep = frame_findings(_metrics(_chk("Establishing", content_frac=0.12, sky_frac=0.5, ground_frac=0.38),_chk("Ant", eye_height_m=3.2, ground_below_m=0.06, ground_below_name="SnowTerrain"),@@ -204,19 +201,6 @@ def test_a_hero_in_the_scene_but_in_no_authored_frame_is_an_error():assert fine.passed and old.passed and not [k for k, _, _ in _kinds(fine) + _kinds(old) if k.startswith("hero_")]-def test_auto_exposure_lifts_a_frame_past_the_gates_dark_line():- """Regression (audit 2026-09-24 N13): the host's auto-exposure stopped at mean 0.10 while the- gate calls < 0.12 "frame too dark", so a lifted frame still drew the ERROR. Pinned by value."""- import re-- from codeverse3d.spatial.frame_metrics import DARK_MEAN_LUM- from codeverse3d.spatial.node import runtime_js_dir-- host = (runtime_js_dir() / "lib" / "scene_host.mjs").read_text()- lo = float(re.search(r"const EXPOSURE_BAND = \[([\d.]+),", host).group(1))- assert lo == DARK_MEAN_LUM--def test_a_blender_payload_gets_bpy_fix_hints_and_three_js_keeps_its_own():"""The thresholds are one; the words are the language's (``metrics["language"]``)."""from codeverse3d.spatial.frame_metrics import HINTS@@ -262,8 +246,7 @@ def test_a_slow_blender_frame_set_warns_and_names_the_heaviest_zone():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."""+ """2026-10-14: glb size_m is ONE placed instance (a 2.2 m sofa x3 read "6.5 m across"); the text names the 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})]})diff --git a/harness/tests/scene_gates/test_frame_motion.py b/harness/tests/scene_gates/test_frame_motion.pyindex bd6d6ef8..bd9905e6 100644--- a/harness/tests/scene_gates/test_frame_motion.py+++ b/harness/tests/scene_gates/test_frame_motion.py@@ -1,10 +1,4 @@-"""Measured inter-frame motion (``spatial.frame_motion``) and its ``scene_frames`` finding.--Why this exists: on the scenes_v1 battery the judge answered `nothing_moves` = true on-four rounds whose water and foliage were in fact animating (0.7–4.7 % of pixels changed) —-the two times reach it as tiles in different montage images. The harness measures the-change instead, so the numbers here are the thing the judge is told to trust.-"""+"""Measured inter-frame motion and its scene_frames finding (the judge misread animated scenes as `nothing_moves`)."""from __future__ import annotationsdiff --git a/harness/tests/scene_gates/test_live_frames.py b/harness/tests/scene_gates/test_live_frames.pyindex f6ee8315..451f84cb 100644--- a/harness/tests/scene_gates/test_live_frames.py+++ b/harness/tests/scene_gates/test_live_frames.py@@ -1,8 +1,4 @@-"""Browser-backed: render_scene → camera_checks coverage, judge subset sheet, scene_frames gate.--The example starter scene must pass; a crushed-dark variant of it must raise-``dark_frame`` ERRORs with the lighting hint.-"""+"""Browser-backed: render_scene → camera_checks, judge subset sheet, scene_frames gate (starter passes, dark variant fails)."""from __future__ import annotations@@ -30,13 +26,10 @@ pytestmark = [pytest.mark.node, needs_browser]def _darken(ws: Workspace) -> None:env = ws.src / "env.js"text = env.read_text()- # the starter lights through lib/environment.js sunRig (2026-09-07): crush the rig's sun and- # fill AFTER it is built (its `fill` option is clamped UP to a readability floor) and drop- # the env map, which lights metals and glass on its own+ # crush the sunRig's sun and fill AFTER it is built (its `fill` is clamped up) and drop the env maptext = text.replace(" scene.environment = rig.envTex;"," scene.environment = null; sun.intensity = 0.05; hemi.intensity = 0.02; hemi.color.set(0x101018); hemi.groundColor.set(0x000000);")- # the placeholder starter's sky is its fog colour (D106: no world shell): black both out, or- # half the frame stays bright sky+ # the starter's sky is its fog colour (D106): black both outtext = text.replace("scene.fog = new THREE.Fog(0xbfc6cc,", "scene.fog = new THREE.Fog(0x000000,")text = text.replace("scene.background = new THREE.Color(scene.fog.color)", "scene.background = new THREE.Color(0x000000)")assert "0.05" in text and text.count("0x000000") >= 3@@ -44,8 +37,7 @@ def _darken(ws: Workspace) -> None:def test_example_scene_passes_frame_gate_and_judge_subset(starter_ws: Workspace):- """Also: plan bounds guard the orbit framing — bounds that contain everything (this run) change- nothing; a zone that sprawls far past tight bounds is dropped in favour of the zones inside them."""+ """Also: plan bounds guard the orbit framing (a zone sprawling past tight bounds is dropped)."""out = starter_ws.renders_dir(0)rs = render_scene(starter_ws, out, times=(0.0, 1.5), width=640, height=360, fps_seconds=0.3,bounds=BBox(center=(0, 3, 0), extents=(90.0, 10, 90.0)))@@ -75,9 +67,7 @@ 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 4 overview-rig tiles (scene: 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+ # 3 authored + 4 overview tiles at t=0, first two authored at t=1.5; the eye rig never reaches the judgeassert len(stamped) == 9 <= JUDGE_MAX_VIEWSassert not any(n.startswith("eye_") for n, _ in stamped)assert stamped == {(v.name, v.time_s) for v in select_judge_views(rs).views}diff --git a/harness/tests/scene_gates/test_live_hero_in_frame.py b/harness/tests/scene_gates/test_live_hero_in_frame.pyindex 79c47693..1531b031 100644--- a/harness/tests/scene_gates/test_live_hero_in_frame.py+++ b/harness/tests/scene_gates/test_live_hero_in_frame.py@@ -1,8 +1,4 @@-"""Browser-backed: a Blender hero (GLB) in the scene but in no authored frame is an ERROR.--``glbCoverage`` renders each loaded GLB as a white mask against black solids (occlusion included)-per camera; the gate reads ``camera_checks[].glb_frac``.-"""+"""Browser-backed: a hero GLB in the scene but in no authored frame is an ERROR (gate reads camera_checks[].glb_frac)."""from __future__ import annotations@@ -21,21 +17,18 @@ pytestmark = [pytest.mark.node, needs_browser]URL = "/assets/hero_cube.glb"-# the hero hangs at (10, 6, 14): on the overview camera's sightline ((26, 14, 34) → (0, 1.5, 0)) and-# outside the pond and windmill shots' frusta; the wall stands halfway between the overview and it+# the hero (10, 6, 14) is on the overview sightline and outside the other shots; the wall stands betweenWALL = """const wall = new THREE.Mesh(new THREE.BoxGeometry(30, 16, 0.5), new THREE.MeshStandardMaterial({ color: 0x888888 }));wall.name = 'StoneWall'; wall.position.set(18, 10, 24); wall.rotation.y = Math.atan2(16, 20); scene.add(wall);"""-ROOM = """const shell = roomShell({ center: [10, 4, 14], extents: [12, 8, 12], thickness: 0.3 });scene.add(shell);"""--# a camera NAMED for the hero, aimed 90 degrees away from it (loop 25's LanternDetail at the tower wall)+# a camera NAMED for the hero, aimed 90 degrees away from it (loop 25's LanternDetail)AWAY_CAMERA = " { name: 'HeroCubeDetail', position: [10, 8, 30], lookAt: [40, 6, 30], fov: 45 },\n"diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.pyindex 786770f0..54d49698 100644--- a/harness/tests/scene_gates/test_placement.py+++ b/harness/tests/scene_gates/test_placement.py@@ -46,8 +46,7 @@ def _by_kind(report, kind):def test_floating_severity_by_gap_then_by_count():- """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."""+ """Strict since 2026-10-14: a hover past 0.08 m is an ERROR, under it a WARN; more than 2 hovers make all ERRORs."""p = get_settings().placementassert (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")))@@ -67,8 +66,7 @@ def test_floating_severity_by_gap_then_by_count():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."""+ """An A/B child's C3D_PLACEMENT__* judges its rounds (read at call time); explicit thresholds= wins."""t = _table(_row("Lantern", gap=0.3))assert _by_kind(placement_findings(t), "floating")[0].severity == Severity.ERRORswitch("C3D_PLACEMENT__FLOATING_ERROR_M", "0.5")@@ -82,8 +80,7 @@ def test_thresholds_are_read_from_settings_when_the_gate_runs(switch):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)."""+ """The probe's OVERLAP_MIN_FRAC and the gate's overlap_warn are one number (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 jsassert Placement().overlap_warn == 0.10 and Placement().overlap_error == 0.35@@ -95,8 +92,7 @@ def test_the_probe_s_overlap_floor_is_the_default_warn_level():_row("GardenStairways", sunk=1.3, into="Terrain", h=2.0), # slope-ok: sunk uphill by construction])def test_the_gate_accepts_what_the_settle_leaves(row):- """Audit 2026-09-24 N27: the settle left these (placement_words.json + the touching rule) and the- gate then reported them every round. One file now says what is seated."""+ """Audit 2026-09-24 N27: what the settle leaves seated is not reported by the gate."""r = placement_findings(_table(row))assert [f for f in r.findings if f.severity != Severity.INFO] == []@@ -110,8 +106,7 @@ 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."""+ """Strict 2026-10-14: sunk 0.10 m WARN; 0.20 m AND 20 % of the height ERROR; name words exempt."""r = placement_findings(_table(_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@@ -263,21 +258,14 @@ def test_a_wrapper_of_instances_is_scale_checked_as_one_instance():assert scale[0].fix_hint.startswith("scale each picket_fence")-def test_the_typed_interior_flag_wins_over_the_setting_words():- from codeverse3d.spatial.scene_placement import is_interior-- assert is_interior({"setting": "a mountain meadow at dawn", "interior": True})- assert not is_interior({"setting": "a mountain meadow at dawn", "interior": False})- assert is_interior({"setting": "a cosy cabin interior at dusk"}) # no flag: the words decide- assert is_interior(_contract_plan().model_copy(update={"interior": True}))- assert is_interior({"setting": "a cosy cabin interior at dusk", "interior": None}) # None = no flag--def test_an_outdoor_flag_is_not_overruled_by_indoor_sounding_words():- """D112, argon loop iteration 5: a zone named GiantTrunkCorridor and a luminance band "inside- 0.42-0.62" put two outdoor plans on the 2 cm indoor tolerance."""+ """D112 (iteration 5): indoor-sounding words in an outdoor plan must not put it on the 2 cm tolerance;+ the typed flag wins over the setting words."""from codeverse3d.spatial.scene_placement import infer_indoor, is_interior+ assert is_interior({"setting": "a mountain meadow at dawn", "interior": True})+ assert is_interior({"setting": "a cosy cabin interior at dusk"}) and is_interior({"setting": "a cosy cabin interior at dusk", "interior": None})+ assert is_interior(_contract_plan().model_copy(update={"interior": True}))redwoods = {"setting": "coastal redwood forest at dawn", "interior": False,"environment": "fog drifts down the GiantTrunkCorridor between the trunks"}canyon = {"setting": "desert slot canyon at noon", "interior": False,@@ -335,9 +323,7 @@ def test_interpenetration_bands_are_the_strict_ones():def test_the_layout_budget_is_a_note_not_a_gate():- """2026-10-15 (owner's rule): the L2 layout's prop / ground-cover counts were never the brief's, so a- zone under them is an INFO line (``density_note``), never the ``underdressed`` ERROR that enforced the- planner's dressing bands as a requirement. The counts a brief states are acceptance items."""+ """2026-10-15 (owner's rule): a zone under the layout's prop counts is an INFO density_note, never an ERROR."""layouts = {"Yard": {"placements": [{"asset": "Lantern", "count": 6}],"mid_props": 20, "small_props": 40, "ground_cover": 400},"House": {"placements": [], "mid_props": 2}}@@ -357,9 +343,7 @@ def test_the_layout_budget_is_a_note_not_a_gate():def test_world_edge_is_a_warn_note_outdoors_and_quiet_when_the_place_continues_or_indoors():- """Until 2026-10-15 this was the ``no_backdrop`` ERROR whose hint prescribed a silhouette ring of- 24-40 pieces. The measurement stands (something >= 2 m tall past 1.25x the half-extent); the finding- is a WARN that states the requirement, and neither its name nor its hint names a ring."""+ """2026-10-15: the no_backdrop ERROR became a WARN stating the requirement; the hint prescribes no ring."""base = {"fog": {"type": "Fog"}, "background": "#aabbcc","placement": _table(_row("Lantern_3", h=0.6), _row("Bench", h=0.9),_row("BenchB", zone="House", h=0.9))}@@ -437,9 +421,7 @@ def test_blender_census_gets_bpy_words_in_placement_hints():# --------------------------------------------------------------------- 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."""+ """w1_tearoom tagged 17 of 36 'free': the tagged share is a WARN past 25 % and an ERROR past 50 % (min two tagged)."""p = get_settings().placementassert (p.free_exempt_warn, p.free_exempt_error) == (0.25, 0.5)stood = [_row(f"Bench{i}") for i in range(6)]@@ -464,9 +446,7 @@ def test_free_exempt_share_is_one_finding_naming_the_tagged_assets():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."""+ """Seated at one of four columns, hanging at the others: a WARN, with the quiet cases listed below."""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")@@ -525,10 +505,7 @@ def test_the_summary_records_the_thresholds_and_the_probe_s():def test_a_zone_past_a_truncated_tables_cut_is_unmeasured_not_empty():- """D111: argon loop iteration 4, r1_01 — an envelope of 337 meshes filled the 400-row table and the- last zone in the scene, built and visibly present, read "placed nothing". A table cut by its ROW CAP- with the zone's built group in the census gives an INFO note and no ``zone_empty`` ERROR; the zone AT- the cut (the last row's) gets an INFO for what may lie past it, not ``missing_content``."""+ """D111 (iteration 4, r1_01): a row-capped table leaves the last built zone INFO-unmeasured, never zone_empty."""table = _table(_row("Lantern"), _row("Bench"), total=9, truncated=True)census = {"groups": [{"name": "Yard", "kind": "content"}, {"name": "House", "kind": "content"}], "placement": table}kinds = {(f.data.get("kind"), f.target, f.severity) for f in placement_gate_safe(census, plan=_contract_plan()).findings}@@ -559,9 +536,7 @@ def test_the_zone_at_a_truncated_tables_cut_is_partly_measured():def test_a_floating_row_states_its_gap_to_the_millimetre_and_the_tolerance_applied():- """D112, iteration 5 r1_07: "floating 0.05 m" for a 0.048 m gap in a scene the prompt calls- outdoors (tolerance 0.05 m) read as a contradiction; the refine session paged the raw probe dump- for 15 minutes to resolve it and was killed before writing."""+ """D112 (iteration 5 r1_07): "floating 0.05 m" for a 0.048 m outdoor gap read as a contradiction; state gap and tolerance."""rows = [_row(f"Boulder{i}", gap=g) for i, g in enumerate((0.048, 0.046, 0.041))]indoor = _by_kind(placement_findings(_table(*rows), indoor=True), "floating")assert [f.severity for f in indoor] == [Severity.ERROR] * 3diff --git a/harness/tests/scene_prompts/test_bpy_templates.py b/harness/tests/scene_prompts/test_bpy_templates.pydeleted file mode 100644index 48ee86e2..00000000--- a/harness/tests/scene_prompts/test_bpy_templates.py+++ /dev/null@@ -1,59 +0,0 @@-"""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="", 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_and_zone_but_not_the_asset_sheet_or_the_refine() -> None:- """A bpy asset session gets the rows its sheet names (``library_rows``), never the whole catalog;- a refine session edits one file with src/lib in the workspace and the skills routed, so it carries- none either — 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"):- assert "effects_catalog" in (tpl / name).read_text(), name- assert "effects_catalog" not in (tpl / "scene_refine_bpy.j2").read_text()- asset = (tpl / "scene_asset_bpy.j2").read_text()- assert "effects_catalog" not in asset and "library_rows" in asset and "asset_contract" 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 "This is an INTERIOR" 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 "INTERIOR" not in env_out and "GLASS HOUSE" not in env_out- # the zone brief names env.py as the enclosure's owner only for an interior (the wording is the prompt's;- # the ownership is the contract: the wrapper builds env first, zones link into their own collection)- zone_in = render("tracks/scene_zone_bpy.j2", **BASE, interior=True)- zone_out = render("tracks/scene_zone_bpy.j2", **BASE, interior=False)- assert "INTERIOR" in zone_in and "`env.py`'s" in zone_in- assert "INTERIOR" not in zone_outdiff --git a/harness/tests/scene_prompts/test_prompt_assembler_contract.py b/harness/tests/scene_prompts/test_prompt_assembler_contract.pydeleted file mode 100644index 3969f32c..00000000--- a/harness/tests/scene_prompts/test_prompt_assembler_contract.py+++ /dev/null@@ -1,27 +0,0 @@-"""The scene prompts teach the hooks the generated src/scene.js actually calls (the `nothing_moves` defect)."""--from __future__ import annotations--from codeverse3d.contracts.plan import CameraPlan-from codeverse3d.languages.scene_threejs import render_scene_js-from codeverse3d.prompts import load_text---def test_the_prompts_teach_the_hooks_the_assembler_calls() -> None:- """Guard the four call sites the prompts promise (if the assembler changes, the prompts must)."""- cams = [CameraPlan(name="Establishing", position=(1.0, 2.0, 3.0), look_at=(0.0, 1.0, 0.0), fov=44.0)]- generated = render_scene_js(["pond_basin"], cams, [], env_ok=True)- assert "import { build as buildPondBasin } from './zones/pond_basin.js';" in generated- assert "const env = (await buildEnv(ctx)) || {};" in generated- assert "if (env.update) env.update(t, dt);" in generated- assert "for (const z of zones) if (z.userData.update) z.userData.update(t, dt);" in generated- assert "tickEnv" not in generated and "userData.tick" not in generated-- zone_prompt, env_prompt = load_text("tracks/scene_zone.j2"), load_text("tracks/scene_env.j2")- assert "export function build(ctx)" in zone_prompt and "userData.update" in zone_prompt- # the historical bug: `userData.tick`, a hook nothing calls, may appear only as a warning- assert all("never called" in ln for ln in zone_prompt.splitlines() if "userData.tick" in ln)- assert "buildEnv(ctx)" in env_prompt and "buildEnv(THREE, scene)" not in env_prompt- assert "update(t, dt)" in env_prompt and "tickEnv" in env_prompt and "NEVER called" in env_prompt- asset = load_text("tracks/scene_asset.j2")- assert "group.userData.update" in asset and "`userData.tick` is never called" in assetdiff --git a/harness/tests/scene_prompts/test_quality_teaching.py b/harness/tests/scene_prompts/test_quality_teaching.pyindex e531dc0a..db58bc6f 100644--- a/harness/tests/scene_prompts/test_quality_teaching.py+++ b/harness/tests/scene_prompts/test_quality_teaching.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport pytestfrom codeverse3d.judges.rubrics import load_rubric-from codeverse3d.prompts import load_textCOMPOSITION_DEFECTS = ("flat_ground", "monotonous_vegetation", "empty_midground","undressed_scene", "thin_atmosphere")@@ -19,36 +18,15 @@ def test_scene_rubric_craft_defects_inform_and_cannot_zero_a_scene() -> None:assert 0.0 < d.penalty <= 0.05 and d.cap is None, did# the five craft items together take at most 0.20: they inform, they cannot sink a sceneassert sum(r.defect(did).penalty for did in COMPOSITION_DEFECTS) == pytest.approx(0.18)- # scene (2026-10-14): the whole checklist sums past 1.0 (was 0.60 under v1's 0.62 bound). The- # weight 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.- # The exact figure is tests/judges/test_scene_judge.py's (the judge lane adds items such as- # diorama_look, 2026-10-15); this test keeps the invariant.+ # the whole checklist sums past 1.0: a scene with EVERY item present scores zero (exact figure: tests/judges/test_scene_judge.py)total = sum(d.penalty for d in r.defects)assert 1.0 <= total <= 1.10, total-def test_no_scene_stage_inlines_cookbook_recipes() -> None:- """Owner, 2026-10-15: the same four ENV and six ZONE cookbook chapters used to be inlined into- every env / zone / refine session whatever the brief ("copy these numbers and snippets"), and- the 60 iteration-0 scenes executed them verbatim. The track has no recipe tables, no recipe- inliner and passes no ``recipes`` variable; the scene templates render without one."""- import inspect-- from codeverse3d.tracks import prompting, scene-- for gone in ("ENV_RECIPES", "ZONE_RECIPES", "ZONE_RECIPES_MAX_CHARS", "refine_recipes"):- assert not hasattr(scene, gone), gone- for gone in ("cookbook_sections", "select_cookbook_chapters", "COOKBOOK_SYNONYMS", "COOKBOOK_ALWAYS", "is_always_chapter"):- assert not hasattr(prompting, gone), gone # D106, then D107: no chapter picker on any track- assert "recipes=" not in inspect.getsource(scene)def test_the_env_and_zone_briefs_hand_the_enclosure_to_env_for_an_interior() -> None:- """Six interior runs were "not enclosed": the env brief owns the walls only when the plan says interior."""+ """Regression: six interior runs were "not enclosed"; env owns the walls only when the plan says interior."""from codeverse3d.prompts import renderbase = dict(title="t", spec_prompt="p", setting="s", mood="m", bounds="b", environment="e", frame_doc="", contract="",@@ -59,32 +37,22 @@ def test_the_env_and_zone_briefs_hand_the_enclosure_to_env_for_an_interior() ->env_out = render("tracks/scene_env.j2", **base, interior=False, glazed=False)assert "This is an INTERIOR" in env_in and "roomShell" in env_in and "openings" in env_inassert "INTERIOR" not in env_out- # the zone brief names env.js as the enclosure's owner only for an interior (the wording is the prompt's;- # the ownership is the contract: createScene builds env first, zones return their own group)zone_in = render("tracks/scene_zone.j2", **base, interior=True)zone_out = render("tracks/scene_zone.j2", **base, interior=False)assert "INTERIOR" in zone_in and "`env.js`'s" in zone_inassert "INTERIOR" not in zone_out-def test_the_practical_light_numbers_live_in_the_lib_and_no_prompt_restates_them() -> None:- """Audit N41: one scene session read PointLight 0.5–2 (system prompt, skill) and 6–14 with- 10–16 lights (same skill), emissive 1.5–4 / ≤ 3 / 2–6, and a night rig of "moon ≤ 0.2, no- HemisphereLight" that sunRig never builds. `PRACTICAL` in environment.js owns the numbers- (the cookbook that once restated them is gone, 2026-10-15); every text points there."""- import re-- from codeverse3d.languages.scene_threejs import lib_files- from codeverse3d.skills import skills_dir-- env = next(p for p in lib_files() if p.name == "environment.js").read_text(encoding="utf-8")- body = re.search(r"export const PRACTICAL = Object\.freeze\(\{([^}]*)\}\)", env)- assert body, "environment.js no longer exports PRACTICAL"- practical = {k: float(v) for k, v in re.findall(r"(\w+): ([\d.]+)", body.group(1))}- assert {"emissiveIntensity", "intensity", "distance", "decay"} <= set(practical)- others = {"system": load_text("scene_threejs/system.md"), "contract": load_text("scene_threejs/contract.md"),- "lighting": (skills_dir() / "c3d-scene-lighting" / "SKILL.md").read_text(encoding="utf-8"),- "materials": (skills_dir() / "c3d-scene-materials" / "SKILL.md").read_text(encoding="utf-8")}- restated = re.compile(r"PointLight\W{0,4}\(?\*{0,2}\d|`intensity` \d|emissive\w*`?\W{0,4}\*{0,2}\d|<= 0\.2|"- r"HemisphereLight` \d")- assert not {k: restated.findall(v) for k, v in others.items() if restated.search(v)}+++def test_the_bpy_env_brief_owns_the_enclosure_only_for_an_interior() -> None:+ from codeverse3d.prompts import 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="", 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="")+ assert "INTERIOR" in render("tracks/scene_env_bpy.j2", **base, interior=True, glazed=False)+ assert "GLASS HOUSE" in render("tracks/scene_env_bpy.j2", **base, interior=True, glazed=True)+ assert "INTERIOR" not in render("tracks/scene_env_bpy.j2", **base, interior=False, glazed=False)diff --git a/harness/tests/scene_runtime/__init__.py b/harness/tests/scene_runtime/__init__.pyindex e69de29b..8b137891 100644--- a/harness/tests/scene_runtime/__init__.py+++ b/harness/tests/scene_runtime/__init__.py@@ -0,0 +1 @@+diff --git a/harness/tests/scene_runtime/blender_scene_fixture.py b/harness/tests/scene_runtime/blender_scene_fixture.pyindex 2aad1ade..e9e341fe 100644--- a/harness/tests/scene_runtime/blender_scene_fixture.py+++ b/harness/tests/scene_runtime/blender_scene_fixture.py@@ -1,15 +1,4 @@-"""A small built ``scene_blender``-shaped workspace for the Blender render tests (lane B).--Until the language's build wrapper exists this stands in for its outputs: ``artifacts/scene.blend``-(ground, a tower, a sphere that moves between t = 0 and t = 1.5 — or does not — a sun, two-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.-"""+"""A small built ``scene_blender``-shaped workspace for the Blender render tests (lane B)."""from __future__ import annotations@@ -102,8 +91,7 @@ def _with_scene_extras(glb: bytes, extras: dict) -> bytes:def build_fixture(ws: Workspace, *, moving: bool = True, probe: bool = True) -> Workspace:- """Write the fixture into ``ws``: the .blend, its census GLB (cameras in the extras) and, with- ``probe``, census.json from the JS probe of that GLB — the path ``SceneBlenderRuntime`` takes."""+ """Write the fixture into ``ws``."""ws.artifacts.mkdir(parents=True, exist_ok=True)script = ws.root / "build_fixture.py"script.write_text(BUILD_BPY)@@ -171,52 +159,3 @@ def build_room_shell(root: Path) -> Path:def blender_available() -> bool:b = get_settings().resolve_blender()return bool(b) and Path(b).exists()---#: a red cube under a 20 m volume-only fog box (density 0.5 /m: opaque) and a 1 m volume puff beside it-FOG_BOX_BPY = """-import sys-import bpy-blend = sys.argv[sys.argv.index("--") + 1]-bpy.ops.wm.read_factory_settings(use_empty=True)-scene = bpy.context.scene-def volume_mat(name, density):- m = bpy.data.materials.new(name)- nodes, links = m.node_tree.nodes, m.node_tree.links- for n in [n for n in nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"]:- nodes.remove(n)- v = nodes.new("ShaderNodeVolumePrincipled")- v.inputs["Density"].default_value = density- links.new(v.outputs["Volume"], nodes["Material Output"].inputs["Volume"])- return m-def cube(name, size, loc, mat):- bpy.ops.mesh.primitive_cube_add(size=size, location=loc)- ob = bpy.context.object- ob.name = name- ob.data.materials.append(mat)- return ob-red = bpy.data.materials.new("Red")-red.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.8, 0.05, 0.05, 1.0)-cube("Crate", 2.0, (0.0, 0.0, 1.0), red)-cube("SiteHaze", 20.0, (0.0, 0.0, 0.0), volume_mat("HazeFog", 0.5))-cube("SteamPuff", 1.0, (3.0, 0.0, 1.0), volume_mat("SteamVol", 0.5))-w = bpy.data.worlds.new("W")-scene.world = w-w.node_tree.nodes["Background"].inputs[1].default_value = 1.0-bpy.ops.object.light_add(type="SUN", location=(0.0, 0.0, 30.0))-bpy.context.object.data.energy = 3.0-bpy.ops.wm.save_as_mainfile(filepath=blend)-"""---def build_fog_box(root: Path) -> Path:- """Write ``root/scene.blend``: a red crate inside an opaque 20 m fog box, a 1 m volume puff beside it."""- root.mkdir(parents=True, exist_ok=True)- script = root / "build_fog_box.py"- script.write_text(FOG_BOX_BPY)- blend = root / "scene.blend"- blender = get_settings().resolve_blender()- proc = run_subprocess([blender, "-b", "--factory-startup", "--python", str(script), "--", str(blend)],- cwd=root, env=blender_env(), timeout_s=120)- assert proc.returncode == 0 and blend.is_file(), proc.stderr[-2000:]- return blenddiff --git a/harness/tests/scene_runtime/glb_fixture.py b/harness/tests/scene_runtime/glb_fixture.pyindex 633a7254..7131bc8c 100644--- a/harness/tests/scene_runtime/glb_fixture.py+++ b/harness/tests/scene_runtime/glb_fixture.py@@ -8,8 +8,7 @@ from pathlib import Pathdef write_box_glb(path: Path, size: tuple[float, float, float] = (2.0, 2.0, 2.0), name: str = "HeroCube") -> Path:- """Write a GLB holding one box mesh (8 vertices, 12 triangles, no normals — the loader's- consumer computes them) centred on the origin. Returns ``path``."""+ """Write a GLB holding one box mesh (8 vertices, 12 triangles, no normals — the loader's consumer computes them) centred on the origin."""sx, sy, sz = (s / 2 for s in size)verts = [(-sx, -sy, -sz), (sx, -sy, -sz), (sx, sy, -sz), (-sx, sy, -sz),(-sx, -sy, sz), (sx, -sy, sz), (sx, sy, sz), (-sx, sy, sz)]diff --git a/harness/tests/scene_runtime/lib/_probe.py b/harness/tests/scene_runtime/lib/_probe.pyindex 80d1dcf2..fca893ca 100644--- a/harness/tests/scene_runtime/lib/_probe.py+++ b/harness/tests/scene_runtime/lib/_probe.py@@ -1,14 +1,4 @@-"""Node probes for the shipped effect library (``starter/src/lib``).--A probe is an ES module run under OUR resolve hook (``runtime_js/lib/resolve_three.mjs``-maps ``three`` / ``three/addons/*`` to the harness's own install), in a private temp-dir holding a copy of the library — never a live workspace. ``measure`` returns the-LAST stdout line of the probe as JSON; ``compile_scene`` compiles every program a-fixture scene builds through ``runtime_js/check_shaders.mjs`` (headless GPU).--The readers the patch tests share live here too: ``SHADER_JS`` (the two hooks-patchStandard injects into, and ``compile``), ``_find`` and ``_main_body``.-"""+"""Node probes for the shipped effect library (``starter/src/lib``)."""from __future__ import annotationsimport json@@ -69,8 +59,7 @@ def _stage(root: Path, libs: tuple[str, ...]) -> None:def measure(script: str, libs: tuple[str, ...] = (), *, timeout_s: float = 120.0) -> dict:- """Run ``script`` (an ES module; ``import ... from './lib/x.js'``) and parse its- last stdout line as JSON. The script is responsible for ``console.log(JSON...)``."""+ """Run ``script`` (an ES module."""_three_ready()with tempfile.TemporaryDirectory(prefix="c3d-libprobe-") as tmp:root = Path(tmp)@@ -88,27 +77,7 @@ def compile_scene(scene_src: str, libs: tuple[str, ...] = (), *,audit_module: str | None = None,report: Path | None = None,timeout_s: float = 180.0) -> tuple[int, str]:- """Compile every program a fixture SCENE builds, on the headless GPU.-- ``scene_src`` is a workspace ``src/scene.js``: it must export- ``createScene({THREE, renderer, loaders})`` returning- ``{scene, cameras, update}`` with at least one camera, because- ``check_shaders.mjs`` boots the workspace through ``openHost`` before it- force-compiles. ``extra`` writes further files under ``src/`` (a fixture- the scene imports). Returns (exit_code, combined output); 0 == every- program compiled, and the LAST line of the output is the JSON report.-- ``audit_module`` scopes the STATIC audit to one staged file (the compile- stage still covers everything). Use it when a fixture of your own calls- ``patchStandard``: the audit's per-file rule cannot see that shader.js- declares and binds ``uTime`` at assembly time, so it reports an- undeclared/unbound pair on GLSL that is correct. ``src/lib/`` is already- exempt for that reason (``shader_report.mjs``); a fixture is not.-- ``report`` also writes the WHOLE JSON report to that path: the output- returned is cut to its last 4000 characters, and a scene with many- programs can overrun that before its report line even starts.- """+ """Compile every program a fixture SCENE builds, on the headless GPU."""_three_ready()with tempfile.TemporaryDirectory(prefix="c3d-compile-scene-") as tmp:root = Path(tmp)diff --git a/harness/tests/scene_runtime/lib/test_accumulation.py b/harness/tests/scene_runtime/lib/test_accumulation.pydeleted file mode 100644index 347844d1..00000000--- a/harness/tests/scene_runtime/lib/test_accumulation.py+++ /dev/null@@ -1,57 +0,0 @@-"""accumulation.js — regression: the lip under a cover's edge darkened walls that carried no deposit at all."""-from __future__ import annotations--import pytest-from _probe import SHADER_JS, _find, _main_body, measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "accumulation.js")---_PRELUDE = SHADER_JS + """-import * as THREE from 'three';-import { patchSnow, patchSand } from './lib/accumulation.js';--const std = (o = {}) => new THREE.MeshStandardMaterial(- Object.assign({ color: 0x8b8478, roughness: 0.7 }, o));-"""---def _probe(body: str) -> dict:- return measure(_PRELUDE + body, _LIBS)---def test_the_cover_shades_only_the_material_it_actually_stops_against():- """The reference took a fixed 0.55 below the coverage threshold, which falls- under 0.55 past a dusting — so zero deposit sat inside the ramp and every bare- wall came back up to 21% darker. The band is a FRACTION of the threshold."""- out = _probe("""-const m = std();-patchSnow(m, { depth: 0.05 });-patchSand(m, { amount: 0.5 });-const s = compile(m);-console.log(JSON.stringify({ fs: s.fragmentShader, vs: s.vertexShader }));-""")- body = _main_body(out["fs"])- for pre in ("sn", "sd"):- lip = _find(rf"float {pre}Lip = \(1\.0 - {pre}K\)"- rf" \* smoothstep\({pre}T \* ([\d.]+),"- rf" {pre}T - ([\d.]+),\s*{pre}D\);", body)- frac_, top = float(lip.group(1)), float(lip.group(2))- assert 0 < frac_ < 1, f"{pre}Lip's floor must scale with {pre}T"- assert frac_ * 0.18 > 0 and top < 0.18, (- f"{pre}Lip's band must stay inside the smallest threshold")- _find(rf"diffuseColor\.rgb \*= 1\.0 - ([\d.]+) \* {pre}Lip;", body)- # No fixed offset anywhere: that is the shape of the bug.- assert "smoothstep(snT - 0.55" not in body- assert "smoothstep(sdT - 0.55" not in body- # Thin snow lets the substrate through; deep snow does not.- thin = _find(r"float snThin = mix\(([\d.]+), 1\.0,"- r" smoothstep\([\d.]+, [\d.]+, snD\)\);", body)- assert 0 < float(thin.group(1)) < 1- _find(r"float snAmt = clamp\(snK \* snThin", body)- # Nothing is displaced, and the vertex stage does no work beyond the world- # position: the base is the whole of it.- vbody = _main_body(out["vs"])- assert "transformed +=" not in vbody and "transformed *=" not in vbodydiff --git a/harness/tests/scene_runtime/lib/test_atmosphere.py b/harness/tests/scene_runtime/lib/test_atmosphere.pydeleted file mode 100644index 0689025b..00000000--- a/harness/tests/scene_runtime/lib/test_atmosphere.py+++ /dev/null@@ -1,54 +0,0 @@-"""atmosphere.js — regression: the fog bank was a baked daylight white, a slab of milk-on a night rig."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node---def test_the_bank_takes_its_colour_from_the_scene_it_stands_in():- """At 0xdce9f2 the bank rendered the ground under it (69,66,64) against a- (26,36,64) night sky. Its colour is the scene's own air: the graded sky- `sunRig` bakes into `scene.environment`; an explicit `color` still wins."""- out = measure("""-import * as THREE from 'three';-import { makeHeightFog } from './lib/atmosphere.js';-import { sunRig } from './lib/environment.js';-const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;-const color = (elevation, fogHex, o = {}) => {- const s = new THREE.Scene();- const rig = sunRig({ azimuth: 215, elevation });- s.add(rig.sun, rig.fill);- s.environment = rig.envTex;- s.fog = new THREE.FogExp2(fogHex, 0.0035);- return makeHeightFog(Object.assign({ scene: s, height: 2.2 }, o)).children[0].material.uniforms.uColor.value;-};-const day = color(38, 0xcfd8e6), night = color(-20, 0x0b0f1a);-console.log(JSON.stringify({- day: lum(day), night: lum(night), fog: lum(new THREE.Color(0x0b0f1a)),- nightRB: night.r / night.b, forced: color(-20, 0x0b0f1a, { color: 0xff0000 }).toArray(),-}));-""", ("atmosphere.js", "environment.js", "sky.js"))- assert out["day"] > 0.5 and 0.02 < out["night"] < 0.08, out- assert out["night"] > out["fog"] * 4 and out["nightRB"] < 0.75, out # lit, and blue- assert out["forced"][0] > 0.9 and out["forced"][2] < 0.05, out--[email protected]("fog, end", [- ("new THREE.FogExp2(0xdbe3ea, 0.0018)", 1 / 0.0018),- # the linear Fog contract.md and the cookbook teach: the ramp once ran on to 600 m,- # four times past the fog wall, where no hue shift can be seen- ("new THREE.Fog(0x9fc4e8, 40, 140)", 140),- ("null", 1 / 0.0018), # no fog: the day mood's e-fold-])-def test_the_aerial_ramp_ends_where_the_scene_fog_closes(fog, end):- out = measure(f"""-import * as THREE from 'three';-import {{ patchAerialPerspective }} from './lib/atmosphere.js';-const scene = new THREE.Scene(); scene.fog = {fog};-const m = patchAerialPerspective(new THREE.MeshStandardMaterial(), {{ scene }});-console.log(JSON.stringify({{ end: m.userData.uniforms.uAerialEnd.value }}));-""", ("atmosphere.js", "environment.js", "sky.js"))- assert out["end"] == pytest.approx(end)diff --git a/harness/tests/scene_runtime/lib/test_building.py b/harness/tests/scene_runtime/lib/test_building.pyindex cf059a06..36ec1d92 100644--- a/harness/tests/scene_runtime/lib/test_building.py+++ b/harness/tests/scene_runtime/lib/test_building.py@@ -32,31 +32,6 @@ function firstHit(root, from, dir) {.intersectObjects(meshes, true);return hit.length ? hit[0].object.name : null;}--/** Texels per metre per triangle: p10/p50/p90 over one merged mesh. */-function texelDensity(geo) {- const pos = geo.attributes.position, uv = geo.attributes.uv;- const idx = geo.index;- const n = idx ? idx.count : pos.count;- const A = new THREE.Vector3(), B = new THREE.Vector3(), C = new THREE.Vector3();- const dens = [];- for (let i = 0; i < n; i += 3) {- const a = idx ? idx.getX(i) : i;- const b = idx ? idx.getX(i + 1) : i + 1;- const c = idx ? idx.getX(i + 2) : i + 2;- A.fromBufferAttribute(pos, a);- B.fromBufferAttribute(pos, b);- C.fromBufferAttribute(pos, c);- const wa = B.clone().sub(A).cross(C.clone().sub(A)).length() * 0.5;- const ua = Math.abs((uv.getX(b) - uv.getX(a)) * (uv.getY(c) - uv.getY(a))- - (uv.getX(c) - uv.getX(a)) * (uv.getY(b) - uv.getY(a)))- * 0.5;- if (wa > 1e-6 && ua > 1e-12) dens.push(Math.sqrt(ua / wa));- }- dens.sort((p, q) => p - q);- const q = (f) => dens[Math.floor(f * (dens.length - 1))];- return { p10: q(0.1), p50: q(0.5), p90: q(0.9), n: dens.length };-}"""@@ -64,6 +39,7 @@ def _measure(script: str) -> dict:return measure(_PRELUDE + script, _LIBS)+def test_roof_clutter_uses_the_hosts_local_roof_after_placement():"""World roof height was added as local Y, applying host transforms twice."""out = _measure("""@@ -96,24 +72,6 @@ console.log(JSON.stringify(layouts));assert transformed["size"] == pytest.approx(plain["size"])[email protected](scope="module")-def facade() -> dict:- return _measure("""-const b = block({ w: 14, d: 12, h: 24, rand: mk(11), style: 'brick' });-console.log(JSON.stringify({ density: texelDensity(b.getObjectByName('Walls').geometry) }));-""")---def test_one_texel_scale_across_the_whole_facade(facade):- """three gives every box face a full 0..1 UV whatever it measures, so one- merged facade stretched a brick tile over a 14 m wall and squeezed it onto- a 0.34 m mullion -- the piers rendered as vertical woodgrain stripes."""- d = facade["density"]- assert d["n"] > 200, d- assert d["p90"] / d["p10"] < 1.05, (- f"texel density varies {d['p90'] / d['p10']:.1f}x across the walls", d)--@pytest.fixture(scope="module")def lit_block() -> dict:return _measure("""@@ -145,9 +103,7 @@ console.log(JSON.stringify({def test_a_lit_block_lights_windows_not_the_whole_shell(lit_block):- """The reveal shell is ONE box spanning the building. Pushing lit panes- onto it and making it emissive lit every window at once, so `lit: 0.45`- rendered as a solid glowing lantern with no dark windows at all."""+ """The reveal shell is ONE box spanning the building."""m = lit_blockassert m["revealEmissive"] == 0, ("the interior shell itself glows -- every window in the building "@@ -165,92 +121,16 @@ def test_a_lit_block_lights_windows_not_the_whole_shell(lit_block):def cot() -> dict:return _measure("""const W = 8, D = 7, H = 3.2, PITCH = 0.85 * W / 2;-const c = cottage({ w: W, d: D, h: H, dormers: 2, roof: 'gable',- rand: mk(23) });--// A bay window on the -Z gable wall, aimed off its mullion cross: the-// first thing seen from outside must be GLASS. A frame box filled solid-// (or a pane buried inside the wall) answers 'Trim' or 'Walls'.-const bayX = -W / 2 + (W / Math.max(1, Math.round(W / 2.6))) * 0.5;-const gableWindow = firstHit(c, [bayX + 0.2, H * 0.55 + 0.2, -30], [0, 0, 1]);-// The same on an eaves (+-X) wall, which carried no openings at all.-// Off the mullion cross in BOTH axes, or the ray meets a glazing bar.-const eavesZ = -D / 2 + (D / Math.max(1, Math.round(D / 2.8))) * 0.5;-const eavesWindow = firstHit(c, [-30, H * 0.55 + 0.2, eavesZ + 0.2], [1, 0, 0]);-// And a dormer, which sat buried INSIDE the roof mass.-const dormerZ = -D / 2 + (D / 3) * 1;-const dormerHit = firstHit(c, [-30, H + PITCH * 0.42, dormerZ], [1, 0, 0]);--// WHICH WAY UP IS THE GABLE. Apex up: the triangle is narrow near the-// ridge and wide at the eaves. Fire along Z at the gable plane, against-// the WALLS mesh only, high in the gable and low in it.+const c = cottage({ w: W, d: D, h: H, dormers: 2, roof: 'gable', rand: mk(23) });+// apex up: the gable triangle is narrow near the ridge, wide at the eaves (walls mesh only)const wallsOnly = new THREE.Group();c.traverse((o) => { if (o.isMesh && o.name === 'Walls') wallsOnly.add(o.clone()); });-const gableAt = (frac) => firstHit(- wallsOnly, [W * 0.35, H + PITCH * frac, 40], [0, 0, -1]);--const glazing = c.getObjectByName('Glazing');-const gb = new THREE.Box3().setFromObject(glazing);--console.log(JSON.stringify({- names: Object.keys(parts(c)).sort(),- gableWindow, eavesWindow, dormerHit,- gableHigh: gableAt(0.75), gableLow: gableAt(0.15),- glazingFrontZ: gb.min.z,- trimIsNotRoof:- c.getObjectByName('Trim').material.uuid- !== c.getObjectByName('Roof').material.uuid,- chimneyIsNotWall: c.getObjectByName('Chimney').material.uuid- !== c.getObjectByName('Walls').material.uuid,-}));+const gableAt = (frac) => firstHit(wallsOnly, [W * 0.35, H + PITCH * frac, 40], [0, 0, -1]);+console.log(JSON.stringify({ gableHigh: gableAt(0.75), gableLow: gableAt(0.15) }));""")-def test_cottage_window_is_glass_not_a_painted_slab(cot):- """The frame was a SOLID box covering the whole opening and the pane sat- inside the wall behind it, so every cottage window rendered as an opaque- rectangle in the roof's terracotta -- the flat-facade complaint itself."""- m = cot- assert m["gableWindow"] == "Glazing", (- f"looking into a bay from outside hits '{m['gableWindow']}'")- assert m["glazingFrontZ"] < -3.5, (- "the pane is buried inside the wall box", m["glazingFrontZ"])---def test_cottage_has_openings_on_every_elevation(cot):- """The eaves (+-X) walls had no windows at all: turned any way but one, a- cottage showed a blank white elevation to the camera."""- m = cot- assert m["eavesWindow"] == "Glazing", m["eavesWindow"]---def test_cottage_dormers_sit_on_the_slope_they_open_through(cot):- """The ridge runs along Z, so the slopes face +-X; dormers spread along X- at one Z were boxes buried inside the roof mass and rendered as nothing."""- m = cot- assert m["dormerHit"] in ("Glazing", "Trim"), (- f"a ray at dormer height meets '{m['dormerHit']}' first")--def test_cottage_gable_ends_are_apex_up(cot):- """three's first radial vertex is at +Z, so `rotateX(+PI/2)` puts the- 3-gon's APEX at y=-1 and a flat edge at +0.5: every gable shipped upside- down, its two top corners poking out through the roof as white wings.- A bbox sees the same triangle either way, so this measures the shape."""- m = cot- assert m["gableLow"] == "Walls", (- "no gable wall low down: the end is open", m["gableLow"])- assert m["gableHigh"] is None, (- "the gable is still wide near the ridge -- it is upside down "- f"({m['gableHigh']})")---def test_cottage_joinery_is_not_roof_tile(cot):- """`trimMat` was built and then discarded (`void trimMat`) while the- frames, sills and door surround were merged into the ROOF mesh."""- m = cot- assert m["trimIsNotRoof"], "the joinery still shares the roof material"- assert "Trim" in m["names"] and "Door" in m["names"], m["names"]- assert m["chimneyIsNotWall"], (- "the stack is limewash, not masonry", m["names"])-+ """`rotateX(+PI/2)` put the 3-gon's apex at y=-1: every gable shipped upside down (a bbox cannot tell)."""+ assert cot["gableLow"] == "Walls", cot+ assert cot["gableHigh"] is None, cotdiff --git a/harness/tests/scene_runtime/lib/test_canopy.py b/harness/tests/scene_runtime/lib/test_canopy.pydeleted file mode 100644index 304c8a7a..00000000--- a/harness/tests/scene_runtime/lib/test_canopy.py+++ /dev/null@@ -1,34 +0,0 @@-"""canopy.js — regression: leaf transmission kept every crown glowing at night."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "noise.js", "grass.js", "foliage_shade.js", "canopy.js")---def test_transmission_through_a_leaf_goes_out_when_the_sun_does():- """`patchLeafSSS` adds its glow to the albedo, so a set sun did not turn it- off. Full strength for any sun at or above the horizon."""- out = measure("""-import * as THREE from 'three';-import { makeCanopy } from './lib/canopy.js';-const amt = (el) => {- const r = el * Math.PI / 180;- const dir = new THREE.Vector3(Math.cos(r), Math.sin(r), 0.2).normalize();- return makeCanopy({ leaves: 200, backlit: { sunDir: dir } })- .getObjectByName('Leaves').material.userData.uniforms.uLeafAmt.value;-};-const off = makeCanopy({ leaves: 200, backlit: false })- .getObjectByName('Leaves').material.userData.uniforms.uLeafAmt;-console.log(JSON.stringify({ high: amt(38), low: amt(1), night: amt(-20),- off: off === undefined }));-""", _LIBS)- assert out["high"] > 0.4, out- # Golden hour keeps the whole effect; it is the best moment for it.- assert abs(out["low"] - out["high"]) < 1e-6, out- assert out["night"] == 0, out- # `backlit: false` never installs the patch at all.- assert out["off"] is True, outdiff --git a/harness/tests/scene_runtime/lib/test_celestial.py b/harness/tests/scene_runtime/lib/test_celestial.pydeleted file mode 100644index 46af7c05..00000000--- a/harness/tests/scene_runtime/lib/test_celestial.py+++ /dev/null@@ -1,85 +0,0 @@-"""celestial.js: the sky opts out of fog with the marker the static GLSL audit reads."""--from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import compile_scene, measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "noise.js", "materials.js", "celestial.js")---def test_the_sky_declares_its_own_fog_opt_out():- """The option the audit's own warning tells you to pass has to write the- marker it reads (`3dcode:`; `astra3d:` still accepted on read)."""- out = measure("""-import { makeStars, makeAurora } from './lib/celestial.js';-const marks = [];-for (const g of [makeStars({ count: 50, seed: 1 }),- makeAurora({ seed: 1 })]) {- g.traverse((o) => {- for (const m of [].concat(o.material || [])) {- if (m && m.fragmentShader) {- marks.push([m.name, m.fog === false,- /(3dcode|astra3d):\\s*no-fog/.test(m.fragmentShader)]);- }- }- });-}-console.log(JSON.stringify({ marks }));-""", _LIBS)- assert out["marks"], "no sky materials found"- for name, flag, marker in out["marks"]:- assert flag, f"{name} does not opt out of fog"- assert marker, f"{name} opts out but writes no marker for the checker"---def test_milky_way_is_faint_and_magnitude_controls_all_starlight():- """Diffuse galactic light must not become a bright cloud or ignore magnitude."""- code, out = compile_scene("""-import * as THREE from 'three';-import {makeStars} from './lib/celestial.js';-export function createScene({renderer}) {- const scene=new THREE.Scene(), camera=new THREE.PerspectiveCamera(100,1,.1,5000);- const target=new THREE.WebGLRenderTarget(96,96,{type:THREE.FloatType});- const pixels=new Float32Array(96*96*4), previous=renderer.getRenderTarget();- const clear=new THREE.Color();renderer.getClearColor(clear);const clearAlpha=renderer.getClearAlpha();- const groups=[1,.5,0].map(magnitude=>makeStars({count:200,seed:18,magnitude}));- const pole=groups[0].getObjectByName('MilkyWayStars').material.uniforms.uPole.value;- const core=groups[0].getObjectByName('MilkyWayStars').material.uniforms.uCore.value;- const directions=[core,core.clone().negate(),new THREE.Vector3(0,1,0),- new THREE.Vector3(-.6,.2,-1).normalize()];- try {- renderer.setClearColor(0,0);renderer.setRenderTarget(target);- for(const direction of directions) {- camera.lookAt(direction);camera.updateMatrixWorld(true);- const energies=[];- for(const group of groups) {- group.getObjectByName('StarField').visible=false;scene.add(group);- renderer.render(scene,camera);renderer.readRenderTargetPixels(target,0,0,96,96,pixels);- let energy=0,peak=0;- for(let i=0;i<pixels.length;i+=4) {- const l=.2126*pixels[i]+.7152*pixels[i+1]+.0722*pixels[i+2];- if(!Number.isFinite(l))throw Error('Nonfinite galactic light');- energy+=l;peak=Math.max(peak,l);- }- if(peak>.035||energy/(96*96)>.008)throw Error('Milky Way became luminous fog: '+[peak,energy]);- energies.push(energy);scene.remove(group);- }- if(energies[0]<=.001)throw Error('Unresolved starlight disappeared');- if(Math.abs(energies[1]/energies[0]-.5)>.0001||energies[2]!==0)- throw Error('Magnitude does not control diffuse starlight: '+energies);- }- const off=groups[2];off.getObjectByName('StarField').visible=true;scene.add(off);- renderer.render(scene,camera);renderer.readRenderTargetPixels(target,0,0,96,96,pixels);- for(let i=0;i<pixels.length;i+=4)if(pixels[i]||pixels[i+1]||pixels[i+2])throw Error('Magnitude zero left visible stars');- } finally {- renderer.setRenderTarget(previous);renderer.setClearColor(clear,clearAlpha);- target.dispose();groups.forEach(g=>g.userData.dispose());- }- return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,0,1],lookAt:[0,0,0]}]};-}-""", _LIBS)- assert code == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_clouds.py b/harness/tests/scene_runtime/lib/test_clouds.pyindex c4941e5d..e3aff3e5 100644--- a/harness/tests/scene_runtime/lib/test_clouds.py+++ b/harness/tests/scene_runtime/lib/test_clouds.py@@ -3,60 +3,11 @@ from __future__ import annotationsimport pytest-from tests.scene_runtime.lib._probe import compile_scene, measure+from tests.scene_runtime.lib._probe import compile_scenepytestmark = pytest.mark.node-def test_the_layer_is_lit_by_the_rig_and_a_set_sun_becomes_the_moon():- """`sunRig().sunDir` keeps reporting the authored sun after it sets; passed- straight through, every night puff is lit from below. A set sun becomes a- moon above the horizon, opposite it."""- m = measure("""-import * as THREE from 'three';-import { makeClouds } from './lib/clouds.js';-const dir = (o) => makeClouds(Object.assign({ seed: 3 }, o)).material.uniforms.uSunDir.value.toArray();-console.log(JSON.stringify({- day: dir({ sunDir: new THREE.Vector3(-0.6, 0.55, -0.3) }),- set: dir({ sunDir: new THREE.Vector3(0.62, -0.34, 0.21) }),- none: dir({}),-}));-""", ("clouds.js",))- assert m["day"][1] > 0.5, m- assert m["set"][1] > 0.4 and m["set"][0] < 0, m- assert m["none"][1] == 1.0, m---def test_cloud_deck_seed_options_and_disposal():- out = measure("""-import {makeClouds} from './lib/clouds.js';-const hash=texture=>{- let h=2166136261;- for(const byte of texture.image.data)h=Math.imul(h^byte,16777619);- return h>>>0;-};-const decks=[makeClouds({seed:7}),makeClouds({seed:7}),makeClouds({seed:8}),makeClouds({count:0})];-const weather=decks.slice(0,3).map(d=>hash(d.material.uniforms.uWeather.value));-const noise=decks.slice(0,3).map(d=>hash(d.material.uniforms.uNoise.value));-let rejected=false;-try {makeClouds({quality:'toString'});} catch(error) {rejected=error instanceof RangeError;}-const empty=decks[3].visible===false;-const counts=[];-for(const deck of decks) {- const u=deck.material.uniforms;- for(const resource of [deck.geometry,deck.material,u.uWeather.value,u.uNoise.value]) {- const at=counts.length;counts.push(0);resource.addEventListener('dispose',()=>counts[at]++);- }- deck.userData.dispose();deck.userData.dispose();-}-console.log(JSON.stringify({weather,noise,rejected,empty,counts}));-""", ("clouds.js",))- for field in (out["weather"], out["noise"]):- assert field[0] == field[1] and field[0] != field[2], out- assert out["rejected"] and out["empty"], out- assert out["counts"] == [1] * 16, out--def test_cloud_transport_matches_beer_lambert_and_camera_projection():"""Constant data isolates optical integration from authored noise and color."""code, out = compile_scene("""diff --git a/harness/tests/scene_runtime/lib/test_environment.py b/harness/tests/scene_runtime/lib/test_environment.pyindex f58720c6..6d018193 100644--- a/harness/tests/scene_runtime/lib/test_environment.py+++ b/harness/tests/scene_runtime/lib/test_environment.py@@ -1,11 +1,6 @@-"""environment.js (91 recorded scenes import it through the starter's env.js): worldShell,-makeOutskirts and the sunRig package, measured under node. A set sun (elevation < 0) is-night with a moon opposite the sun. The silhouette ridge and the outskirts' copses are-opt-in (2026-10-15: library defaults no longer pre-decide the backdrop)."""+"""environment.js (91 recorded scenes import it through the starter's env.js)."""from __future__ import annotations-import math-import pytestfrom _probe import measure@@ -54,28 +49,6 @@ console.log(JSON.stringify(states));assert all(s["canReturnToDay"] for s in out)-def test_moon_angular_size_is_independent_of_sky_radius_and_scene_fog():- out = _measure("""-import * as THREE from 'three';-import { sunRig } from './lib/environment.js';-const moons = [400,4000,12000].map(radius => {- const rig=sunRig({mood:'night',radius}), moon=rig.sunDisc;- const diameter=THREE.MathUtils.radToDeg(2*Math.atan(moon.geometry.parameters.radius/moon.position.length()));- const state={diameter,fog:moon.material.fog,depthWrite:moon.material.depthWrite,- aligned:moon.position.clone().normalize().dot(rig.lightDir)};- rig.dispose();return state;-});-const day=sunRig({mood:'day',radius:4000});-const daytime={radius:day.sunDisc.geometry.parameters.radius,segments:day.sunDisc.geometry.parameters.segments};-day.dispose();console.log(JSON.stringify({moons,daytime}));-""")- for moon in out["moons"]:- assert moon["diameter"] == pytest.approx(.52)- assert not moon["fog"] and not moon["depthWrite"]- assert moon["aligned"] == pytest.approx(1)- assert out["daytime"] == {"radius": 48, "segments": 24}--_SHELL = """import * as THREE from 'three';import { worldShell } from './lib/environment.js';@@ -85,12 +58,6 @@ env.group.updateMatrixWorld(true);const hitsFor = (dir) => new THREE.Raycaster(new THREE.Vector3(0, 1.7, 0), dir.normalize()).intersectObject(env.group, true).map((h) => h.object.name);const outward = [];for (let a = 0; a < 8; a++) outward.push(hitsFor(new THREE.Vector3(Math.cos(a / 8 * Math.PI * 2), 0, Math.sin(a / 8 * Math.PI * 2))));-const sky = env.group.getObjectByName('SkyGradient');-const cols = sky.geometry.attributes.color, pos = sky.geometry.attributes.position;-let zenithB = null, horizonB = null;-for (let i = 0; i < pos.count; i++) { if (pos.getY(i) > 3990) zenithB = cols.getZ(i); if (Math.abs(pos.getY(i)) < 40) horizonB = cols.getZ(i); }-let tris = 0;-env.group.traverse((o) => { if (o.isMesh) tris += o.geometry.attributes.position.count / 3; });const noRidge = worldShell({ rand, mood: 'day', ridge: false });const bare = worldShell({ rand, mood: 'day' });const T = (rho, d) => Math.exp(-((rho * d) ** 2));@@ -107,8 +74,7 @@ for (let i = 0; i < sp.count; i++) {}const big = worldShell({ rand: mk(), mood: 'day', bounds: 1200 });const over = worldShell({ rand: mk(), mood: 'overcast', bounds: 1200 });-console.log(JSON.stringify({ outward, fogHex: env.fog.color.getHexString(), zenithB, horizonB, tris: Math.round(tris),- ridgeOptional: !noRidge.group.getObjectByName('HorizonRidge'), ridgeOffByDefault: !bare.group.getObjectByName('HorizonRidge'),+console.log(JSON.stringify({ outward, ridgeOptional: !noRidge.group.getObjectByName('HorizonRidge'), ridgeOffByDefault: !bare.group.getObjectByName('HorizonRidge'),bareOutward: hitsFor(new THREE.Vector3(1, 0, 0)), eastTop, westTop, fogIsExp2: env.fog.isFogExp2 === true,smallD: worldShell({ rand: mk(), mood: 'day', bounds: 150 }).fog.density, bareD: worldShell({ rand: mk(), mood: 'day' }).fog.density,bigFarT: T(big.fog.density, 2400), overFarT: T(over.fog.density, 2400), unclampedFarT: T(env.fog.density, 2400),@@ -127,21 +93,8 @@ def test_no_outward_ray_escapes_into_void(shell):assert "SkyGradient" in shell["bareOutward"], shell["bareOutward"] # the dome alone closes the sky-def test_the_fog_matches_the_horizon_tint(shell):- assert shell["fogHex"] == "dbe3ea" and shell["fogIsExp2"]---def test_the_sky_is_a_gradient_not_a_flat_colour(shell):- assert abs(shell["zenithB"] - shell["horizonB"]) > 0.1, shell---def test_the_shell_is_nearly_free_and_the_ridge_optional(shell):- assert shell["tris"] < 2000 and shell["ridgeOptional"]--def test_the_ridge_is_opt_in_and_can_be_shaped_by_sector(shell):- """A library default no longer rings every exterior with the same 360-degree crest: the- ridge is off unless asked, and `ridgeProfile` makes it directional or partial."""+ """A library default no longer rings every exterior with the same 360-degree crest."""assert shell["ridgeOffByDefault"]assert shell["eastTop"] <= 1e-6 < shell["westTop"], (shell["eastTop"], shell["westTop"])assert shell["westTop"] == pytest.approx(4000 * 0.1, rel=1e-6)@@ -181,22 +134,7 @@ for (const mood of ['day', 'golden', 'night', 'overcast']) {bias: rig.sun.shadow.bias, normalBias: rig.sun.shadow.normalBias,frustumRight: rig.sun.shadow.camera.right, night: rig.night, moodName: rig.mood };}-// The shadow map follows the FRUSTUM: one fixed size gave every scene-// whatever texel it happened to get (the library default landed at 0.146 m).-out.texel = {};-for (const b of [8, 25, 60, 150, 400, 1200]) {- const r = sunRig({ bounds: b });- out.texel[b] = { map: r.sun.shadow.mapSize.x, size: (2 * b) / r.sun.shadow.mapSize.x,- normalBias: r.sun.shadow.normalBias };-}out.nightFloor = sunRig({ mood: 'night', fill: 0.2 }).fill.intensity;-const tinted = sunRig({ mood: 'golden', fillSky: 0x7a5aa0, fillGround: 0x3a2e22 });-out.tinted = { sky: tinted.fill.color.getHex(), ground: tinted.fill.groundColor.getHex(),- nadir: sample(tinted, new THREE.Vector3(0, -1, 0)), plainNadir: sample(sunRig({ mood: 'golden' }), new THREE.Vector3(0, -1, 0)) };-out.discOptional = sunRig({ mood: 'day', disc: false }).sunDisc === null;-const floors = (o) => { const r = sunRig(o); return { sun: r.sun.intensity, fill: r.fill.intensity }; };-out.floors = { dayAsked: floors({ mood: 'day', intensity: 2.8, fill: 0.65 }), goldenAsked: floors({ mood: 'golden', intensity: 2.0, fill: 0.3 }),- nightAsked: floors({ mood: 'night', intensity: 0.8, fill: 0.6 }), dayBright: floors({ mood: 'day', intensity: 9.0 }) };// A set sun is night: moon opposite, up 30-55 deg; sunDir still the authored sun.const set = sunRig({ azimuth: 215, elevation: -20 });const moon = set.sun.position.clone().normalize();@@ -222,38 +160,13 @@ def test_azimuth_zero_is_plus_x_and_ninety_is_plus_z(sun):assert sun["axes"] == [[1, 0, 0], [0, 0, 1]]-def test_the_env_texture_is_a_linear_half_float_equirect(sun):- for mood in _MOODS:- m = sun[mood]- assert m["envW"] >= 64 and m["envH"] >= 32 and m["equirect"], m- assert m["halfFloat"] and m["linear"], m---def test_the_sun_disc_sits_on_the_light_vector(sun):- for mood in _MOODS:- assert sun[mood]["dot"] > 0.999 and sun[mood]["lightIsSun"], (mood, sun[mood])--def test_the_baked_env_glow_agrees_with_the_shadow_sun(sun):for mood in _MOODS:assert sun[mood]["lumSun"] > sun[mood]["lumAway"] * 1.15, (mood, sun[mood])-def test_the_day_env_is_an_hdr_sky_with_a_warm_ground_half(sun):- """What chrome, water and glass reflect: a blue zenith, a pale (not white)- horizon in the dome's own family, an HDR sun, and a ground bounce below."""- d = sun["day"]- assert d["zenith"][2] > d["zenith"][0] * 2, d["zenith"]- hl = 0.2126 * d["horizon"][0] + 0.7152 * d["horizon"][1] + 0.0722 * d["horizon"][2]- assert 0.5 < hl < 2.5, d["horizon"] # toward the sun's azimuth: ~236 sRGB after ACES, not clipped- assert d["lumSun"] > 3.0, "the sun in the env is HDR (bloom-friendly), not a clipped band"- assert d["nadir"][0] > d["nadir"][2], "ground bounce is warm"- assert d["nadir"][0] < d["horizon"][0]--def test_the_night_rig_is_dark_but_lit(sun):- """Measured on ACES/exposure 1.0: the reference moon (0.8 / fill 0.6) put the- ground at 17/255; 2.2 / 1.0 reads moonlit (ground ~45, shade ~14)."""+ """Measured on ACES/exposure 1.0."""n = sun["night"]assert n["sun"] >= 2.0 and n["fill"] >= 0.8 and n["night"], nassert sun["nightFloor"] >= 0.55@@ -261,15 +174,6 @@ def test_the_night_rig_is_dark_but_lit(sun):assert zl < 0.03 and n["zenith"][2] > n["zenith"][0], n["zenith"]-def test_the_fill_colours_can_be_tinted_and_the_env_ground_half_follows(sun):- """The cookbook's time-of-day rows tint the hemisphere (cool sky / warm ground per hour);- the boat-workshop run (loop 8, 2026-09-07) passed `fillSky`/`fillGround` and the rig- silently ignored them."""- t = sun["tinted"]- assert t["sky"] == 0x7A5AA0 and t["ground"] == 0x3A2E22, t- assert t["nadir"] != t["plainNadir"], "the baked ground bounce follows the override"--def test_the_shadow_sun_is_fitted_and_biased(sun):for mood in _MOODS:m = sun[mood]@@ -281,38 +185,6 @@ def test_the_shadow_sun_is_fitted_and_biased(sun):assert 0 < m["normalBias"] <= 2 * 120 / m["shadowMap"] * 1.001, m-def test_the_shadow_map_is_sized_to_the_frustum_it_covers(sun):- """Measured 2026-09-01 on OUR PCFSoftShadowMap (no post chain to hide it):- a fixed 2048 over the library's default bounds 150 gave 0.146 m/texel and- the contact shadow of a 1 m sphere came back a 14-texel staircase."""- t = sun["texel"]- for b, m in t.items():- assert 1024 <= m["map"] <= 4096, (b, m)- assert m["map"] == 2 ** round(math.log2(m["map"])), (b, m)- # Small worlds are not handed a 4096 map they cannot use...- assert t["8"]["map"] == 1024 and t["25"]["map"] == 1024, t- # ...and every world up to the 0.05 m target gets there.- for b in ("8", "25", "60"):- assert t[b]["size"] <= 0.05, (b, t[b])- # Past it the map caps and the texel grows with the world, never the reverse.- assert t["150"]["map"] == 4096 and t["1200"]["map"] == 4096, t- assert t["150"]["size"] < t["400"]["size"] < t["1200"]["size"], t- # The library default (bounds 150) is at least twice as fine as the old fixed map.- assert t["150"]["size"] <= (2 * 150 / 2048) / 2 + 1e-9, t["150"]---def test_the_disc_can_be_skipped(sun):- assert sun["discOptional"]---def test_daylight_has_a_sun_floor_because_colour_dies_with_the_light(sun):- f = sun["floors"]- assert f["dayAsked"]["sun"] >= 4.5 and f["dayAsked"]["fill"] >= 1.2- assert f["goldenAsked"]["sun"] >= 4.5- assert f["nightAsked"]["sun"] == 0.8, "night is legitimately dark: an explicit ask stands"- assert f["dayBright"]["sun"] == 9.0--def test_a_set_sun_is_night_with_a_moon_opposite(sun):s = sun["set"]assert s["night"] and s["mood"] == "night" and s["sunY"] < 0@@ -323,50 +195,8 @@ def test_a_set_sun_is_night_with_a_moon_opposite(sun):assert s["envZenith"][2] > s["envZenith"][0] and s["sunIntensity"] >= 2.0-def test_outskirts_meets_the_scene_ground_at_its_seam():- out = _measure("""-import { makeOutskirts } from './lib/environment.js';-const ground = (x, z) => 2.0 + 0.01 * x;-const g = makeOutskirts({ inner: 150, baseY: 0, heightAt: ground, relief: 30, seed: 9, clumps: 140 });-const land = g.children.find((o) => o.name === 'OutskirtsLand');-const pos = land.geometry.attributes.position;-let seamWorst = 0, maxR = 0, maxY = -1e9, farLift = 0, nFar = 0;-for (let i = 0; i < pos.count; i++) {- const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i), r = Math.hypot(x, z);- maxR = Math.max(maxR, r); maxY = Math.max(maxY, y);- if (r < 151) seamWorst = Math.max(seamWorst, Math.abs(y - ground(x, z)));- if (r > 900) { farLift += y; nFar++; }-}-const copses = g.children.find((o) => o.name === 'OutskirtsCopses');-const a = makeOutskirts({ inner: 100, seed: 4 }).children[0].geometry.attributes.position;-const b = makeOutskirts({ inner: 100, seed: 4 }).children[0].geometry.attributes.position;-const c = makeOutskirts({ inner: 100, seed: 5 }).children[0].geometry.attributes.position;-let same = true, differ = false;-for (let i = 0; i < a.count * 3; i++) { if (a.array[i] !== b.array[i]) same = false; if (a.array[i] !== c.array[i]) differ = true; }-const reach = (o) => { const p = o.children[0].geometry.attributes.position; let r = 0;- for (let i = 0; i < p.count; i++) r = Math.max(r, Math.hypot(p.getX(i), p.getZ(i))); return r; };-const bare = makeOutskirts({ inner: 100, seed: 4 });-const plain = makeOutskirts({ inner: 100, seed: 4, fields: false });-console.log(JSON.stringify({ seamWorst, maxR, maxY, meanFarY: farLift / nFar, meshes: g.children.length,- copseCount: copses ? copses.count : 0, patched: !!land.material.userData.astraShader, same, differ,- bareMeshes: bare.children.length, plainPatched: !!plain.children[0].material.userData.astraShader,- small: reach(makeOutskirts({ inner: 120, shellRadius: 1200, seed: 2 })), big: reach(makeOutskirts({ inner: 300, shellRadius: 9000, seed: 2 })),- clamped: reach(makeOutskirts({ inner: 120, shellRadius: 1200, outer: 5000, seed: 2 })),- shorter: reach(makeOutskirts({ inner: 120, shellRadius: 1200, outer: 600, seed: 2 })) }));-""")- assert out["seamWorst"] < 0.05, out- assert 3279 <= out["maxR"] <= 3281 and out["maxY"] < 80 and out["meanFarY"] > 1.0, out- assert out["meshes"] == 2 and out["copseCount"] > 50 and out["patched"], out- assert out["bareMeshes"] == 1, "copses are opt-in (a temperate cue, not a default)"- assert out["plainPatched"], "`fields: false` still patches the land shader (one tone, mottled)"- assert out["same"] and out["differ"]- assert abs(out["small"] - 984) < 1.5 and abs(out["big"] - 7380) < 2.0- assert abs(out["clamped"] - 984) < 1.5 and abs(out["shorter"] - 600) < 1.5--def test_the_sky_dome_keeps_or_sets_the_background_the_gate_reads():- """D112: makeSky nulled scene.background ("the dome IS the backdrop") and the harness's own- no_background gate then failed three iteration-5 scenes that had set one before calling it."""+ """D112."""out = _measure("""import * as THREE from 'three';import { makeSky } from './lib/sky.js';diff --git a/harness/tests/scene_runtime/lib/test_exterior_starter.py b/harness/tests/scene_runtime/lib/test_exterior_starter.pydeleted file mode 100644index 3d6238b7..00000000--- a/harness/tests/scene_runtime/lib/test_exterior_starter.py+++ /dev/null@@ -1,88 +0,0 @@-"""The starter's env.js is the EXAMPLE scene's environment (the plan-less skeleton the live tests-build): a level plate named Ground, the library's sun rig and a fog — no landform, shell or-outskirts (the library landscape it used to ship was kept byte for byte by 29 of 30 iteration-0-scenes). A PLAN skeleton never ships it: ``_env_for_plan`` writes an interface stub with the-plan's data, a plate, and no light, sky or atmosphere — it fails the gates until the author writes-the brief's (a passing placeholder was kept for the same reason the landscape was; 2026-10-15)."""-from __future__ import annotations--from pathlib import Path--from _probe import measure--from codeverse3d.contracts.common import Track-from codeverse3d.contracts.plan import ScenePlan-from codeverse3d.languages.scene_threejs import STARTER_DIR, _env_for_plan-from codeverse3d.tracks.planner import plan_example--_LIBS = ("environment.js", "terrain.js", "noise.js", "materials.js", "sky.js", "shader.js")---def _probe_script(env: str | None = None) -> str:- env = (STARTER_DIR / "env.js").read_text() if env is None else env- body = env.replace("import * as THREE from 'three';", "").replace("export function", "function").replace("export const", "const")- return f"""-import * as THREE from 'three';-{body}-const scene = new THREE.Scene();-const out = buildEnv({{ scene, THREE }});-const names = [];-scene.traverse((o) => {{ if (o.name) names.push(o.name); }});-const h = (x, z) => heightAt(x, z);-console.log(JSON.stringify({{- names,- fog: !!scene.fog,- bgIsFog: !!scene.fog && scene.background.getHex() === scene.fog.color.getHex(),- fogFar: scene.fog ? scene.fog.far : 0,- lights: names.filter((n) => /Sun|Fill|Light/.test(n)).length,- groundSize: out.ground.geometry.parameters.width,- heights: [[0, 0], [20, 10], [-30, 25], [70, 0], [0, -75]].map(([x, z]) => h(x, z)),- envMap: !!scene.environment,-}}));-"""---def test_the_example_env_passes_the_env_gates():- got = measure(_probe_script(), _LIBS)- for n in ("Environment", "Ground", "SunRigSun", "SunRigFill"):- assert n in got["names"], (n, got["names"])- for n in ("WorldShell", "SkyGradient", "HorizonRidge", "Outskirts"): # no landscape decided for the author- assert n not in got["names"], (n, got["names"])- assert got["fog"] and got["bgIsFog"] and got["envMap"], got # no_fog / no_background / lit PBR- assert all(isinstance(v, (int, float)) and v == v for v in got["heights"]), got- assert got["fogFar"] >= 2 * (got["groundSize"] / 3), got # fog_short on the plan the plate was sized for---def test_the_plan_stub_ships_a_plate_and_the_plans_light_and_nothing_that_passes():- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- env = _env_for_plan(plan)- span = max(plan.bounds.extents[0], plan.bounds.extents[2])- assert f"export const GROUND_SIZE = {int(span * 3)};" in env- assert "export const SUN_AZIMUTH_DEG = 250;" in env and "export const SUN_ELEVATION_DEG = 8;" in env # the plan's, not a constant- code = "\n".join(ln for ln in env.splitlines() if not ln.lstrip().startswith("//"))- for word in ("CONTENT_RADIUS", "worldShell(", "makeOutskirts(", "flat:", "TUNE these", "sunRig(", "MOOD", "scene.fog =",- "scene.background =", "scene.environment =", "Light("):- assert word not in code, word- assert "export function heightAt(x, z)" in env and "export function buildEnv(ctx)" in env and "ground.name = 'Ground'" in env- # a plan that states no sun: the rig's own guess, flagged as such, never a decided light- blank = _env_for_plan(plan.model_copy(update={"environment": "a cave; no sky"}))- assert "export const SUN_AZIMUTH_DEG = 45;" in blank and "rig's guess" in blank and "SUN_ELEVATION_DEG = null" in blank- got = measure(_probe_script(_env_for_plan(plan)), _LIBS)- assert "Ground" in got["names"] and not got["fog"] and not got["envMap"] and not got["lights"], got # fails no_fog / dark_frame as shipped- starter = Path(STARTER_DIR / "env.js").read_text()- assert "export function heightAt(x, z)" in starter and "export function buildEnv(ctx)" in starter- assert "export const SUN_AZIMUTH_DEG" in starter---def test_the_ground_height_is_finite_for_a_signed_zero_column():- """terrain.ground(): a coordinate of -1.5e-14 wrapped to exactly N and read past the lattice- row — 15 NaN vertices in the outskirts ring, a NaN bounding box in the render console."""- got = measure("""-import * as THREE from 'three';-import { mulberry32 } from './lib/noise.js';-import { ground } from './lib/terrain.js';-const G = ground({ size: 160, segments: 16, rand: mulberry32(7), relief: 3, scale: 60 });-console.log(JSON.stringify({ tiny: G.height(-1.5e-14, -80), zero: G.height(0, -80), far: G.height(-1.5e-14, -84.73), neg: G.height(-160.00000001, 12) }));-""", ("terrain.js", "noise.js", "materials.js", "shader.js"))- assert all(isinstance(v, (int, float)) and v == v for v in got.values()), got- assert abs(got["tiny"] - got["zero"]) < 1e-6diff --git a/harness/tests/scene_runtime/lib/test_figure.py b/harness/tests/scene_runtime/lib/test_figure.pydeleted file mode 100644index 4df01e54..00000000--- a/harness/tests/scene_runtime/lib/test_figure.py+++ /dev/null@@ -1,50 +0,0 @@-"""figure.js — regressions: carry() put the load on the head and the hands behind-the body, and an unset `skin` rendered every face as a white ball."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("figure.js", "materials.js")--[email protected](scope="module")-def m() -> dict:- return measure("""-import * as THREE from 'three';-import { figure, carry } from './lib/figure.js';-const find = (root, name) => { let hit = null; root.traverse((o) => { if (o.name === name) hit = o; }); return hit; };-const c = figure({ height: 1.72 });-const held = new THREE.Object3D();-carry(c, held);-c.updateMatrixWorld(true);-held.updateMatrixWorld(true);-const hand = new THREE.Vector3().setFromMatrixPosition(find(c, 'handL').matrixWorld);-const heldW = new THREE.Vector3().setFromMatrixPosition(held.matrixWorld);-const skin = find(figure({ height: 1.72 }), 'head').material.color;-console.log(JSON.stringify({- handY: hand.y, handZ: hand.z, heldY: heldW.y, heldZ: heldW.z,- headMinY: new THREE.Box3().setFromObject(find(c, 'head')).min.y,- skinPeak: Math.max(skin.r, skin.g, skin.b), skinWarm: skin.r - skin.b,-}));-""", _LIBS)---def test_carry_hands_land_on_the_held_object(m):- """The old elbow sign left the hands BEHIND the body plane."""- assert m["handZ"] < -0.25 and 0.80 < m["handY"] < 1.10, m---def test_the_held_object_sits_at_the_hands_not_on_the_head(m):- """`held` is parented to the waist pivot and was offset by a figure-root- height as well: the render showed a crate balanced on the carrier's head."""- assert 0 < m["heldY"] - m["handY"] < 0.12, m- assert m["heldY"] < m["headMinY"] and m["heldZ"] < -0.25, m---def test_skin_is_never_the_undefined_white_ball(m):- """`MAT.skin({ color: opts.skin })` with no `skin` copied `color: undefined`- over the default — albedo 1.0 on every face and hand."""- assert m["skinPeak"] < 0.72 and m["skinWarm"] > 0.05, mdiff --git a/harness/tests/scene_runtime/lib/test_flowers.py b/harness/tests/scene_runtime/lib/test_flowers.pydeleted file mode 100644index ff1165b3..00000000--- a/harness/tests/scene_runtime/lib/test_flowers.py+++ /dev/null@@ -1,62 +0,0 @@-"""flowers.js — regression: the flowers cast the shadow of their petal CARDS."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "noise.js", "grass.js", "foliage_shade.js", "finish.js", "flowers.js")---# Run a material's patch chain the way three does, and hand back the GLSL.-_COMPILE = """-const compile = (mat, vs, fs) => {- const shader = { uniforms: {}, vertexShader: vs, fragmentShader: fs };- mat.onBeforeCompile(shader, {});- return shader;-};-const STD_V = '#include <begin_vertex>\\n';-const STD_F = 'void main() {\\n#include <color_fragment>\\n}\\n';-const DEPTH_F = 'void main() {\\n#include <alphatest_fragment>\\n}\\n';-"""---def test_the_shadow_is_cut_to_the_petal_and_not_to_its_card():- """three's depth shader has no `<color_fragment>`, so the petal carving was- dropped in silence and every daisy stamped a slab. The cut is spliced above- the alpha test and reads the SURFACE's profile uniform."""- out = measure(_COMPILE + """-import { makeFlowers } from './lib/flowers.js';-const m = makeFlowers({ kind: 'daisy', extent: 2, density: 4,- shadows: true }).children[0];-const dep = m.customDepthMaterial;-const d = compile(dep, STD_V, DEPTH_F);-const surf = compile(m.material, STD_V, STD_F);-console.log(JSON.stringify({- cuts: /discard/.test(d.fragmentShader),- byProfile: d.fragmentShader.indexOf('flowProfile(vFlow.y, uFlowProf)') >= 0,- aboveAlphaTest: d.fragmentShader.indexOf('discard')- < d.fragmentShader.indexOf('#include <alphatest_fragment>'),- // The one thing that makes the cut the SAME cut: the depth material is- // handed the surface's own uniform map, profile and all.- sameProfileObject: dep.userData.uniforms.uFlowProf- === m.material.userData.uniforms.uFlowProf,- uploaded: !!d.uniforms.uFlowProf,- varying: /varying vec4 vFlow;/.test(d.fragmentShader),- writesVarying: /vFlow = vec4/.test(d.vertexShader),- // and the surface still discards by the same profile.- surfaceProfile: surf.fragmentShader.indexOf('flowProfile(') >= 0,- // one helper, not two: the vertex head carries it as well and a second- // copy in one stage is a GLSL redefinition.- vertexCopies: (d.vertexShader.match(/float flowProfile\\(/g) || []).length,- fragCopies: (d.fragmentShader.match(/float flowProfile\\(/g) || []).length,-}));-""", _LIBS)- assert out["cuts"] and out["byProfile"], out- assert out["aboveAlphaTest"], out- assert out["sameProfileObject"] and out["uploaded"], out- assert out["varying"] and out["writesVarying"], out- assert out["surfaceProfile"], out- assert out["fragCopies"] == 1, out- assert out["vertexCopies"] == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_grass.py b/harness/tests/scene_runtime/lib/test_grass.pydeleted file mode 100644index 15ed70c7..00000000--- a/harness/tests/scene_runtime/lib/test_grass.py+++ /dev/null@@ -1,82 +0,0 @@-"""grass.js (12 recorded scenes import it): the field stands on the caller's ground, and-the blade normal is wound the way the strip is."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "noise.js", "grass.js")--# Run a material's patch chain the way three does, and hand back the GLSL.-_COMPILE = """-const compile = (mat) => {- const shader = {- uniforms: {},- vertexShader: '#include <begin_vertex>\\n',- fragmentShader: 'void main() {\\n#include <color_fragment>\\n}\\n',- };- mat.onBeforeCompile(shader, {});- return shader;-};-"""---def test_blades_and_mat_stand_on_the_callers_ground():- """Grass that ignores `heightAt` floats over a slope or buries- itself in it — the one defect a still frame shows immediately."""- out = measure("""-import { makeGrass } from './lib/grass.js';-const h = (x, z) => 0.8 * Math.sin(x * 0.3) * Math.cos(z * 0.21) + 0.9;-const g = makeGrass({ extent: 10, density: 300, seed: 8, heightAt: h });-const iPos = g.getObjectByName('Blades').geometry.attributes.iPos.array;-let bladeErr = 0;-for (let i = 0; i < iPos.length; i += 3) {- bladeErr = Math.max(bladeErr,- Math.abs(iPos[i + 1] - h(iPos[i], iPos[i + 2])));-}-const p = g.getObjectByName('Sward').geometry.attributes.position;-let matErr = 0, lift = 0;-for (let v = 0; v < p.count; v++) {- const d = p.getY(v) - h(p.getX(v), p.getZ(v));- matErr = Math.max(matErr, Math.abs(d - 0.012));- lift = Math.max(lift, d);-}-const flat = makeGrass({ extent: 6, density: 300, seed: 8 });-const fPos = flat.getObjectByName('Blades').geometry.attributes.iPos.array;-let flatMax = 0;-for (let i = 1; i < fPos.length; i += 3) flatMax = Math.max(flatMax, fPos[i]);-console.log(JSON.stringify({- bladeErr, matErr, lift, flatMax,- boxLow: g.getObjectByName('Blades').geometry.boundingBox.min.y,-}));-""", _LIBS)- assert out["bladeErr"] < 1e-4, out- assert out["matErr"] < 1e-4, out- # Just clear of the ground: level with it the mat z-fights, higher- # and the blades look planted in a tray.- assert 0.005 < out["lift"] < 0.05, out- # No heightAt: the field rests exactly on y = 0.- assert out["flatMax"] == 0, out- assert out["boxLow"] <= 0.11, out---def test_the_shading_normal_is_wound_the_way_the_strip_is():- """The reference wrote `cross(grTan, grSide)`, the BACK face of the swept- strip; DOUBLE_SIDED cannot rescue it (vNormal and gl_FrontFacing flip- together), and a front-lit meadow rendered black."""- out = measure(_COMPILE + """-import { makeGrass } from './lib/grass.js';-const vs = compile(makeGrass({ extent: 4, density: 100 })- .getObjectByName('Blades').material).vertexShader;-console.log(JSON.stringify({- right: vs.includes('cross(grSide, grTan) - grSide * aCorner.x'),- wrong: vs.includes('cross(grTan, grSide)'),- guarded: vs.includes('#ifndef FLAT_SHADED'),-}));-""", _LIBS)- assert out["right"], out- assert not out["wrong"], out- # The depth pass defines FLAT_SHADED, and a depth shader has no vNormal.- assert out["guarded"], outdiff --git a/harness/tests/scene_runtime/lib/test_instancing.py b/harness/tests/scene_runtime/lib/test_instancing.pydeleted file mode 100644index fcdc7384..00000000--- a/harness/tests/scene_runtime/lib/test_instancing.py+++ /dev/null@@ -1,108 +0,0 @@-"""instancing.js — regressions: a multi-material mesh kept only material[0], and a-bucket mergeGeometries could not merge was dropped (a part silently missing)."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("instancing.js",)--# A cottage: walls (a MULTI-material box, timber on +Z), a roof of a second-# material, and a chimney that shares the wall material 2.75 m up — the-# sub-part offset that a bare geometry.clone() would lose.-_ASSET = """-import * as THREE from 'three';-const plaster = new THREE.MeshStandardMaterial({ color: 0xb9a891 });-const tile = new THREE.MeshStandardMaterial({ color: 0x8a4b36 });-const timber = new THREE.MeshStandardMaterial({ color: 0x6d5540 });-function cottage(opts = {}) {- const g = new THREE.Group();- const walls = new THREE.Mesh(new THREE.BoxGeometry(2.6, 1.9, 2.6),- opts.plain ? plaster : [plaster, plaster, plaster, plaster, timber, plaster]);- walls.position.y = 0.95;- g.add(walls);- const roof = new THREE.Mesh(new THREE.ConeGeometry(2, 1.15, 4), tile);- roof.position.y = 2.5;- g.add(roof);- const chimney = new THREE.Mesh(new THREE.BoxGeometry(0.38, 1.1, 0.38), plaster);- chimney.position.set(0.62, 2.75, 0.55);- g.add(chimney);- if (opts.rootAt) g.position.set(...opts.rootAt);- return g;-}-const tris = (geo) => (geo.index ? geo.index.count : geo.attributes.position.count) / 3;-"""---def test_a_multi_material_mesh_keeps_its_second_material():- """`material[0]` for the whole geometry painted the timber front face with- plaster. Each geometry group is its own draw; no triangle lost or doubled."""- out = measure(_ASSET + """-import { instanceAsset } from './lib/instancing.js';-const split = instanceAsset(cottage, [{ position: [0, 0, 0] }]);-const plain = instanceAsset(cottage, [{ position: [0, 0, 0] }],- { buildOpts: { plain: true } });-const rows = (g) => g.children.map((m) => ({- mat: m.material.color.getHexString(), tris: tris(m.geometry) }))- .sort((a, b) => a.mat.localeCompare(b.mat));-const front = split.children.find((m) => m.material.color.getHexString() === '6d5540');-front.geometry.computeBoundingBox();-console.log(JSON.stringify({- split: rows(split), plain: rows(plain),- // the +Z face, and only that face- frontZ: +front.geometry.boundingBox.min.z.toFixed(3),- backZ: +front.geometry.boundingBox.max.z.toFixed(3),-}));-""", _LIBS)- assert out["split"] == [- {"mat": "6d5540", "tris": 2}, # the one face- {"mat": "8a4b36", "tris": 8}, # the roof cone- {"mat": "b9a891", "tris": 22}, # five box faces + the chimney- ], out- # Same triangles either way — the split adds draws, not geometry.- assert sum(r["tris"] for r in out["split"]) == 32, out- assert out["plain"] == [{"mat": "8a4b36", "tris": 8},- {"mat": "b9a891", "tris": 24}], out- assert out["frontZ"] == out["backZ"] == 1.3, out---def test_a_bucket_that_cannot_merge_falls_back_to_draws_not_to_a_hole():- """`mergeGeometries` returns null on an attribute mismatch (a vertex-coloured- piece beside a plain one) and that bucket was dropped."""- out = measure(_ASSET + """-import { instanceAsset } from './lib/instancing.js';-const mixed = () => {- const g = new THREE.Group();- const mat = new THREE.MeshStandardMaterial({ color: 0x777777, vertexColors: true });- const a = new THREE.BoxGeometry(1, 1, 1);- const n = a.attributes.position.count;- a.setAttribute('color', new THREE.BufferAttribute(new Float32Array(n * 3).fill(0.4), 3));- const b = new THREE.BoxGeometry(1, 1, 1); // no color attribute- const m1 = new THREE.Mesh(a, mat); m1.position.y = 0.5;- const m2 = new THREE.Mesh(b, mat); m2.position.y = 2.0;- g.add(m1, m2);- return g;-};-const g = instanceAsset(mixed, [{ position: [0, 0, 0] }, { position: [5, 0, 0] }]);-const geo = g.children[0].geometry;-geo.computeBoundingBox();-const c = geo.attributes.color;-let lo = 9, hi = -9;-for (let i = 0; i < c.count; i++) { lo = Math.min(lo, c.getX(i)); hi = Math.max(hi, c.getX(i)); }-console.log(JSON.stringify({- draws: g.children.length, tris: g.children.reduce((a, m) => a + tris(m.geometry), 0),- top: +geo.boundingBox.max.y.toFixed(3), hasColor: !!c, lo, hi,-}));-""", _LIBS)- assert out["draws"] == 1, out # harmonised, so still ONE draw- assert out["tris"] == 24, out # and both boxes are there- assert out["top"] == 2.5, out # including the one 2 m up- # The geometry that had no colour is filled with white, not with black:- # a vertexColors material reads a missing attribute as zero and the part- # renders black.- assert out["lo"] == pytest.approx(0.4), out- assert out["hi"] == pytest.approx(1.0), out--diff --git a/harness/tests/scene_runtime/lib/test_library.py b/harness/tests/scene_runtime/lib/test_library.pyindex 9760ce72..82aa5ab5 100644--- a/harness/tests/scene_runtime/lib/test_library.py+++ b/harness/tests/scene_runtime/lib/test_library.py@@ -1,13 +1,4 @@-"""The shipped effect library (``starter/src/lib``, D51/D74) as a whole.--Three claims cover every module: it imports under node and-exports every call effects_catalog.md advertises for it; its factories build;-and every program they make compiles on the real renderer, fogged and-unfogged. The ten surface-patch libraries are compiled chain by chain in-test_patch_union.py; ``shader.js``'s own construction paths in test_shader.py.-Per-module behaviour tests exist only for modules generated scenes import, and-for named bugs.-"""+"""The shipped effect library (``starter/src/lib``, D51/D74) as a whole."""from __future__ import annotationsimport json@@ -17,7 +8,7 @@ import pytestfrom codeverse3d.languages.scene_threejs import lib_filesfrom codeverse3d.prompts import PROMPTS_DIR-from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure+from tests.scene_runtime.lib._probe import compile_scene, measurefrom tests.scene_runtime.lib.test_patch_union import LIBRARIES as PATCH_UNIONpytestmark = pytest.mark.node@@ -27,14 +18,10 @@ MODULES = sorted(p.name for p in lib_files())# backticked words in catalog rows that name an option or a hook, not a call_PROSE = {"update", "tick", "ambient", "sunDir", "shadows", "true", "false", "color"}-# One build per module, as a scene calls it: a JS expression over `L` (every-# module's namespace, by stem), THREE, `rand`, `heightAt`, `sunDir`, `scene`,-# `on(patch...)` (a mesh whose standard material wears those patches) and-# `inst(patch...)` (the same as a 4-copy InstancedMesh, flat-shaded — the-# only compile of a patch's USE_INSTANCING branch). Every value is an array-# of Object3Ds to add; await is allowed.+# One build per module, as a scene calls it: a JS expression over `L` (module namespaces by stem), THREE,+# `rand`, `heightAt`, `sunDir`, `scene`, `on(patch...)` (a mesh wearing those patches) and `inst(patch...)`+# (a 4-copy InstancedMesh: the only compile of a patch's USE_INSTANCING branch); each value is an array of Object3Ds.BUILD: dict[str, str] = {- "accumulation.js": "[on((m) => L.accumulation.patchSnow(m), (m) => L.accumulation.patchSand(m))]","aging.js": "[on((m) => L.aging.patchDripStains(m), (m) => L.aging.patchRust(m),"" (m) => L.aging.patchDust(m))]","atmosphere.js": "[L.atmosphere.makeHeightFog({ scene, extent: 30, top: 4, heightAt, seed: 4 }),"@@ -46,7 +33,6 @@ BUILD: dict[str, str] = {" L.building.cityFabric({ rand, width: 60, depth: 60 }).group]; })()","canopy.js": "[L.canopy.makeCanopy({ crowns: [{ position: [0, 4, 0], radius: 2, height: 3 },"" { position: [6, 1, 0], size: [4, 1.5, 1] }], shadows: true })]",- "caustics.js": "[on((m) => L.caustics.patchCaustics(m, { level: 1, sunDir }))]","celestial.js": "[L.celestial.makeHeatShimmer({ seed: 1 }), L.celestial.makeStars({ count: 200, seed: 2 }),"" L.celestial.makeStars({ count: 200, seed: 4, ambient: 0.9 }),"" L.celestial.makeAurora({ seed: 3 }), L.celestial.makeAurora({ seed: 5, ambient: 0.9 })]",@@ -63,11 +49,6 @@ BUILD: dict[str, str] = {" L.environment.makeOutskirts({ inner: 30, heightAt, seed: 2 }),"" L.environment.roomShell({ center: [0, 1.5, 30], extents: [6, 3, 5],"" openings: [{ wall: 'south', width: 1.2, height: 2 }] })]; })()",- "figure.js": "(() => { const a = L.figure.figure({ rand }); L.figure.walk(a, 0.4);"- " const b = L.figure.figure({ rand, fem: 1 }); L.figure.sit(b, 0.45);"- " const c = L.figure.figure({ rand });"- " L.figure.carry(c, new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.1, 0.3), std()));"- " return [a, b, c]; })()","finish.js": "[on((m) => L.finish.patchTranslucency(m, { thickness: 0.01 }),"" (m) => L.finish.patchIridescence(m, { seed: 4 }))]","flock.js": "[L.flock.makeFlock({ count: 60, seed: 4 }),"@@ -81,9 +62,6 @@ BUILD: dict[str, str] = {"godrays.js": "[L.godrays.makeGodRays({ count: 4, height: 5, seed: 4 }),"" L.godrays.makeGodRays({ count: 3, height: 5, ambient: 0.05, seed: 9 })]","grass.js": "[L.grass.makeGrass({ extent: 6, density: 40, heightAt, shadows: true })]",- "instancing.js": "[L.instancing.instanceAsset(() => { const g = new THREE.Group();"- " g.add(new THREE.Mesh(new THREE.BoxGeometry(1, 2, 1), std())); return g; },"- " L.instancing.scatterGrid({ x: 0, z: 0, w: 20, d: 20 }, 5, rand, { tint: 0.2 }))]","materials.js": "['plaster', 'brick', 'granite', 'cobble', 'weatheredWood', 'brushedSteel', 'fabric',"" 'foliage', 'soil', 'skin', 'water', 'glass'].map((n, i) => {"" const k = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),"@@ -92,9 +70,7 @@ BUILD: dict[str, str] = {"new THREE.BoxGeometry(1, 1, 1), std({ color: 0x806040 + i })); k.position.x = i * 2;"" return k; }))]","neon.js": "(() => { const tube = L.neon.makeNeonTube({ radius: 0.05, seed: 5 });"- # the spill chained under two other libraries' patches (D74 keeps windows.js for it)" const wall = on((m) => L.surface_wear.patchMicroBreakup(m),"- " (m) => L.windows.patchWindowInteriors(m, { seed: 4 }),"" (m) => L.neon.patchNeonSpill(m, { sources: [{ position: [0, 1, 1], color: 0xff2e6a }] }));"" return [tube, L.neon.makeNeonTube({ ambient: 0.8, seed: 6 }), wall,"" L.neon.makeLightTrails({ path: [[-10, 0, 0], [10, 0, 0]], seed: 2 })]; })()",@@ -102,31 +78,11 @@ BUILD: dict[str, str] = {" L.noise.displaceY(g, 1, 0.2, 3);"" return [new THREE.Mesh(g, std({ map: L.noise.noiseDataTexture(32,"" (x, y) => L.noise.fbm2(x * 8, y * 8)) }))]; })()",- "place.js": "(() => { const hero = new THREE.Mesh(new THREE.BoxGeometry(2, 3, 2), std());"- " hero.position.y = 1.5; L.place.seat(hero, []);"- " L.place.establishingShot('wide', hero); L.place.alongPath([[0, 0, 0], [5, 0, 0],"- " [5, 0, 5]], 6); const f = L.figure.figure({ rand });"- " L.place.crowdOn(L.place.route([[0, 0, 0], [10, 0, 0], [10, 0, 10]]), [f]).tick(1);"- " return [hero, f]; })()",- "rain.js": "(() => { const car = new THREE.Mesh(new THREE.BoxGeometry(4, 1.4, 2),"- " std({ color: 0x2a3542 })); L.rain.wetten(car);"- " return [car, L.rain.makeRain({ seed: 5, count: 300 }),"- " L.rain.makeSplashes({ seed: 11, count: 100, surfaces: [car] }),"- " L.rain.makePuddle(4, 3, { seed: 3 })]; })()","roadway.js": "[on((m) => L.roadway.patchRoadSurface(m), (m) => L.roadway.patchSeamBand(m),"" (m) => L.roadway.patchTracks(m))]","shader.js": "[]",- "signage.js": "[await L.signage.makeText('OPEN', { size: 0.4, emissive: 0xff3a4e }),"- " await L.signage.makeText('MARKET', { size: 0.5 }),"- " await L.signage.makeText('EST', { size: 0.2, variation: 0 })]","sky.js": "(L.sky.makeSky(scene, {}), [])",- "smalllife.js": "[...['midge', 'butterfly', 'firefly'].map((kind) =>"- " L.smalllife.makeInsects({ kind, count: 20, extent: 3, height: 2, seed: 4 })),"- " L.smalllife.makeReeds({ extent: 4, density: 10, waterY: 0.4, heightAt,"- " shadows: true, seed: 2 })]","strata.js": "[on((m) => L.strata.patchRockStrata(m), (m) => L.strata.patchErosionStreaks(m))]",- "submerged.js": "[on((m) => L.submerged.patchUnderwater(m), (m) => L.submerged.patchThinIce(m)),"- " L.submerged.makeRainRings({ count: 8 })]","surface_wear.js": "[on((m) => L.surface_wear.patchMicroBreakup(m), (m) => L.surface_wear.patchEdgeWear(m))]","terrain.js": "[L.terrain.ground({ size: 40, segments: 24, rand, relief: 4 }).mesh,"" L.terrain.cliff({ length: 20, height: 8, rand }).mesh]",@@ -143,21 +99,12 @@ BUILD: dict[str, str] = {" L.watermist.makeSpray({ origin: [0, 0, 0], seed: 3 })]","waterside.js": "[on((m) => L.waterside.patchShoreWet(m), (m) => L.waterside.patchShoreFoam(m),"" (m) => L.waterside.patchShallowWater(m))]",- "wetground.js": "[L.wetground.makeMirrorFloor(12, 10, { puddleMask: true, seed: 3 }),"- " L.wetground.makeMirrorFloor(6, 6, { fresnel: 0, detail: 0, ripple: 0 })]",- "windows.js": "(() => { const b = L.building.block({ w: 16, d: 12, h: 24, rand, lit: 0.4 });"- " L.windows.makeNightWindows(b, { seed: 3 });"- " return [b, inst((m) => L.windows.patchWindowInteriors(m, { seed: 5 }))]; })()","woodland.js": "[on((m) => L.woodland.patchBark(m, { kind: 'oak' })),"" L.woodland.makeImposters({ count: 30, extent: 20, heightAt })]","cloudvolume.js": "[(() => { const c = L.cloudvolume.makeCloudVolume({ size: [60, 18, 36], quality: 'low',"" seed: 3 }); c.position.y = 20; return c; })()]","fire.js": "[L.fire.makeFire({ radius: 0.3, height: 0.9, quality: 'low', seed: 7 }),"" L.fire.makeCandle({ seed: 2 })]",- "firefield.js": "[L.firefield.makeFireField({ emitters: [{ position: [0, 0, 0], radius: 0.3, height: 1,"- " strength: 1 }, { position: [0.8, 0, 0.2], radius: 0.2, height: 0.6, strength: 0.7 }],"- " quality: 'low', seed: 5 })]",- "ice.js": "[L.ice.makeFracturedIce({ size: [4, 3], thickness: 0.2, seed: 3 })]","lifecycle.js": "(() => { const g = new THREE.Group(); g.add(new THREE.Mesh(new THREE.BoxGeometry(), std()));"" L.lifecycle.attachDisposal(g, L.lifecycle.snapshotResources(g)); return [g]; })()","meadow.js": "[L.meadow.makeMeadow({ size: [2, 2], density: 60, heightAt, seed: 4 })]",@@ -168,27 +115,24 @@ BUILD: dict[str, str] = {" L.rock.makeRockField({ count: 6, radius: 3, seed: 5 })]","sand.js": "[L.sand.makeSandTerrain({ size: [20, 20], seed: 3 })]","smoke.js": "[L.smoke.makeSmoke({ quality: 'low', seed: 2 }), L.smoke.makeSteam({ quality: 'low' })]",- "stream.js": "[L.stream.makeStream({ points: [[0, 0.6, -8], [2, 0.3, 0], [0, 0, 8]], width: 2, depth: 0.3,"- " seed: 4, reflectionSize: 256, obstacles: [{ u: 0.5, lateral: 0.2, radius: 0.3 }] })]","tree.js": "[L.tree.makeTree({ species: 'birch', height: 4, maxLeaves: 600, seed: 3 }),"" L.tree.makeShrub({ maxLeaves: 300, seed: 2 })]",- "waterfall.js": "[L.waterfall.makeWaterfall({ width: 2, height: 3, seed: 4 })]",}# What the GPU compiles here, in groups so xdist spreads the browser boots.# shader.js is compiled through its own construction paths (test_shader.py)-# and the ten patch libraries chain by chain (test_patch_union.py).+# and the seven patch libraries chain by chain (test_patch_union.py).GROUPS: dict[str, tuple[str, ...]] = {"vegetation": ("canopy.js", "cloth.js", "flowers.js", "foliage_shade.js", "grass.js",- "smalllife.js", "woodland.js", "dapple.js"),+ "woodland.js", "dapple.js"),"sky_and_air": ("atmosphere.js", "celestial.js", "clouds.js", "environment.js", "godrays.js","sky.js", "veils.js", "flock.js"),- "water": ("rain.js", "water.js", "watermist.js", "wetground.js", "finish.js"),- "volumes": ("cloudvolume.js", "fire.js", "firefield.js", "smoke.js"),+ "water": ("water.js", "watermist.js", "finish.js"),+ "volumes": ("cloudvolume.js", "fire.js", "smoke.js"),"ground": ("lifecycle.js", "meadow.js", "paving.js", "rock.js", "sand.js", "tree.js"),- "flowing_water": ("ice.js", "ocean.js", "stream.js", "waterfall.js"),- "built": ("building.js", "figure.js", "instancing.js", "materials.js", "merge.js", "neon.js",- "noise.js", "place.js", "signage.js", "terrain.js", "urban.js", "windows.js"),+ "flowing_water": ("ocean.js",),+ "built": ("building.js", "materials.js", "merge.js", "neon.js",+ "noise.js", "terrain.js", "urban.js"),}_PRELUDE = "\n".join(f"import * as L_{m[:-3]} from './lib/{m}';" for m in MODULES) + """@@ -220,8 +164,7 @@ def _builds(modules: tuple[str, ...]) -> str:def test_every_module_is_built_and_compiled_somewhere():- """A module added to the library without a build here, or a group entry- for a module that no longer ships, fails by name."""+ """A module added to the library without a build here, or a group entry for a module that no longer ships, fails by name."""assert set(BUILD) == set(MODULES)grouped = [m for g in GROUPS.values() for m in g]assert len(grouped) == len(set(grouped))@@ -229,10 +172,7 @@ def test_every_module_is_built_and_compiled_somewhere():def test_every_module_imports_and_exports_what_the_catalog_advertises():- """Every module imports under node (a syntax error or a bad import is a- scene that cannot boot), and every call a catalog row names is a real- export of a module that row names — the catalog is the agent's only index,- and a stale name is an import that cannot resolve."""+ """Every module imports under node (a syntax error or a bad import is a scene that cannot boot), and every call a catalog row names is a real export o..."""out = measure("""const names = """ + json.dumps(MODULES) + """;const exports = {}, errors = {};@@ -260,7 +200,7 @@ console.log(JSON.stringify({ exports, errors }));# the planner routes an element to a zone that cannot build it (or, listed short, to a hand-built asset)plan = (PROMPTS_DIR / "tracks" / "plan_scene.j2").read_text(encoding="utf-8")shipped = re.findall(r"`([a-z_]+\.js)`\s*\(([^)]*)\)", plan)- assert len(shipped) >= 13, shipped+ assert len(shipped) >= 9, shippedstale += [f"plan_scene.j2: {n} ({m})" for m, calls in shippedfor n in re.findall(r"`(make[A-Za-z]+)`", calls) if n not in exported.get(m, ())]assert not stale, stale@@ -269,10 +209,7 @@ console.log(JSON.stringify({ exports, errors }));@pytest.mark.parametrize("fog", [True, False], ids=["fogged", "unfogged"])@pytest.mark.parametrize("group", sorted(GROUPS))def test_every_program_compiles_on_the_real_renderer(group, fog, tmp_path):- """The one witness for GLSL: every build above, in a lit scene whose sun- casts (or no depth material compiles), fogged and then not — USE_FOG is a- define, and rain.js shipped a fog branch that could not compile for months- because no fogged scene ever built it."""+ """The one witness for GLSL."""modules = GROUPS[group]scene = _PRELUDE + """export const BOUNDS = { min: [-40, 0, -40], max: [40, 30, 40] };@@ -320,9 +257,6 @@ export async function createScene({ renderer }) {# Named bugs where a factory once built silently broken output from input it# should refuse: (module, call, a phrase the RangeError must carry).REFUSALS = [- # a bend tighter than the bank folded the ribbon into down-facing water- ("stream.js", "makeStream({ points: [[0, 1, 0], [6, .9, 4], [0, .8, 8], [6, .7, 12]], width: 2 })",- "bends tighter"),# a NaN wind direction normalised to NaN and poisoned every dune vertex("sand.js", "makeSandTerrain({ windDirection: [NaN, 1] })", "windDirection"),]@@ -340,79 +274,29 @@ console.log(JSON.stringify({{ error }}));assert out["error"] and phrase in out["error"], out-def test_fire_field_depth_proxies_follow_the_live_occluders():- """Named bug: a proxy for an occluder removed or hidden since the last- capture stayed in the proxy scene for the field's lifetime."""- code, out = compile_scene(r"""-import * as THREE from 'three';-import { makeFireField } from './lib/firefield.js';-export function createScene({ renderer }) {- const root = new THREE.Group(), mat = new THREE.MeshStandardMaterial();- const a = new THREE.Mesh(new THREE.BoxGeometry(), mat), b = new THREE.Mesh(new THREE.BoxGeometry(), mat);- root.add(a, b);- const field = makeFireField({ occluders: [root], quality: 'low' }), depth = field.userData.depthCapture;- const camera = new THREE.PerspectiveCamera(50, 1, .1, 50);- camera.position.set(0, 1, 4); camera.lookAt(0, .5, 0); camera.updateMatrixWorld(true);- const view = new THREE.Vector4(0, 0, 64, 64), counts = [];- depth.capture(renderer, camera, view); counts.push(depth.proxies);- root.remove(b); depth.capture(renderer, camera, view); counts.push(depth.proxies);- a.visible = false; depth.capture(renderer, camera, view); counts.push(depth.proxies);- a.visible = true; depth.capture(renderer, camera, view); counts.push(depth.proxies);- if (counts.join() !== '2,1,0,1') throw Error('proxy counts ' + counts.join());- field.userData.dispose();- return { scene: new THREE.Scene(), cameras: [{ name: 'probe', position: [0, 3, 5], lookAt: [0, 0, 0] }] };-}-""", ("firefield.js",), audit_module="src/scene.js")- assert code == 0, out---def test_the_per_frame_hook_is_taught_as_update_only():- """Every moving factory sets `userData.update` (and keeps a `tick` alias, which 72- recorded zone/env files call); the docs used to teach `tick` while the cookbook- calls a hook named `tick` the `nothing_moves` cause. The docs say `update`."""- taught, unaliased = [], []- for p in sorted(LIB_DIR.glob("*.js")):- src = p.read_text(encoding="utf-8")- taught += [f"{p.name}: {ln.strip()}" for ln in src.splitlines()- if re.match(r"\s*(\*|//)", ln) and "userData.tick" in ln]- if "userData.tick =" in src and "userData.update" not in src:- unaliased.append(p.name)- catalog = (PROMPTS_DIR / "scene_threejs" / "effects_catalog.md").read_text(encoding="utf-8")- assert not taught and not unaliased and "userData.tick" not in catalog, (taught, unaliased)---# One option rule (audit N33): a missing/`null` option takes its default, an invalid one-# throws a RangeError naming it, a seed is any finite number, and the sun is `sunDir`-# everywhere. Before: the same derived seed built in one effect and threw in its-# neighbour (null / 3.7 / 2**40 each refused by some), and ocean ignored `sunDir`.+# One option rule (audit N33): null takes the default, an invalid one throws a RangeError naming it, a seed is+# any finite number, the sun is `sunDir` everywhere (a derived seed built in one effect and threw in its neighbour)._OPTIONS = """import * as THREE from 'three';import { makeFire } from './lib/fire.js';-import { makeFireField } from './lib/firefield.js';import { makeTree } from './lib/tree.js';import { makeMeadow } from './lib/meadow.js';import { makeOceanSurface } from './lib/ocean.js';-import { makeStream } from './lib/stream.js';import { makeSmoke } from './lib/smoke.js';import { makeClouds } from './lib/clouds.js';import { makeCloudVolume } from './lib/cloudvolume.js';-import { makeWaterfall } from './lib/waterfall.js';-import { makeRain } from './lib/rain.js';import { makeSandTerrain } from './lib/sand.js';import { makeRock } from './lib/rock.js';import { makePaving } from './lib/paving.js';-import { makeFracturedIce } from './lib/ice.js';import { readVec3 } from './lib/shader.js';const calls = {- fire: (o) => makeFire(o), firefield: (o) => makeFireField({ emitters: [{ position: [0, 0, 0] }], quality: 'low', ...o }),+ fire: (o) => makeFire(o),tree: (o) => makeTree({ leafDensity: .05, ...o }), meadow: (o) => makeMeadow({ size: [1, 1], density: 20, ...o }),ocean: (o) => makeOceanSurface({ width: 10, depth: 10, segments: 16, ...o }),- stream: (o) => makeStream({ points: [[0, .6, -8], [0, 0, 8]], stoneCount: 4, ...o }),smoke: (o) => makeSmoke({ quality: 'low', ...o }), clouds: (o) => makeClouds({ count: 2, ...o }),- cloudvolume: (o) => makeCloudVolume({ quality: 'low', ...o }), waterfall: (o) => makeWaterfall(o),- rain: (o) => makeRain({ count: 10, ...o }), sand: (o) => makeSandTerrain({ size: [10, 10], segments: 16, ...o }),+ cloudvolume: (o) => makeCloudVolume({ quality: 'low', ...o }),+ sand: (o) => makeSandTerrain({ size: [10, 10], segments: 16, ...o }),rock: (o) => makeRock(o), paving: (o) => makePaving({ size: [2, 2], ...o }),- ice: (o) => makeFracturedIce({ size: [4, 3], ...o }),};const seeds = { null: null, big: 2 ** 40, fraction: 3.7, text: '7' };const run = (f) => { try { f(); return 'ok'; } catch (e) { return e instanceof RangeError ? e.message : 'not a RangeError: ' + e; } };@@ -421,7 +305,7 @@ for (const [name, call] of Object.entries(calls))out.seed[name] = Object.fromEntries(Object.entries(seeds).map(([k, seed]) => [k, run(() => call({ seed }))]));const sunOf = (g) => { let v; g.traverse((o) => { const u = o.material?.uniforms; v ??= (u?.seaSun ?? u?.uSunWorld)?.value; }); return v?.toArray(); };out.sun = { ocean: sunOf(calls.ocean({ sunDir: [0, 1, 0] })), cloudvolume: sunOf(calls.cloudvolume({ sunDir: [0, 1, 0] })) };-out.nullDefaults = run(() => calls.stream({ width: null, speed: null }) && calls.meadow({ height: null }) && calls.ice({ gap: null }));+out.nullDefaults = run(() => calls.meadow({ height: null }));out.fireClamps = run(() => makeFire({ radius: 1e6 }));out.badNames = [run(() => calls.meadow({ height: 'tall' })), run(() => calls.smoke({ spread: 5 })), run(() => calls.cloudvolume({ coverage: 2 }))];out.point = readVec3([1, 2]).toArray().concat(readVec3(null, 4, 5, 6).toArray(), readVec3({ x: 1 }).toArray());@@ -439,29 +323,3 @@ def test_every_factory_reads_its_options_by_one_rule():for phrase, message in zip(("height", "spread", "coverage"), out["badNames"], strict=True):assert phrase in message, out["badNames"]assert out["point"] == [1, 2, 0, 4, 5, 6, 1, 0, 0]---def test_sample_height_is_null_off_the_patch_and_never_throws():- """Audit N36: sand returned its clamped edge height off the patch, ocean kept- extrapolating its waves (and threw on NaN), meadow returned 0."""- out = measure("""-import { makeSandTerrain } from './lib/sand.js';-import { makePaving } from './lib/paving.js';-import { makeFracturedIce } from './lib/ice.js';-import { makeOceanSurface } from './lib/ocean.js';-import { makeMeadow } from './lib/meadow.js';-const objs = { sand: makeSandTerrain({ size: [10, 10], segments: 16 }), paving: makePaving({ size: [4, 4] }),- ice: makeFracturedIce({ size: [8, 6] }), ocean: makeOceanSurface({ width: 10, depth: 10, segments: 16 }),- meadow: makeMeadow({ size: [2, 2], density: 20, heightAt: (x, z) => 0.5 + 0 * x * z }) };-const out = {};-for (const [k, o] of Object.entries(objs)) {- const f = o.userData.sampleHeight;- const at = (...a) => { try { return f(...a); } catch (e) { return 'THROW ' + e.message; } };- out[k] = { inside: at(0.3, 0.2), outside: at(50, 0), nan: at(NaN, 0), badTime: at(0.3, 0.2, NaN) };-}-console.log(JSON.stringify(out));-""", tuple(MODULES))- for name, r in out.items():- assert isinstance(r["inside"], (int, float)), (name, r)- assert r["outside"] is None and r["nan"] is None, (name, r)- assert out["ocean"]["badTime"] is None and out["meadow"]["inside"] == 0.5, outdiff --git a/harness/tests/scene_runtime/lib/test_lifecycle.py b/harness/tests/scene_runtime/lib/test_lifecycle.pydeleted file mode 100644index 222eea34..00000000--- a/harness/tests/scene_runtime/lib/test_lifecycle.py+++ /dev/null@@ -1,57 +0,0 @@-"""Construction-time resource ownership, including independent instance buffers."""-import pytest--from tests.scene_runtime.lib._probe import measure--pytestmark = pytest.mark.node---def test_owned_buffers_shadows_and_explicit_textures_release_once():- out = measure("""-import * as THREE from 'three';-import {snapshotResources,attachDisposal} from './lib/lifecycle.js';-const root=new THREE.Group(), geometry=new THREE.BoxGeometry();-const borrowedMap=new THREE.Texture(), ownedMap=new THREE.DataTexture();-const material=new THREE.MeshStandardMaterial({map:borrowedMap});-const mesh=new THREE.InstancedMesh(geometry,material,2);-mesh.customDepthMaterial=new THREE.MeshDepthMaterial();-mesh.customDistanceMaterial=new THREE.MeshDistanceMaterial();-root.add(mesh,new THREE.Mesh(geometry,material));-const resources=snapshotResources(root);resources.add(ownedMap);-attachDisposal(root,resources);-const callerMesh=new THREE.InstancedMesh(new THREE.BoxGeometry(),material,1);-root.add(callerMesh);-const events={};-for(const [name,res] of Object.entries({geometry,material,mesh,ownedMap,borrowedMap,- depth:mesh.customDepthMaterial,distance:mesh.customDistanceMaterial,- callerMesh,callerGeometry:callerMesh.geometry})) {- events[name]=0;res.addEventListener('dispose',()=>events[name]++);-}-resources.add(borrowedMap); // The attached ownership set is itself a snapshot.-const first=root.userData.dispose(),second=root.userData.dispose();-console.log(JSON.stringify({events,first,second}));-""")- assert out == {"events": {"geometry": 1, "material": 1, "mesh": 1,- "ownedMap": 1, "borrowedMap": 0, "depth": 1,- "distance": 1, "callerMesh": 0, "callerGeometry": 0},- "first": True, "second": False}---def test_borrowed_categories_and_failed_disposer_do_not_skip_cleanup():- out = measure("""-import * as THREE from 'three';-import {snapshotResources,attachDisposal} from './lib/lifecycle.js';-const mesh=new THREE.Mesh(new THREE.BoxGeometry(),new THREE.MeshStandardMaterial());-const resources=snapshotResources(mesh,{materials:false});-let geometry=0,material=0,extra=0,failures=0;-mesh.geometry.addEventListener('dispose',()=>geometry++);-mesh.material.addEventListener('dispose',()=>material++);-resources.add({dispose(){throw new Error('broken extension');}});-resources.add({dispose(){extra++;}});-attachDisposal(mesh,resources);-try {mesh.userData.dispose();} catch(error) {failures=error.errors.length;}-const repeated=mesh.userData.dispose();-console.log(JSON.stringify({geometry,material,extra,failures,repeated}));-""")- assert out == {"geometry": 1, "material": 0, "extra": 1,- "failures": 1, "repeated": False}diff --git a/harness/tests/scene_runtime/lib/test_light_probe.py b/harness/tests/scene_runtime/lib/test_light_probe.pydeleted file mode 100644index f6dffc73..00000000--- a/harness/tests/scene_runtime/lib/test_light_probe.py+++ /dev/null@@ -1,78 +0,0 @@-"""Effects must choose a light that actually contributes at their sample point."""-from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import measure--pytestmark = pytest.mark.node--[email protected](scope="module")-def lights():- return measure("""-import * as THREE from 'three';-import { makeLightProbe } from './lib/shader.js';-const read = makeLightProbe(), near = new THREE.Vector3();-const selected = (lights) => {- const scene = new THREE.Scene(); scene.add(...lights);- const value = read(scene, near);- return { sun: value.sun?.name ?? null, point: value.point?.name ?? null };-};-const directional = (name, color, intensity) => {- const light = new THREE.DirectionalLight(color, intensity); light.name = name; return light;-};-const point = (name, color, intensity, x, range = 0, decay = 2) => {- const light = new THREE.PointLight(color, intensity, range, decay);- light.position.x = x; light.name = name; return light;-};-const results = {- directionalColor: selected([directional('red', 0xff0000, 2), directional('green', 0x00ff00, 1)]),- black: selected([directional('black', 0, 1e6), point('black', 0, 1e6, .1)]),- pointColor: selected([point('red', 0xff0000, 2, 2), point('green', 0x00ff00, 1, 2)]),- outsideRange: selected([point('out', 0xffffff, 1e6, 2, 1), point('in', 0xffffff, 1, 3)]),- smoothRange: selected([point('edge', 0xffffff, 100, 9.99, 10), point('far', 0xffffff, 1, 20)]),- decay: selected([point('decaying', 0xffffff, 100, 10), point('constant', 0xffffff, 2, 10, 0, 0)]),-};-const scene = new THREE.Scene(), hidden = new THREE.Group(); hidden.visible = false;-hidden.add(directional('hidden', 0xffffff, 1e6), point('hidden', 0xffffff, 1e6, .1));-scene.add(hidden, new THREE.AmbientLight(0xff0000, .5), new THREE.HemisphereLight(0x00ff00, 0x0000ff, 2));-const rig = new THREE.Group(); rig.position.set(3, 4, 5);-const sun = directional('world', 0xffffff, 1); sun.position.set(2, 3, 4);-sun.target.position.set(2, 1, 4); rig.add(sun, sun.target); scene.add(rig);-const value = read(scene, near);-results.world = { sun: value.sun.name, point: value.point?.name ?? null,- direction: value.sunDirection.toArray(), ambient: value.ambient.toArray(),- sky: value.sky.toArray(), ground: value.ground.toArray() };-const empty = read(new THREE.Scene());-results.reset = { sun: empty.sun, point: empty.point, direction: empty.sunDirection.toArray(),- ambient: empty.ambient.toArray(), sky: empty.sky.toArray(), ground: empty.ground.toArray() };-console.log(JSON.stringify(results));-""")---def test_directional_selection_uses_emitted_color(lights):- assert lights["directionalColor"]["sun"] == "green"- assert lights["black"] == {"sun": None, "point": None}--[email protected]("case,expected", [- ("pointColor", "green"), ("outsideRange", "in"),- ("smoothRange", "far"), ("decay", "constant"),-])-def test_point_selection_accounts_for_color_range_and_decay(lights, case, expected):- assert lights[case]["point"] == expected---def test_visible_scene_lights_sum_and_use_world_space(lights):- world = lights["world"]- assert world["sun"] == "world" and world["point"] is None- assert world["direction"] == pytest.approx([0, 1, 0])- assert world["ambient"] == pytest.approx([.5, 0, 0])- assert world["sky"] == pytest.approx([0, 2, 0])- assert world["ground"] == pytest.approx([0, 0, 2])---def test_reused_probe_clears_previous_scene_lights(lights):- assert lights["reset"] == {"sun": None, "point": None, "direction": [0, 1, 0],- "ambient": [0, 0, 0], "sky": [0, 0, 0], "ground": [0, 0, 0]}diff --git a/harness/tests/scene_runtime/lib/test_materials.py b/harness/tests/scene_runtime/lib/test_materials.pydeleted file mode 100644index b852d3a5..00000000--- a/harness/tests/scene_runtime/lib/test_materials.py+++ /dev/null@@ -1,99 +0,0 @@-"""materials.js (imported by the library's own factories): a city of one look costs one-material bucket, and every noise map tiles without a seam."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_CACHE = """-import * as MAT from './lib/materials.js';-const mats = new Set(), tex = new Set();-for (let i = 0; i < 2552; i++) {- const m = MAT.plaster({ variant: (i * 0.37) % 1, color: 0xd8cfc0 });- mats.add(m.uuid);- for (const s of ['map', 'roughnessMap']) if (m[s]) tex.add(m[s].uuid);-}-const seeded = new Set(), seededTex = new Set();-for (let i = 0; i < 500; i++) {- const m = MAT.foliage({ color: 0x3d662f, scale: 16, seed: 40 + i * 7 });- seeded.add(m.uuid);- for (const s of ['map', 'roughnessMap']) if (m[s]) seededTex.add(m[s].uuid);-}-console.log(JSON.stringify({ fabricMaterials: mats.size, fabricTextures: tex.size,- seededMaterials: seeded.size, seededTextures: seededTex.size }));-"""--[email protected](scope="module")-def cache() -> dict:- return measure(_CACHE, ("materials.js",))---def test_a_city_of_one_look_costs_one_material_bucket(cache):- """2 552 plaster calls at jittered variants collapse to the 9 variant buckets- (and their texture pairs), not 2 552 materials / 1 309 textures."""- assert cache["fabricMaterials"] <= 9, cache- assert cache["fabricTextures"] <= 18, cache---def test_a_per_copy_seed_does_not_buy_a_per_copy_texture(cache):- assert cache["seededMaterials"] <= 6 and cache["seededTextures"] <= 12, cache---_ALBEDO = """-import * as MAT from './lib/materials.js';-const out = {};-// SEAMS: a repeated map whose lattice does not wrap shows a hard line at-// every tile edge. Compare the wrap-edge step (last column against the-// first) with an interior step of the same texture: a seamless field makes-// them the same size, an unwrapped one makes the wrap ~12x bigger.-const seam = (o) => {- const t = MAT.noiseTexture(o), d = t.image.data, n = t.image.width;- let wrapX = 0, innerX = 0, wrapY = 0, innerY = 0;- for (let y = 0; y < n; y++) {- wrapX += Math.abs(d[(y * n + n - 1) * 4] - d[y * n * 4]);- innerX += Math.abs(d[(y * n + n / 2 - 1) * 4] - d[(y * n + n / 2) * 4]);- }- for (let x = 0; x < n; x++) {- wrapY += Math.abs(d[((n - 1) * n + x) * 4] - d[x * 4]);- innerY += Math.abs(d[(n / 2 - 1) * n * 4 + x * 4] - d[(n / 2) * n * 4 + x * 4]);- }- return { wrapX: wrapX / n, innerX: innerX / n, wrapY: wrapY / n, innerY: innerY / n };-};-out.seams = {- soil: seam({ scale: 20, seed: 3, contrast: 0.4, hueBreak: 0.18 }),- wood: seam({ scale: 8, seed: 5, contrast: 0.4, streak: 0.9 }),- steel: seam({ scale: 18, seed: 2, contrast: 0.12, streak: 0.95 }),- rough: seam({ scale: 34, seed: 50, contrast: 0.5, linear: true }),- fractional: seam({ scale: 10.2, seed: 8, contrast: 0.5 }),-};-// The field still averages the authored colour after the wrap.-const meanOf = (o) => { const d = MAT.noiseTexture(o).image.data; let s = 0, n = 0;- for (let i = 0; i < d.length; i += 4) { s += d[i]; n++; } return s / n / 255; };-out.means = { soil: meanOf({ scale: 20, seed: 3, contrast: 0.4 }),- plain: meanOf({ scale: 6, seed: 1, contrast: 0.3 }) };-console.log(JSON.stringify(out));-"""--[email protected](scope="module")-def albedo() -> dict:- return measure(_ALBEDO, ("materials.js",))---def test_every_noise_map_tiles_without_a_seam(albedo):- """Measured 2026-09-01: the reference lattice did not wrap, so a soil map's- wrap edge stepped 11.83 grey levels against an interior 0.94 — the hard grid- lines a 120 m ground at repeat 10 showed as paving joints in the dirt."""- for name, s in albedo["seams"].items():- assert s["wrapX"] <= max(1.6 * s["innerX"], 1.0), (name, s)- assert s["wrapY"] <= max(1.6 * s["innerY"], 1.0), (name, s)---def test_the_wrapped_field_still_delivers_the_authored_colour(albedo):- """A colour map MULTIPLIES the authored colour, so the field must still- average ~0.5 of full scale after the lattice wrap (base 1, so ~0.93 here)."""- for name, m in albedo["means"].items():- assert 0.85 <= m <= 1.0, (name, m)diff --git a/harness/tests/scene_runtime/lib/test_merge.py b/harness/tests/scene_runtime/lib/test_merge.pyindex dbe3e79b..c7671159 100644--- a/harness/tests/scene_runtime/lib/test_merge.py+++ b/harness/tests/scene_runtime/lib/test_merge.py@@ -1,5 +1,4 @@-"""merge.js — regressions: the merged material kept only colour, a mirrored piece baked-inside out, and a patched batch lost its patch chain."""+"""merge.js — regressions."""from __future__ import annotationsimport pytest@@ -9,63 +8,9 @@ pytestmark = pytest.mark.node_LIBS = ("merge.js",)-def test_the_surface_response_survives_the_merge():- """The rebuilt material dropped `emissive` (lanterns rendered as dead grey- blocks) and `side` (DoubleSide slats were culled); a batch that disagrees- about the response says so."""- out = measure("""-import * as THREE from 'three';-import { mergeStatic } from './lib/merge.js';-const tex = new THREE.Texture();-const mat = new THREE.MeshStandardMaterial({- color: 0x334455, roughness: 0.31, metalness: 0.22, side: THREE.DoubleSide,- emissive: new THREE.Color(0xff9944), emissiveIntensity: 2.6,- transparent: true, opacity: 0.8, envMapIntensity: 1.7, flatShading: true,- normalMap: tex, aoMap: tex, alphaMap: tex, dithering: true,-});-mat.normalScale.set(0.4, 0.4);-const mk = (m) => new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), m);-const one = mergeStatic([mk(mat)]).material;--// a batch whose second piece disagrees about more than colour warns once-const warns = [];-const realWarn = console.warn;-console.warn = (msg) => warns.push(String(msg));-const odd = new THREE.MeshStandardMaterial({ color: 0x334455, roughness: 0.9 });-mergeStatic([mk(mat), mk(odd)]);-mergeStatic([mk(mat), mk(mat.clone())]); // colour-equal: no warning-console.warn = realWarn;--console.log(JSON.stringify({- emissive: one.emissive.getHexString(),- emissiveIntensity: one.emissiveIntensity,- doubleSide: one.side === THREE.DoubleSide,- roughness: one.roughness, metalness: one.metalness,- opacity: one.opacity, transparent: one.transparent,- envMapIntensity: one.envMapIntensity, flatShading: one.flatShading,- dithering: one.dithering,- maps: ['normalMap', 'aoMap', 'alphaMap'].filter((k) => one[k] === tex).length,- normalScale: one.normalScale.x,- // colour is NOT copied: it lives per-vertex, and copying it would- // multiply the bake a second time- white: one.color.getHex() === 0xffffff,- warnCount: warns.length, warned: warns.join(' ').includes('surface response'),-}));-""", _LIBS)- assert out["emissive"] == "ff9944" and out["emissiveIntensity"] == 2.6, out- assert out["doubleSide"], "side dropped — back-facing cards disappear"- assert out["transparent"] and out["opacity"] == 0.8, out- assert out["envMapIntensity"] == 1.7 and out["flatShading"], out- assert out["dithering"], "dithering dropped — merged gradients band"- assert out["maps"] == 3 and out["normalScale"] == 0.4, out- assert abs(out["roughness"] - 0.31) < 1e-6, out- assert out["white"], "the first material's colour was copied AND baked"- assert out["warnCount"] == 1 and out["warned"], out-def test_a_mirrored_piece_is_not_baked_inside_out():- """`scale.x = -1` reverses the winding once baked; the slab rendered as its- own interior until the bake flipped it back."""+ """`scale.x = -1` reverses the winding once baked."""out = measure("""import * as THREE from 'three';import { mergeStatic } from './lib/merge.js';@@ -108,43 +53,3 @@ console.log(JSON.stringify({ plain, mirrored, nonIdx, both }));out_faces, tris = out[name]assert tris > 0 and out_faces == tris, (f"{name}: {out_faces}/{tris} triangles wind outward")---def test_a_shader_patched_batch_keeps_its_patch():- """Rebuilding the material threw the patch chain away; it is replayed over- the SOURCE uniform map, so one `tickShaders` still advances both."""- out = measure("""-import * as THREE from 'three';-import { mergeStatic } from './lib/merge.js';-import { patchStandard, tickShaders } from './lib/shader.js';-const mat = new THREE.MeshStandardMaterial({ color: 0x8b8377 });-patchStandard(mat, { name: 'Strata', uniforms: { uBand: { value: 0.4 } },- fragmentBody: 'diffuseColor.rgb *= 1.0 - uBand;' });-patchStandard(mat, { name: 'Streaks', fragmentBody: 'diffuseColor.rgb *= 0.9;' });-const merged = mergeStatic([new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), mat)]);-const mm = merged.material;-const s = { uniforms: {}, vertexShader: '#include <begin_vertex>',- fragmentShader: '#include <color_fragment>' };-mm.onBeforeCompile(s, null);-const root = new THREE.Group();-root.add(merged);-tickShaders(root, 3.25);-console.log(JSON.stringify({- patches: (mm.userData.astraPatches || []).map((p) => p.name),- key: mm.customProgramCacheKey(),- sharedUniforms: mm.userData.uniforms === mat.userData.uniforms,- glslInOrder: s.fragmentShader.indexOf('1.0 - uBand')- < s.fragmentShader.indexOf('*= 0.9'),- boundUniform: s.uniforms.uBand !== undefined,- ticked: mat.userData.uniforms.uTime.value,- stillVertexColors: mm.vertexColors === true,-}));-""", ("merge.js", "shader.js"))- assert out["patches"] == ["Strata", "Streaks"], out- assert out["key"] == "astra:Strata+Streaks", out- assert out["sharedUniforms"], "the merged material got a dead uniform map"- assert out["glslInOrder"] and out["boundUniform"], out- assert out["ticked"] == 3.25, "tickShaders no longer reaches the patch"- assert out["stillVertexColors"], "the replay dropped vertexColors"--diff --git a/harness/tests/scene_runtime/lib/test_noise.py b/harness/tests/scene_runtime/lib/test_noise.pydeleted file mode 100644index 256ab725..00000000--- a/harness/tests/scene_runtime/lib/test_noise.py+++ /dev/null@@ -1,82 +0,0 @@-"""noise.js (82 recorded scenes import it): seeded, non-flat, tiling."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_PROBE = """-import * as THREE from 'three';-import { mulberry32, fbm2, fbm3, noiseDataTexture, displaceY } from './lib/noise.js';--const build = (seed) => {- const g = new THREE.PlaneGeometry(160, 160, 64, 64);- g.rotateX(-Math.PI / 2);- displaceY(g, 14, 0.02, seed);- return g;-};-const a = build(3).attributes.position, b = build(3).attributes.position, c = build(9).attributes.position;-let minY = 1e9, maxY = -1e9, maxSame = 0, maxOther = 0;-for (let i = 0; i < a.count; i++) {- minY = Math.min(minY, a.getY(i)); maxY = Math.max(maxY, a.getY(i));- maxSame = Math.max(maxSame, Math.abs(a.getY(i) - b.getY(i)));- maxOther = Math.max(maxOther, Math.abs(a.getY(i) - c.getY(i)));-}-const n = build(3).attributes.normal;-let tilted = 0;-for (let i = 0; i < n.count; i++) if (n.getY(i) < 0.999) tilted++;--const tex = noiseDataTexture(64, (u, v) => 0.5 + 0.5 * fbm2(u * 6, v * 6, { seed: 5 }));-const d = tex.image.data;-let tMin = 255, tMax = 0;-for (let i = 0; i < d.length; i += 4) { tMin = Math.min(tMin, d[i]); tMax = Math.max(tMax, d[i]); }--const r1 = mulberry32(42), r2 = mulberry32(42);-let seqSame = true, inRange = true;-for (let i = 0; i < 100; i++) { const v1 = r1(), v2 = r2(); if (v1 !== v2) seqSame = false; if (!(v1 >= 0 && v1 < 1)) inRange = false; }--let fMin = 1e9, fMax = -1e9, fDiff = 0;-for (let i = 0; i < 400; i++) {- const x = (i % 20) * 0.37, z = Math.floor(i / 20) * 0.53;- const v = fbm2(x, z, { seed: 1 });- fMin = Math.min(fMin, v); fMax = Math.max(fMax, v);- fDiff = Math.max(fDiff, Math.abs(v - fbm2(x, z, { seed: 2 })));- const v3 = fbm3(x, 0.7, z, { octaves: 5 });- fMin = Math.min(fMin, v3); fMax = Math.max(fMax, v3);-}-console.log(JSON.stringify({ yRange: maxY - minY, maxSame, maxOther, tiltedFrac: tilted / n.count,- wraps: tex.wrapS === THREE.RepeatWrapping && tex.wrapT === THREE.RepeatWrapping,- mipmapped: tex.minFilter === THREE.LinearMipmapLinearFilter && tex.generateMipmaps === true,- texSpread: tMax - tMin, seqSame, inRange, fMin, fMax, fDiff }));-"""--[email protected](scope="module")-def probe() -> dict:- return measure(_PROBE, ("noise.js",))---def test_displaced_plane_is_not_flat_and_normals_follow(probe):- assert probe["yRange"] > 5, probe["yRange"]- assert probe["tiltedFrac"] > 0.5, probe["tiltedFrac"]---def test_same_seed_rebuilds_the_identical_terrain(probe):- assert probe["maxSame"] == 0 and probe["maxOther"] > 0.5, probe---def test_noise_texture_wraps_filters_and_is_non_uniform(probe):- """RepeatWrapping for tiled maps, mipmaps so a puddle mask does not tear- into stair-steps at grazing angles, and real content."""- assert probe["wraps"] and probe["mipmapped"]- assert probe["texSpread"] > 30, probe["texSpread"]---def test_mulberry32_is_reproducible_and_uniform_range(probe):- assert probe["seqSame"] and probe["inRange"]---def test_fbm_stays_normalized(probe):- assert probe["fMin"] >= -1.001 and probe["fMax"] <= 1.001, probe- assert probe["fMax"] - probe["fMin"] > 0.5 and probe["fDiff"] > 0.1, probediff --git a/harness/tests/scene_runtime/lib/test_patch_union.py b/harness/tests/scene_runtime/lib/test_patch_union.pyindex 8d9e9ed2..a3601f1a 100644--- a/harness/tests/scene_runtime/lib/test_patch_union.py+++ b/harness/tests/scene_runtime/lib/test_patch_union.py@@ -1,21 +1,4 @@-"""The ten surface-patch libraries on ONE material: the names each owns, and-every chain of them on the real renderer.--terrain_shade, waterside, surface_wear, aging, accumulation, strata, damp,-roadway, caustics and submerged are written to land on the same materials —-a submerged, weathered, splatted bank wears half of them at once — and-`patchStandard` chains whatever it is handed. Every way that goes wrong is-silent or far from its cause. patchStandard DROPS a repeated uniform or-varying and keeps the first, so a name two libraries share leaves one patch-reading the other's value with nothing reported; a helper two libraries both-define is deduped while the bodies match and THROWS the day either is edited;-a main() local two bodies both declare is a redefinition that takes the whole-material down; and a chain that compiles in one order, one variant or next-to one neighbour only is a scene that renders black the day an author picks-another.--This file is the GPU compile of these ten for test_library.py.-"""+"""The seven surface-patch libraries on ONE material."""from __future__ import annotationsimport itertools@@ -36,18 +19,15 @@ from tests.scene_runtime.lib._probe import (pytestmark = pytest.mark.node-# The ten, and the patches each ships.+# The seven, and the patches each ships.LIBRARIES: dict[str, tuple[str, ...]] = {"terrain_shade.js": ("patchTriplanar", "patchSlopeSplat"),"waterside.js": ("patchShoreWet", "patchShoreFoam", "patchShallowWater"),"surface_wear.js": ("patchMicroBreakup", "patchEdgeWear"),"aging.js": ("patchDripStains", "patchRust", "patchDust"),- "accumulation.js": ("patchSnow", "patchSand"),"strata.js": ("patchRockStrata", "patchErosionStreaks"),"damp.js": ("patchMoss", "patchMoisture", "patchCrackedMud"),"roadway.js": ("patchRoadSurface", "patchSeamBand", "patchTracks"),- "caustics.js": ("patchCaustics",),- "submerged.js": ("patchUnderwater", "patchThinIce"),}ALL = [p for patches in LIBRARIES.values() for p in patches]@@ -56,16 +36,6 @@ ALL = [p for patches in LIBRARIES.values() for p in patches]# WORLD_VARYINGS), so a material wearing several declares ONE.SHARED = {"uniform": {"uTime"}, "varying": {"vAstraWorld", "vAstraWorldN"}}-# Each library's name prefix, so a name added later stays inside its library-# rather than merely missing today's neighbours.-SPELLING = {- "caustics.js": {"uniform": ("uCau",), "local": ("cau",)},- "submerged.js": {"uniform": ("uSub", "uIce"), "local": ("sub", "ice"),- "helper": ("astraIce",)},- "strata.js": {"helper": ("astraStrata",)},- "roadway.js": {"helper": ("astraRoad",)},-}-# Every patch at its defaults, but the splat's snow line pulled into frame# so its snow branch is live code. Shared by the probe and the scene._APPLY_JS = "\n".join(@@ -92,30 +62,12 @@ _DECL = re.compile(r"^\s*(?:uniform|varying)\s+(?:(?:lowp|mediump|highp)\s+)?\w+def _unguarded(src: str) -> str:- """Drop ``#ifndef X ... #endif`` blocks, which may repeat verbatim.-- terrain_shade ships astraFbmUnit from two patches behind one guard, so the- TEXT carries it twice and the preprocessor keeps one. Only an unguarded- repeat is a redefinition.- """+ """Drop ``#ifndef X ..."""return re.sub(r"#ifndef\b.*?#endif", "", src, flags=re.S)def test_no_library_declares_a_name_another_owns():- """All 45 pairs, both stages, four kinds of name — each library compiled- ALONE, so a clash is caught however the two ever meet. Uniforms by the- keys patchStandard merges (the map it dedupes silently), varyings and- helpers by the heads, locals by what the bodies declare inside main().-- Then every chain at once, forward and reversed: no declaration, helper- or main() local may appear twice in either stage. And each library's- vertex stage is its world base and no more: the point and normal it- writes fold in `instanceMatrix` (the vertex hook runs before- <project_vertex>, so without it every copy of a scattered rock shades- from the mesh ORIGIN), three declares that attribute itself, nothing- fragment-only is called there (the util block ships in both stages, so- fwidth and astraStroke may be DEFINED in it, never called), and nothing- displaces `transformed`, or a hard-edged bed would tear open at its rim."""+ """All 45 pairs, both stages, four kinds of name — each library compiled ALONE, so a clash is caught however the two ever meet."""out = measure(SHADER_JS + """import * as THREE from 'three';import { GLSL_UTIL } from './lib/shader.js';@@ -152,12 +104,6 @@ console.log(JSON.stringify({ per, util: GLSL_UTIL, forward: union(ALL),for (a, mine), (b, theirs) in itertools.combinations(owns.items(), 2)for kind in mine if (both := mine[kind] & theirs[kind])]assert not clashes, "\n".join(clashes)- for lib, rules in SPELLING.items():- for kind, stems in rules.items():- names = owns[lib][kind]- assert names, (lib, kind)- stray = sorted(n for n in names if not n.startswith(stems))- assert not stray, f"{lib}: {kind}(s) outside {stems}: {stray}"for order in ("forward", "reversed"):for stage in ("vs", "fs"):@@ -167,42 +113,21 @@ console.log(JSON.stringify({ per, util: GLSL_UTIL, forward: union(ALL),("main() local", _LOCAL.findall(_main_body(src)))):twice = sorted(n for n, c in Counter(found).items() if c > 1)assert not twice, f"{order} chain, {stage}: {kind}(s) {twice} twice"-+ # each library's vertex stage is its world base and no more: instancing folds in `instanceMatrix`+ # (else every copy of a scattered rock shades from the mesh origin), no stage-split varying,+ # nothing displaces `transformed` (a hard-edged bed would tear open at its rim)for lib, got in out["per"].items():vs, fs = got["vs"], got["fs"]body = _main_body(vs)p = _find(r"vAstraWorld = \(modelMatrix \* (\w+)\)\.xyz;", body).group(1)- n = _find(r"vAstraWorldN = astraNormalTransform\(mat3\(modelMatrix\), (\w+)\);",- body).group(1)- assert "#ifdef USE_INSTANCING" in body, libassert f"{p} = instanceMatrix * {p};" in body, (lib, p)- assert f"{n} = astraNormalTransform(mat3(instanceMatrix), {n});" in body, (lib, n)- assert "attribute mat4 instanceMatrix" not in vs, lib- # A varying declared in one stage only is a link failure, and the- # symptom is the patch simply not drawing.assert set(_VARYING.findall(vs)) == set(_VARYING.findall(fs)), lib- assert SHARED["varying"] <= set(_VARYING.findall(vs)), lib- called = [t for t in ("fwidth(", "dFdx(", "dFdy(", "astraStroke(") if t in body]- assert not called and "gl_FragCoord" not in vs, (lib, called)assert not re.search(r"\btransformed\s*[-+*/]?=", body), lib-# Every chain the scene compiles: (material name, patches, options, instances).-# Each patch ALONE: only that catches a body reading a uniform, helper or-# local that a sibling patch or another library declares, because every-# bigger chain supplies it. Then all of them on one material, forward and-# reversed (a body that reads what a LATER one declares fails one of the-# two) — the case terrain_shade's own two patches once failed together-# ('astraWp' redefinition, 'astraFbmUnit' already has a body: a dead-# material, found only when a sibling library landed on the same bank) —-# and across the variants that change the program: flat shading-# (three omits vNormal), instancing (the only compile of each base's-# USE_INSTANCING branch), transparency (three defines OPAQUE otherwise),-# maps with a bump map and vertex colours (three's own uv and colour-# varyings arrive), and `fog: false` — the fogless branch the waterline-# sheen falls back to, which in a fogged scene only a fogless material-# compiles. The variants share programs because each whole-chain program-# costs about a second and a half of ANGLE's time on this GPU.+# Every chain the scene compiles: (name, patches, options, instances). Each patch ALONE (catches a body+# reading what a sibling declares), all of them forward and reversed, and the variants that change the+# program: flat shading, instancing (the only compile of USE_INSTANCING), transparency, maps, `fog: false`.MATERIALS: list[tuple[str, list[str], dict, int]] = [*((f"{name} alone", [name], {}, 0) for name in ALL),("every patch", ALL, {}, 0),@@ -212,20 +137,13 @@ MATERIALS: list[tuple[str, list[str], dict, int]] = [{"transparent": True, "opacity": 0.6, "textured": True, "fog": False}, 0),]-# A workspace SCENE for check_shaders.mjs, which boots it through the host:-# fogged, because USE_FOG is a define and a define that is never set compiles-# nothing (rain.js shipped a fog branch that could not compile at all for-# months behind exactly that); a sun that CASTS, or no program carries the-# shadow-map chunks; a camera, or the host reports the scene as not booted-# and never reaches the compile stage. Around the chains: terrain.js's-# ground and cliff wearing the splat and the triplanar as the terrain suite-# shipped them, and the rain rings, which assemble their OWN shader and so-# take their fog and depth chunks from makeShaderMaterial alone.+# A workspace SCENE for check_shaders.mjs: fogged (USE_FOG is a define, never compiled otherwise), a+# CASTING sun (else no shadow-map chunks), a camera (else the host reports no boot), plus terrain.js's+# ground and cliff wearing the splat and triplanar._SCENE = """import * as THREE from 'three';import { tickShaders } from './lib/shader.js';import { ground, cliff } from './lib/terrain.js';-import { makeRainRings } from './lib/submerged.js';""" + _APPLY_JS + """const MATERIALS = """ + json.dumps(MATERIALS) + """;@@ -291,7 +209,7 @@ export function createScene({ renderer }) {const wall = cliff({ length: 30, height: 12, rand });tag(patchTriplanar(wall.mesh.material, { scale: 3.5 }), 'cliff() with patchTriplanar');wall.mesh.position.set(0, 0, -20);- scene.add(land.mesh, wall.mesh, makeRainRings({ count: 16 }));+ scene.add(land.mesh, wall.mesh);return {scene,cameras: [{ name: 'hero', position: [0, 16, 26], lookAt: [0, 1, 0], fov: 60 }],@@ -302,9 +220,7 @@ export function createScene({ renderer }) {def _library_line(glsl: str | None) -> str:- """Where a quoted GLSL line lives in the library. The report maps a line- back through template strings, and these libraries write their GLSL as- arrays of quoted lines, which it cannot see."""+ """Where a quoted GLSL line lives in the library."""needle = (glsl or "").strip()hits = [f"{lib}:{n}" for lib in (*LIBRARIES, "shader.js")for n, text in enumerate((LIB_DIR / lib).read_text(encoding="utf-8").splitlines(), 1)@@ -313,14 +229,7 @@ def _library_line(glsl: str | None) -> str:def test_every_chain_compiles_on_the_real_renderer(tmp_path):- """The only witness that counts. Everything above reads strings; whether- the GPU takes every chain of the ten — two dozen bodies in one main, each- library's instancing branch, the fog and no-fog branches, flat and- textured variants, a Voronoi with nested loops, a refract into a parallax- — cannot be asserted from source, and a patch that does not compile is- worth nothing. Runs the preflight the authoring agent runs, on our own- renderer; a failure names the library line, the GLSL error and the chain- whose program did not link."""+ """The only witness that counts."""report_path = tmp_path / "report.json"code, out = compile_scene(_SCENE, (*LIBRARIES, "terrain.js"), report=report_path)@@ -332,7 +241,7 @@ def test_every_chain_compiles_on_the_real_renderer(tmp_path):assert code == 0 and report["ok"] and not problems, "\n".join(problems) or outcompiled = report["compile"]assert compiled["gpu"], "this claim is only worth a real GPU"- # Every chain above is its own program (plus ground, cliff and rings):+ # Every chain above is its own program (plus ground and cliff):# a green exit on a compile that skipped them would prove nothing.- assert compiled["custom_materials"] >= len(MATERIALS) + 3, compiled- assert compiled["programs"] >= len(MATERIALS) + 3, compiled+ assert compiled["custom_materials"] >= len(MATERIALS) + 2, compiled+ assert compiled["programs"] >= len(MATERIALS) + 2, compileddiff --git a/harness/tests/scene_runtime/lib/test_place.py b/harness/tests/scene_runtime/lib/test_place.pydeleted file mode 100644index acaf5c28..00000000--- a/harness/tests/scene_runtime/lib/test_place.py+++ /dev/null@@ -1,265 +0,0 @@-"""place.js — regressions: buried and roof-top cameras, seat under an arch, a ridge-blocked-establishing shot, ping-pong wheels, and an open path a gap short."""-from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node--_LIBS = ("place.js",)---_PROBE = """-import * as THREE from 'three';-import { shot } from './lib/place.js';--// A bumpy ground whose surface sits around y = 3.-const geo = new THREE.PlaneGeometry(80, 80, 40, 40);-geo.rotateX(-Math.PI / 2);-const gp = geo.attributes.position;-for (let i = 0; i < gp.count; i++) {- gp.setY(i, 3 + Math.sin(gp.getX(i) * 0.35) * 1.2- + Math.cos(gp.getZ(i) * 0.25) * 0.8);-}-geo.computeVertexNormals();-const ground = new THREE.Mesh(geo, new THREE.MeshBasicMaterial());-ground.updateMatrixWorld(true);--const groundAt = (x, z) => {- const r = new THREE.Raycaster(new THREE.Vector3(x, 200, z),- new THREE.Vector3(0, -1, 0));- return r.intersectObject(ground, true)[0].point.y;-};-const surfaceY = groundAt(0, 0);--// A wall directly between the camera and its subject, 0.4 m away.-const wall = new THREE.Mesh(new THREE.BoxGeometry(30, 40, 0.5),- new THREE.MeshBasicMaterial());-wall.position.set(0, surfaceY + 20, -0.65); // near face at z = -0.4-wall.updateMatrixWorld(true);--// The measured failure shape: requested 1 m BELOW the surface and-// 0.4 m from a wall that fills the frame.-const cam = shot('street', [0, surfaceY - 1, 0], [0, surfaceY + 2, -30],- 55, [ground, wall]);--console.log(JSON.stringify({- surfaceY,- camY: cam.position[1],- groundAtCam: groundAt(cam.position[0], cam.position[2]),-}));-"""--[email protected](scope="module")-def probe() -> dict:- return measure(_PROBE, _LIBS)---def test_a_buried_camera_is_lifted_above_the_ground_it_shoots_from(probe):- """A camera below its own terrain photographs the unlit backside.-- The Santorini failure: 3 of 5 authored cameras below the exported- h(x, z), including the establishing shot.- """- m = probe- assert m["camY"] > m["surfaceY"] + 1.5, m- assert m["camY"] > m["groundAtCam"] + 1.5, m---_PORT = """-import * as THREE from 'three';-import { shot, establishingShot, seat, alongPath, route } from './lib/place.js';--const basic = () => new THREE.MeshBasicMaterial();-const out = {};--// A room with a real ceiling — the catalog tells composers to hand the-// whole room group to shot(), not just the floor.-const room = new THREE.Group();-const floor = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 6), basic());-floor.position.y = -0.1; // top at y = 0-room.add(floor);-const ceil = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 6), basic());-ceil.position.y = 2.9; // ceiling slab, top at 3.0-room.add(ceil);-const backWall = new THREE.Mesh(new THREE.BoxGeometry(6, 2.8, 0.2), basic());-backWall.position.set(0, 1.4, -2.9);-room.add(backWall);-room.updateMatrixWorld(true);-const interior = shot('interior', [0, 1.65, 2.0], [0, 1.2, -2.6], 50, [room]);-out.interiorEyeY = interior.position[1];-out.ceilingTop = 3.0;-// ... and a room too LOW for the 1.6 m clearance still keeps the eye in it.-const low = new THREE.Group();-const lowFloor = floor.clone(); low.add(lowFloor);-const lowCeil = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 6), basic());-lowCeil.position.y = 1.7; // ceiling top at 1.8-low.add(lowCeil);-low.updateMatrixWorld(true);-out.lowRoomEyeY = shot('low', [0, 1.2, 2.0], [0, 1.0, -2.0], 50,- [low]).position[1];--// seat(): a crate under an arch stays under the arch.-const gnd = new THREE.Mesh(new THREE.BoxGeometry(400, 0.2, 400), basic());-gnd.position.y = -0.1; // top at y = 0-gnd.updateMatrixWorld(true);-const arch = new THREE.Mesh(new THREE.BoxGeometry(4, 0.3, 4), basic());-arch.position.set(0, 3, 0); // underside 2.85, top 3.15-arch.updateMatrixWorld(true);-const crate = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), basic());-crate.position.set(0, 0.5, 0);-seat(crate, [gnd, arch]);-out.crateUnderArchY = crate.position.y;-// the quay/seabed rule is unchanged: what is UNDER the object wins.-const quay = new THREE.Mesh(new THREE.BoxGeometry(8, 1, 8), basic());-quay.position.set(0, 1.5, 0); // deck top at 2.0-quay.updateMatrixWorld(true);-const seabed = new THREE.Mesh(new THREE.BoxGeometry(40, 0.2, 40), basic());-seabed.position.y = -3.1;-seabed.updateMatrixWorld(true);-const barrel = new THREE.Mesh(new THREE.BoxGeometry(0.8, 0.8, 0.8), basic());-barrel.position.set(0, 6, 0);-seat(barrel, [seabed, quay]);-out.barrelOnQuayY = barrel.position.y;-// an object authored at y = 0 on a hillside — nothing under it at all,-// so the LOWEST surface above wins and the hut is lifted onto the hill.-const hill = new THREE.Mesh(new THREE.BoxGeometry(20, 0.4, 20), basic());-hill.position.set(600, 12, 0); // top at 12.2, off the plate-hill.updateMatrixWorld(true);-const hut = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), basic());-hut.position.set(600, 1, 0);-seat(hut, [gnd, hill]);-out.hutOnHillY = hut.position.y;--// establishingShot(): a ridge between the eye and the hero.-const hero = new THREE.Mesh(new THREE.BoxGeometry(3, 4, 3), basic());-hero.position.set(0, 2, 0);-hero.updateMatrixWorld(true);-const ridge = new THREE.Mesh(new THREE.BoxGeometry(40, 9, 3), basic());-ridge.position.set(0, 4.5, 6); // a wall 6 m to +z of it-ridge.updateMatrixWorld(true);-const est = establishingShot('est', hero, { azDeg: 90, elDeg: 14, fov: 45,- coverage: 0.7, surfaces: [gnd, ridge] });-const ep = new THREE.Vector3(...est.position);-const ec = new THREE.Vector3(...est.lookAt);-const dir = ec.clone().sub(ep);-const dist = dir.length();-const ray = new THREE.Raycaster(ep, dir.clone().normalize());-ray.far = dist;-const rh = ray.intersectObjects([gnd, ridge], true);-out.estBlockedAt = rh.length ? rh[0].distance : null;-out.estClearNeeded = Math.max(2, dist * 0.05);-const ecam = new THREE.PerspectiveCamera(est.fov, 16 / 9, 0.1, 1e6);-ecam.position.copy(ep); ecam.lookAt(ec); ecam.updateMatrixWorld(true);-const hb = new THREE.Box3().setFromObject(hero);-let inside = 0;-for (const cx of [hb.min.x, hb.max.x])- for (const cy of [hb.min.y, hb.max.y])- for (const cz of [hb.min.z, hb.max.z]) {- const n = new THREE.Vector3(cx, cy, cz).project(ecam);- if (Math.abs(n.x) <= 1 && Math.abs(n.y) <= 1 && Math.abs(n.z) <= 1) {- inside++;- }- }-out.estInside = inside;--// route(): ping-pong wheels roll with the direction of travel.-const axle = new THREE.Object3D();-const cart = new THREE.Object3D();-const pp = route([[0, 0, 0], [10, 0, 0]],- { closed: false, speed: 2, wheels: [{ node: axle, radius: 0.5 }] });-const at = (t) => { pp.poseAt(t, cart);- return { x: cart.position.x, rot: axle.rotation.x }; };-const o1 = at(1.0), o2 = at(1.2); // outbound (turns at t = 5)-const b1 = at(6.0), b2 = at(6.2); // return leg-out.outDx = o2.x - o1.x;-out.outDrot = o2.rot - o1.rot;-out.backDx = b2.x - b1.x;-out.backDrot = b2.rot - b1.rot;-out.wheelRadius = 0.5;-// a closed loop must not snap the wheel at the lap boundary.-const axle2 = new THREE.Object3D();-const loop = route([[0, 0, 0], [5, 0, 0], [5, 0, 5], [0, 0, 5]],- { closed: true, speed: 3, wheels: [{ node: axle2, radius: 0.4 }] });-const dummy = new THREE.Object3D();-loop.poseAt(loop.length / 3 - 0.001, dummy);-const r1 = axle2.rotation.x;-loop.poseAt(loop.length / 3 + 0.001, dummy);-out.loopRotJump = Math.abs(axle2.rotation.x - r1);--// alongPath(): an open path spans end to end, a closed one does not.-const open = alongPath([[0, 0, 0], [12, 0, 0]], 6, { closed: false });-out.openFirstX = open[0].position.x;-out.openLastX = open[open.length - 1].position.x;-out.openN = open.length;-const ring = alongPath([[0, 0, 0], [6, 0, 0], [6, 0, 6], [0, 0, 6]], 8, {});-out.ringN = ring.length;-out.ringFirstToLast = ring[0].position.distanceTo(ring[7].position);-out.ringStep = ring[0].position.distanceTo(ring[1].position);--console.log(JSON.stringify(out));-"""--[email protected](scope="module")-def port() -> dict:- return measure(_PORT, _LIBS)---def test_an_interior_camera_stays_under_its_own_ceiling(port):- """Handed the room group, the eye stayed 1.6 m above the CEILING and- the shot shipped from on top of the roof (measured 4.60 in a 3.00 m- room). It must stand on the floor instead, and a room too low for- the clearance keeps it inside rather than ejecting it."""- m = port- assert m["interiorEyeY"] < m["ceilingTop"] - 0.2, m- assert m["interiorEyeY"] >= 1.6 - 1e-6, m- assert 0.3 <= m["lowRoomEyeY"] <= 1.8 - 0.25 + 1e-6, m---def test_seat_puts_a_body_on_what_is_under_it_not_on_the_roof(port):- """The old down-ray took the top of the column: a crate under a 3 m- arch seated at 3.62. The quay-beats-seabed and lift-onto-the-hill- behaviours both have to survive the fix."""- m = port- assert abs(m["crateUnderArchY"] - 0.47) < 0.02, m # 0.5 - bite- assert abs(m["barrelOnQuayY"] - (2.0 + 0.4 - 0.03)) < 0.02, m- assert abs(m["hutOnHillY"] - (12.2 + 1.0 - 0.03)) < 0.02, m---def test_an_establishing_shot_is_not_a_photograph_of_the_ridge(port):- """A hero behind a 9 m ridge shipped a frame blocked at 1.19 m of an- 8.92 m shot. Sliding along the fit sphere has to clear the view AND- keep the hero framed — retreating would only shrink it."""- m = port- assert (m["estBlockedAt"] is None- or m["estBlockedAt"] >= m["estClearNeeded"] - 1e-6), m- assert m["estInside"] >= 6, m---def test_ping_pong_wheels_roll_the_way_the_cart_is_going(port):- """`s` only grows, so the return leg drove backwards with the wheels- spinning forwards. Roll is the arc distance COVERED — and a closed- loop must still not snap at the lap boundary."""- m = port- assert m["outDx"] > 0 and m["outDrot"] > 0, m- assert m["backDx"] < 0 and m["backDrot"] < 0, m- for dx, drot in ((m["outDx"], m["outDrot"]), (m["backDx"], m["backDrot"])):- assert abs(drot - dx / m["wheelRadius"]) < 2e-3, m # no slip- assert m["loopRotJump"] < 0.05, m---def test_an_open_path_reaches_its_last_waypoint(port):- """6 posts over a 12 m quay ended at x = 10 — a whole gap short. A- CLOSED path keeps dividing by n: its last sample belongs one step- before the start, not on top of it."""- m = port- assert m["openN"] == 6, m- assert abs(m["openFirstX"]) < 1e-6, m- assert abs(m["openLastX"] - 12) < 1e-6, m- assert m["ringN"] == 8, m- assert abs(m["ringFirstToLast"] - m["ringStep"]) < 0.35 * m["ringStep"], m--diff --git a/harness/tests/scene_runtime/lib/test_planar_capture.py b/harness/tests/scene_runtime/lib/test_planar_capture.pydeleted file mode 100644index a5e61aed..00000000--- a/harness/tests/scene_runtime/lib/test_planar_capture.py+++ /dev/null@@ -1,172 +0,0 @@-"""GPU behavior of addon-based planar captures and their shared state scope."""-from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import compile_scene--_LIBS = ("water.js", "wetground.js", "ocean.js")---# ocean: its reflection once ran in override passes and clobbered the viewport.[email protected]("factory", ["wetground", "water", "ocean"])-def test_addon_capture_preserves_affine_projection_and_renderer_state(factory: str) -> None:- script = r"""-import * as THREE from 'three';-import { makeMirrorFloor } from './lib/wetground.js';-import { makeOcean } from './lib/water.js';-import { makeOceanSurface } from './lib/ocean.js';-import { withRendererState } from './lib/shader.js';-export function createScene({renderer}) {- const kind='FACTORY';- const scene=new THREE.Scene();scene.background=new THREE.Color(0x667788);- const object=kind==='wetground'?makeMirrorFloor(8,8,{rttSize:64,detail:0,ripple:0})- :kind==='ocean'?makeOceanSurface({width:8,depth:8,segments:16,reflectionSize:64}):makeOcean(8,8,{rttSize:64,distortionScale:0});- const surface=kind==='wetground'?object.getObjectByName('MirrorSurface'):kind==='ocean'?object.userData.surface:object;- // Caller attachments include a mesh, a camera, a bone hierarchy, and a- // manually managed world transform; no capture may take ownership of them.- const attached=new THREE.Mesh(new THREE.BoxGeometry(.2,.3,.4),new THREE.MeshBasicMaterial());- attached.position.set(.3,.4,.5);surface.add(attached);- const attachedCamera=new THREE.PerspectiveCamera();attachedCamera.position.set(.2,.7,.1);attached.add(attachedCamera);- const bone=new THREE.Bone(),tip=new THREE.Bone();bone.position.set(.1,.2,.3);tip.position.y=.8;- attached.add(bone);bone.add(tip);- const manual=new THREE.Object3D();manual.matrixAutoUpdate=false;manual.matrixWorldAutoUpdate=false;- manual.matrixWorld.makeTranslation(9,8,7);attached.add(manual);- const attachments=[attached,attachedCamera,bone,tip,manual];- const attachmentMatrices=()=>JSON.stringify(attachments.map(o=>({world:o.matrixWorld.toArray(),- inverse:o.isCamera?o.matrixWorldInverse.toArray():null})));- const attachmentFlags=()=>attachments.map(o=>[o.matrixAutoUpdate,o.matrixWorldAutoUpdate,o.matrixWorldNeedsUpdate]);- const child=new THREE.Group(),parent=new THREE.Group();child.add(object);parent.add(child);scene.add(parent);- const marker=new THREE.Mesh(new THREE.BoxGeometry(.8,.8,.8),new THREE.MeshBasicMaterial({color:0xeeaa22}));scene.add(marker);- const camera=new THREE.PerspectiveCamera(45,1,.1,100),expectedCamera=new THREE.PerspectiveCamera();- const originalRender=renderer.render,originalSetTarget=renderer.setRenderTarget;- const originalRatio=renderer.getPixelRatio();- const cube=new THREE.WebGLCubeRenderTarget(32,{generateMipmaps:true,minFilter:THREE.LinearMipmapLinearFilter});- cube.viewport.set(2,3,12,11);cube.scissor.set(3,4,9,8);cube.scissorTest=true;- const state=()=>{- const gl=renderer.getContext();return {- target:renderer.getRenderTarget()===cube?'cube':renderer.getRenderTarget()?'other':'canvas',- face:renderer.getActiveCubeFace(),mip:renderer.getActiveMipmapLevel(),- viewport:renderer.getCurrentViewport(new THREE.Vector4()).toArray(),glViewport:Array.from(gl.getParameter(gl.VIEWPORT)),- logicalViewport:renderer.getViewport(new THREE.Vector4()).toArray(),logicalScissor:renderer.getScissor(new THREE.Vector4()).toArray(),- scissor:Array.from(gl.getParameter(gl.SCISSOR_BOX)),scissorTest:gl.isEnabled(gl.SCISSOR_TEST),logicalTest:renderer.getScissorTest(),- xr:renderer.xr.enabled,shadow:renderer.shadowMap.autoUpdate,tone:renderer.toneMapping,- clear:renderer.getClearColor(new THREE.Color()).toArray(),alpha:renderer.getClearAlpha(),visible:surface.visible,- attachments:attachmentMatrices(),attachmentFlags:attachmentFlags(),- matrix:surface.matrixWorld.toArray(),autoUpdate:surface.matrixWorldAutoUpdate,needsUpdate:surface.matrixWorldNeedsUpdate,- targetViewport:cube.viewport.toArray(),targetScissor:cube.scissor.toArray(),targetTest:cube.scissorTest,- setTargetIdentity:renderer.setRenderTarget===originalSetTarget,- };- };- try {- withRendererState(renderer,()=>{- for(const transform of [0,1,2]){- parent.scale.set(transform===2?-2:2,transform?.4:2,transform?1.6:2);- parent.rotation.set(transform?.1:0,transform?.5:0,transform?.2:0);parent.position.set(2,1,3);- child.rotation.set(transform?.35:0,transform?.2:0,transform?-.25:0);scene.updateMatrixWorld(true);- const world=surface.matrixWorld.clone(),normal=new THREE.Vector3(0,0,1).applyMatrix3(new THREE.Matrix3().getNormalMatrix(world)).normalize();- const center=new THREE.Vector3().setFromMatrixPosition(world),tangent=new THREE.Vector3(1,0,0).transformDirection(world);- camera.position.copy(center).addScaledVector(normal,4).addScaledVector(tangent,2);camera.lookAt(center);camera.updateMatrixWorld(true);- marker.position.copy(center).addScaledVector(normal,1.2);scene.updateMatrixWorld(true);- const reflect=p=>p.clone().addScaledVector(normal,-2*p.clone().sub(center).dot(normal));- expectedCamera.position.copy(reflect(camera.position));- expectedCamera.up.copy(camera.up).transformDirection(camera.matrixWorld).reflect(normal);- expectedCamera.lookAt(reflect(camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()))));expectedCamera.updateMatrixWorld(true);- attached.matrixWorldNeedsUpdate=true;- const expectedAttachments=attachmentMatrices();- let actualCamera=null,captures=0;- renderer.render=function(s,c){- captures++;actualCamera=c.position.clone();- if(captures>1)throw Error('Planar callback recursed');- surface.onBeforeRender(this,s,c); // The explicit re-entry must be inert.- const result=originalRender.call(this,s,c); // Actual GPU render updates scene matrices.- if(attachmentMatrices()!==expectedAttachments)throw Error('Nested capture changed caller attachment matrices');- return result;- };- const before=state();surface.onBeforeRender(renderer,scene,camera);- if(captures!==1||actualCamera.distanceTo(expectedCamera.position)>1e-10)throw Error('Wrong transformed mirror camera');- if(JSON.stringify(before)!==JSON.stringify(state()))throw Error('Capture changed affine matrix or renderer state');- const bias=new THREE.Matrix4().set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);- const expected=bias.multiply(camera.projectionMatrix).multiply(expectedCamera.matrixWorldInverse);- const actual=surface.material.uniforms.textureMatrix.value;- for(const point of [[0,0,0],[1,0,0],[0,1,0],[-2,.7,0],[.4,-1.3,0]]){- const local=new THREE.Vector4(...point,1),wp=local.clone().applyMatrix4(world);- const a=(kind==='water'?wp:local).clone().applyMatrix4(actual),b=wp.clone().applyMatrix4(expected);- if(Math.abs(a.x/a.w-b.x/b.w)>1e-10||Math.abs(a.y/a.w-b.y/b.w)>1e-10)throw Error('Wrong local/world reflection projection');- }- renderer.render=originalRender;- }- parent.scale.set(1,1,1);parent.rotation.set(0,0,0);parent.position.set(0,0,0);child.rotation.set(0,0,0);scene.updateMatrixWorld(true);- camera.position.set(0,3,5);camera.lookAt(0,0,0);camera.updateMatrixWorld(true);- for(const ratio of [1,2])for(const override of [false,true])for(const throws of [false,true]){- renderer.setPixelRatio(ratio);renderer.setRenderTarget(cube,3,1);- if(override){renderer.setViewport(4,5,10,9);renderer.setScissor(5,6,7,6);renderer.setScissorTest(false);}- renderer.xr.enabled=true;renderer.shadowMap.autoUpdate=true;surface.visible=true;- renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.setClearColor(0x123456,.37);- attached.matrixWorldNeedsUpdate=true;- const before=state();let caught=false,captures=0;- renderer.render=function(...args){- captures++;const result=originalRender.apply(this,args);- if(attachmentMatrices()!==before.attachments)throw Error('Nested capture changed attachments before success/failure');- if(throws){this.toneMapping=THREE.NoToneMapping;this.setClearColor(0xffffff,0);throw Error('injected capture failure');}- return result;- };- try{surface.onBeforeRender(renderer,scene,camera);}catch(e){if(e.message!=='injected capture failure')throw e;caught=true;}- if(captures!==1||caught!==throws||JSON.stringify(before)!==JSON.stringify(state()))throw Error('Planar capture leaked state '+JSON.stringify({ratio,override,throws,before,after:state()}));- renderer.render=originalRender;- }- let captures=0;renderer.render=()=>{captures++;};- scene.overrideMaterial=new THREE.MeshNormalMaterial();surface.onBeforeRender(renderer,scene,camera);- scene.overrideMaterial.dispose();scene.overrideMaterial=null;- if(captures!==0)throw Error('Override pass performed colour capture');- const originalMaterial=surface.material,foreignMaterial=new THREE.MeshNormalMaterial();- surface.material=foreignMaterial;surface.onBeforeRender(renderer,scene,camera);- surface.material=originalMaterial;surface.onBeforeRender(renderer,scene,camera,surface.geometry,foreignMaterial);- foreignMaterial.dispose();- if(captures!==0)throw Error('Material replacement pass performed colour capture');- const projection=surface.material.uniforms.textureMatrix.value.clone();- camera.position.set(0,-3,5);camera.lookAt(0,0,0);camera.updateMatrixWorld(true);- surface.onBeforeRender(renderer,scene,camera);surface.onBeforeRender(renderer,scene,camera);- if(captures!==0||!projection.equals(surface.material.uniforms.textureMatrix.value))throw Error('Back-face skip changed cached projection');- });- } finally {- renderer.render=originalRender;renderer.setPixelRatio(originalRatio);cube.dispose();- let callerDisposals=0;- attached.geometry.addEventListener('dispose',()=>callerDisposals++);- attached.material.addEventListener('dispose',()=>callerDisposals++);- object.userData.dispose();- if(callerDisposals)throw Error('Factory disposed caller attachments');- attached.geometry.dispose();attached.material.dispose();- marker.geometry.dispose();marker.material.dispose();- }- return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,3,5],lookAt:[0,0,0]}]};-}-""".replace("FACTORY", factory)- code, output = compile_scene(script, _LIBS, audit_module="src/scene.js")- assert code == 0, output---def test_renderer_state_scope_is_nested_and_keeps_callback_result_and_exception() -> None:- code, output = compile_scene(r"""-import * as THREE from 'three';-import {withRendererState} from './lib/shader.js';-export function createScene({renderer}) {- const old=renderer.getRenderTarget();- const a=new THREE.WebGLRenderTarget(32,32),b=new THREE.WebGLRenderTarget(16,16);- const read=()=>JSON.stringify({target:renderer.getRenderTarget()?.uuid||null,viewport:renderer.getCurrentViewport(new THREE.Vector4()).toArray(),scissor:renderer.getScissor(new THREE.Vector4()).toArray(),alpha:renderer.getClearAlpha(),tone:renderer.toneMapping});- try{- renderer.setRenderTarget(a);renderer.setViewport(1,2,23,24);renderer.setScissor(3,4,17,18);- const initial=read();- const result=withRendererState(renderer,()=>{- renderer.setRenderTarget(b);renderer.setViewport(2,3,8,9);renderer.setScissor(1,2,7,8);renderer.setClearAlpha(.41);- const middle=read(),error=new Error('nested failure');let caught;- try{withRendererState(renderer,()=>{renderer.setRenderTarget(null);renderer.setClearAlpha(.17);renderer.toneMapping=THREE.NoToneMapping;throw error;});}catch(e){caught=e;}- if(caught!==error||read()!==middle)throw Error('Nested scope did not restore its own entry state');- return 37;- });- if(result!==37||read()!==initial)throw Error('Outer scope result or state changed');- }finally{renderer.setRenderTarget(old);a.dispose();b.dispose();}- return {scene:new THREE.Scene(),cameras:[{name:'probe',position:[0,3,5],lookAt:[0,0,0]}]};-}-""", audit_module="src/scene.js")- assert code == 0, outputdiff --git a/harness/tests/scene_runtime/lib/test_rain.py b/harness/tests/scene_runtime/lib/test_rain.pydeleted file mode 100644index 6f14f49b..00000000--- a/harness/tests/scene_runtime/lib/test_rain.py+++ /dev/null@@ -1,125 +0,0 @@-"""rain.js: splashes land where they are aimed, and a numeric `area` is not NaN."""--from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "rain.js")---def test_splashes_land_on_the_surfaces_they_are_given():- """Drops hit the car roof at its real height, not THROUGH it onto the road;- a steep face collects none, and a rejected sample is re-drawn, not dropped."""- out = measure("""-import * as THREE from 'three';-import { makeSplashes } from './lib/rain.js';-const car = new THREE.Mesh(new THREE.BoxGeometry(2, 1.4, 4.5), new THREE.MeshStandardMaterial());-car.position.set(0, 0.7, 0);-car.updateMatrixWorld(true);-const area = { x: 0, z: 0, w: 20, d: 20 };-const rings = makeSplashes({ seed: 11, count: 300, surfaces: [car], area }).getObjectByName('SplashRings');-const off = rings.geometry.attributes.iOff.array, nrm = rings.geometry.attributes.iNrm.array;-let onRoof = 0, onGround = 0, sideways = 0;-for (let i = 0; i < off.length / 3; i++) {- if (off[i * 3 + 1] > 1.4) onRoof++; else if (off[i * 3 + 1] < 0.1) onGround++;- if (nrm[i * 3 + 1] < 0.4) sideways++;-}-const wall = new THREE.Mesh(new THREE.PlaneGeometry(8, 8),- new THREE.MeshStandardMaterial({ side: THREE.DoubleSide }));-wall.rotation.x = -Math.PI / 2 + 1.4; // 80 deg off horizontal-wall.position.set(0, 3, 0);-wall.updateMatrixWorld(true);-const onWall = makeSplashes({ seed: 4, count: 120, surfaces: [wall], area, surfaceBias: 1.0 })- .getObjectByName('SplashRings');-const mixed = makeSplashes({ seed: 4, count: 120, surfaces: [wall], area }).getObjectByName('SplashRings');-let mixedHigh = 0;-const mo = mixed.geometry.attributes.iOff.array;-for (let i = 0; i < mo.length / 3; i++) if (mo[i * 3 + 1] > 0.5) mixedHigh++;-console.log(JSON.stringify({ onRoof, onGround, sideways, mixedHigh,- wallStuck: onWall ? onWall.geometry.instanceCount : 0, mixedCount: mixed.geometry.instanceCount }));-""", _LIBS)- assert out["onRoof"] > 60 and out["onGround"] > 40, out- assert out["sideways"] == 0 and out["wallStuck"] == 0 and out["mixedHigh"] == 0, out- assert out["mixedCount"] == 120, out---def test_a_square_area_given_as_one_number_is_not_nan():- """`area: 12` read x and w as undefined, and every ground-fallback impact- landed at NaN while still being created and drawn."""- out = measure("""-import { makeSplashes } from './lib/rain.js';-const finite = (g) => {- let bad = 0, total = 0;- g.traverse((o) => {- const a = o.geometry && o.geometry.getAttribute('iOff');- if (!a) return;- for (let i = 0; i < a.array.length; i++) { total++; if (!Number.isFinite(a.array[i])) bad++; }- });- return { bad, total };-};-console.log(JSON.stringify(finite(makeSplashes({ area: 12, y: 0, seed: 4 }))));-""", _LIBS)- assert out["total"] > 0 and out["bad"] == 0, out---def test_hidden_surfaces_do_not_collect_splashes_or_shelter_rain():- """A hidden ancestor/material must agree with what is actually rendered."""- out = measure("""-import * as THREE from 'three';-import { makeRain, makeSplashes } from './lib/rain.js';-const scene = new THREE.Scene(), hidden = new THREE.Group();-hidden.visible = false; scene.add(hidden);-const roof = new THREE.Mesh(new THREE.BoxGeometry(5, .3, 5), new THREE.MeshStandardMaterial());-roof.position.y = 4; hidden.add(roof);-const invisible = roof.clone(); invisible.material = roof.material.clone();-invisible.material.visible = false; invisible.position.y = 2; scene.add(invisible);-scene.updateMatrixWorld(true);-const surfaces = [roof, invisible];-const splashes = makeSplashes({ surfaces, area: 4, count: 60, surfaceBias: 0, crowns: false });-const impact = splashes.getObjectByName('SplashRings').geometry.attributes.iOff;-const rainfall = makeRain({ surfaces, radius: 3, count: 2, follow: false, groundY: 0 });-scene.add(rainfall); scene.updateMatrixWorld(true);-const camera = new THREE.PerspectiveCamera(); camera.position.set(0, 3, 6); camera.updateMatrixWorld(true);-rainfall.onBeforeRender({}, scene, camera, rainfall.geometry, rainfall.material);-rainfall.onAfterRender({}, scene, camera, rainfall.geometry, rainfall.material);-console.log(JSON.stringify({ heights: Array.from({length: impact.count}, (_, i) => impact.getY(i)),- shelter: rainfall.userData.sampleShelterHeight(0, 0) }));-splashes.userData.dispose(); rainfall.userData.dispose();-""", _LIBS)- assert out["shelter"] == 0, out- assert out["heights"] == pytest.approx([0.012] * 60), out---def test_instanced_splash_normals_follow_affine_surface_and_reject_steep_faces():- """The normal and lift belong to each tilted instance, including parent scale."""- out = measure("""-import * as THREE from 'three';-import { makeSplashes } from './lib/rain.js';-const parent = new THREE.Group(); parent.rotation.y = .4; parent.scale.set(1.6, .8, 1.2);-const geometry = new THREE.PlaneGeometry(5, 5); geometry.rotateX(-Math.PI / 2);-const roof = new THREE.InstancedMesh(geometry, new THREE.MeshStandardMaterial({side: THREE.DoubleSide}), 1);-parent.add(roof); const instance = new THREE.Matrix4().makeRotationZ(.55);-instance.setPosition(0, 3, 0); roof.setMatrixAt(0, instance); parent.updateMatrixWorld(true);-const expected = new THREE.Vector3(0, 1, 0).applyMatrix3(new THREE.Matrix3()- .getNormalMatrix(roof.matrixWorld.clone().multiply(instance))).normalize();-const center = new THREE.Vector3(0, 0, 0).applyMatrix4(roof.matrixWorld.clone().multiply(instance));-const splash = makeSplashes({surfaces: [roof], count: 80, surfaceBias: 1, ground: false, crowns: false});-const rings = splash.getObjectByName('SplashRings'), normal = rings.geometry.attributes.iNrm, off = rings.geometry.attributes.iOff;-let normalError = 0, liftError = 0;-for (let i = 0; i < off.count; i++) {- normalError = Math.max(normalError, new THREE.Vector3().fromBufferAttribute(normal, i).distanceTo(expected));- liftError = Math.max(liftError, Math.abs(new THREE.Vector3().fromBufferAttribute(off, i).sub(center).dot(expected) - .012));-}-instance.makeRotationZ(1.48).setPosition(0, 3, 0); roof.setMatrixAt(0, instance);-roof.computeBoundingBox(); roof.computeBoundingSphere();-const steep = makeSplashes({surfaces: [roof], count: 40, surfaceBias: 1, ground: false, crowns: false});-console.log(JSON.stringify({normalError, liftError, count: off.count, steepCount: steep.children.length}));-splash.userData.dispose(); steep.userData.dispose();-""", _LIBS)- assert out["count"] == 80, out- assert out["normalError"] < 1e-6 and out["liftError"] < 1e-6, out- assert out["steepCount"] == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_shader.py b/harness/tests/scene_runtime/lib/test_shader.pyindex 2c3a381c..a90dbbdd 100644--- a/harness/tests/scene_runtime/lib/test_shader.py+++ b/harness/tests/scene_runtime/lib/test_shader.py@@ -1,18 +1,14 @@-"""shader.js — the hub every library module builds on: assembly, patch chaining, the-cache key, roughness composition, one tick, and every construction path on the GPU."""+"""shader.js — the hub every library module builds on."""from __future__ import annotationsimport math-import reimport pytest-from _probe import LIB_DIR, compile_scene, measure+from _probe import compile_scene, measurepytestmark = pytest.mark.node_LIBS = ("shader.js",)-_CHUNKS = ("logdepthbuf_pars_vertex", "logdepthbuf_vertex",- "logdepthbuf_pars_fragment", "logdepthbuf_fragment")def _measure(script: str) -> dict:@@ -20,9 +16,7 @@ def _measure(script: str) -> dict:def compile_fixture(fixture_src: str, libs: tuple[str, ...] = _LIBS, *, timeout_s: float = 180.0) -> tuple[int, str]:- """GPU-compile what a fixture's build() makes, inside the lit, fogged scene- below. The static audit is scoped to the wrapper: its per-file uTime rule- cannot see that shader.js binds uTime at assembly time."""+ """GPU-compile what a fixture's build() makes, inside the lit, fogged scene below."""return compile_scene(_WRAPPER, libs, extra={"fixture.js": fixture_src},audit_module="src/scene.js", timeout_s=timeout_s)@@ -48,55 +42,8 @@ export async function createScene() {"""-def test_raw_sources_are_repaired_not_trusted():- out = _measure("""-import { makeShaderMaterial } from './lib/shader.js';-const m = makeShaderMaterial({- vertexShader: 'void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',- fragmentShader: 'void main() { gl_FragColor = vec4(1.0); }',-});-console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader }));-""")- for chunk in _CHUNKS:- assert f"#include <{chunk}>" in out["vs"] + out["fs"], chunk- fs = out["fs"]- main_body = fs[fs.index("void main"):]- assert main_body.index("logdepthbuf_fragment") < main_body.index("gl_FragColor")- assert out["vs"].rindex("logdepthbuf_vertex") > out["vs"].rindex("gl_Position")---def test_utime_is_declared_wherever_it_is_read():- out = _measure("""-import { makeShaderMaterial } from './lib/shader.js';-const m = makeShaderMaterial({ varyings: 'varying vec2 vUv;',- vertexMain: ' vUv = uv;\\n transformed.y += sin(uTime);',- fragmentMain: ' gl_FragColor = vec4(vUv, sin(uTime), 1.0);' });-const q = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(1.0);' });-const count = (s) => (s.match(/uniform float uTime;/g) || []).length;-console.log(JSON.stringify({ vs: count(m.vertexShader), fs: count(m.fragmentShader),- unusedVs: count(q.vertexShader), unusedFs: count(q.fragmentShader) }));-""")- assert out["vs"] == 1 and out["fs"] == 1- assert out["unusedVs"] == 0 and out["unusedFs"] == 0---def test_a_redeclared_varying_is_absorbed_not_a_compile_error():- out = _measure("""-import { makeShaderMaterial } from './lib/shader.js';-const m = makeShaderMaterial({ varyings: 'varying vec2 vUv;', vertexMain: ' vUv = uv;',- fragmentHead: 'varying vec2 vUv;\\nuniform float uScale;',- fragmentMain: ' gl_FragColor = vec4(vUv * uScale, 0.0, 1.0);' });-const count = (s) => (s.match(/varying vec2 vUv;/g) || []).length;-console.log(JSON.stringify({ vs: count(m.vertexShader), fs: count(m.fragmentShader),- keptUniform: m.fragmentShader.includes('uniform float uScale;') }));-""")- assert out["vs"] == 1 and out["fs"] == 1 and out["keptUniform"]--def test_a_custom_shader_recedes_into_the_scene_fog():- """Every scene here sets scene.fog; three delivers fog ONLY through the- chunks and their uniforms. Opting out (`fog: false`) leaves nothing- behind and writes the marker OUR static audit reads (`3dcode: no-fog`)."""+ """Every scene here sets scene.fog."""out = _measure("""import { makeShaderMaterial } from './lib/shader.js';const m = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(0.5, 0.6, 0.7, 1.0);' });@@ -119,116 +66,6 @@ console.log(JSON.stringify({ vs: m.vertexShader, fs: m.fragmentShader, fogFlag:assert "3dcode: no-fog" in out["offFs"], "the opt-out marker our audit reads"-def test_a_custom_shader_ends_the_way_three_ends_its_own():- """No post chain on this renderer: tone map + sRGB happen in the fragment- tail, so a custom shader without three's two closing chunks renders dark- and untonemapped next to every built-in."""- out = _measure("""-import { makeShaderMaterial } from './lib/shader.js';-const m = makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(1.0);' });-const raw = makeShaderMaterial({ fragmentShader: 'void main() { gl_FragColor = vec4(1.0); }' });-const tail = (s) => s.slice(s.lastIndexOf('gl_FragColor'));-console.log(JSON.stringify({- assembledTone: /tonemapping_fragment/.test(m.fragmentShader),- assembledSpace: /colorspace_fragment/.test(m.fragmentShader),- rawGetsThemToo: /colorspace_fragment/.test(raw.fragmentShader),- afterFog: m.fragmentShader.indexOf('colorspace_fragment') > m.fragmentShader.indexOf('fog_fragment'),- aloneOnTheirLines: tail(m.fragmentShader).split('\\n').filter((l) => l.includes('#include'))- .every((l) => l.trim().startsWith('#include')) }));-""")- assert out["assembledTone"] and out["assembledSpace"] and out["rawGetsThemToo"]- assert out["afterFog"] and out["aloneOnTheirLines"]---def test_patched_builtins_do_not_share_one_program():- out = _measure("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-const a = patchStandard(new THREE.MeshStandardMaterial(), { name: 'wet', fragmentBody: ' diffuseColor.rgb *= 0.5;' });-const b = patchStandard(new THREE.MeshStandardMaterial(), { name: 'dusty', fragmentBody: ' diffuseColor.rgb += 0.1;' });-const shaderA = { vertexShader: 'void main() { #include <begin_vertex> }',- fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };-a.onBeforeCompile(shaderA);-console.log(JSON.stringify({ keyA: a.customProgramCacheKey(), keyB: b.customProgramCacheKey(),- injected: shaderA.fragmentShader.includes('diffuseColor.rgb *= 0.5'), gotUniform: !!shaderA.uniforms.uTime }));-""")- assert out["keyA"] != out["keyB"] and out["injected"] and out["gotUniform"]---def test_two_patches_on_one_material_both_survive_in_call_order():- out = _measure("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-const m = new THREE.MeshStandardMaterial();-patchStandard(m, { name: 'wet', uniforms: { uWet: { value: 0.5 } }, fragmentBody: ' diffuseColor.rgb *= 0.5; // FIRST' });-patchStandard(m, { name: 'dusty', uniforms: { uDust: { value: 0.2 } }, vertexBody: ' transformed.y += 0.01;',- fragmentBody: ' diffuseColor.rgb += 0.1; // SECOND' });-patchStandard(m, { name: 'wet', uniforms: { uWet: { value: 0.5 } }, fragmentBody: ' diffuseColor.rgb *= 0.5; // FIRST' });-const shader = { vertexShader: 'void main() { #include <begin_vertex> }',- fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };-m.onBeforeCompile(shader);-const fs = shader.fragmentShader;-console.log(JSON.stringify({ key: m.customProgramCacheKey(),- order: fs.indexOf('// FIRST') < fs.indexOf('// SECOND'), onceEach: (fs.match(/\\/\\/ FIRST/g) || []).length,- vertex: shader.vertexShader.includes('transformed.y += 0.01'),- uWet: !!shader.uniforms.uWet, uDust: !!shader.uniforms.uDust,- utilOnce: (fs.match(/float astraFbm2/g) || []).length }));-""")- assert out["order"] and out["onceEach"] == 1 and out["vertex"]- assert out["uWet"] and out["uDust"]- assert out["key"] == "astra:wet+dusty", out["key"]- assert out["utilOnce"] == 1---def test_patch_declarations_are_deduped_and_utime_declared():- out = _measure("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-const m = new THREE.MeshStandardMaterial();-const head = 'varying float vK;\\nuniform float uTime;\\nuniform vec3 uShared[8];';-patchStandard(m, { name: 'a', vertexHead: head, fragmentHead: head,- vertexBody: ' vK = sin(uTime);', fragmentBody: ' diffuseColor.rgb += uShared[0] * vK;' });-patchStandard(m, { name: 'b', vertexHead: head, fragmentHead: head, vertexBody: ' transformed.x += cos(uTime);' });-const sway = patchStandard(new THREE.MeshStandardMaterial(), { name: 'sway',- vertexBody: ' transformed.x += sin(uTime) * 0.1;', fragmentBody: ' diffuseColor.rgb *= 0.9 + 0.1 * sin(uTime);' });-const s1 = { vertexShader: 'void main() { #include <begin_vertex> }', fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };-const s2 = { vertexShader: 'void main() { #include <begin_vertex> }', fragmentShader: 'void main() { #include <color_fragment> }', uniforms: {} };-m.onBeforeCompile(s1); sway.onBeforeCompile(s2);-const count = (s, re) => (s.match(re) || []).length;-console.log(JSON.stringify({- vK: count(s1.vertexShader, /varying float vK;/g) + count(s1.fragmentShader, /varying float vK;/g),- time: count(s1.vertexShader, /uniform float uTime;/g), arr: count(s1.fragmentShader, /uniform vec3 uShared\\[8\\];/g),- both: s1.vertexShader.includes('sin(uTime)') && s1.vertexShader.includes('cos(uTime)'),- swayVs: count(s2.vertexShader, /uniform float uTime;/g), swayFs: count(s2.fragmentShader, /uniform float uTime;/g) }));-""")- assert out["vK"] == 2 and out["time"] == 1 and out["arr"] == 1 and out["both"]- assert out["swayVs"] == 1 and out["swayFs"] == 1---def test_two_patches_defining_one_function_name_say_so():- out = _measure("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-const compile = (type, a, b) => {- const fn = (body) => `${type} astraShared(vec2 p) {\\n return ${body};\\n}`;- const m = new THREE.MeshStandardMaterial();- patchStandard(m, { name: 'first', fragmentHead: fn(a), fragmentBody: ' diffuseColor.rgb *= 1.0;' });- patchStandard(m, { name: 'second', fragmentHead: ' ' + fn(b) });- const s = { uniforms: {}, vertexShader: 'void main() {}', fragmentShader: '#include <color_fragment>' };- try { m.onBeforeCompile(s); return { ok: true, copies: (s.fragmentShader.match(/astraShared\\(vec2/g) || []).length }; }- catch (e) { return { ok: false, msg: e.message }; }-};-const same = compile('float', 'p.x', 'p.x'), differ = compile('float', 'p.x', 'p.y');-console.log(JSON.stringify({ sameOk: same.ok, sameCopies: same.copies, differThrew: !differ.ok,- namesBoth: !differ.ok && /first/.test(differ.msg) && /second/.test(differ.msg) && /astraShared/.test(differ.msg),- ivec: !compile('ivec3', 'ivec3(0)', 'ivec3(1)').ok, bvec: !compile('bvec2', 'bvec2(true)', 'bvec2(false)').ok,- matNxM: !compile('mat2x3', 'mat2x3(0.0)', 'mat2x3(1.0)').ok }));-""")- assert out["sameOk"] and out["sameCopies"] == 1- assert out["differThrew"] and out["namesBoth"]- assert out["ivec"] and out["bvec"] and out["matNxM"]--def test_roughness_composes_across_libraries_in_any_order_within_range():out = _measure("""import * as THREE from 'three';@@ -248,26 +85,8 @@ console.log(JSON.stringify({ a: a.roughness, b: b.roughness, base: a.userData.asassert out["floor"] == 0.04 and out["basic"]-def test_tick_drives_every_shader_from_one_call():- out = _measure("""-import * as THREE from 'three';-import { makeShaderMaterial, patchStandard, tickShaders } from './lib/shader.js';-const scene = new THREE.Scene();-const a = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), makeShaderMaterial({ fragmentMain: ' gl_FragColor = vec4(uTime);' }));-const b = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), patchStandard(new THREE.MeshStandardMaterial(), { name: 'x' }));-const c = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());-scene.add(a, b, c);-const n = tickShaders(scene, 4.25);-console.log(JSON.stringify({ n, a: a.material.uniforms.uTime.value, b: b.material.userData.uniforms.uTime.value }));-""")- assert out["n"] == 2 and out["a"] == 4.25 and out["b"] == 4.25--def test_every_construction_path_compiles_on_our_gpu():- """Assembled mains, raw sources, an additive veil, a billboard field, two- chained patches with shadowLike, instanceVariation on a built-in, and the- three later hooks (only the GPU can say roughnessFactor and metalnessFactor- are in scope where they inject) — plain and instanced."""+ """Assembled mains, raw sources, an additive veil, a billboard field, two chained patches with shadowLike, instanceVariation on a built-in, and the th..."""code, out = compile_fixture("""import * as THREE from 'three';import { makeShaderMaterial, patchStandard, shadowLike, instanceVariation, instancedQuad, keepOutOfDepthPasses } from './lib/shader.js';@@ -338,82 +157,18 @@ export function build() {assert "ERROR" not in out, out-def test_the_later_hooks_land_after_their_own_chunks_in_order():- """Each opt-in hook lands after the chunk that puts its variable in scope- (gl_FragColor while still LINEAR), and bodies join in CALL order."""- out = _measure("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-const m = new THREE.MeshStandardMaterial({ color: 0x8b8478, roughness: 0.4 });-patchStandard(m, { name: 'rust',- roughnessBody: ' roughnessFactor = mix(roughnessFactor, 0.95, 0.5);',- metalnessBody: ' metalnessFactor *= 0.4;',- outputBody: ' gl_FragColor.rgb += vec3(0.02, 0.01, 0.0);' });-patchStandard(m, { name: 'dust',- roughnessBody: ' roughnessFactor = min(1.0, roughnessFactor + 0.2);',- outputBody: ' gl_FragColor.rgb *= 0.98;' });-const shader = { vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',- fragmentShader: ['void main() {', '#include <color_fragment>',- '#include <roughnessmap_fragment>', '#include <metalnessmap_fragment>',- '#include <opaque_fragment>', '}'].join('\\n'), uniforms: {} };-m.onBeforeCompile(shader);-console.log(JSON.stringify({ fs: shader.fragmentShader }));-""")- fs = out["fs"]- for chunk, body in (- ("roughnessmap_fragment", "roughnessFactor = mix(roughnessFactor, 0.95, 0.5);"),- ("metalnessmap_fragment", "metalnessFactor *= 0.4;"),- ("opaque_fragment", "gl_FragColor.rgb += vec3(0.02, 0.01, 0.0);"),- ):- inc, at = f"#include <{chunk}>", fs.index(body)- assert fs.index(inc) < at, f"{body} landed before {inc}"- # Call order, both hooks that two patches wrote into.- assert fs.index("roughnessFactor = mix(") < fs.index("roughnessFactor = min("), fs- assert fs.index("gl_FragColor.rgb +=") < fs.index("gl_FragColor.rgb *="), fs- # A patch that asks for none of them injects none of them.- assert fs.count("#include <opaque_fragment>") == 1, fs---def test_a_material_with_no_later_hooks_is_byte_for_byte_unchanged():- """The hooks are additive: every patch shipped before them asks for none,- so their chunks must come back untouched — no stray blank line, nothing- for a later `.replace()` in this chain to land on twice."""- out = _measure("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-const m = new THREE.MeshStandardMaterial({ color: 0x8b8478 });-patchStandard(m, { name: 'albedo',- fragmentBody: ' diffuseColor.rgb *= 0.9;' });-const src = ['void main() {', '#include <color_fragment>',- '#include <roughnessmap_fragment>', '#include <metalnessmap_fragment>',- '#include <opaque_fragment>', '}'].join('\\n');-const shader = { vertexShader: 'void main() {\\n#include <begin_vertex>\\n}',- fragmentShader: src, uniforms: {} };-m.onBeforeCompile(shader);-const tail = shader.fragmentShader.slice(- shader.fragmentShader.indexOf('#include <roughnessmap_fragment>'));-console.log(JSON.stringify({ tail }));-""")- assert out["tail"] == ("#include <roughnessmap_fragment>\n"- "#include <metalnessmap_fragment>\n"- "#include <opaque_fragment>\n}")--# The catalog's one wind object, the [x,z] pair the fire/smoke rows use, a number and a# Vector3: each handed to every wind reader. Before readWind, the object threw in-# firefield/smoke/clouds/cloudvolume (RangeError) and rain (TypeError), fire read no wind,-# snow read NaN, and windOf ignored the pair and blew the default way.+# smoke/clouds/cloudvolume (RangeError), fire read no wind,+# and windOf ignored the pair and blew the default way._WIND = """import * as THREE from 'three';import { readWind } from './lib/shader.js';import { windOf } from './lib/grass.js';import { makeFire } from './lib/fire.js';-import { makeFireField } from './lib/firefield.js';import { makeSmoke } from './lib/smoke.js';-import { makeRain } from './lib/rain.js';import { makeCloudVolume } from './lib/cloudvolume.js';import { makeClouds } from './lib/clouds.js';-import { patchSnow } from './lib/accumulation.js';import { makeRainVeil } from './lib/veils.js';const uni = (g, name) => { let u; g.traverse((o) => { const v = o.material?.uniforms?.[name]; if (v && !u) u = v.value; }); return u; };const xz = (v) => v.isVector3 ? [v.x, v.z] : typeof v === 'number' ? [v, 0] : [v.x, v.y];@@ -426,20 +181,17 @@ for (const [k, w] of Object.entries(winds)) {read: [r.dir.x, r.dir.y],windOf: xz(windOf(w).dir),fire: xz(uni(makeFire({ wind: w }), 'uWind')),- firefield: 'ok' && makeFireField({ emitters: [{ position: [0, 0, 0], radius: 0.3, height: 1 }], wind: w, quality: 'low' }) && 'ok',smoke: xz(makeSmoke({ wind: w }).material.uniforms.uWind.value),- rain: (({ x, z }) => [x, z])(makeRain({ wind: w, count: 10 }).material.uniforms.uVel.value),cloudVolume: xz(makeCloudVolume({ wind: w, quality: 'low' }).material.uniforms.uWind.value),clouds: uni(makeClouds({ wind: w, count: 2 }), 'uWind'),- snow: xz(patchSnow(new THREE.MeshStandardMaterial(), { wind: w }).userData.uniforms.uSnowWind.value),veil: xz(uni(makeRainVeil({ direction: w }), 'uWind')),};}console.log(JSON.stringify(out));"""-_WIND_LIBS = ("grass.js", "fire.js", "firefield.js", "smoke.js", "rain.js", "cloudvolume.js",- "clouds.js", "accumulation.js", "veils.js")+_WIND_LIBS = ("grass.js", "fire.js", "smoke.js", "cloudvolume.js",+ "clouds.js", "veils.js")@pytest.fixture(scope="module")@@ -454,7 +206,7 @@ def test_one_wind_is_read_the_same_way_by_every_effect(wind, spelling):# the number has no direction of its own: it blows along the fallback'sexpect = [1, 0] if spelling == "number" else [1 / math.hypot(1, 0.3), 0.3 / math.hypot(1, 0.3)]assert ref == pytest.approx(expect)- for reader in ("fire", "smoke", "rain", "cloudVolume", "snow", "veil"):+ for reader in ("fire", "smoke", "cloudVolume", "veil"):v = w[reader]n = math.hypot(*v)assert n > 0 and all(math.isfinite(c) for c in v), (reader, v)@@ -462,27 +214,4 @@ def test_one_wind_is_read_the_same_way_by_every_effect(wind, spelling):assert (v[0] / n, v[1] / n) == pytest.approx(tuple(ref), abs=1e-6), (reader, v)if spelling != "number": # windOf's own fallback direction is (1, 0.45)assert w["windOf"] == pytest.approx(ref)- assert w["firefield"] == "ok" and math.isfinite(w["clouds"]) and w["clouds"] > 0---def test_the_surface_gradient_bump_is_written_once():- """astraBump/astraBumpSlope return n at a degenerate footprint (det 0); five modules- kept their own copy after the helper landed, and stream.js's had no guard, so a- grazing pixel shaded NaN. Only tree.js's clamped variant and windows.js's- cotangent frame (a different job) build a screen-space frame of their own."""- frame = re.compile(r"cross\(\s*\w+\s*,\s*(normal|n)\s*\)")- own = sorted(p.name for p in LIB_DIR.glob("*.js") if frame.search(p.read_text(encoding="utf-8")))- assert own == ["shader.js", "tree.js", "windows.js"], own---def test_seed_lattice_keeps_the_formula_the_five_copies_used():- """neon, urban, caustics, submerged and windows each carried this body; the one- helper must give every recorded seed the same pattern it had."""- out = measure("""-import { seedLattice } from './lib/shader.js';-const old = (seed, k, m) => (Math.abs(Math.round(seed === undefined ? 1 : seed)) % 9973 * k) % m;-const seeds = [undefined, 0, 1, 7, -7, 3.6, 9980, 123456];-console.log(JSON.stringify(seeds.flatMap((s) => [[16807, 9973], [48271, 9973], [16807, 257]]- .map(([k, m]) => seedLattice(s, k, m) === old(s, k, m)))));-""", _LIBS)- assert out and all(out), out+ assert math.isfinite(w["clouds"]) and w["clouds"] > 0diff --git a/harness/tests/scene_runtime/lib/test_shader_geometry.py b/harness/tests/scene_runtime/lib/test_shader_geometry.pyindex 65de1b56..dea4463d 100644--- a/harness/tests/scene_runtime/lib/test_shader_geometry.py+++ b/harness/tests/scene_runtime/lib/test_shader_geometry.py@@ -3,97 +3,11 @@ import jsonimport pytest-from tests.scene_runtime.lib._probe import compile_scene, measure+from tests.scene_runtime.lib._probe import compile_scenepytestmark = pytest.mark.node-def test_override_guard_preserves_callbacks_material_arrays_and_draw_range():- out = measure("""-import * as THREE from 'three';-import {keepOutOfDepthPasses} from './lib/shader.js';-const geometry=new THREE.BoxGeometry();geometry.setDrawRange(3,12);-const materials=[new THREE.MeshStandardMaterial(),new THREE.MeshStandardMaterial()];-const mesh=new THREE.Mesh(geometry,materials),foreign=new THREE.MeshNormalMaterial();-let before=0,after=0,correctThis=true,restoredAtCallback=true;-mesh.onBeforeRender=function(){before++;correctThis&&=this===mesh;};-mesh.onAfterRender=function(){after++;correctThis&&=this===mesh;restoredAtCallback&&=geometry.drawRange.count===12;};-keepOutOfDepthPasses(mesh);keepOutOfDepthPasses(mesh);-const args=[null,null,null,geometry,foreign];-mesh.onBeforeRender(...args);const excluded=geometry.drawRange.count===0;-mesh.onAfterRender(...args);-args[4]=materials[1];mesh.onBeforeRender(...args);const arrayVisible=geometry.drawRange.count===12;mesh.onAfterRender(...args);-mesh.material=new THREE.MeshBasicMaterial();args[4]=mesh.material;-mesh.onBeforeRender(...args);const replacementVisible=geometry.drawRange.count===12;mesh.onAfterRender(...args);-console.log(JSON.stringify({before,after,correctThis,restoredAtCallback,excluded,arrayVisible,replacementVisible,range:geometry.drawRange}));-""")- assert out == {"before": 3, "after": 3, "correctThis": True,- "restoredAtCallback": True, "excluded": True,- "arrayVisible": True, "replacementVisible": True,- "range": {"start": 3, "count": 12}}---def test_patched_clone_keeps_typed_uniforms_and_borrows_textures():- out = measure("""-import * as THREE from 'three';-import {patchStandard,clonePatchedMaterial} from './lib/shader.js';-const texture=new THREE.WebGLRenderTarget(4,4).texture;-const original=new THREE.MeshStandardMaterial({map:texture});-patchStandard(original,{name:'typed-patch',uniforms:{- uOffset:{value:new THREE.Vector3(1,2,3)},uSample:{value:texture},- uColors:{value:[new THREE.Color(.2,.3,.4)]},uWeights:{value:new Float32Array([1,2])}},- fragmentHead:'uniform vec3 uOffset;',fragmentBody:'diffuseColor.rgb *= uOffset;'});-original.userData.shared=true;-const clone=clonePatchedMaterial(original),a=original.userData.uniforms,b=clone.userData.uniforms;-b.uOffset.value.x=8;b.uColors.value[0].r=.9;b.uWeights.value[0]=9;-patchStandard(clone,{name:'second',fragmentBody:'diffuseColor.rgb *= 0.5;'});-const shader={vertexShader:'void main(){\\n#include <begin_vertex>\\n}',- fragmentShader:'void main(){\\n#include <color_fragment>\\n}',uniforms:{}};-clone.onBeforeCompile(shader);-console.log(JSON.stringify({typed:b.uOffset.value.isVector3&&b.uColors.value[0].isColor,- old:[a.uOffset.value.x,a.uColors.value[0].r,a.uWeights.value[0]],- texture:b.uSample.value===texture&&clone.map===texture,- chain:original.userData.astraPatches.length,cloneChain:clone.userData.astraPatches.length,- applied:shader.fragmentShader.includes('diffuseColor.rgb *= uOffset;')&&shader.fragmentShader.includes('diffuseColor.rgb *= 0.5;'),- shared:!!clone.userData.shared,sourceShared:original.userData.shared}));-""")- assert out == {"typed": True, "old": [1, 0.2, 1], "texture": True,- "chain": 1, "cloneChain": 2, "applied": True,- "shared": False, "sourceShared": True}---def test_shader_clone_borrows_samplers_and_preserves_uniform_sharing():- out = measure("""-import * as THREE from 'three';-import {makeShaderMaterial,clonePatchedMaterial} from './lib/shader.js';-const target=new THREE.WebGLRenderTarget(4,4),texture=new THREE.Texture();-const results=[],warnings=[];console.warn=(...args)=>warnings.push(args.join(' '));-for(const factory of [opts=>new THREE.ShaderMaterial(opts),- opts=>new THREE.RawShaderMaterial(opts),opts=>makeShaderMaterial(opts)]) {- const uniforms={uTarget:{value:target.texture},uMap:{value:texture},- uNested:{value:{samples:[target.texture,texture],offset:new THREE.Vector3(1,2,3)}},- uWeights:{value:new Float32Array([1,2])}};- const original=factory({uniforms});original.userData.uniforms=original.uniforms;- const clone=clonePatchedMaterial(original),shared=clonePatchedMaterial(original,{shareUniforms:true});- const source=original.uniforms,copy=clone.uniforms;- copy.uNested.value.offset.x=7;copy.uWeights.value[0]=8;- results.push({type:clone.type===original.type,- borrowed:copy.uTarget.value===target.texture&©.uMap.value===texture&&- copy.uNested.value.samples[0]===target.texture&©.uNested.value.samples[1]===texture,- independent:copy!==source&©.uTarget!==source.uTarget&&- copy.uNested.value.offset.isVector3&&source.uNested.value.offset.x===1&&source.uWeights.value[0]===1,- alias:clone.userData.uniforms===copy,- shared:shared.uniforms===source&&shared.userData.uniforms===source,- intact:source.uTarget.value===target.texture&&source.uMap.value===texture});- clone.dispose();shared.dispose();original.dispose();-}-target.dispose();texture.dispose();console.log(JSON.stringify({results,warnings}));-""")- assert out == {"results": [dict.fromkeys(- ["type", "borrowed", "independent", "alias", "shared", "intact"], True)] * 3,- "warnings": []}--def test_cloned_and_merged_shader_sample_live_render_target_on_gpu():code, out = compile_scene("""import * as THREE from 'three';@@ -185,88 +99,3 @@ export function createScene({renderer}) {""")assert code == 0, outassert json.loads(out.strip().splitlines()[-1])["ok"]---def test_depth_and_distance_share_clock_displacement_and_alpha_silhouette():- out = measure("""-import * as THREE from 'three';-import {patchStandard,shadowLike,tickShaders} from './lib/shader.js';-const mesh=new THREE.Mesh(new THREE.PlaneGeometry(),new THREE.MeshStandardMaterial());-const head='varying vec2 vCut;';-const body='vCut=uv; transformed.x += sin(uTime);';-patchStandard(mesh.material,{name:'sway',vertexHead:head,vertexBody:body});-shadowLike(mesh,'sway-shadow',head,body,{fragmentHead:head,- fragmentBody:'if(length(vCut-0.5)>0.4) discard;'});-tickShaders(mesh,2.5);-const compiled=[['depth',mesh.customDepthMaterial],['distance',mesh.customDistanceMaterial]]- .map(([key,material])=>{- const template=THREE.ShaderLib[key];- const shader={vertexShader:template.vertexShader,fragmentShader:template.fragmentShader,uniforms:{}};- material.onBeforeCompile(shader);- return {time:material.userData.uniforms.uTime.value,- shared:material.userData.uniforms===mesh.material.userData.uniforms,- displaced:shader.vertexShader.includes('transformed.x += sin(uTime);'),- cut:shader.fragmentShader.includes('if(length(vCut-0.5)>0.4) discard;'),- beforeAlpha:shader.fragmentShader.indexOf('if(length(vCut-0.5)>0.4) discard;')<shader.fragmentShader.indexOf('#include <alphatest_fragment>')};- });-console.log(JSON.stringify({compiled,depth:mesh.customDepthMaterial.isMeshDepthMaterial,- distance:mesh.customDistanceMaterial.isMeshDistanceMaterial}));-""")- assert out["depth"] and out["distance"]- assert out["compiled"] == [{"time": 2.5, "shared": True, "displaced": True,- "cut": True, "beforeAlpha": True}] * 2---def test_point_light_shadow_displacement_and_cut_compile_on_gpu():- code, out = compile_scene("""-import * as THREE from 'three';-import {patchStandard,shadowLike,tickShaders} from './lib/shader.js';-export function createScene() {- const scene=new THREE.Scene();scene.background=new THREE.Color(0x203040);- const light=new THREE.PointLight(0xffffff,60,20);light.position.set(2,4,3);light.castShadow=true;scene.add(light);- const material=new THREE.MeshStandardMaterial({side:THREE.DoubleSide});- const head='varying vec2 vCut;';- const body='vCut=uv; transformed.x += .3*sin(uTime+position.y);';- const cut='if(length(vCut-0.5)>0.4) discard;';- patchStandard(material,{name:'point-cut',vertexHead:head,vertexBody:body,fragmentHead:head,alphaBody:cut});- const mesh=new THREE.Mesh(new THREE.PlaneGeometry(2,2,8,8),material);mesh.position.y=1.5;- shadowLike(mesh,'point-shadow',head,body,{fragmentHead:head,fragmentBody:cut});scene.add(mesh);- const floor=new THREE.Mesh(new THREE.PlaneGeometry(12,12),new THREE.MeshStandardMaterial());- floor.rotation.x=-Math.PI/2;floor.receiveShadow=true;scene.add(floor);- return {scene,cameras:[{name:'a',position:[4,3,6],lookAt:[0,1,0],fov:45}],update(t){tickShaders(scene,t);}};-}-""", audit_module="src/scene.js")- assert code == 0, out---def test_transmission_hook_runs_after_maps_and_survives_clone_on_gpu():- code, out = compile_scene("""-import * as THREE from 'three';-import {patchStandard,clonePatchedMaterial} from './lib/shader.js';-export function createScene({renderer}) {- const scene=new THREE.Scene();- const map=new THREE.DataTexture(new Uint8Array([64,128,255,255]),1,1);map.needsUpdate=true;- const original=new THREE.MeshPhysicalMaterial({transmission:.8,thickness:2,- transmissionMap:map,thicknessMap:map,toneMapped:false});- patchStandard(original,{name:'optical-add',transmissionBody:- 'material.thickness += .2; material.transmission += .1;'});- patchStandard(original,{name:'optical-scale',transmissionBody:- 'material.thickness *= .5; material.transmission *= .5;',- outputBody:'gl_FragColor=vec4(material.thickness*.5,material.transmission,0.,1.);'});- const mesh=new THREE.Mesh(new THREE.PlaneGeometry(4,4),original);scene.add(mesh);- const camera=new THREE.PerspectiveCamera(40,1,.01,100);camera.position.z=5;- const target=new THREE.WebGLRenderTarget(16,16),previous=renderer.getRenderTarget();- const clone=clonePatchedMaterial(original),pixel=new Uint8Array(4);- try {- for(const material of [original,clone]) {- mesh.material=material;renderer.setRenderTarget(target);renderer.render(scene,camera);- renderer.readRenderTargetPixels(target,8,8,1,1,pixel);- const expected=[(2*128/255+.2)*.25,(.8*64/255+.1)*.5,0];- if(expected.some((v,i)=>Math.abs(pixel[i]/255-v)>.006))- throw new Error('Optical map/patch order or cloned chain failed: '+Array.from(pixel));- }- } finally {renderer.setRenderTarget(previous);target.dispose();}- return {scene,cameras:[{name:'a',position:[0,0,5],lookAt:[0,0,0],fov:40}]};-}-""", audit_module="src/scene.js")- assert code == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_signage.py b/harness/tests/scene_runtime/lib/test_signage.pydeleted file mode 100644index f7af263f..00000000--- a/harness/tests/scene_runtime/lib/test_signage.py+++ /dev/null@@ -1,20 +0,0 @@-"""signage.js — the default font path loads under plain node with no node_modules."""--from __future__ import annotations--from tests.scene_runtime.lib._probe import measure---def test_default_font_path_yields_real_glyph_geometry():- """In a bare temp dir with no node_modules and no NODE_PATH — the case that- threw MODULE_NOT_FOUND and killed every census-side `makeText`."""- m = measure("""-import { makeText } from './lib/signage.js';-const a = await makeText('OPEN', { size: 1 });-a.geometry.computeBoundingBox();-const bb = a.geometry.boundingBox;-console.log(JSON.stringify({ w: bb.max.x - bb.min.x, h: bb.max.y - bb.min.y, d: bb.max.z - bb.min.z,- verts: a.geometry.attributes.position.count }));-""", ("signage.js",))- assert m["w"] > m["h"] > 0.5 and m["h"] <= 1.1, m- assert 0.1 < m["d"] < 0.3 and m["verts"] > 500, mdiff --git a/harness/tests/scene_runtime/lib/test_smalllife.py b/harness/tests/scene_runtime/lib/test_smalllife.pydeleted file mode 100644index 56159094..00000000--- a/harness/tests/scene_runtime/lib/test_smalllife.py+++ /dev/null@@ -1,17 +0,0 @@-"""smalllife.js — regression: a camera inside a swarm put a butterfly across a quarter of the frame."""--from __future__ import annotations--from tests.scene_runtime.lib._probe import LIB_DIR---def test_an_insect_at_the_lens_fades_instead_of_becoming_the_subject():- """The close ones fade in the shader, measured from the instance centre, so- every swarm gets it."""- src = (LIB_DIR / "smalllife.js").read_text(encoding="utf-8")- # The fade is measured from the INSTANCE centre in world space, not from- # the mesh origin: every insect in one swarm shares that.- assert "distance(cameraPosition, cW)" in src- assert "vNear = smoothstep(0.35, 1.8" in src- # And it must actually reach the alpha, not just be computed.- assert "a *= vNear;" in srcdiff --git a/harness/tests/scene_runtime/lib/test_surface_filtering.py b/harness/tests/scene_runtime/lib/test_surface_filtering.pydeleted file mode 100644index f706d60f..00000000--- a/harness/tests/scene_runtime/lib/test_surface_filtering.py+++ /dev/null@@ -1,77 +0,0 @@-"""Unresolved material grain averages away, including its chroma variation."""-import json--import pytest--from tests.scene_runtime.lib._probe import compile_scene--pytestmark = pytest.mark.node---def test_micro_breakup_keeps_resolved_detail_and_filters_subpixel_color():- code, out = compile_scene("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-import { patchMicroBreakup } from './lib/surface_wear.js';-export function createScene({renderer}) {- const scene = new THREE.Scene();- const material = new THREE.MeshStandardMaterial({color:new THREE.Color(.4,.4,.4),toneMapped:false});- patchMicroBreakup(material,{strength:.3,hue:.5,scale:.4,seed:7});- patchStandard(material,{name:'read-albedo',outputBody:'gl_FragColor=vec4(diffuseColor.rgb,1.0);'});- const plane = new THREE.Mesh(new THREE.PlaneGeometry(2,2),material);scene.add(plane);- const camera = new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;- const target = new THREE.WebGLRenderTarget(64,64),pixels = new Uint8Array(64*64*4);- const previous = renderer.getRenderTarget();- try {- renderer.setRenderTarget(target);- for (const scale of [.4, .0001]) {- material.userData.uniforms.uMicroScale.value=scale;- renderer.render(scene,camera);renderer.readRenderTargetPixels(target,0,0,64,64,pixels);- let lo=255,hi=0,maxError=0;- for(let i=0;i<pixels.length;i+=4) for(let c=0;c<3;c++) {- lo=Math.min(lo,pixels[i+c]);hi=Math.max(hi,pixels[i+c]);- maxError=Math.max(maxError,Math.abs(pixels[i+c]-102));- }- if(scale>.1 && hi-lo<12) throw new Error('Resolved material lost its grain: '+[lo,hi]);- if(scale<.1 && maxError>1) throw new Error('Subpixel material grain/chroma did not filter to its mean: '+maxError);- }- } finally {- renderer.setRenderTarget(previous);target.dispose();plane.geometry.dispose();material.dispose();- }- scene.remove(plane);- return {scene,cameras:[{name:'probe',position:[0,0,2],lookAt:[0,0,0],fov:45}]};-}-""", libs=("surface_wear.js",))- assert code == 0, out- assert json.loads(out.strip().splitlines()[-1])["ok"]---def test_moss_casts_no_edge_shadow_on_a_dry_sun_facing_wall():- code, out = compile_scene("""-import * as THREE from 'three';-import { patchStandard } from './lib/shader.js';-import { patchMoss } from './lib/damp.js';-export function createScene({renderer}) {- const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);- camera.position.z=2;- const material=new THREE.MeshStandardMaterial({color:new THREE.Color(.4,.4,.4),toneMapped:false});- // The wall faces +Z; the shaded side is -Z. There is no local concavity.- patchMoss(material,{amount:1,north:[0,0,-1]});- patchStandard(material,{name:'dry-wall-albedo',outputBody:'gl_FragColor=vec4(diffuseColor.rgb,1.0);'});- const plane=new THREE.Mesh(new THREE.PlaneGeometry(2,2),material);scene.add(plane);- const target=new THREE.WebGLRenderTarget(32,32),pixels=new Uint8Array(32*32*4);- const previous=renderer.getRenderTarget();- try {- renderer.setRenderTarget(target);renderer.render(scene,camera);- renderer.readRenderTargetPixels(target,0,0,32,32,pixels);- for(let i=0;i<pixels.length;i+=4) for(let c=0;c<3;c++)- if(Math.abs(pixels[i+c]-102)>1) throw new Error('Absent moss darkened the dry wall: '+pixels[i+c]);- } finally {- renderer.setRenderTarget(previous);target.dispose();plane.geometry.dispose();material.dispose();- }- scene.remove(plane);- return {scene,cameras:[{name:'probe',position:[0,0,2],lookAt:[0,0,0],fov:45}]};-}-""", libs=("damp.js",))- assert code == 0, out- assert json.loads(out.strip().splitlines()[-1])["ok"]diff --git a/harness/tests/scene_runtime/lib/test_terrain.py b/harness/tests/scene_runtime/lib/test_terrain.pyindex 7c83afc3..42d1b52b 100644--- a/harness/tests/scene_runtime/lib/test_terrain.py+++ b/harness/tests/scene_runtime/lib/test_terrain.py@@ -1,5 +1,4 @@-"""terrain.js (72 recorded scenes import it through the starter's env.js): the ground ships-as a height function that agrees with its mesh; the cliff is one ribbon."""+"""terrain.js (72 recorded scenes import it through the starter's env.js)."""from __future__ import annotationsimport pytest@@ -11,76 +10,23 @@ _LIBS = ("terrain.js", "materials.js")_PROBE = """import * as THREE from 'three';-import { ground, cliff } from './lib/terrain.js';+import * as MAT from './lib/materials.js';+import { ground } from './lib/terrain.js';const prng = (seed) => { let s = seed; return () => (s = (s * 16807) % 2147483647) / 2147483647; };--// ground(): mesh + height agree, textured and tiled, seeded, flat() damps.const g1 = ground({ size: 200, rand: prng(5), relief: 6 });-const g2 = ground({ size: 200, rand: prng(5), relief: 6 });-const g3 = ground({ size: 200, rand: prng(6), relief: 6 });const pos = g1.mesh.geometry.attributes.position;-let drift = 0, same = 0, other = 0, minY = 1e9, maxY = -1e9;-for (let i = 0; i < pos.count; i += 7) {- drift = Math.max(drift, Math.abs(g1.height(pos.getX(i), pos.getZ(i)) - pos.getY(i)));- same = Math.max(same, Math.abs(g2.mesh.geometry.attributes.position.getY(i) - pos.getY(i)));- other = Math.max(other, Math.abs(g3.mesh.geometry.attributes.position.getY(i) - pos.getY(i)));- minY = Math.min(minY, pos.getY(i)); maxY = Math.max(maxY, pos.getY(i));-}-const flat = ground({ size: 200, rand: prng(5), relief: 6, flat: (x, z) => (Math.hypot(x, z) < 30 ? 1 : 0) });-const m = g1.mesh.material;--// cliff(): one connected ribbon, strata as vertex colours, faceAt on the mesh.-const c = cliff({ length: 300, height: 40, rand: prng(11) });-let meshes = 0; c.mesh.traverse((o) => { if (o.isMesh) meshes++; });-const geo = c.mesh.geometry, cp = geo.attributes.position;-const xs = [...new Set(Array.from({ length: cp.count }, (_, i) => Math.round(cp.getX(i) * 1000) / 1000))].sort((a, b) => a - b);-let maxGap = 0;-for (let i = 1; i < xs.length; i++) maxGap = Math.max(maxGap, xs[i] - xs[i - 1]);-const cell = (xs[xs.length - 1] - xs[0]) / (xs.length - 1);-const bb = new THREE.Box3().setFromObject(c.mesh);-const colAttr = geo.attributes.color;-const distinct = new Set();-for (let i = 0; i < colAttr.count; i++) distinct.add([0, 1, 2].map((k) => Math.round(colAttr.array[i * 3 + k] * 50)).join(','));-let fdrift = 0;-for (const i of [0, Math.floor(cp.count / 3), Math.floor(cp.count / 2), cp.count - 1]) {- const p = c.faceAt(cp.getX(i) + 150, cp.getY(i));- fdrift = Math.max(fdrift, Math.abs(p.z - cp.getZ(i)), Math.abs(p.x - cp.getX(i)), Math.abs(p.y - cp.getY(i)));-}-const c3 = cliff({ length: 120, height: 30, rand: prng(7), strata: [0xff0000, 0x00ff00, 0x0000ff] });-const p3 = c3.mesh.geometry.attributes.position, k3 = c3.mesh.geometry.attributes.color;-const domAt = (ty) => {- let best = 0, bd = 1e9;- for (let i = 0; i < p3.count; i++) { const d = Math.abs(p3.getX(i)) + Math.abs(p3.getY(i) - ty); if (d < bd) { bd = d; best = i; } }- const r = k3.array[best * 3], g = k3.array[best * 3 + 1], b = k3.array[best * 3 + 2];- return r > g && r > b ? 'r' : g > b ? 'g' : 'b';-};-// The default material comes from the SHARED library cache: retiling it in-// place reached back through that cache into every other asset of the look.-import * as MAT from './lib/materials.js';+let drift = 0;+for (let i = 0; i < pos.count; i += 7) drift = Math.max(drift, Math.abs(g1.height(pos.getX(i), pos.getZ(i)) - pos.getY(i)));+// the default material is the SHARED library cache: retiling it in place reached into every other asset of the lookconst wall = MAT.soil();-const wallRepeatBefore = wall.map.repeat.x;const small = ground({ size: 120, rand: prng(5) });const big = ground({ size: 480, rand: prng(5) });-const leak = { wallRepeatBefore, wallRepeatAfter: wall.map.repeat.x,- wallMaterialReused: small.mesh.material === wall, wallMapReused: small.mesh.material.map === wall.map,- smallRepeat: small.mesh.material.map.repeat.x, bigRepeat: big.mesh.material.map.repeat.x,- bumpIsMap: small.mesh.material.bumpMap === small.mesh.material.map,- sharesGpuSource: small.mesh.material.map.source === big.mesh.material.map.source,- wraps: small.mesh.material.map.wrapS === THREE.RepeatWrapping };-// A caller's OWN material is still honoured (and still retiled on a copy).const mine = new THREE.MeshStandardMaterial({ color: 0x808080 });const custom = ground({ size: 240, rand: prng(5), material: mine });-leak.customKept = custom.mesh.material === mine;--console.log(JSON.stringify({- leak,- ground: { drift, same, other, relief: maxY - minY, flatCentre: Math.abs(flat.height(0, 0)), flatEdge: Math.abs(flat.height(90, 90)),- textured: !!m.map && !!m.roughnessMap, repeat: m.map ? m.map.repeat.x : 0,- wraps: m.map ? m.map.wrapS === THREE.RepeatWrapping : false, receives: g1.mesh.receiveShadow, name: g1.mesh.name },- cliff: { meshes, children: c.mesh.children.length, maxGap, cell, minY: bb.min.y, maxY: bb.max.y, zSpan: bb.max.z - bb.min.z,- hasColor: !!colAttr, colorCount: colAttr.count, posCount: cp.count, distinct: distinct.size, drift: fdrift,- band0: domAt(5), band1: domAt(15), band2: domAt(25), children3: c3.mesh.children.length },-}));+console.log(JSON.stringify({ drift, wallRepeat: wall.map.repeat.x, wallReused: small.mesh.material === wall || small.mesh.material.map === wall.map,+ smallRepeat: small.mesh.material.map.repeat.x, bigRepeat: big.mesh.material.map.repeat.x,+ bumpIsMap: small.mesh.material.bumpMap === small.mesh.material.map,+ sharesGpuSource: small.mesh.material.map.source === big.mesh.material.map.source, customKept: custom.mesh.material === mine }));"""@@ -90,59 +36,15 @@ def probe() -> dict:def test_ground_returns_the_height_function_it_displaced_with(probe):- g = probe["ground"]- assert g["drift"] < 1e-5, g- assert g["relief"] > 3, g- assert g["receives"] and g["name"] == "Ground"---def test_ground_is_seeded_and_flat_damps_relief(probe):- g = probe["ground"]- assert g["same"] == 0 and g["other"] > 0.5, g- assert g["flatCentre"] < 1e-9 and g["flatEdge"] > 0.1, g+ assert probe["drift"] < 1e-5, probedef test_ground_retiles_a_copy_never_the_shared_library_material(probe):- """Measured 2026-09-01: `MAT.soil()` is a CACHED material whose maps are- shared with every other caller of that look, and `ground()` set the repeat on- it in place — a wall built with soil before a 480 m ground came out at- repeat 40x40, and two grounds of different sizes fought over one texture."""- k = probe["leak"]- assert k["wallRepeatBefore"] == 1 and k["wallRepeatAfter"] == 1, k- assert not k["wallMaterialReused"] and not k["wallMapReused"], k+ """`MAT.soil()` is cached and its maps are shared; ground() set the repeat on it in place (two grounds fought over one texture)."""+ k = probe+ assert k["wallRepeat"] == 1 and not k["wallReused"], kassert k["smallRepeat"] == 10 and k["bigRepeat"] == 40, k- # bumpMap is the same object as map: one clone, or the emboss slides off.- assert k["bumpIsMap"] and k["wraps"], k- # A Texture clone shares its GPU source: the copy is state, not an upload.- assert k["sharesGpuSource"], k- # A material the caller owns is theirs — never swapped out underneath them.- assert k["customKept"], k---def test_ground_textures_by_default_and_tiles_to_its_size(probe):- g = probe["ground"]- assert g["textured"] and g["wraps"]- assert abs(g["repeat"] - 200 / 12) < 1e-6, g---def test_cliff_is_one_connected_ribbon_with_no_gaps(probe):- c = probe["cliff"]- assert c["meshes"] == 1 and c["children"] == 0- assert c["maxGap"] <= c["cell"] * 1.5 + 1e-6, c---def test_cliff_strata_are_vertex_colors_on_the_face(probe):- c = probe["cliff"]- assert c["hasColor"] and c["colorCount"] == c["posCount"]- assert c["distinct"] >= 6 and c["children3"] == 0- assert (c["band0"], c["band1"], c["band2"]) == ("r", "g", "b"), c---def test_cliff_faceat_matches_the_displaced_mesh(probe):- c = probe["cliff"]- assert c["drift"] < 1e-4, c- assert abs(c["minY"]) < 1e-6 and abs(c["maxY"] - 40) < 1e-6- assert c["zSpan"] > 2, c+ assert k["bumpIsMap"] and k["sharesGpuSource"] and k["customKept"], kdef test_surface_samplers_match_triangles_between_vertices_after_parent_transform():@@ -183,4 +85,3 @@ console.log(JSON.stringify({ groundError, cliffError,assert result["groundError"] < 2e-5, resultassert result["cliffError"] < 2e-5, resultassert result["finiteFlatColors"] and result["edge"], result-diff --git a/harness/tests/scene_runtime/lib/test_terrain_shade.py b/harness/tests/scene_runtime/lib/test_terrain_shade.pydeleted file mode 100644index 2015330e..00000000--- a/harness/tests/scene_runtime/lib/test_terrain_shade.py+++ /dev/null@@ -1,111 +0,0 @@-"""terrain_shade.js — regressions: an off snow line rendered NaN black, and the splat-erased the triplanar it landed on."""-from __future__ import annotations--from tests.scene_runtime.lib._probe import SHADER_JS, measure--_LIBS = ("shader.js", "terrain_shade.js")---def _measure(script: str) -> dict:- return measure(SHADER_JS + script, _LIBS)---def test_snow_is_off_by_default_and_never_settles_on_a_cliff():- """`snowLine: Infinity` cannot reach a float uniform — smoothstep(inf, inf, y)- is NaN, black over the whole terrain — so it is a finite sentinel whose band- still resolves in float32; above the line the steepest faces stay bare."""- out = _measure("""-import * as THREE from 'three';-import { patchSlopeSplat } from './lib/terrain_shade.js';-const sh = fake();-const off = patchSlopeSplat(new THREE.MeshStandardMaterial());-off.onBeforeCompile(sh);-const on = patchSlopeSplat(new THREE.MeshStandardMaterial(),- { snowLine: 180, snow: 0xffffff });-const tight = patchSlopeSplat(new THREE.MeshStandardMaterial(),- { snowLine: 9, snowBand: 1.8 });-const offTight = patchSlopeSplat(new THREE.MeshStandardMaterial(),- { snowBand: 0.05 });-const u = (m, k) => m.userData.uniforms[k].value;-const y = (m) => u(m, 'uSplatSnowY'), b = (m) => u(m, 'uSplatSnowBand');-const resolves = (m) =>- Math.fround(y(m) + b(m)) !== Math.fround(y(m) - b(m));-console.log(JSON.stringify({- fs: sh.fragmentShader,- off: y(off), on: y(on), band: b(off),- tightY: y(tight), tightBand: b(tight),- offTightBand: b(offTight),- bandResolves: resolves(off) && resolves(offTight) && resolves(tight),-}));-""")- assert out["on"] == 180- assert 1e5 <= out["off"] < 1e9, "a sentinel, not Infinity"- assert out["band"] == 5, "the documented default half-width, in metres"- assert out["tightY"] == 9 and out["tightBand"] == 1.8- assert out["offTightBand"] >= 1.0, "a 0.05 m band cannot resolve at 1e6"- assert out["bandResolves"], "the band must survive float32 everywhere"- assert "smoothstep(uSplatHigh, uSplatLow, spUp)" in out["fs"], "snow needs a hold"---def test_the_splat_keeps_the_triplanar_it_lands_on():- """Both patches assigned `diffuseColor.rgb`, so whichever ran second erased- the other; over a triplanar the splat now carries its grain and value through."""- out = measure("""-import * as THREE from 'three';-import { patchTriplanar, patchSlopeSplat } from './lib/terrain_shade.js';-const compile = (build) => {- const m = new THREE.MeshStandardMaterial();- build(m);- const s = { uniforms: {},- vertexShader: 'void main() { #include <begin_vertex> }',- fragmentShader: '#include <color_fragment>' };- m.onBeforeCompile(s);- return s.fragmentShader;-};-const both = compile((m) => { patchTriplanar(m, {}); patchSlopeSplat(m, {}); });-const triOnly = compile((m) => patchTriplanar(m, {}));-const splatOnly = compile((m) => patchSlopeSplat(m, {}));-// The composed body must READ the triplanar's own noise, not just-// declare it and throw it away.-const lastWrite = both.slice(both.lastIndexOf('diffuseColor.rgb ='));-console.log(JSON.stringify({- composedUsesTriNoise: /tpN/.test(lastWrite.split(';')[0]),- composedUsesTriValue: /tpV/.test(lastWrite.split(';')[0]),- triAloneStillAssigns: /diffuseColor\\.rgb = tpC;/.test(triOnly),- splatAloneUnchanged:- /diffuseColor\\.rgb = spC \\* mix\\(0\\.86, 1\\.14, spVar\\);/- .test(splatOnly),- // The detection must survive the documented `name` option: it- // used to key off the name, so one custom name undid the fix.- survivesACustomName: (() => {- const m = new THREE.MeshStandardMaterial();- patchTriplanar(m, { name: 'myRock' });- patchSlopeSplat(m, {});- const s = { uniforms: {},- vertexShader: 'void main() { #include <begin_vertex> }',- fragmentShader: '#include <color_fragment>' };- m.onBeforeCompile(s);- const last = s.fragmentShader.slice(- s.fragmentShader.lastIndexOf('diffuseColor.rgb ='));- return /tpN/.test(last.split(';')[0]);- })(),- // Different structure means a different program: sharing the cache- // key would serve one compiled shader to both shapes.- distinctKey: (() => {- const a = new THREE.MeshStandardMaterial();- patchTriplanar(a, {}); patchSlopeSplat(a, {});- const b = new THREE.MeshStandardMaterial();- patchSlopeSplat(b, {});- return a.customProgramCacheKey() !== b.customProgramCacheKey();- })(),-}));-""", _LIBS)- assert out["composedUsesTriNoise"], (- "the splat threw the triplanar away again")- assert out["composedUsesTriValue"], (- "the splat flattened the triplanar's mass value and up-face wash")- assert out["triAloneStillAssigns"] and out["splatAloneUnchanged"]- assert out["survivesACustomName"], (- "a custom name must not undo the composition")- assert out["distinctKey"]diff --git a/harness/tests/scene_runtime/lib/test_vegetation_dynamics.py b/harness/tests/scene_runtime/lib/test_vegetation_dynamics.pydeleted file mode 100644index f9ddba53..00000000--- a/harness/tests/scene_runtime/lib/test_vegetation_dynamics.py+++ /dev/null@@ -1,220 +0,0 @@-"""Numerical regressions for world wind and normals of deformed cloth."""-from __future__ import annotations--import re--import pytest--from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure--pytestmark = pytest.mark.node--_LIBS = ("grass.js", "flowers.js", "smalllife.js", "canopy.js", "cloth.js",- "foliage_shade.js", "finish.js")--# Run the production material's actual vertex patch, with constant per-plant-# attributes across a screen quad. Float readback measures positions/normals-# independently of rasterized blade size, lighting, or camera-facing widths.-_VERTEX_PROBE = """-function vertexProbe(source, renderer, scene, camera, target) {- const compiled = {uniforms:{}, fragmentShader:'void main() {}', vertexShader:`- uniform vec3 uProbePoint, uProbeRoot;- uniform float uProbeNormal;- varying vec3 vNormal, vProbe;- void main() {- vNormal=vec3(0.,0.,1.);- #include <begin_vertex>- vProbe=uProbeNormal>.5 ? vNormal : (modelMatrix*vec4(transformed,1.)).xyz-uProbeRoot;- gl_Position=vec4(position.xy,0.,1.);- }`};- source.material.onBeforeCompile(compiled);- const uniforms={...compiled.uniforms,uProbePoint:{value:new THREE.Vector3()},- uProbeRoot:{value:new THREE.Vector3()},uProbeNormal:{value:0}};- const material=new THREE.ShaderMaterial({uniforms,- vertexShader:compiled.vertexShader.replace('#include <begin_vertex>','#include <begin_vertex>\\n transformed=uProbePoint;'),- fragmentShader:'varying vec3 vProbe; void main(){gl_FragColor=vec4(vProbe,1.);}',- toneMapped:false,depthTest:false,depthWrite:false});- const geometry=new THREE.PlaneGeometry(2,2);- for(const [name,attribute] of Object.entries(source.geometry.attributes)) {- if(['position','normal','uv'].includes(name)) continue;- const value=Array.from(attribute.array.slice(0,attribute.itemSize));- geometry.setAttribute(name,new THREE.Float32BufferAttribute(Array(4).fill(value).flat(),attribute.itemSize));- }- const mesh=new THREE.Mesh(geometry,material);mesh.frustumCulled=false;mesh.matrixAutoUpdate=false;- const pixel=new Float32Array(4);- return {- sample({matrix=new THREE.Matrix4(),root=new THREE.Vector3(),point=new THREE.Vector3(),attrs={},normal=false,time=0}={}) {- mesh.matrix.copy(matrix);uniforms.uProbePoint.value.copy(point);uniforms.uProbeRoot.value.copy(root);- uniforms.uProbeNormal.value=normal?1:0;uniforms.uTime.value=time;- for(const [name,value] of Object.entries(attrs)) {- const a=geometry.attributes[name];for(let i=0;i<a.count;i++)a.array.set(value,i*a.itemSize);a.needsUpdate=true;- }- scene.add(mesh);renderer.setRenderTarget(target);renderer.render(scene,camera);- renderer.readRenderTargetPixels(target,1,1,1,1,pixel);scene.remove(mesh);- if(!Array.from(pixel).every(Number.isFinite)||pixel[3]!==1)throw new Error('Nonfinite/empty vertex readback: '+pixel);- return new THREE.Vector3().fromArray(pixel);- },- dispose(){geometry.dispose();material.dispose();},uniforms,- };-}-"""---def test_legacy_vegetation_shares_world_wind_after_parent_rotation_and_translation():- code, out = compile_scene("""-import * as THREE from 'three';-import {makeGrass} from './lib/grass.js';-import {makeFlowers} from './lib/flowers.js';-import {makeReeds} from './lib/smalllife.js';-import {makeCanopy} from './lib/canopy.js';-import {makeWheatField} from './lib/cloth.js';-""" + _VERTEX_PROBE + """-export function createScene({renderer}) {- const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;- const opts={extent:2,density:2,seed:5,wind:{dir:[1,.35],strength:1.4},shadows:true};- const groups=[makeGrass(opts),makeFlowers(opts),makeReeds(opts),makeWheatField(opts),makeCanopy({density:4,...opts})];- const names=['Blades','Plants','Stems','Stalks','Leaves'];- const shape=[{iShape:[1,.05,0,0],iVar:[0,.37,.2,0]},- {iShape:[1,.02,1,1],iBend:[.6,0,0,.4],iVar:[0,.4,.3,1],aPart:[0,0,0]},- {iShape:[1,.02,.2,.03],iBend:[.5,.1,0,0],iVar:[.37,.2,.3,.4],aPart:[0]},- {iCrop:[1,.01,.8,1],iVar:[.37,0,0],aPart:[0]},- {iAxis:[0,1,0],iVar:[0,.2,.4,1]}];- const target=new THREE.WebGLRenderTarget(4,4,{type:THREE.FloatType}),previous=renderer.getRenderTarget();- let error=0,shadowError=0;- try {- for(let kind=0;kind<groups.length;kind++) {- const source=groups[kind].getObjectByName(names[kind]);- const probe=vertexProbe(source,renderer,scene,camera,target);- const shadow=vertexProbe({geometry:source.geometry,material:source.customDepthMaterial},renderer,scene,camera,target);- for(const root of [new THREE.Vector3(0,0,0),new THREE.Vector3(2.5,0,-4)]) for(const time of [0,.73,3.1]) {- let reference=null;- for(const yaw of [0,Math.PI/2,-Math.PI/3]) {- const matrix=new THREE.Matrix4().makeRotationY(yaw);- matrix.setPosition(yaw===0?0:3,0,yaw===0?0:-2);- const local=root.clone().applyMatrix4(matrix.clone().invert());- const attrs={...shape[kind],iPos:local.toArray(),aCorner:[0,1,0]};- if(kind===4)attrs.iSpray=[...local.toArray(),.4];- const sample={matrix,root,attrs,time},actual=probe.sample(sample),depth=shadow.sample(sample);- if(reference)error=Math.max(error,actual.distanceTo(reference));else reference=actual;- shadowError=Math.max(shadowError,actual.distanceTo(depth));- }- }- probe.dispose();shadow.dispose();- }- } finally {renderer.setRenderTarget(previous);target.dispose();groups.forEach(g=>g.userData.dispose());}- if(error>.002||shadowError>.00001)throw new Error('World-wind/depth mismatch: '+JSON.stringify({error,shadowError}));- return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};-}-""", _LIBS, audit_module="src/scene.js")- assert code == 0, out---def test_flag_and_banner_normals_match_finite_differences_of_their_displacement():- code, out = compile_scene("""-import * as THREE from 'three';-import {makeFlag,makeBanner} from './lib/cloth.js';-""" + _VERTEX_PROBE + """-export function createScene({renderer}) {- const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;- const groups=[makeFlag({width:2,height:1,wind:3}),makeBanner({width:2,drop:2,wind:3})];- const target=new THREE.WebGLRenderTarget(4,4,{type:THREE.FloatType}),previous=renderer.getRenderTarget();- let error=0;- try {- for(let kind=0;kind<2;kind++) {- const source=groups[kind].getObjectByName(kind?'BannerCloth':'FlagSheet');- const probe=vertexProbe(source,renderer,scene,camera,target);- const sample=(x,y,time,normal=false)=>{- const u=x/2+.5,s=-y/2,k=5;- // Analytic profiles isolate the displacement from tessellation density.- const attrs=kind?{aBan:[s,Math.sin(k*x),k*Math.cos(k*x),k*k*x/2+k*Math.sin(2*k*x)/4]}:- {aFlag:[u,u**1.6,1.6*u**.6,u**4.2/4.2]};- return probe.sample({point:new THREE.Vector3(x,y,0),attrs,time,normal});- };- const epsilon=.0005;- for(const x of [-.73,.13,.77])for(const y of [-.25,-.8])for(const time of [.4,1.6]) {- const dx=sample(x+epsilon,y,time).sub(sample(x-epsilon,y,time));- const dy=sample(x,y+epsilon,time).sub(sample(x,y-epsilon,time));- const expected=dx.cross(dy).normalize(),actual=sample(x,y,time,true).normalize();- error=Math.max(error,1-expected.dot(actual));- }- probe.dispose();- }- } finally {renderer.setRenderTarget(previous);target.dispose();groups.forEach(g=>g.userData.dispose());}- if(error>.00005)throw new Error('Cloth normal does not follow displaced tangents: '+error);- return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};-}-""", ("cloth.js", "grass.js"), audit_module="src/scene.js")- assert code == 0, out---def test_legacy_transition_masks_have_defined_edges():- """Equal snow slopes and six reversed silhouette ramps were undefined GLSL."""- out = measure("""-import * as THREE from 'three';-import {patchSlopeSplat} from './lib/terrain_shade.js';-const values=[];-for(const pair of [[.6,.6],[.6,.6+1e-10],[.45,.75],[.75,.45]]) {- const m=patchSlopeSplat(new THREE.MeshStandardMaterial(),{slopeLow:pair[0],slopeHigh:pair[1]});- const u=m.userData.uniforms,lo=Math.fround(u.uSplatHigh.value),hi=Math.fround(u.uSplatLow.value);- const masks=[lo-.01,(lo+hi)/2,hi+.01].map(x=>THREE.MathUtils.smoothstep(x,lo,hi));- values.push({lo,hi,masks});-}-console.log(JSON.stringify({values}));-""", ("terrain_shade.js",))- for item in out["values"]:- assert item["lo"] < item["hi"]- assert item["masks"] == pytest.approx([0, .5, 1], abs=1e-8)- for module in ("flock.js", "smalllife.js", "woodland.js"):- # GLSL leaves edge0 >= edge1 undefined even when one GPU accepts it.- for match in re.finditer(r"smoothstep\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,",- (LIB_DIR / module).read_text()):- assert float(match[1]) < float(match[2]), (module, match[0])---def test_falling_sample_matches_gpu_after_parent_and_child_transforms():- """World wind must have the same local velocity in the public CPU sampler."""- code, out = compile_scene("""-import * as THREE from 'three';-import {makeFalling} from './lib/flowers.js';-""" + _VERTEX_PROBE + """-export function createScene({renderer}) {- const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1,1,1,-1,.1,10);camera.position.z=2;- const parent=new THREE.Group(),group=makeFalling({count:7,seed:13,extent:8,height:5,- wind:{dir:[1,.35],strength:1.4}}),source=group.getObjectByName('Drift');- parent.add(group);parent.matrixAutoUpdate=group.matrixAutoUpdate=source.matrixAutoUpdate=false;- const matrix=(position,rotation,scale)=>new THREE.Matrix4().compose(new THREE.Vector3(...position),- new THREE.Quaternion().setFromEuler(new THREE.Euler(...rotation)),new THREE.Vector3(...scale));- const identity=new THREE.Matrix4(),outer=matrix([3,.7,-4],[.2,.6,-.1],[1.7,.65,2.3]);- const local=matrix([-.5,.2,.8],[0,.47,0],[.8,1.2,1.4]);- const child=matrix([.3,.4,-.6],[.2,.9,.4],[.8,1.2,2.1]);- const nearSingular=new THREE.Matrix4().set(1,0,1,0, 0,1,0,0, 0,0,1e-9,0, 0,0,0,1);- const transforms=[[identity,identity,identity],- [matrix([2,0,-1],[0,Math.PI/2,0],[1,1,1]),identity,identity],- [outer,local,identity],[outer,local,child],- [identity,identity,new THREE.Matrix4().makeScale(0,1,1)],- [identity,identity,nearSingular]];- const target=new THREE.WebGLRenderTarget(4,4,{type:THREE.FloatType}),previous=renderer.getRenderTarget();- const probe=vertexProbe(source,renderer,scene,camera,target);- let error=0;- try {- for(const [parentMatrix,groupMatrix,childMatrix] of transforms) {- parent.matrix.copy(parentMatrix);group.matrix.copy(groupMatrix);source.matrix.copy(childMatrix);- // No scene update/render precedes sample(): it must refresh its ancestors.- for(const time of [.73,0,3.1,-2.4,31.7])for(const index of [-4,3,99]) {- const expected=group.userData.sample(index,time);- // Rendering refreshes matrices independently of the public CPU sampler.- source.updateWorldMatrix(true,false);expected.applyMatrix4(group.matrixWorld);- const k=Math.min(6,Math.max(0,index)),attrs={aCorner:[0,0,0]};- for(const name of ['aPos','aFall','aAxis','aWob','aVar']) {- const a=source.geometry.attributes[name];attrs[name]=Array.from(a.array.slice(k*a.itemSize,(k+1)*a.itemSize));- }- const actual=probe.sample({matrix:source.matrixWorld,attrs,time});- error=Math.max(error,actual.distanceTo(expected));- }- }- } finally {renderer.setRenderTarget(previous);probe.dispose();target.dispose();group.userData.dispose();}- if(error>.00015)throw new Error('Falling CPU/GPU transformed sample mismatch: '+error);- return {scene,cameras:[{name:'a',position:[0,0,2],lookAt:[0,0,0],fov:45}]};-}-""", _LIBS, audit_module="src/scene.js")- assert code == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_veils.py b/harness/tests/scene_runtime/lib/test_veils.pydeleted file mode 100644index cb2e8f93..00000000--- a/harness/tests/scene_runtime/lib/test_veils.py+++ /dev/null@@ -1,68 +0,0 @@-"""veils.js (15 recorded scenes import it): a veil is lit by the scene it hangs in, and-none of the three fields is a wall to a depth or shadow pass."""--from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import measure--pytestmark = pytest.mark.node---def test_no_veil_is_a_wall_to_a_depth_or_shadow_pass():- """An override pass (GTAO) draws a stack of transparent sheets as solid- floors. Every other veil in the library was guarded; these three were not."""- out = measure("""-import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';-const out = {};-for (const [k, g, name] of [['veil', makeRainVeil({ extent: 90, height: 40 }), 'RainSheets'],- ['snow', makeSnowfall({ extent: 36, height: 16 }), 'Snowflakes'],- ['mote', makeMotes({ extent: 5, height: 3 }), 'DustMotes']]) {- const m = g.getObjectByName(name);- out[k] = [!!m.userData.astraNoOverride, m.castShadow === true];-}-console.log(JSON.stringify(out));-""", ("shader.js", "veils.js"))- for k, (guarded, casts) in out.items():- assert guarded and not casts, k---def test_a_veil_carries_the_light_of_the_scene_it_hangs_in():- """An unlit pale card is the brightest thing in any frame that is not- daylight (a moonlit rain curtain measured +0.189 luminance over a 0.170- scene). The probe answers with the irradiance where the field hangs,- normalised so the library's own day rig is 1.0."""- out = measure("""-import * as THREE from 'three';-import { makeRainVeil, makeSnowfall, makeMotes } from './lib/veils.js';-import { sunRig } from './lib/environment.js';-// the light probe hangs off onBeforeRender, the only place a Mesh is handed its scene-const R = { info: { render: { frame: 0 } } };-const lit = (field, scene, frame) => {- scene.add(field);- scene.updateMatrixWorld(true);- R.info.render.frame = frame;- const m = field.children[0];- m.onBeforeRender(R, scene, new THREE.PerspectiveCamera(), m.geometry, m.material, null);- return m.material.uniforms.uLight.value.toArray();-};-const rigScene = (elev, fog) => {- const s = new THREE.Scene();- const rig = sunRig({ azimuth: 215, elevation: elev });- s.add(rig.sun, rig.fill);- s.fog = new THREE.FogExp2(fog, 0.0035);- return s;-};-const night = rigScene(-20, 0x0b0f1a);-console.log(JSON.stringify({- day: lit(makeRainVeil({ extent: 70 }), rigScene(38, 0xcfd8e6), 100),- night: lit(makeRainVeil({ extent: 70 }), night, 200),- snow: lit(makeSnowfall({ extent: 30, height: 14 }), night, 200),- mote: lit(makeMotes({ extent: 5, height: 3 }), night, 200),-}));-""", ("shader.js", "veils.js", "environment.js", "sky.js"))- day, night = out["day"], out["night"]- assert all(0.85 <= c <= 1.25 for c in day), day # daylight unchanged- assert max(night) < 0.55 * min(day) and night[2] > night[0] * 1.3, out # dark, and blue- assert max(out["snow"]) < 0.55 * min(day) and max(out["mote"]) < 0.7 * min(day), outdiff --git a/harness/tests/scene_runtime/lib/test_water_transport.py b/harness/tests/scene_runtime/lib/test_water_transport.pydeleted file mode 100644index a870cb64..00000000--- a/harness/tests/scene_runtime/lib/test_water_transport.py+++ /dev/null@@ -1,129 +0,0 @@-"""Rendered water lighting and refracted caustic transport regressions."""-from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import compile_scene, measure--pytestmark = pytest.mark.node---def test_normal_texture_resolution_preserves_wave_slopes():- out = measure("""-import { makeWaterNormals } from './lib/water.js';-const slopes = (size, broadband) => {- const texture = makeWaterNormals(size, {broadband}), data = texture.image.data;- let sum = 0;- for(let i = 0; i < data.length; i += 4) {- const x = data[i] / 255 * 2 - 1, y = data[i + 1] / 255 * 2 - 1, z = data[i + 2] / 255 * 2 - 1;- sum += (x * x + y * y) / (z * z);- }- texture.dispose(); return Math.sqrt(sum / (data.length / 4));-};-console.log(JSON.stringify({ narrow: [128, 256, 512].map(s => slopes(s, false)),- broad: [128, 256, 512].map(s => slopes(s, true)) }));-""", ("water.js",))- for spectrum in out.values():- assert spectrum == pytest.approx([spectrum[1]] * 3, rel=0.025), out- # The default 256px appearance is preserved, not flattened to the 512px one.- assert out["narrow"][1] == pytest.approx(0.6003103576558382), out---def test_underwater_extinction_is_finite_nonnegative_and_caller_owned():- out = measure("""-import * as THREE from 'three';-import { patchUnderwater } from './lib/submerged.js';-const invalid = [-1, NaN, Infinity, [-1, .2, .3], [0, NaN, 1], [0, 1],- new THREE.Vector3(0, -.2, .3), new THREE.Vector3(0, Infinity, .3)];-let rejected = 0;-for(const extinction of invalid) {- const material = new THREE.MeshStandardMaterial();- try { patchUnderwater(material, {extinction}); }- catch(error) { if(error instanceof RangeError) rejected++; else throw error; }- material.dispose();-}-const input = new THREE.Vector3(0, .2, .3), material = new THREE.MeshStandardMaterial();-patchUnderwater(material, {extinction: input});-const before = material.userData.uniforms.uSubExt.value.toArray(); input.set(1, 1, 1);-console.log(JSON.stringify({rejected, total: invalid.length, before,- after: material.userData.uniforms.uSubExt.value.toArray()}));-material.dispose();-""", ("submerged.js",))- assert out["rejected"] == out["total"], out- assert out["before"] == out["after"] == [0, 0.2, 0.3], out---def test_water_sums_fill_and_caustics_follow_the_refracted_beam():- code, output = compile_scene(r"""-import * as THREE from 'three';-import { makeOcean } from './lib/water.js';-import { patchCaustics } from './lib/caustics.js';-import { withRendererState } from './lib/shader.js';-export function createScene({renderer}) {- const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(45, 1, .1, 50);- camera.position.set(0, 4, 5); camera.lookAt(0, 0, 0); camera.updateMatrixWorld(true);- const sky = new THREE.HemisphereLight(0x6ca1ca, 0x101010, .7);- const fill = new THREE.AmbientLight(0xc99771, .45);- const other = new THREE.AmbientLight(0x637486, .3);- const key = new THREE.DirectionalLight(0xffbbaa, 2); key.position.set(4, 7, 1);- key.target.position.set(1, 2, -2); scene.add(sky, fill, other, key, key.target);- const water = makeOcean(6, 6, { rttSize: 64 }); scene.add(water); scene.updateMatrixWorld(true);- const checkColor = (a, b) => {- if (Math.max(...a.toArray().map((v, i) => Math.abs(v - b.toArray()[i]))) > 1e-10)- throw Error('Water omitted ambient/hemisphere illumination');- };- water.onBeforeRender(renderer, scene, camera);- checkColor(water.material.uniforms.ambientColor.value, sky.color.clone().multiplyScalar(.7)- .add(fill.color.clone().multiplyScalar(.45)).add(other.color.clone().multiplyScalar(.3)).multiplyScalar(1 / Math.PI));- const expectedDirection = key.position.clone().sub(key.target.position).normalize();- if(water.material.uniforms.sunDirection.value.distanceTo(expectedDirection) > 1e-10) throw Error('Water ignored light target');- sky.visible = false; fill.visible = false; other.visible = false;- water.onBeforeRender(renderer, scene, camera);- checkColor(water.material.uniforms.ambientColor.value, new THREE.Color(0, 0, 0));- scene.remove(water); water.userData.dispose();- const pinned = makeOcean(6, 6, { rttSize: 64, ambient: 0x123456, sunDir: new THREE.Vector3(1, 2, 3), sunColor: 0xabcdef });- scene.add(pinned); scene.updateMatrixWorld(true); pinned.onBeforeRender(renderer, scene, camera);- checkColor(pinned.material.uniforms.ambientColor.value, new THREE.Color(0x123456));- checkColor(pinned.material.uniforms.sunColor.value, new THREE.Color(0xabcdef));- if(pinned.material.uniforms.sunDirection.value.distanceTo(new THREE.Vector3(1, 2, 3).normalize()) > 1e-10) throw Error('Water changed pinned direction');- scene.remove(pinned); pinned.userData.dispose();-- const basin = new THREE.Scene(), top = new THREE.OrthographicCamera(-1, 1, 1, -1, .1, 20);- top.position.set(0, 4, 0); top.up.set(0, 0, -1); top.lookAt(0, -1, 0); top.updateMatrixWorld(true);- const sun = new THREE.Vector3(1, .1, 0).normalize();- const material = new THREE.MeshStandardMaterial({color: 0xffffff, roughness: 1, side: THREE.DoubleSide});- patchCaustics(material, {sunDir: sun, level: 0, strength: 1, color: 0xffffff, depthFade: 3});- const geometry = new THREE.PlaneGeometry(2, 2); geometry.rotateX(-Math.PI / 2);- const surface = new THREE.Mesh(geometry, material); surface.position.y = -1; basin.add(surface);- const target = new THREE.WebGLRenderTarget(32, 32, {type: THREE.FloatType});- const pixels = new Float32Array(32 * 32 * 4), u = material.userData.uniforms;- function energy(normal) {- for(let i = 0; i < geometry.attributes.normal.count; i++) geometry.attributes.normal.setXYZ(i, ...normal);- geometry.attributes.normal.needsUpdate = true;- renderer.setRenderTarget(target); renderer.render(basin, top); renderer.readRenderTargetPixels(target, 0, 0, 32, 32, pixels);- const sum = [0, 0, 0];- for(let i = 0; i < pixels.length; i += 4) for(let c = 0; c < 3; c++) sum[c] += pixels[i + c];- return sum;- }- try { withRendererState(renderer, () => {- renderer.toneMapping = THREE.NoToneMapping;- const upward = energy([0, 1, 0]), facing = energy([1, 0, 0]), away = energy([-1, 0, 0]);- const slide = u.uCauSlide.value.length(), cosWater = 1 / Math.hypot(1, slide);- if(upward[0] <= 0 || Math.abs(facing[0] / upward[0] - slide) > .002) throw Error('Caustic incidence used the air ray');- if(Math.max(...away) > 1e-6) throw Error('Back-facing surface received direct caustics');- // Move to twice the depth while preserving the surface entry point. The- // pattern, focus and incidence stay fixed; only Beer-Lambert changes.- surface.position.set(-u.uCauSlide.value.x, -2, -u.uCauSlide.value.y);- top.position.x = surface.position.x; top.position.z = surface.position.z; top.updateMatrixWorld(true);- const deep = energy([0, 1, 0]);- for(let c = 0; c < 3; c++) {- const expected = Math.exp(-u.uCauAbs.value.getComponent(c) / cosWater);- if(Math.abs(deep[c] / upward[c] - expected) > .003) throw Error('Caustics absorbed over vertical depth instead of beam length');- }- u.uCauSun.value.y *= -1;- if(Math.max(...energy([0, 1, 0])) > 1e-6) throw Error('A set sun still produced caustics');- }); } finally { target.dispose(); geometry.dispose(); material.dispose(); }- return {scene: new THREE.Scene(), cameras: [{name: 'probe', position: [0, 3, 5], lookAt: [0, 0, 0]}]};-}-""", ("water.js", "caustics.js"), audit_module="src/scene.js")- assert code == 0, outputdiff --git a/harness/tests/scene_runtime/lib/test_watermist.py b/harness/tests/scene_runtime/lib/test_watermist.pydeleted file mode 100644index 69b161b8..00000000--- a/harness/tests/scene_runtime/lib/test_watermist.py+++ /dev/null@@ -1,54 +0,0 @@-"""watermist.js (8 recorded scenes import it) — regression: a set sun still lit the mist bank."""--from __future__ import annotations--from tests.scene_runtime.lib._probe import measure--_LIBS = ("shader.js", "watermist.js")---def test_the_sun_below_the_horizon_delivers_nothing():- """`sunRig` keeps reporting the authored sun after it sets; a sun gain that- ignored elevation put a lit bank into a night frame."""- out = measure("""-import { makeWaterMist, makeSpray } from './lib/watermist.js';-const gain = (dir) => [- makeWaterMist({ sunDir: dir }).getObjectByName('MistCards')- .material.uniforms.uSunGain.value,- makeSpray({ rate: 60, sunDir: dir }).getObjectByName('SprayDroplets')- .material.uniforms.uSunGain.value,-];-const dirOf = (o) => o.getObjectByName('MistCards')- .material.uniforms.uSunDir.value.toArray();-console.log(JSON.stringify({- high: gain([-0.65, 0.62, -0.45]),- grazing: gain([-0.8, 0.06, -0.6]),- set: gain([-0.6, -0.34, -0.72]),- none: gain(undefined),- noneDir: dirOf(makeWaterMist({})),- unit: dirOf(makeWaterMist({ sunDir: [0, 4, 3] })),-}));-""", _LIBS)- assert out["set"] == [0, 0], out- assert all(g > 0.5 for g in out["high"]), out- # A grazing sun delivers a fraction, not all of it and not none.- for a, b in zip(out["grazing"], out["high"], strict=True):- assert 0 < a < b, out- # No rig to hand: top lit at full strength, which is the old look.- assert out["none"] == out["high"], out- assert out["noneDir"] == [0, 1, 0], out- assert abs(sum(v * v for v in out["unit"]) - 1.0) < 1e-6, out---def test_zero_mist_density_has_zero_optical_opacity():- out = measure("""-import { makeWaterMist } from './lib/watermist.js';-const alpha = density => {- const mist = makeWaterMist({ density, extent: 4 });- const a = mist.getObjectByName('MistCards').material.uniforms.uAlpha.value;- mist.userData.dispose(); return a;-};-console.log(JSON.stringify({ off: alpha(0), faint: alpha(.0001), normal: alpha(.5) }));-""", _LIBS)- assert out["off"] == 0, out- assert 0 < out["faint"] < out["normal"], outdiff --git a/harness/tests/scene_runtime/lib/test_windows.py b/harness/tests/scene_runtime/lib/test_windows.pydeleted file mode 100644index 82637479..00000000--- a/harness/tests/scene_runtime/lib/test_windows.py+++ /dev/null@@ -1,48 +0,0 @@-"""windows.js — regression: the cell id hashed a perspective-interpolated key, and every facade rendered as static."""--from __future__ import annotations--from tests.scene_runtime.lib._probe import SHADER_JS, measure--_LIBS = ("shader.js", "windows.js")--# A fresh window-interior patch, run through the two hooks of SHADER_JS.-_PATCHED = """-const patched = (opts) => {- const sh = fake();- patchWindowInteriors(new THREE.MeshStandardMaterial(), opts || {})- .onBeforeCompile(sh);- return sh;-};-"""--_PRELUDE = """-import * as THREE from 'three';-import { patchWindowInteriors } from './lib/windows.js';-""" + SHADER_JS + _PATCHED---def _measure(script: str, libs: tuple[str, ...] = _LIBS) -> dict:- return measure(_PRELUDE + script, libs)---def test_the_cell_id_is_a_whole_number_lattice_or_the_facade_is_static():- """A perspective-correct varying comes back a few ULPs apart per pixel, and two- chained astraHash21 calls amplify that into a per-pixel coin flip. Every term- of the id is rounded; drop one floor() and the facade fizzes again."""- out = _measure("""-const sh = patched();-console.log(JSON.stringify({ fs: sh.fragmentShader }));-""")- fs = out["fs"]- assert "vec3 winKq = floor(vWinKey * 16.0 + 0.5);" in fs- assert ("float winFace = dot(floor(winNn * 4.0 + 0.5),"- " vec3(11.0, 29.0, 53.0));") in fs- assert ("float winB = floor(astraHash21(winKq.xz + winKq.y) * 29.0)"- " + winFace;") in fs- assert "vec2 winId = floor(winG)" in fs- assert "vec2(uWinSeed + winB, floor(uWinSeed * 1.7) - winB);" in fs- # The furniture noise enters its lattice through the cell HASHES, not- # through the id, so its coordinate stays small enough to interpolate.- assert "vec2 winNz = winHit.xy * 3.0 + vec2(winHt, winHl) * 37.0;" in fs- assert "winShade *= mix(0.55, 1.0, astraNoise2(winNz));" in fsdiff --git a/harness/tests/scene_runtime/test_assemble.py b/harness/tests/scene_runtime/test_assemble.pyindex c5e76363..1381e734 100644--- a/harness/tests/scene_runtime/test_assemble.py+++ b/harness/tests/scene_runtime/test_assemble.py@@ -6,92 +6,18 @@ import mathimport pytest-from codeverse3d.contracts.plan import CameraPlanfrom codeverse3d.languages.scene_threejs import (- ZoneProbe,assemble,- cameras_from_specs,lint,- render_scene_js,sun_azimuth,)-from tests.scene_runtime.conftest import needs_browser, needs_node--BOX_A = {"min": [-10, 0, -10], "max": [10, 6, 10], "size": [20, 6, 20]}-BOX_B = {"min": [20, 0, -5], "max": [30, 3, 5], "size": [10, 3, 10]}--# what probe_scene.mjs --sun-azimuth 90 emits for the two-zone layout above-# (camera-fit math is owned by runtime_js/lib/orbit.mjs; tested in test_orbit.py)-SPECS = {- "azimuth": 90,- "overview": {"position": [55.0, 22.0, 0.0], "lookAt": [10.0, 3.0, 0.0], "fov": 50},- "zones": [- {"group": "__zone__harbour", "position": [14.4, 2.2, 0.0], "lookAt": [0.0, 2.6, 0.0], "fov": 50},- {"group": "__zone__market", "position": [32.2, 1.9, 0.0], "lookAt": [25.0, 1.55, 0.0], "fov": 50},- ],-}---def test_cameras_from_specs_sun_side_and_order():- probes = {- "harbour": ZoneProbe(name="harbour", file="src/zones/harbour.js", ok=True, bbox=BOX_A),- "market": ZoneProbe(name="market", file="src/zones/market.js", ok=True, bbox=BOX_B),- "broken": ZoneProbe(name="broken", file="src/zones/broken.js", ok=False, error="boom"),- }- cams = cameras_from_specs(SPECS, probes)- assert [c.name for c in cams] == ["overview", "harbour_view", "market_view"]- ov = cams[0]- assert ov.position == (55.0, 22.0, 0.0) and ov.look_at == (10.0, 3.0, 0.0)- assert ov.purpose.startswith("fallback:") # a fitted camera is a fallback the plan did not name (D106)- hv = cams[1]- assert hv.position[0] > 10 and math.dist(hv.position, hv.look_at) > 10- assert cams[2].purpose.startswith("fallback: zone Market")---def test_cameras_from_specs_fallback_without_zones_or_specs():- cams = cameras_from_specs({}, {})- assert len(cams) == 1 and cams[0].name == "overview" and "fallback" in cams[0].purpose- # measurable zones but no driver specs (e.g. probe ran without --sun-azimuth)- probes = {"harbour": ZoneProbe(name="harbour", file="src/zones/harbour.js", ok=True, bbox=BOX_A)}- cams2 = cameras_from_specs({}, probes)- assert len(cams2) == 1 and "fallback" in cams2[0].purpose---def test_render_scene_js_contents():- cams = [CameraPlan(name="overview", position=(1, 2, 3), look_at=(0, 0, 0), fov=50)]- src = render_scene_js(["harbour", "fish_market"], cams, ["crane"], env_ok=True)- assert "import { build as buildHarbour } from './zones/harbour.js';" in src- assert "addZone(buildFishMarket, 'FishMarket');" in src- # the loader carries the URL *and* the name to stamp on the loaded root- assert "crane: { name: 'Crane', url: '/assets/crane.glb' }" in src- assert "root.name = a.name;" in src- assert "name: 'overview', position: [1, 2, 3]" in src- assert "import { buildEnv, heightAt } from './env.js';" in src- assert "const addZone = async (build, name) => {" in src- assert "const g = await build(ctx);" in src- assert "await addZone(buildHarbour, 'Harbour');" in src- assert "const env = (await buildEnv(ctx)) || {};" in src- src2 = render_scene_js([], cams, [], env_ok=False)- assert "env.js" not in src2 and "heightAt: () => 0" in src2- assert "assetFiles" not in src2 and "loadAsync" not in src2 # no GLB asset, no loader---@needs_node-def test_assemble_without_probe_writes_all_zones(starter_ws):- assert sun_azimuth(starter_ws) == 60.0 # the starter env's sun: the side every derived camera stands on- res = assemble(starter_ws, probe=False)- assert set(res.zones_included) == {"meadow", "pondside"}- assert (starter_ws.src / "scene.js").read_text().startswith("// src/scene.js — ASSEMBLED")- assert lint(starter_ws).passed- assert (starter_ws.artifacts / "assemble.json").is_file()+from tests.scene_runtime.conftest import needs_browser@pytest.mark.node@needs_browserdef test_assemble_probes_each_zone_excludes_the_broken_and_boots(starter_ws):- """One probed assembly: a throwing zone and a zone with no build are excluded with- their reasons, an async build() is awaited, the driver fits an overview plus one- camera per measured zone, and the assembled scene then boots through the probe."""+ """One probed assembly."""zones = starter_ws.src / "zones"(zones / "broken.js").write_text("export function build(ctx) { throw new Error('kaboom'); }\n")(zones / "nobuild.js").write_text("export const x = 1;\n")@@ -129,9 +55,7 @@ def test_assemble_probes_each_zone_excludes_the_broken_and_boots(starter_ws):@pytest.mark.node@needs_browserdef test_fitted_overview_faces_the_lit_side_inside_the_plan_bounds(tmp_ws):- """Regressions (audit 2026-09-24 N8, N9): the assembler's fitted cameras stand on the side- `sunRig({azimuth})` lights — at 135° they stood exactly opposite the sun — and the overview- is framed inside the plan bounds like the render rig's, not around a 400 m meadow (549 m out)."""+ """Regressions (audit 2026-09-24 N8, N9)."""import jsonfrom codeverse3d.languages.scene_threejs import probe_zone_modulesdiff --git a/harness/tests/scene_runtime/test_backdrop.py b/harness/tests/scene_runtime/test_backdrop.pyindex cd672a4f..26d49e4a 100644--- a/harness/tests/scene_runtime/test_backdrop.py+++ b/harness/tests/scene_runtime/test_backdrop.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-from pathlib import Pathimport pytest@@ -13,28 +12,21 @@ from tests.scene_runtime.conftest import needs_node, run_node_jsonpytestmark = [pytest.mark.node, needs_node]RUNTIME_JS = get_settings().runtime_js_dir()-LIB_DIR = Path(__file__).resolve().parents[2] / "codeverse3d/languages/scene_threejs/starter/src/lib"CASES = [# (name, box size [sx, sy, sz], instanced, content span, expected)("SkyDome", [400, 200, 400], False, 0, "sky"),- ("Anything", [3000, 10, 3000], False, 0, "sky"),("GroundPlane", [60, 0.2, 60], False, 0, "ground"),- ("Terrain", [30, 1.0, 30], False, 0, "ground"), # named ground, flat enough("Meadow", [100, 0.5, 100], False, 0, "ground"), # unnamed but very wide + flat("Grass", [80, 1.0, 80], True, 0, "content"), # scatter: instanced wins("Cabin", [6, 4, 5], False, 0, "content"),- ("Cabin", [6, 4, 5], False, 3, "content"),("Path", [30, 0.1, 30], False, 5, "ground"), # far larger than the content bbox("Path", [30, 0.1, 30], False, 0, "content"), # same box, no content bbox known("Rug", [3, 0.05, 3], False, 40, "content"), # small relative to content: not backdrop("PlanetSkyBackdrop", [205, 205, 205], False, 0, "sky"),- ("planet_sky_backdrop", [205, 205, 205], False, 0, "sky"),("SkyAtmosphereBand0", [90, 4, 90], False, 0, "sky"),("MoonLamp", [1, 1, 1], False, 0, "content"), # a solid prop remains content("SkyScraper", [25, 200, 25], False, 0, "content"), # the size guard still matters- ("HDRISky", [400, 200, 400], False, 0, "sky"), # acronym names split like to_snake (N5)- ("GPUTerrain", [30, 1.0, 30], False, 0, "ground"),]@@ -66,81 +58,13 @@ def test_classifier_rule_table():assert got == [c[4] for c in CASES] + ["sky", "content"], list(zip([c[0] for c in CASES], got, strict=False))-def test_background_planet_and_small_moon_do_not_move_content_framing():- body = f"""-import * as THREE from 'three';-import {{ sceneCensus }} from '{RUNTIME_JS}/lib/host_census.mjs';-import {{ framingBox }} from '{RUNTIME_JS}/lib/orbit.mjs';-const scene = new THREE.Scene(), environment = new THREE.Group();-environment.name = 'Environment'; scene.add(environment);-const subject = new THREE.Mesh(new THREE.BoxGeometry(30, 20, 40), new THREE.MeshStandardMaterial());-subject.name = 'Hangar'; subject.position.y = 10; environment.add(subject);-const planet = new THREE.Mesh(new THREE.SphereGeometry(100), new THREE.MeshBasicMaterial());-planet.name = 'PlanetSkyBackdrop'; planet.position.set(25, -55, -200); environment.add(planet);-const moon = new THREE.Mesh(new THREE.CircleGeometry(2.5), new THREE.MeshBasicMaterial({{ depthWrite: false }}));-moon.name = 'MoonDisc'; moon.position.set(-277, 137, -103); environment.add(moon);-const census = sceneCensus(scene, THREE);-console.log(JSON.stringify({{ content: census.content_bbox, all: census.bbox, framed: framingBox(census) }}));-"""- got = run_node_json(body)- assert got["content"]["min"] == [-15, 0, -20]- assert got["content"]["max"] == [15, 20, 20]- assert got["framed"] == got["content"]- assert got["all"]["min"][0] < -270 # background geometry is retained and still counted---def test_explicit_sky_metadata_requires_non_depth_writing_materials():- got = run_node_json(f"""-import * as THREE from 'three';-import {{ classifyBackdrop, drawableBox }} from '{RUNTIME_JS}/lib/backdrop.mjs';-const clear = new THREE.MeshBasicMaterial({{ depthWrite: false }});-const solid = new THREE.MeshBasicMaterial();-const classify = (material, marker) => {{- const mesh = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), material);- mesh.name = 'WeatherPart'; mesh.userData.sceneBackdrop = marker;- return classifyBackdrop(mesh, drawableBox(mesh, THREE));-}};-console.log(JSON.stringify([- classify(clear, 'sky'), classify(solid, 'sky'), classify([clear, solid], 'sky'),- classify(clear, undefined), classify(clear, 'content'),-]));-""")- assert got == ["sky", "content", "content", "content", "content"]---def test_compact_clouds_preserve_content_framing_with_custom_names_and_scale():- got = run_node_json(f"""-import * as THREE from 'three';-import {{ makeClouds, makeCirrus }} from '{LIB_DIR}/clouds.js';-import {{ sceneCensus }} from '{RUNTIME_JS}/lib/host_census.mjs';-import {{ framingBox }} from '{RUNTIME_JS}/lib/orbit.mjs';-const results = [];-for (const factory of [makeClouds, makeCirrus]) for (const custom of [false, true]) {{- const scene = new THREE.Scene();- const subject = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshStandardMaterial());- subject.name = 'House'; scene.add(subject);- const cloud = factory({{ count: 1, area: 600, quality: 'low', ...(custom ? {{ name: 'WeatherDeck' }} : {{}}) }});- if (custom) cloud.scale.setScalar(.01);- scene.add(cloud);- const census = sceneCensus(scene, THREE);- results.push({{ kind: census.groups[1].kind, framed: framingBox(census) }});- cloud.userData.dispose(); subject.geometry.dispose(); subject.material.dispose();-}}-console.log(JSON.stringify(results));-""")- for result in got:- assert result["kind"] == "sky", result- assert result["framed"] == {"min": [-5, -5, -5], "max": [5, 5, 5], "size": [10, 10, 10]}, result--#: names on both sides of every JS name rule: acronyms, instance separators, long numeric idsNAMES = ["Leg_2", "Rock.003", "Fence-1", "Leg2", "DonkeyCart_800006", "Leg_", "Planter_12", "LEDStairs","HDRISky", "UVGround", "GPUTerrain", "PondWater", "pond_water", "SkyAtmosphereBand0", "TV-Stand.2", ""]def test_js_name_rules_mirror_conventions():- """Audit 2026-09-24 N3/N5: `splitInstance` IS `conventions.split_instance` and `nameWords` IS- `to_snake`'s words — the census/placement copies split `Fence-1` and `LEDStairs` otherwise."""+ """Audit 2026-09-24 N3/N5."""from codeverse3d.conventions import split_instance, to_snakegot = run_node_json(f"""@@ -154,8 +78,7 @@ console.log(JSON.stringify({{ split: names.map(splitInstance), words: names.map(def test_instanced_scatter_is_one_box_for_census_and_coverage():- """Audit 2026-09-24 N28: 40 cloud puffs over 3 km were `sky` to the census (its own- per-instance box) and `content` to coverage (`drawableBox` = one 10 m puff)."""+ """Audit 2026-09-24 N28."""got = run_node_json(f"""import * as THREE from 'three';import {{ classifyBackdrop, drawableBox }} from '{RUNTIME_JS}/lib/backdrop.mjs';diff --git a/harness/tests/scene_runtime/test_camera_inside_volume.py b/harness/tests/scene_runtime/test_camera_inside_volume.pyindex 59d52b24..246de780 100644--- a/harness/tests/scene_runtime/test_camera_inside_volume.py+++ b/harness/tests/scene_runtime/test_camera_inside_volume.py@@ -1,9 +1,4 @@-"""A lens is "inside" a mesh's VOLUME, not its bounding box.--Regression: a camera 4.9 m from the nearest surface was `camera_in_geometry` because a-windmill's 22 m lattice sails' bbox contained the eye; the repair moved it for nothing.-`eyeInsideMesh` decides by ray parity over the mesh's triangles; the bbox is a pre-filter.-"""+"""A lens is "inside" a mesh's VOLUME, not its bounding box."""from __future__ import annotationsimport pytest@@ -47,11 +42,6 @@ for (const m of sails.children) { m.name = 'Sails_1'; }sails.position.set(0, 12, 0); sails.rotation.y = Math.PI / 4; scene.add(sails);"""-ROOM = """-const room = new THREE.Mesh(new THREE.BoxGeometry(6, 3, 6), solid);-room.name = 'CottageShell'; room.position.set(0, 1.5, 0); scene.add(room);-"""-# a 3 m snow mound 40 m from the lens: the census's highest ground surface, not the ground under the eyeMOUND = """const mound = new THREE.Mesh(new THREE.BoxGeometry(10, 3, 10), solid);@@ -83,8 +73,6 @@ def got() -> dict:"""Every case below, in one node process."""return run_node_json(HEAD + "".join([_case("sails_near", SAILS, "4.5, 12, 4.5"), # inside the 45-degree sails' world bbox, 6.4 m from the hub, in the air- _case("room", ROOM, "0.5, 1.6, 0.5"),- _case("hub", SAILS, "0, 12, 0"), # the hub itself, inside both arms_case("mound", MOUND, "0, 1.6, 0"),_case("void", MOUND, "60, 1.6, 60"), # off the 80 x 80 m ground: nothing beneath the lens_case("pillar", PILLAR, "0, 1.6, 0", "[0, 1.6, -4]", js=_PILLAR_JS),@@ -100,23 +88,8 @@ def test_a_lens_near_lattice_sails_is_not_inside_them(got):assert g["camera_in_geometry"] is False, g-def test_a_lens_in_a_back_face_culled_room_is_still_inside(got):- """The case the bbox rule was written for keeps its verdict: a FrontSide box around the- eye is all back faces to a Raycaster, and parity still counts it."""- g = got["room"]- assert g["inside_mesh_bbox"] == ["CottageShell"], g- assert g["camera_in_geometry"] is True, g---def test_a_lens_inside_a_solid_arm_is_inside(got):- g = got["hub"]- assert "Sails_1" in g["inside_mesh_bbox"], g- assert g["camera_in_geometry"] is True, g--def test_the_ground_under_the_lens_is_the_ray_straight_down_not_the_highest_ground(got):- """Loop 21's ski station (2026-09-09): eye 3.2 m on relief terrain, the highest snow 3.14 m,- the gate said "0.06 m above ground — ant's-eye view" and the judge repeated it."""+ """Ski station: eye 3.2 m on relief, highest snow 3.14 m read as 0.06 m above ground."""g = got["mound"]assert abs(g["ground_below_m"] - 1.6) < 1e-3 and g["ground_below_name"] == "Ground", gassert got["void"]["ground_below_m"] is None, got["void"]diff --git a/harness/tests/scene_runtime/test_camera_repair.py b/harness/tests/scene_runtime/test_camera_repair.pyindex bb3c8a2c..dc249d10 100644--- a/harness/tests/scene_runtime/test_camera_repair.py+++ b/harness/tests/scene_runtime/test_camera_repair.py@@ -33,13 +33,6 @@ const after = fix ? nearGeometry(scene, makeCam(fix.spec), THREE) : null;// a camera with open air in front needs no repairconst fine = { name: 'Establishing', position: [10, 4, 10], lookAt: [0, 1, 0], fov: 45 };const noFix = repairCameraSpec(scene, fine, THREE, makeCam);-// a lens under a 60 m terrain raised to y = 3 (cmp6's lighthouse SlipwaySurge): lifted to eye level above it-const head = new THREE.Mesh(new THREE.PlaneGeometry(60, 60, 2, 2), mat);-head.name = 'HeadlandTerrain'; head.rotation.x = -Math.PI / 2; head.position.set(0, 3.0, -40); scene.add(head);-scene.updateMatrixWorld(true);-const buried = { name: 'SlipwaySurge', position: [5, 1.6, -40], lookAt: [0, 4.0, -30], fov: 45 };-const lifted = repairCameraSpec(scene, buried, THREE, makeCam);-const liftedAfter = lifted ? nearGeometry(scene, makeCam(lifted.spec), THREE) : null;// a squat pillar 0.8 m before the lens, the subject 4 m behind it (loop 22's crypt: 9 of 9 rays on a// well, a black frame): stepped out of it sideways / up, and the line of sight to lookAt is open afterconst pillar = new THREE.Mesh(new THREE.BoxGeometry(1.2, 3.2, 1.2), mat);@@ -48,7 +41,7 @@ scene.updateMatrixWorld(true);const staring = { name: 'AthanorDetail', position: [20, 1.6, 20], lookAt: [20, 1.2, 16], fov: 45 };const stepped = repairCameraSpec(scene, staring, THREE, makeCam);const steppedAfter = stepped ? nearGeometry(scene, makeCam(stepped.spec), THREE, undefined, staring.lookAt) : null;-console.log(JSON.stringify({ fix, after, noFix, lifted, liftedAfter, stepped, steppedAfter }));+console.log(JSON.stringify({ fix, after, noFix, stepped, steppedAfter }));"""@@ -67,18 +60,6 @@ def test_a_lens_inside_geometry_retreats_until_clear(result):assert after["nearest_hit_m"] is None or after["nearest_hit_m"] >= 0.5-def test_a_clear_camera_is_left_exactly_as_authored(result):- assert result["noFix"] is None---def test_a_lens_under_a_ground_surface_is_lifted_to_eye_level_above_it(result):- lifted = result["lifted"]- assert lifted is not None and lifted["under_before"] == "HeadlandTerrain", lifted- assert abs(lifted["spec"]["position"][1] - (3.0 + 1.6)) < 1e-6, lifted # terrain at 3 m + 1.6 m eye- after = result["liftedAfter"]- assert after["ground_above_m"] is None and abs(after["ground_below_m"] - 1.6) < 1e-3, after--def test_a_lens_staring_at_a_surface_is_stepped_out_of_it_and_its_line_of_sight_opened(result):stepped = result["stepped"]assert stepped is not None and stepped["blocked_before"] is True and stepped["cut_before"] == "StonePillar_3", steppeddiff --git a/harness/tests/scene_runtime/test_census_instances.py b/harness/tests/scene_runtime/test_census_instances.pyindex e73a4af2..bc5a7d41 100644--- a/harness/tests/scene_runtime/test_census_instances.py+++ b/harness/tests/scene_runtime/test_census_instances.py@@ -69,34 +69,3 @@ export function createScene({renderer}) {}""", audit_module="src/scene.js")assert code == 0, output---def test_bound_gpu_capacity_ignores_unused_short_instanced_attributes():- """Only attributes used by the linked program constrain Three's draw."""- code, output = compile_scene("""-import * as THREE from 'three';-import {sceneCensus} from '/__runtime/lib/host_census.mjs';-export function createScene({renderer}) {- const scene=new THREE.Scene(),geo=new THREE.InstancedBufferGeometry().copy(new THREE.PlaneGeometry());- geo.setAttribute('activeOffset',new THREE.InstancedBufferAttribute(new Float32Array(24),3));- geo.setAttribute('unusedShort',new THREE.InstancedBufferAttribute(new Float32Array(3),3));- const material=new THREE.ShaderMaterial({vertexShader:- 'attribute vec3 activeOffset;void main(){gl_Position=projectionMatrix*modelViewMatrix*vec4(position+activeOffset,1.0);}',- fragmentShader:'void main(){gl_FragColor=vec4(.3,.6,.8,1.0);}'});- const mesh=new THREE.Mesh(geo,material);mesh.frustumCulled=false;scene.add(mesh);- const camera=new THREE.PerspectiveCamera(45,1,.01,100);camera.position.z=3;- const target=new THREE.WebGLRenderTarget(32,32),previous=renderer.getRenderTarget();- try {- for(const requested of [8,3,Infinity]) {- geo.instanceCount=requested;- renderer.setRenderTarget(target);renderer.render(scene,camera);- const census=sceneCensus(scene,THREE).totals,expected=Math.min(requested,8);- if(geo._maxInstanceCount!==8 || census.instances!==expected ||- census.triangles!==renderer.info.render.triangles || census.triangles!==expected*2)- throw new Error(JSON.stringify({requested,census,capacity:geo._maxInstanceCount,render:renderer.info.render}));- }- } finally {renderer.setRenderTarget(previous);target.dispose();}- return {scene,cameras:[{name:'a',position:[0,0,3],lookAt:[0,0,0]}]};-}-""", audit_module="src/scene.js")- assert code == 0, outputdiff --git a/harness/tests/scene_runtime/test_census_stamps.py b/harness/tests/scene_runtime/test_census_stamps.pyindex b7ec58e0..1bc9a934 100644--- a/harness/tests/scene_runtime/test_census_stamps.py+++ b/harness/tests/scene_runtime/test_census_stamps.py@@ -1,5 +1,4 @@-"""The census measures a stamped ring: >= 8 copies of a family, how evenly they sit on a circle-round their centroid and how alike their sizes are (`groups[].stamps`, 2026-09-09)."""+"""The census measures a stamped ring."""from __future__ import annotations@@ -49,8 +48,3 @@ def test_a_perfect_ring_of_instances_reads_as_stamped():assert peaks["radius_cv"] < 0.01 and peaks["gap_cv"] < 0.01 and peaks["size_cv"] < 0.01, peakscols = st["Column"] # numbered plain meshes are one familyassert cols["n"] == 10 and abs(cols["radius_m"] - 5) < 0.2, cols---def test_a_jittered_ring_is_not():- peaks = _stamps(0.25)["Peaks"]- assert peaks["radius_cv"] > 0.1 and peaks["size_cv"] > 0.1, peaksdiff --git a/harness/tests/scene_runtime/test_driver_flags.py b/harness/tests/scene_runtime/test_driver_flags.pyindex 354c409b..3a44c004 100644--- a/harness/tests/scene_runtime/test_driver_flags.py+++ b/harness/tests/scene_runtime/test_driver_flags.py@@ -1,10 +1,4 @@-"""Every documented driver flag must PARSE.--Regression: --no-settle / --camera-repair / --auto-exposure were read but never declared-in the parseArgs whitelist, so the first battery to enable them crashed every render.-Each driver runs with all optional flags and no workspace: it must die on OUR-'--ws is required', never in the argument parser.-"""+"""Every documented driver flag must PARSE."""from __future__ import annotations@@ -17,7 +11,7 @@ from tests.scene_runtime.conftest import needs_nodepytestmark = [pytest.mark.node, needs_node]-FLAGS = ["--no-settle", "--camera-repair", "--auto-exposure", "--no-post"]+FLAGS = ["--no-settle", "--camera-repair", "--no-post"]@pytest.mark.parametrize("driver", ["render_scene.mjs", "probe_scene.mjs"])diff --git a/harness/tests/scene_runtime/test_env_check.py b/harness/tests/scene_runtime/test_env_check.pyindex d5532519..3e1b54bb 100644--- a/harness/tests/scene_runtime/test_env_check.py+++ b/harness/tests/scene_runtime/test_env_check.py@@ -1,7 +1,4 @@-"""D112: ``SceneThreeJsRuntime.check_env`` / ``lib_interface`` — the env module alone, checked before a-recovered env counts as written (argon loop iteration 5: 5 of 21 recovered modules failed only at-assembly — ``materials.js does not export 'gravel'``, ``pavingPatch is not defined`` — and one more was-unlit)."""+"""D112: env.js check; a good env passes, a bad import, a throw or an unlit scene says why."""from __future__ import annotations@@ -51,15 +48,3 @@ def test_a_good_env_passes_and_each_broken_one_says_why(tmp_path):error = check_env(_ws(tmp_path / name, env))assert says in error, (name, error)assert not list((tmp_path / "good" / "run" / "src").glob("_c3v_env_probe*")), "the probe entry is deleted"---def test_an_arrow_function_export_is_listed_with_its_parameters(tmp_path):- """D112 review: the material factories are ``export const asphalt = (o = {}) => …`` — listed as bare- names, a single-shot writer could not tell them from constants. A parenthesised value is not a call."""- from codeverse3d.languages._js_lint import export_signatures-- row = next(r for r in lib_interface(_ws(tmp_path, GOOD)).splitlines() if r.startswith("lib/materials.js: "))- assert "asphalt(o = {})" in row.split(": ", 1)[1].split(", ")- src = ("export const a = (x, {y = 1} = {}) => x;\nexport const b = async (p) => p;\nexport const c = q => q;\n"- "export let d = function named(m, n) { return m; };\nexport const K = (1 + 2) * 3;\nexport const ARR = [1, 2];\n")- assert export_signatures(src) == ["ARR", "K", "a(x, {y = 1} = {})", "b(p)", "c(q)", "d(m, n)"]diff --git a/harness/tests/scene_runtime/test_external_shaders.py b/harness/tests/scene_runtime/test_external_shaders.pyindex af0662ff..dccc7b3a 100644--- a/harness/tests/scene_runtime/test_external_shaders.py+++ b/harness/tests/scene_runtime/test_external_shaders.py@@ -84,59 +84,3 @@ def test_real_gpu_compiles_external_sources_and_maps_failures(tmp_path, broken):and "missingExternalFactor" in item["message"] for item in failures), failureselse:assert report["ok"] and report["errors"] == []---@needs_browser[email protected]("declaration", [True, False])-def test_external_uniform_header_can_be_joined_with_inline_glsl(tmp_path, declaration):- root = stage(tmp_path)- (root / "src/shaders/panel.frag").write_text("uniform float uTime;\n" if declaration else "// No declaration\n")- scene = SCENE.replace("fragmentShader:common + '\\n' + fragment,",- "fragmentShader:common + '\\n' + fragment + `\\nvoid main(){gl_FragColor=vec4(vec3(uTime),1.0);}`, ")- assert scene != SCENE- (root / "src/scene.js").write_text(scene)- proc = subprocess.run(["node", str(RUNTIME_JS / "check_shaders.mjs"), "--ws", str(root)],- capture_output=True, text=True, timeout=120)- assert proc.returncode == (0 if declaration else 1), proc.stdout + proc.stderr- report = json.loads(proc.stdout.strip().splitlines()[-1])- if declaration:- assert report["ok"] and report["errors"] == []- assert any(item["kind"] == "undeclared_uniform" and item.get("validation") == "runtime_compile_passed"- for item in report["warnings"])- else:- assert any(item["kind"] == "compile" for item in report["errors"])- assert any(item["kind"] == "undeclared_uniform" for item in report["errors"])---@needs_browser[email protected]("unused", ["other_file", "same_file", "duplicate_file"])-def test_valid_external_header_does_not_clear_unused_declaration_errors(tmp_path, unused):- """GPU success proves the evaluated body, not every literal in the workspace."""- root = stage(tmp_path)- (root / "src/shaders/panel.frag").write_text("uniform float uTime;\n")- body = "void main(){gl_FragColor=vec4(vec3(uTime),1.0);}"- scene = SCENE.replace("fragmentShader:common + '\\n' + fragment,",- f"fragmentShader:common + '\\n' + fragment + `\\n{body}`, ")- inactive = body if unused == "duplicate_file" else body.replace("vec3(uTime)", "vec3(uTime*.37)")- unused_source = f"export const unusedFragment = `{inactive}`;\n"- if unused == "same_file":- scene += unused_source- expected_file = "src/scene.js"- else:- expected_file = "src/shaders/unused.js"- (root / expected_file).write_text(unused_source)- (root / "src/scene.js").write_text(scene)- proc = subprocess.run(["node", str(RUNTIME_JS / "check_shaders.mjs"), "--ws", str(root)],- capture_output=True, text=True, timeout=120)- assert proc.returncode == 1, proc.stdout + proc.stderr- report = json.loads(proc.stdout.strip().splitlines()[-1])- assert report["compile"]["programs"] > 0- assert not any(item["kind"] == "compile" for item in report["errors"])- assert any(item["kind"] == "undeclared_uniform" and item["file"] == expected_file- for item in report["errors"]), report- if unused == "other_file":- assert any(item["kind"] == "undeclared_uniform" and item["file"] == "src/scene.js"- and item.get("validation") == "runtime_compile_passed"- for item in report["warnings"]), reportdiff --git a/harness/tests/scene_runtime/test_glb_asset_naming.py b/harness/tests/scene_runtime/test_glb_asset_naming.pyindex bca3f0b9..c492344e 100644--- a/harness/tests/scene_runtime/test_glb_asset_naming.py+++ b/harness/tests/scene_runtime/test_glb_asset_naming.py@@ -1,9 +1,4 @@-"""A loaded GLB root is named after its asset, or nothing can find it.--Regression: a glTF root carries whatever the exporter wrote ("Scene" from Blender),-and the assembler handed that to the zones, so `scene_placement` reported a loaded-`LoungeSofa` as missing from both zones that held it.-"""+"""A loaded GLB root is named after its asset, or nothing can find it."""from __future__ import annotations@@ -14,8 +9,7 @@ import pytestfrom codeverse3d.contracts.plan import CameraPlanfrom codeverse3d.languages.scene_threejs import render_scene_jsfrom codeverse3d.spatial.node import run_node-from tests.scene_runtime.conftest import needs_browser, needs_node-from tests.scene_runtime.glb_fixture import write_box_glb+from tests.scene_runtime.conftest import needs_nodepytestmark = [pytest.mark.node, needs_node]@@ -79,9 +73,7 @@ def test_a_loaded_glb_carries_its_planned_name_and_plays_its_clip(tmp_path):def test_a_procedural_asset_is_rendered_on_the_hero_rig(tmp_ws):- """`render_asset` is the hook `scene_assets` judges a threejs asset through: the module is- exported by the object track's exporter and rendered on the quick rig a hero's GLB gets.- Nothing defined it until 2026-09-07, so 0 of 860 recorded procedural assets were judged."""+ """`render_asset` is the hook `scene_assets` judges a threejs asset through."""from codeverse3d.languages.scene_threejs import SceneThreeJsRuntime(tmp_ws.src / "assets").mkdir(parents=True, exist_ok=True)@@ -95,32 +87,3 @@ 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) >= 4assert (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, rowdiff --git a/harness/tests/scene_runtime/test_glsl_audit.py b/harness/tests/scene_runtime/test_glsl_audit.pyindex d9e40e86..07560ca6 100644--- a/harness/tests/scene_runtime/test_glsl_audit.py+++ b/harness/tests/scene_runtime/test_glsl_audit.py@@ -54,8 +54,7 @@ export const m = new THREE.ShaderMaterial({ fragmentShader: frag });"""def test_the_static_audit_rules():- """Every rule the shader preflight reports before (or without) a GPU compile, with its- severity and its file line — the finding an agent is handed."""+ """Every rule the shader preflight reports before (or without) a GPU compile, with its severity and its file line — the finding an agent is handed."""got = audit_all({"include": (INCLUDE, {}), "out_plus": (OUT_PLUS_FRAGCOLOR, {}),"utime_bare": (UTIME_BARE, {}), "utime_ok": (UTIME_OK, {}),@@ -82,16 +81,3 @@ def test_the_static_audit_rules():assert "no_fog" not in kinds(got["fog_unused"])assert "no_fog" in kinds(got["fog_used"])assert "no_fog" not in kinds(got["fog_opt_out"])---def test_locate_source_line_maps_to_file_and_line():- files = [- {"file": "src/shaders/a.js", "text": "const f = `\nvoid main() {\n float x = undefinedThing;\n}`;"},- {"file": "src/shaders/b.js", "text": "const g = `\nvoid main() { gl_FragColor = vec4(1.0); }`;"},- ]- body = f"""-import {{ locateSourceLine }} from './lib/glsl_audit.mjs';-console.log(JSON.stringify(locateSourceLine({json.dumps(files)}, 'float x = undefinedThing;')));-"""- loc = run_node_json(body)- assert loc == {"file": "src/shaders/a.js", "line": 3, "candidates": 1}diff --git a/harness/tests/scene_runtime/test_js_named_imports.py b/harness/tests/scene_runtime/test_js_named_imports.pyindex 9bde7c7b..b9f71423 100644--- a/harness/tests/scene_runtime/test_js_named_imports.py+++ b/harness/tests/scene_runtime/test_js_named_imports.py@@ -1,17 +1,9 @@-"""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``."""+"""The named-import half of the JS import policy (``languages/_js_lint``)."""from __future__ import annotations-from pathlib import Path--from codeverse3d.contracts.artifacts import GateFinding, Severityfrom codeverse3d.languages._js_lint import (NamedImport,- check_named_imports,- describe_exports,- exported_names,- module_exports,named_import_specs,)@@ -33,63 +25,3 @@ def test_named_import_specs_forms():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.pyindex b019b565..0d313f14 100644--- a/harness/tests/scene_runtime/test_lint.py+++ b/harness/tests/scene_runtime/test_lint.py@@ -15,15 +15,6 @@ def _msgs(report, sev=None):return [(f.target, f.message) for f in report.findings if sev is None or f.severity == sev]-def test_required_scene_entry_and_export(ws):- rep = lint(ws)- assert not rep.passed- assert any("src/scene.js is missing" in m for _, m in _msgs(rep, Severity.ERROR))- (ws.src / "scene.js").write_text("import * as THREE from 'three';\nexport function makeScene() {}\n")- rep = lint(ws)- assert any("does not export createScene" in m for _, m in _msgs(rep, Severity.ERROR))--def test_forbidden_imports_and_globals(ws):(ws.src / "scene.js").write_text("import * as THREE from 'three';\n"@@ -77,12 +68,6 @@ def test_zone_without_build_and_asset_without_factory(ws):assert any("asset module exports no build" in m for _, m in _msgs(rep, Severity.WARN))-def test_large_file_warning(ws):- (ws.src / "scene.js").write_text("export function createScene() { return {}; }\n" + "// pad\n" * 900)- 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"@@ -110,9 +95,7 @@ def _zone_errors(ws, zone: str) -> list[tuple[str, str, str]]: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."""+ """it00_scene_threejs_r1_18."""(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")@@ -136,45 +119,3 @@ def test_every_export_form_is_recognised(ws):_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.pyindex 68151074..1a6d8a41 100644--- a/harness/tests/scene_runtime/test_orbit.py+++ b/harness/tests/scene_runtime/test_orbit.py@@ -20,8 +20,7 @@ VIEWS = [def test_orbit_rig_fitting():- """The rig's convention, the orbit views, the per-zone eye and the overview — every- camera the harness derives for a scene, in one node process."""+ """The rig's convention, the orbit views, the per-zone eye and the overview — every camera the harness derives for a scene, in one node process."""body = f"""import {{ fitOrbitCameras, fitZoneCamera, fitOverviewCamera, orbitDirection }} from './lib/orbit.mjs';const zone = {{ min: [20, 0, -5], max: [30, 3, 5], size: [10, 3, 10] }};@@ -70,31 +69,3 @@ console.log(JSON.stringify({{assert cam["position"][0] > 40 and cam["position"][1] > 0.5assert 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'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.pyindex 5d827564..fc73468b 100644--- a/harness/tests/scene_runtime/test_placement_census.py+++ b/harness/tests/scene_runtime/test_placement_census.py@@ -93,15 +93,6 @@ def test_supported_floating_and_sunk_boxes(table):assert anvil["supported"] and not anvil["floating"]-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)]- assert pairs[0]["inside_frac"] > 0.2 and pairs[0]["zone_a"] == "Yard"- for name in ("CrateA", "CrateB"):- r = _row(table, name)- assert r["sunk_m"] == 0 and r["ground_gap_m"] == 0 and r["attached"] == ["CrateB" if name == "CrateA" else "CrateA"]--def test_no_false_positives_on_legitimate_placements(table):"""Nested furniture, canopy, water, and terrain contacts classify correctly."""for name, support in (("Table", "Ground"), ("Cup", "Table"), ("Chair", "Ground"), ("Tree", "Ground"), ("Bench", "Ground")):@@ -115,7 +106,6 @@ def test_no_false_positives_on_legitimate_placements(table):assert rock["sunk_into"] == "Ground" and 0.3 < rock["sunk_m"] < 0.5 and not rock["floating"]-SETTLE_JS = """import * as THREE from 'three';import fs from 'node:fs';diff --git a/harness/tests/scene_runtime/test_placement_inner_families.py b/harness/tests/scene_runtime/test_placement_inner_families.pyindex 4d0acc0a..098761cf 100644--- a/harness/tests/scene_runtime/test_placement_inner_families.py+++ b/harness/tests/scene_runtime/test_placement_inner_families.py@@ -1,11 +1,4 @@-"""The placement row's `inner` names count FAMILIES (2026-09-07).--D59 lists a row's named descendants (capped at `MAX_INNER_NAMES`) so the plan-contents check-can see through a wrapper group. The cap counted every distinct name, so a wrapper holding-30 `Planter_N` before the hero clone hid the hero and the check reported it missing. One-slot per family (`Planter_3` / `Planter.003` → `Planter`) keeps the hero visible and the-by-name check still matches on the plan's word.-"""+"""The placement row's `inner` names count FAMILIES (2026-09-07)."""from __future__ import annotationsimport pytest@@ -47,11 +40,7 @@ console.log(JSON.stringify({{ cap: MAX_INNER_NAMES, inner: row.inner, hasHero: r@pytest.mark.parametrize("sep", ["", "_", "-"])def test_a_wrapper_of_scattered_instances_reports_the_instance_size(sep: str):- """`families`: twelve 2.2 m fence panels along a 15 m path are one row ('PicketFences');- the row's bbox is the run, `families.PicketFence` is the panel (loop 9 lighthouse,- 2026-09-07: the scale check read 14.7 m against the plan's 2.4 m panel). Numbered- panels (`PicketFence-3`) are one family by `conventions.split_instance` (audit- 2026-09-24 N3: the JS copy of the rule missed the hyphen)."""+ """`families`."""body = f"""import * as THREE from 'three';import {{ sceneCensus }} from '{RUNTIME_JS}/lib/host_census.mjs';diff --git a/harness/tests/scene_runtime/test_placement_volumetric.py b/harness/tests/scene_runtime/test_placement_volumetric.pyindex 5a46597b..3dfbcbae 100644--- a/harness/tests/scene_runtime/test_placement_volumetric.py+++ b/harness/tests/scene_runtime/test_placement_volumetric.py@@ -1,10 +1,4 @@-"""A mesh that writes no depth is fog, not matter: it supports nothing, swallows-nothing and overlaps nothing.--Regression: two correct scenes failed `scene_placement` on their own atmosphere — a-pine "sunken 3.46 m into AtmosphereHaze", a window overlapping a MoonlightShaft.-DepthWrite:false shells are the generator's standard way to write a volumetric.-"""+"""A mesh that writes no depth is fog, not matter."""from __future__ import annotations@@ -85,21 +79,8 @@ def test_a_depthless_shell_is_exempt_and_indexes_nothing(volumetric):assert _row(volumetric, "MoonlightShaft")["exempt"] == "volumetric"-def test_a_tree_inside_the_haze_stands_on_the_ground(volumetric):- pine = _row(volumetric, "BlackPine")- assert pine["exempt"] == ""- assert pine["sunk_into"] == "" and pine["sunk_m"] == 0- assert pine["supported"] is True and pine["floating"] is False---def test_a_light_shaft_through_a_window_is_not_an_interpenetration(volumetric):- assert volumetric["pairs"] == []--def test_the_same_shells_WITH_depth_write_are_still_measured(solid_control):- """The control: the rule is `depthWrite`, not the name, the opacity or the size.- Turn depth writing back on and the identical geometry produces exactly the two- findings the baseline reported."""+ """The control."""assert "volumetric" not in solid_control["exempt"]pine = _row(solid_control, "BlackPine")assert pine["sunk_into"] == "AtmosphereHaze" and pine["sunk_m"] == pytest.approx(3.45, abs=0.05)@@ -108,34 +89,3 @@ def test_the_same_shells_WITH_depth_write_are_still_measured(solid_control):# every one of them is a solid object against fog — which is the whole pointassert all("AtmosphereHaze" in p or "MoonlightShaft" in p for p in pairs)assert ["AtmosphereHaze", "BlackPine"] in pairs---SCATTER_JS = """-import * as THREE from 'three';-import { sceneCensus } from './lib/host_census.mjs';-const solid = new THREE.MeshStandardMaterial();-const fog = new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.04, depthWrite: false });-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, 8, 8), solid);-ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2; env.add(ground);-const zone = new THREE.Group(); zone.name = 'Meadow'; scene.add(zone);-// scatter AND a haze shell in one asset: both reasons apply, the instanced one is better-const mixed = new THREE.Group(); mixed.name = 'TuftsAndHaze';-mixed.add(new THREE.InstancedMesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), solid, 40));-const shell = new THREE.Mesh(new THREE.BoxGeometry(20, 4, 20), fog);-shell.position.y = 2; mixed.add(shell);-zone.add(mixed);-scene.updateMatrixWorld(true);-const t = sceneCensus(scene, THREE, { placement: true }).placement;-console.log(JSON.stringify({ exempt: t.exempt,- rows: t.assets.map((a) => ({ name: a.name, exempt: a.exempt })) }));-"""---def test_scatter_that_also_carries_fog_is_exempt_as_instanced():- """Both reasons are true; `instanced` says the useful thing (its instances cannot be- sampled at this budget), so it wins."""- out = run_node_json(SCATTER_JS)- row = [a for a in out["rows"] if a["name"] == "TuftsAndHaze"]- assert row and row[0]["exempt"] == "instanced"diff --git a/harness/tests/scene_runtime/test_post.py b/harness/tests/scene_runtime/test_post.pyindex 444e740b..33373b38 100644--- a/harness/tests/scene_runtime/test_post.py+++ b/harness/tests/scene_runtime/test_post.py@@ -1,18 +1,4 @@-"""The scene post chain (runtime_js/lib/browser/post.js): GTAO + selective bloom + grade.--The three properties that must not regress, each pinned against a raw render of-the SAME scene:-- * the chain is colour-neutral by itself — with AO and bloom off, a post render- matches `--no-post` (only MSAA separates them). This is what lets the grade- default to the identity and lets us attribute any shift to AO or bloom.- * bloom is SELECTIVE: it fires on an emissive material and does nothing at all- on a scene whose brightest thing is merely bright. A global luminance- bright-pass (what the reference chain used) cannot tell those apart on our- renderer — the sky dome outshines every authored emissive — and fogged a- daylit frame, so the mask is the whole design and this is its guard.- * `scene.userData.grade` reaches the shader and is clamped.-"""+"""The scene post chain (runtime_js/lib/browser/post.js)."""from __future__ import annotations@@ -23,7 +9,7 @@ import pytestfrom PIL import Imagefrom codeverse3d.proc import read_json_or_none-from codeverse3d.spatial.render_scene import post_chain_args, run_scene_script+from codeverse3d.spatial.render_scene import run_scene_scriptfrom codeverse3d.workspace import Workspacefrom tests.scene_runtime.conftest import needs_browser, needs_node@@ -66,8 +52,7 @@ def mean_lum(path: Path) -> float:def render(ws: Workspace, out: Path, *extra_args: str) -> Path:- """One authored-camera frame at t=0, straight through the driver so the test- can pass --post-options / --no-post (render_scene() owns neither)."""+ """One authored-camera frame at t=0, straight through the driver so the test can pass --post-options / --no-post (render_scene() owns neither)."""out.mkdir(parents=True, exist_ok=True)run_scene_script("render_scene.mjs", ["--ws", str(ws.root), "--out", str(out), "--cameras", "authored",@@ -77,28 +62,10 @@ def render(ws: Workspace, out: Path, *extra_args: str) -> Path:return out / "cam_t0.png"-def test_post_chain_args_follow_the_env_switch(switch):- switch("C3D_POST", None)- assert post_chain_args() == [] # ON by default for scene pictures- switch("C3D_POST", "0")- assert post_chain_args() == ["--no-post"]- switch("C3D_POST", "on")- assert post_chain_args() == []--@needs_node@needs_browserdef test_bloom_is_selective_and_the_chain_alone_is_colour_neutral(tmp_path):- """An EMISSIVE box blooms; an equally bright NON-emissive box does not.-- Both scenes are lit the same and the plain box is the brighter of the two in- the raw render — so anything that keys off frame luminance fails this test,- which is exactly the reference chain's failure mode.-- And AO off, bloom off, grade at its defaults → the same picture as no chain.- Without that the grade could drift and nobody would notice: every later- measurement of AO or bloom is a delta against a raw render.- """+ """An EMISSIVE box blooms."""emissive = make_ws(tmp_path, "emissive", EMISSIVE)plain = make_ws(tmp_path, "plain", BRIGHT)@@ -116,17 +83,3 @@ def test_bloom_is_selective_and_the_chain_alone_is_colour_neutral(tmp_path):assert abs(mean_lum(p_post) - mean_lum(p_raw)) < 0.005, "a merely bright box must not bloom"chain = render(plain, tmp_path / "p_chain", "--post-options", '{"ao":0,"bloom":0}')assert abs(mean_lum(chain) - mean_lum(p_raw)) < 0.005, (mean_lum(p_raw), mean_lum(chain))---@needs_node-@needs_browser-def test_scene_grade_hint_reaches_the_shader_and_is_clamped(tmp_path):- """`scene.userData.grade` is the scene's only lever on the grade; a value far- outside the sane range is clamped rather than obeyed or ignored."""- ws = make_ws(tmp_path, "graded", BRIGHT, extra="scene.userData.grade = { exposure: 99, warmth: 0.4 };")- out = tmp_path / "graded_out"- render(ws, out, "--post-options", '{"ao":0,"bloom":0}')- grade = read_json_or_none(out / "metrics.json")["census"]["post"]["grade"]- assert grade["exposure"] == 8.0 # clamped from 99- assert grade["warmth"] == pytest.approx(0.4)- assert read_json_or_none(out / "metrics.json")["census"]["post"]["grade_neutral"] is Falsediff --git a/harness/tests/scene_runtime/test_probe_timeout.py b/harness/tests/scene_runtime/test_probe_timeout.pyindex 5bc6ab92..0326326c 100644--- a/harness/tests/scene_runtime/test_probe_timeout.py+++ b/harness/tests/scene_runtime/test_probe_timeout.py@@ -1,13 +1,4 @@-"""D111: a scene probe that runs out of its budget is a verdict on the code, not a harness failure.--Argon loop iteration 4, r1_08 (2026-10-15): the refine's new 37 k-vertex terrain met the zones'-per-vertex raycast seating and the scene stopped booting inside the 120 s probe budget. The probe-called it "a harness/driver failure, not your code", the agent stopped working, and the round spent-3 x 240 s rebuilding identical code and was never scored. After the driver's one retry (on a browser-of its own) a timeout INSIDE the scene's own code — the watchdog's ``phase`` — is now a typed ERROR-against the entry file, so the round's repair session receives it; a timeout anywhere else (browser-launch, page ready, the shader preflight, node itself starved) and any census-GLB boot stay the box's.-"""+"""D111: a scene probe that times out inside the scene's own code is a typed ERROR against the code (repair gets it); a timeout anywhere else stays the box's."""from __future__ import annotations@@ -19,11 +10,10 @@ import codeverse3d.spatial.probes as probes_modimport codeverse3d.spatial.render_scene as RSfrom codeverse3d.contracts.artifacts import GateReportfrom codeverse3d.languages.scene_threejs import SceneThreeJsRuntime-from codeverse3d.spatial.node import OWN_BROWSER_ENV, NodeError, NodeResult+from codeverse3d.spatial.node import OWN_BROWSER_ENV, NodeResultfrom codeverse3d.spatial.render_scene import SCENE_PHASES, SceneRenderError, run_scene_scriptfrom codeverse3d.tracks import repair as Rfrom codeverse3d.tracks.generation import GenerationResult-from tests.scene_runtime.conftest import needs_browserTIMEOUT = {"ok": False, "error": "timeout after 120000 ms", "timed_out": True, "phase": "scene"}@@ -61,43 +51,6 @@ def test_a_timeout_outside_the_scenes_code_is_not_the_scenes(monkeypatch, phase)assert ei.value.timed_out and not ei.value.scene_timed_out and phase not in SCENE_PHASES-def test_the_process_clock_is_the_box(monkeypatch):- """Node's own watchdog runs 20 s inside the process clock; when the process clock fires, node itself- was starved — no phase, never the code's."""- def starved(path, args, *, cwd, timeout_s, env_extra, check):- raise NodeError("timed out", result=NodeResult(rc=-9, stdout="", stderr="", last_json=None, duration_ms=1,- timed_out=True))-- monkeypatch.setattr(RS, "run_node", starved)- with pytest.raises(SceneRenderError) as ei:- run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)- assert ei.value.timed_out and ei.value.phase == "" and not ei.value.scene_timed_out---def test_a_driver_that_fails_otherwise_is_not_timed_out(monkeypatch):- _feed(monkeypatch, [NodeResult(rc=2, stdout="", stderr="", last_json={"ok": False, "error": "--ws is required"},- duration_ms=1)])- with pytest.raises(SceneRenderError) as ei:- run_scene_script("probe_scene.mjs", [], timeout_s=10)- assert ei.value.timed_out is False---@needs_browser-def test_the_driver_watchdog_names_the_phase_it_fired_in(starter_ws):- """A real ``probe_scene.mjs`` boot whose createScene() blocks the page: the watchdog fires inside- the scene's code and says so. (The block is bounded, so the page frees itself after the test.)"""- from codeverse3d.spatial.node import run_node-- (starter_ws.src / "scene.js").write_text(- "import * as THREE from 'three';\n"- "export function createScene() { const end = Date.now() + 25000; while (Date.now() < end) {}\n"- " return { scene: new THREE.Scene(), cameras: [], update() {} }; }\n")- r = run_node(RS.runtime_js_dir() / "probe_scene.mjs", ["--ws", str(starter_ws.root), "--timeout-ms", "12000"],- cwd=RS.runtime_js_dir(), timeout_s=60, env_extra=dict(OWN_BROWSER_ENV), check=False)- assert r.rc == 3 and r.summary.get("timed_out") is True and r.summary.get("phase") == "scene", r.summary--@pytest.mark.parametrize("phase", sorted(SCENE_PHASES))def test_a_timed_out_probe_is_an_error_against_the_code(tmp_ws, monkeypatch, phase):monkeypatch.setattr(probes_mod, "run_scene_script", lambda script, args, **kw: (_ for _ in ()).throw(_timed_out(phase)))@@ -121,36 +74,8 @@ def test_a_probe_that_could_not_run_is_still_the_harnesss(tmp_ws, monkeypatch, eassert probe.findings[0].data.get("harness_failure") is True-def test_a_census_glb_that_never_boots_stays_the_harnesss(tmp_ws, monkeypatch):- """scene_blender: the author's bpy already ran in Blender; the GLB the probe loads is the harness's- export, and a three.js hint ("createScene, update") names nothing a bpy author has."""- monkeypatch.setattr(probes_mod, "run_scene_script", lambda script, args, **kw: (_ for _ in ()).throw(_timed_out("scene")))- probe, _, _ = probes_mod.run_probe(tmp_ws, timeout_s=120, glb=tmp_ws.artifacts / "census.glb")- assert probe.findings[0].data.get("harness_failure") is True and probe.findings[0].data.get("kind") != "probe_timeout"---def test_the_probe_tool_and_the_build_share_one_budget(tmp_ws, monkeypatch):- """The ``scene_probe`` tool probed at 60 s while the build allowed 120 s: with a timeout now the code's,- the agent's own tool would condemn a scene the build accepts."""- from codeverse3d.languages.scene_threejs import write_example-- write_example(tmp_ws)- budgets: list[str] = []-- def capture(script, args, **kw):- budgets.append(args[args.index("--timeout-ms") + 1])- raise SceneRenderError("stop here")-- monkeypatch.setattr(probes_mod, "run_scene_script", capture)- rt = SceneThreeJsRuntime()- rt.probe(tmp_ws)- rt.build(tmp_ws)- assert len(budgets) == 2 and budgets[0] == budgets[1], budgets--def test_the_scene_build_hands_a_timeout_to_repair_not_to_rebuilds(tmp_ws, monkeypatch):- """The scene_threejs build's BuildResult is not a harness failure, so ``build_with_repair`` runs a- repair session on the first pass instead of MAX_HARNESS_REBUILDS identical rebuilds."""+ """The scene_threejs build's BuildResult is not a harness failure, so ``build_with_repair`` runs a repair session on the first pass instead of MAX_HAR..."""from codeverse3d.languages.scene_threejs import write_examplewrite_example(tmp_ws)diff --git a/harness/tests/scene_runtime/test_probes.py b/harness/tests/scene_runtime/test_probes.pyindex 4f105ba3..062c0a10 100644--- a/harness/tests/scene_runtime/test_probes.py+++ b/harness/tests/scene_runtime/test_probes.py@@ -34,29 +34,13 @@ def test_probe_scene_flags_bad_shape_and_cameras(starter_ws):assert [m for m, sev in graded.items() if sev == "error"][0].startswith("cameras: cameras[2] position must be")-def test_probe_scene_catches_update_throw_and_console_errors(starter_ws):- (starter_ws.src / "scene.js").write_text(- "import * as THREE from 'three';\n"- "export function createScene() { const scene = new THREE.Scene(); scene.add(new THREE.AmbientLight()); scene.add(new THREE.Mesh(new THREE.BoxGeometry(1,1,1), new THREE.MeshBasicMaterial()));\n"- " console.error('custom failure 42');\n"- " return { scene, cameras: [{ name: 'x', position: [3, 3, 3], lookAt: [0, 0, 0], fov: 50 }], update(t) { if (t > 0.1) throw new Error('update boom'); } }; }\n"- )- gate, _ = probe_scene(starter_ws)- msgs = " | ".join(f.message for f in gate.errors)- assert "update boom" in msgs and "custom failure 42" in msgs--def preflight(ws):"""The shader_preflight report the build and the ``shader_probe`` tool both read."""return run_probe(ws, compile=True)[1]def test_the_shader_preflight_runs_raw(ws, tmp_path, monkeypatch):- """The shader_probe tool once booted with the post chain ON (openHost's default) while the- build's probe_scene --compile runs raw, so it compiled — and counted, and would have- blamed on the scene — the harness's own GTAO / bloom / grade programs. Only the chain- reads `scene.userData.grade`, so a read of it means the chain was built. The tool now- reports the build's own probe + preflight, which must stay raw."""+ """The shader_probe tool once booted with the post chain ON (openHost's default) while the build's probe_scene --compile runs raw, so it compiled — an..."""from codeverse3d.spatial.render_scene import render_scenews.src.mkdir(parents=True, exist_ok=True)@@ -76,8 +60,7 @@ def test_the_shader_preflight_runs_raw(ws, tmp_path, monkeypatch):def test_preflight_maps_patch_and_static_audit_errors_to_file_line(starter_ws):- """An onBeforeCompile patch's compile error lands on the patch's own file:line, and- the static audit reports a shader file no scene imports, all in one preflight."""+ """An onBeforeCompile patch's compile error lands on the patch's own file:line, and the static audit reports a shader file no scene imports, all in on..."""(starter_ws.src / "shaders" / "glow.js").write_text("import * as THREE from 'three';\n""export function makeGlow(T = THREE) {\n"@@ -111,28 +94,6 @@ def test_preflight_maps_patch_and_static_audit_errors_to_file_line(starter_ws):assert any(f.target == "src/shaders/bad.js:2" for f in rep.errors)-def test_probe_scene_hanging_create_scene_times_out_as_agent_finding(starter_ws):- """A hanging createScene times out as an agent finding, not a harness crash."""- (starter_ws.src / "scene.js").write_text(- "import * as THREE from 'three';\n"- "export async function createScene({ THREE: T, renderer, loaders }) {\n"- " const tex = await new Promise((resolve) => loaders.texture.load('/assets/missing.png', resolve));\n"- " return { scene: new THREE.Scene(), cameras: [], update() {} };\n"- "}\n"- )- # createScene gets 0.6 x the driver budget (host_page.createTimeoutMs): 18 s, leaving the- # page boot 12 s before the watchdog — at 10 s (6 s + 4 s) a loaded box hit the watchdog first- res = probe_scene(starter_ws, timeout_s=30)- gate = res.gate- assert not gate.passed- err = next(f for f in gate.errors if f.data.get("stage") == "createScene")- assert "did not resolve within" in err.message and "never settled" in err.message- assert "failed to load /assets/missing.png" in err.message- assert "createScene({THREE, renderer, loaders})" in err.fix_hint- assert res.ok and res.errors == [] # the probe TOOL ran fine (agent-fixable failure)- assert not any("harness/driver failure" in f.fix_hint for f in gate.findings)--def test_probe_result_tool_semantics(starter_ws, monkeypatch):"""Tool success is distinct from agent-fixable gate success."""import codeverse3d.spatial.probes as probes_moddiff --git a/harness/tests/scene_runtime/test_render_blender.py b/harness/tests/scene_runtime/test_render_blender.pyindex 5eecc7c6..9604d31d 100644--- a/harness/tests/scene_runtime/test_render_blender.py+++ b/harness/tests/scene_runtime/test_render_blender.py@@ -1,9 +1,4 @@-"""scene_blender rendering (lane B, D1/D3/D8): Blender makes the pixels, the JS host measures them.--Real Blender + headless Chrome on a small fixture scene (``blender_scene_fixture``), rendered at-192x108 with 4 Cycles samples on the CPU (the GPU is shared on this box) — plus pure-python tests-of the GPU-slot policy with a fake driver.-"""+"""scene_blender rendering (lane B, D1/D3/D8)."""from __future__ import annotations@@ -16,8 +11,7 @@ from PIL import Image, ImageStatfrom codeverse3d.config import get_settingsfrom codeverse3d.contracts.artifacts import Severity-from codeverse3d.conventions import from_authoring_frame, to_authoring_frame-from codeverse3d.proc import ProcResult, read_json_or_none+from codeverse3d.proc import ProcResultfrom codeverse3d.spatial import render_blender as rbfrom codeverse3d.spatial.frame_metrics import frame_findingsfrom codeverse3d.spatial.render_scene import SceneRenderError, render_scene@@ -25,7 +19,6 @@ from codeverse3d.workspace import Workspacefrom tests.scene_runtime.blender_scene_fixture import (blender_available,build_fixture,- build_fog_box,build_room_shell,)from tests.scene_runtime.conftest import needs_browser@@ -53,14 +46,6 @@ def moving(tmp_path_factory):return ws, rs, json.loads((root / "renders" / "metrics.json").read_text())[email protected]("v", [(1.0, 2.0, 3.0), (-4.5, 0.25, 7.0)])-def test_the_frame_round_trip_is_the_identity(v):- z_up = to_authoring_frame(v, "blender")- assert z_up == (v[0], -v[2], v[1])- assert from_authoring_frame(z_up, "blender") == pytest.approx(v)- assert from_authoring_frame(v, "scene_threejs") == v--@pytest.mark.blender@pytest.mark.node@needs_blender@@ -166,8 +151,7 @@ def _half_png(path: Path) -> None:@pytest.mark.node@needs_browserdef test_exposure_statistics_of_a_known_png_come_from_the_external_frame(tmp_path):- """Half black, half white: mean 0.5, half near-black, half blown, the modal bucket 50 % — from- the Blender PNG, not from the host's own (bright grey) render of the same camera."""+ """Half black, half white."""ws = Workspace(tmp_path / "run").create()import trimesh # a 40 m ground as the census GLB the geometry pass boots (lib/glb_scene.mjs)@@ -194,28 +178,6 @@ def test_exposure_statistics_of_a_known_png_come_from_the_external_frame(tmp_patassert [v["name"] for v in metrics["views"]] == ["K"]-@needs_blender-def test_a_held_gpu_slot_sends_a_real_render_to_the_cpu(tmp_path, monkeypatch):- monkeypatch.setenv("C3D_CACHE_DIR", str(tmp_path / "cache"))- monkeypatch.setenv("C3D_RENDER__BLENDER_GPU_SLOTS", "1")- monkeypatch.setenv("C3D_RENDER__BLENDER_GPU_WAIT_S", "0.2")- get_settings.cache_clear()- ws = build_fixture(Workspace(tmp_path / "run").create(), probe=False)- out = tmp_path / "out"- out.mkdir()- job = {"out": str(out), "result": str(out / rb.RESULT_NAME), "engine": "cycles", "samples": 2, "width": 64,- "height": 36, "times": [0.0], "authored": True, "cameras": []}- held = rb.gpu_slots().take(1.0)- try:- res = rb.render_frames(ws.artifacts / "scene.blend", out, job, timeout_s=120)- finally:- rb.Slots.give(held)- assert res["device"] == "CPU" and "busy" in res["fallback"] and len(res["frames"]) == 2- free = rb.render_frames(ws.artifacts / "scene.blend", out, job, timeout_s=120)- 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:@@ -227,12 +189,7 @@ def _centre_rgb(path: Path) -> tuple[float, float, float]:@pytest.mark.blender@needs_blenderdef 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``."""+ """Review 2026-10-14 finding 8."""_cpu_env(monkeypatch, tmp_path / "cache")blend = build_room_shell(tmp_path / "room")out = tmp_path / "out"@@ -255,42 +212,9 @@ def test_a_no_fog_view_lifts_the_room_shells_lid_and_the_next_view_gets_it_back(assert "hidden" not in rb._glb_view(res["frames"][0]), "views.json keeps the three.js schema"-@needs_blender-def test_a_no_fog_view_hides_a_fog_box_but_not_a_steam_puff_and_the_next_view_gets_it_back(tmp_path, monkeypatch):- """2026-10-15: the judge's fog-free views only unlinked the WORLD volume, while ``lib.sky.haze`` builds- the fog as a volume-only box — so the placement views were rendered through the haze (iteration 2's- milky overviews). A red crate inside an opaque 20 m fog box: the ``no_fog`` view names the box in- ``fog_hidden`` (never the 1 m steam puff) and its centre is the red crate; the same camera without- ``no_fog``, rendered next, sees the fog again — the restore in the driver's ``finally``."""- _cpu_env(monkeypatch, tmp_path / "cache")- blend = build_fog_box(tmp_path / "fog")- out = tmp_path / "out"- out.mkdir()- top = {"name": "overview_top", "kind": "orbit", "position": [0.0, 0.0, 6.0], "look_at": [0.0, 0.0, 1.0], "fov": 40.0,- "no_fog": True, "times": [0.0]}- fogged = {**top, "name": "fogged", "no_fog": False}- 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, fogged]}- res = rb.render_frames(blend, out, job, timeout_s=180)- assert res["errors"] == [] and [f["name"] for f in res["frames"]] == ["overview_top", "fogged"]- assert {f["name"]: f["fog_hidden"] for f in res["frames"]} == {"overview_top": ["SiteHaze"], "fogged": []}- clear, hazy = _centre_rgb(out / "overview_top_t0.png"), _centre_rgb(out / "fogged_t0.png")- assert clear[0] > max(clear[1], clear[2]) + 25, f"the fog-free view must show the red crate, got {clear}"- assert not hazy[0] > max(hazy[1], hazy[2]) + 25, f"the fogged view must not see the crate clearly, got {hazy}"---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")- assert rs.views == [] and "scene.blend" in rs.console_errors[0]- assert read_json_or_none(tmp_path / "out" / "metrics.json")["language"] == "scene_blender"--# --------------------------------------------------------------------------- the slot policy (no Blender)class FakeDriver:- """Stands in for ``_run_driver``: records the device of every run, can fail / time out on the GPU,- and checks the slot is HELD while a GPU run is out."""+ """Stands in for ``_run_driver``."""def __init__(self, gpu: str = "ok"):self.gpu = gpu@@ -320,15 +244,6 @@ def one_slot(tmp_path, monkeypatch):return tmp_path-def test_a_free_slot_renders_on_the_gpu_and_holds_the_slot_meanwhile(one_slot, monkeypatch):- fake = FakeDriver()- monkeypatch.setattr(rb, "_run_driver", fake)- res = rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)- assert fake.devices == ["GPU"] and res["device"] == "GPU" and res["fallback"] == ""- assert fake.slot_free_during_gpu is False, "the one slot must be held while the GPU render runs"- assert rb.gpu_slots().busy() == 0, "and handed back after it"--def test_all_slots_busy_falls_back_to_the_cpu_after_the_wait(one_slot, monkeypatch):fake = FakeDriver()monkeypatch.setattr(rb, "_run_driver", fake)@@ -358,16 +273,3 @@ def test_a_timeout_is_the_scene_not_the_device_no_cpu_retry(one_slot, monkeypatcwith pytest.raises(SceneRenderError, match="timed out"):rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)assert fake.devices == ["GPU"] and rb.gpu_slots().busy() == 0---def test_device_cpu_never_touches_a_slot(one_slot, monkeypatch, switch):- switch("C3D_RENDER__BLENDER_DEVICE", "cpu")- fake = FakeDriver()- monkeypatch.setattr(rb, "_run_driver", fake)- held = rb.gpu_slots().take(1.0)- try:- t0 = time.monotonic()- res = rb.render_frames(one_slot / "x.blend", one_slot, {}, timeout_s=10)- finally:- rb.Slots.give(held)- assert fake.devices == ["CPU"] and res["fallback"] == "" and time.monotonic() - t0 < 0.2diff --git a/harness/tests/scene_runtime/test_render_scene.py b/harness/tests/scene_runtime/test_render_scene.pyindex 470116d8..cf9acb68 100644--- a/harness/tests/scene_runtime/test_render_scene.py+++ b/harness/tests/scene_runtime/test_render_scene.py@@ -2,8 +2,6 @@from __future__ import annotations-import json-import loggingfrom pathlib import Pathimport pytest@@ -15,7 +13,6 @@ from codeverse3d.proc import read_json_or_nonefrom codeverse3d.spatial import render_scene as rs_modfrom codeverse3d.spatial.render_scene import (SceneRenderError,- probe_env_args,render_scene,run_scene_script,)@@ -86,29 +83,10 @@ def test_driver_failures_raise(fake_runtime):run_scene_script("nope.mjs", [], timeout_s=5)-@needs_browser-def test_camera_in_geometry_is_detected(starter_ws, monkeypatch):- # this test asserts DETECTION, so the default-on camera repair must stand down- # (the repair itself is covered by test_camera_repair.py)- monkeypatch.setenv("C3D_CAMERA_REPAIR", "0")- cams = [CameraPlan(name="buried", position=(12.0, 2.0, -2.0), look_at=(12.0, 2.0, -10.0), fov=50)] # inside the windmill tower- out = starter_ws.renders_dir(1)- render_scene(starter_ws, out, cameras=cams, orbit=False, times=(0.0,), fps_seconds=0, sheet=False)- m = read_json_or_none(out / "metrics.json")- chk = m["camera_checks"][0]- assert chk["camera_in_geometry"] is True- # repair off → everything renders from the AUTHORED camera and no repair is recorded- assert "camera_repair" not in (m.get("census") or {})- assert all("repaired_position" not in v for v in m["views"])--@pytest.mark.node@needs_browserdef test_camera_repair_is_observable_in_census_and_views(starter_ws, monkeypatch):- """Review-3 S5 (V8): with the default-ON repair, a buried camera leaves a- census.camera_repair row and the view records where the pixels really came- from — repair used to fire AFTER census capture and vanish."""+ """Review-3 S5 (V8)."""monkeypatch.delenv("C3D_CAMERA_REPAIR", raising=False)cams = [CameraPlan(name="buried", position=(12.0, 2.0, -2.0), look_at=(12.0, 2.0, -10.0), fov=50)] # inside the windmill towerout = starter_ws.renders_dir(2)@@ -122,32 +100,6 @@ def test_camera_repair_is_observable_in_census_and_views(starter_ws, monkeypatchassert m["camera_checks"][0]["camera_in_geometry"] is False # the effective camera is clear-@needs_node-def test_camera_repair_telemetry_survives_the_python_reader(fake_runtime, ws, tmp_path):- """The python side keeps metrics-only telemetry intact: census.camera_repair and- per-view repaired_position stay readable, RenderView keeps the authored camera."""- (fake_runtime / "render_scene.mjs").write_text(FAKE_DRIVER.replace(- "const metrics = {",- "for (const v of views) v.repaired_position = [1, 2.6, 4.1];\nconst metrics = {",- ).replace(- "census: { totals: { meshes: 1 } }",- "census: { totals: { meshes: 1 }, camera_repair: [{ name: 'authored_a', moved_back_m: 1.1, moved_up_m: 0.6, inside_before: ['BarCounter'] }] }",- ).replace(- "fs.writeFileSync(path.join(out, 'metrics.json'), JSON.stringify(metrics));",- "fs.writeFileSync(path.join(out, 'metrics.json'), JSON.stringify(metrics));\nfs.writeFileSync(path.join(out, 'views.json'), JSON.stringify(views));",- ))- out = tmp_path / "out"- rs = render_scene(ws, out, cameras=[CameraPlan(name="cam_a", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)],- orbit=False, times=(0.0,), sheet=False)- assert rs.views[0].camera_position == (1.0, 2.0, 3.0)- m = read_json_or_none(out / "metrics.json")- assert m["census"]["camera_repair"][0]["name"] == "authored_a"- assert m["views"][0]["repaired_position"] == [1, 2.6, 4.1]- # the judge-flag rewrite of views.json must not strip the telemetry rider- entries = json.loads((out / "views.json").read_text())- assert entries[0]["repaired_position"] == [1, 2.6, 4.1] and "judge" in entries[0]--@needs_nodedef test_driver_crash_after_metrics_degrades_to_renderset(fake_runtime, ws, tmp_path):"""A crash after metrics yields a degraded RenderSet rather than losing frames."""@@ -164,43 +116,6 @@ def test_driver_crash_after_metrics_degrades_to_renderset(fake_runtime, ws, tmp_assert any("render_scene.mjs failed (exit 2)" in e for e in rs.console_errors)-# The post chain cannot read this grade, so it is never built and every frame renders RAW-# (a boot-time host warning); the box refuses the coverage instrument's flat-white mask pass-# (a warning pushed while the camera checks run, i.e. AFTER boot).-_HOST_WARNING_SCENE = """-import * as THREE from 'three';-export function createScene() {- const scene = new THREE.Scene();- scene.add(new THREE.AmbientLight(0xffffff, 1.0));- Object.defineProperty(scene.userData, 'grade', { get() { throw new Error('grade unreadable'); } });- const box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());- box.name = 'Box';- box.onBeforeRender = (r, s) => { if (s.overrideMaterial && s.overrideMaterial.isMeshBasicMaterial) throw new Error('no masks'); };- scene.add(box);- return { scene, cameras: [{ name: 'cam', position: [0, 1, 4], lookAt: [0, 0, 0], fov: 50 }], update() {} };-}-"""---@needs_browser-def test_host_warnings_reach_metrics_and_the_log(ws, caplog):- """Host warnings were copied into boot.host_warnings once, at the END of boot, and nothing- read even that copy: a scene rendered and judged without its post chain, or with the- coverage instrument (content_small / hero_unseen) switched off, left no trace at all."""- ws.src.mkdir(parents=True, exist_ok=True)- (ws.src / "scene.js").write_text(_HOST_WARNING_SCENE)- out = ws.renders_dir(0)- with caplog.at_level(logging.WARNING, logger=rs_mod.__name__):- rs = render_scene(ws, out, orbit=False, times=(0.0,), width=320, height=180, fps_seconds=0, sheet=False)- warnings = read_json_or_none(out / "metrics.json")["host_warnings"]- assert any(w.startswith("post chain unavailable") and "grade unreadable" in w for w in warnings), warnings- assert any(w.startswith("coverage failed for cam") and "no masks" in w for w in warnings), warnings- logged = [r.getMessage() for r in caplog.records]- assert any("post chain unavailable" in m for m in logged) and any("coverage failed for cam" in m for m in logged)- assert [v.name for v in rs.views] == ["cam"] # the frame itself still renders--@pytest.mark.node@needs_browserdef test_update_throw_mid_render_yields_frames_and_console_error(starter_ws):@@ -224,60 +139,16 @@ def test_update_throw_mid_render_yields_frames_and_console_error(starter_ws):assert m["update_errors"] and "update() disabled" in m["update_errors"][0]-@needs_browser-def test_request_failure_line_filters_phantom_aborts():- """Consumed or offsite request failures do not create phantom gate errors."""- from tests.scene_runtime.conftest import run_node_json-- res = run_node_json(- "import { requestFailureLine, createTimeoutMs } from './lib/host_page.mjs';\n"- "console.log(JSON.stringify({\n"- " phantom: requestFailureLine('http://x/assets/a.glb', 'http://x', true, 'net::ERR_ABORTED'),\n"- " aborted: requestFailureLine('http://x/assets/a.glb', 'http://x', false, 'net::ERR_ABORTED'),\n"- " responded: requestFailureLine('http://x/assets/a.glb', 'http://x', true, 'net::ERR_FAILED'),\n"- " real: requestFailureLine('http://x/assets/a.glb', 'http://x', false, 'net::ERR_CONNECTION_REFUSED'),\n"- " offsite: requestFailureLine('http://cdn/other.js', 'http://x', false, 'net::ERR_FAILED'),\n"- " cs_default: createTimeoutMs(240000),\n"- " cs_small_budget: createTimeoutMs(10000),\n"- "}));\n"- )- assert res["phantom"] is None and res["aborted"] is None and res["responded"] is None- assert res["real"] == "request failed: /assets/a.glb (net::ERR_CONNECTION_REFUSED)"- assert res["offsite"] is None- assert res["cs_default"] == 20000 and res["cs_small_budget"] == 6000--# ---------------------------------------------------------------- env flags (review-3 S4)-_FLAG_WORDS = ("--no-settle", "--camera-repair", "--auto-exposure")+_FLAG_WORDS = ("--no-settle", "--camera-repair")def _flags(args):return sorted(a for a in args if a in _FLAG_WORDS)[email protected](("env", "expect"), [- ({}, ["--camera-repair"]),- ({"C3D_CAMERA_REPAIR": "0"}, []),- ({"C3D_CAMERA_REPAIR": "false"}, []),- ({"C3D_SETTLE": "false"}, ["--camera-repair", "--no-settle"]),- ({"C3D_AUTO_EXPOSURE": "true"}, ["--auto-exposure", "--camera-repair"]),- ({"C3D_AUTO_EXPOSURE": "garbage"}, ["--camera-repair"]),-])-def test_probe_env_args_speaks_the_canonical_flag_words(monkeypatch, env, expect):- """C3D_CAMERA_REPAIR=false must DISABLE, C3D_SETTLE=false must disable,- C3D_AUTO_EXPOSURE=true must enable — the raw '0'/'1' compares silently- ignored every other word of the documented on/off vocabulary (config.Flag)."""- for k in ("C3D_SETTLE", "C3D_CAMERA_REPAIR", "C3D_AUTO_EXPOSURE"):- monkeypatch.delenv(k, raising=False)- for k, v in env.items():- monkeypatch.setenv(k, v)- assert _flags(probe_env_args()) == expect--def test_every_driver_invocation_carries_the_env_flags(monkeypatch, switch, ws, tmp_path):- """Review-3 S4 (V7c): the combined single-boot build probes under the SAME- settle / camera-repair / auto-exposure flags as the standalone probe and- render paths — it used to pass none of them."""+ """Review-3 S4 (V7c)."""import codeverse3d.spatial.probes as probes_modcaptured: dict[str, list[str]] = {}@@ -288,7 +159,7 @@ def test_every_driver_invocation_carries_the_env_flags(monkeypatch, switch, ws,monkeypatch.setattr(probes_mod, "run_scene_script", fake_run)monkeypatch.setattr(rs_mod, "run_scene_script", fake_run)- for k in ("C3D_SETTLE", "C3D_CAMERA_REPAIR", "C3D_AUTO_EXPOSURE", "C3D_POST"):+ for k in ("C3D_SETTLE", "C3D_CAMERA_REPAIR", "C3D_POST"):monkeypatch.delenv(k, raising=False)# defaults: camera repair ON everywhere, settle on (no flag), exposure offdiff --git a/harness/tests/scene_runtime/test_runtime.py b/harness/tests/scene_runtime/test_runtime.pyindex f545c34b..4a5415aa 100644--- a/harness/tests/scene_runtime/test_runtime.py+++ b/harness/tests/scene_runtime/test_runtime.py@@ -8,28 +8,10 @@ from types import SimpleNamespaceimport pytestfrom codeverse3d.contracts.artifacts import Severity-from codeverse3d.contracts.common import TRACK_LANGUAGES, Language, Track-from codeverse3d.languages import get_runtime-from codeverse3d.languages.base import LanguageRuntime, SceneRuntime+from codeverse3d.contracts.common import Language, Trackfrom codeverse3d.languages.scene_threejs import SceneThreeJsRuntime-from codeverse3d.prompts.catalog import language_textfrom tests.scene_runtime.conftest import needs_browser--def test_runtime_registered_conforms_and_writes_skeleton(ws):- rt = get_runtime(Language.SCENE_THREEJS)- assert isinstance(rt, SceneThreeJsRuntime)- assert isinstance(rt, LanguageRuntime)- # the scene track reaches every scene language only through SceneRuntime (D101)- assert all(isinstance(get_runtime(lang), SceneRuntime) for lang in TRACK_LANGUAGES[Track.SCENE])- assert rt.language == Language.SCENE_THREEJS- assert "src/scene.js" in rt.entry_globs and "src/zones/*.js" in rt.entry_globs- doc = language_text(rt.language, "contract.md")- assert "createScene" in doc and "update(t, dt)" in doc- paths = rt.skeleton(ws, None)- assert (ws.src / "scene.js") in paths--#: an asset module composing an effect-library factory around its own plinth (D100)LIB_ASSET = """import { makeTree } from '../lib/tree.js';export function buildBirchStand(THREE, opts = {}) {@@ -53,9 +35,7 @@ def add_lib_asset(ws, body: str = LIB_ASSET) -> str:@pytest.mark.nodedef test_asset_composing_a_library_factory_passes_the_asset_check(starter_ws):- """D100: an asset may import ``../lib/``. The factory's triangles are the library's, not the- asset's budget, and its foot is its origin (a tree's roots go below grade by design) — before,- every such asset failed the check (80k tris "over budget", roots "sinking") and escalated."""+ """D100."""from codeverse3d.languages.scene_threejs import lintfrom codeverse3d.tracks.scene_assets import ASSET_MAX_TRIS, check_threejs_asset@@ -79,8 +59,7 @@ def test_asset_composing_a_library_factory_passes_the_asset_check(starter_ws):@pytest.mark.node@needs_browserdef test_build_ok_on_example(starter_ws):- """The example scene: one probe boot passes both gates and records its census — with a zone- placing an asset that composes a library factory (D100)."""+ """The example scene."""add_lib_asset(starter_ws)meadow = starter_ws.src / "zones" / "meadow.js"meadow.write_text(meadow.read_text()@@ -130,17 +109,6 @@ def test_build_fails_with_file_line_on_shader_error(starter_ws):assert err.fix_hint-@needs_browser-def test_build_fails_on_import_error(starter_ws):- (starter_ws.src / "scene.js").write_text("import { x } from './nope.js';\nexport function createScene() {}\n")- res = SceneThreeJsRuntime().build(starter_ws)- assert not res.ok and res.error_file == "src/scene.js" and "nope.js" in res.error_message- err = res.gates[0].errors[0]- assert err.data.get("stage") == "import" and err.target == "src/scene.js"- assert "fix the syntax/import error" in err.fix_hint--def test_build_interprets_combined_summary_offline(ws, monkeypatch):"""One probe boot yields both gate reports, including the no-boot shape."""import codeverse3d.languages.scene_threejs as rt_mod@@ -175,47 +143,11 @@ def test_build_interprets_combined_summary_offline(ws, monkeypatch):assert shaders["findings"][0]["target"] == "src/shaders/x.js:7"assert (ws.artifacts / "census.json").is_file()- # boot failure → shader gate failed-empty (old two-call behaviour preserved)- def fake_run_noboot(script, args, **kw):- return NodeResult(1, "", "", {- "ok": False, "boot": {"ok": False, "stage": "import", "error": "SyntaxError: x"},- "console_errors": [], "console_warnings": [], "shader_errors": [],- "shader_report": {"ok": False, "skipped": "scene did not boot", "errors": [], "warnings": []},- }, 5)-- monkeypatch.setattr(probes_mod, "run_scene_script", fake_run_noboot)- res2 = rt_mod.SceneThreeJsRuntime().build(ws)- assert not res2.ok- shaders2 = _json.loads((ws.artifacts / "gates" / "shader_preflight.json").read_text())- assert not shaders2["passed"] and shaders2["findings"] == []---def test_probe_crash_leaves_no_stale_probe_outputs(ws, monkeypatch):- """A probe crash removes prior outputs and publishes a failed build."""- import codeverse3d.spatial.probes as probes_mod- from codeverse3d.spatial.render_scene import SceneRenderError-- for name in ("census.json", "scene_probe.json", "shader_preflight.json"):- (ws.artifacts / name).write_text('{"stale": true}')- (ws.artifacts / "build.json").write_text('{"ok": true}')-- def crash(script, args, **kw):- raise SceneRenderError("chrome went away")-- monkeypatch.setattr(probes_mod, "run_scene_script", crash)- res = SceneThreeJsRuntime().build(ws)- assert not res.ok- for name in ("census.json", "scene_probe.json", "shader_preflight.json"):- assert not (ws.artifacts / name).exists(), name- assert json.loads((ws.artifacts / "build.json").read_text())["ok"] is False-@pytest.mark.nodedef test_hand_over_of_a_library_composing_asset_is_self_contained(starter_ws):- """D100: the deliverable and the dataset sample read the round's commit, and ``src/lib/`` is- committed with ``src/`` — every import of the handed-over code resolves inside it."""+ """D100."""from codeverse3d.addons.dataset.sample import code_files_for_round- from codeverse3d.contracts.common import Trackfrom codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatusfrom codeverse3d.contracts.spec import Specfrom codeverse3d.languages.scene_threejs import lintdiff --git a/harness/tests/scene_runtime/test_scene_driver_retry.py b/harness/tests/scene_runtime/test_scene_driver_retry.pydeleted file mode 100644index 5a3ebf36..00000000--- a/harness/tests/scene_runtime/test_scene_driver_retry.py+++ /dev/null@@ -1,98 +0,0 @@-"""A scene driver that LOST ITS BROWSER is retried once on a browser of its own.--Regression: under load Chrome reaped render tabs ("Attempted to use detached Frame"),-the round kept zero renders and the judge was skipped after the generator was paid.-"""--from __future__ import annotations--import pytest--import codeverse3d.spatial.render_scene as RS-from codeverse3d.spatial.node import NodeResult-from codeverse3d.spatial.render_scene import SceneRenderError, run_scene_script--DETACHED = "render failed: Attempted to use detached Frame '10276B428E350BFA074A02AF37D52E6C'."---def _result(rc: int, summary: dict | None) -> NodeResult:- return NodeResult(rc=rc, stdout="", stderr="", last_json=summary, duration_ms=1)---def _record(monkeypatch, results: list[NodeResult]) -> list[dict[str, str]]:- """Feed `results` to run_scene_script in order; collect each call's env_extra."""- envs: list[dict[str, str]] = []-- def fake(path, args, *, cwd, timeout_s, env_extra, check):- envs.append(dict(env_extra or {}))- return results[len(envs) - 1]-- monkeypatch.setattr(RS, "run_node", fake)- return envs---def test_a_lost_browser_is_retried_on_an_owned_browser(monkeypatch):- envs = _record(monkeypatch, [- _result(2, {"ok": False, "error": DETACHED}),- _result(0, {"ok": True, "n_views": 8}),- ])- r = run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)- assert r.summary["n_views"] == 8, "the second attempt's result is the one returned"- assert len(envs) == 2, "a browser loss must be retried"- assert envs[0].get("C3D_BROWSER_REUSE") is None- assert envs[1]["C3D_BROWSER_REUSE"] == "off", "the retry must not reuse the browser that died"---def test_a_driver_error_that_is_not_a_browser_loss_is_not_retried(monkeypatch):- envs = _record(monkeypatch, [_result(2, {"ok": False, "error": "--ws and --out are required"})])- with pytest.raises(SceneRenderError, match="--ws and --out are required"):- run_scene_script("render_scene.mjs", [], timeout_s=10)- assert len(envs) == 1---def test_a_retry_that_loses_the_browser_again_raises(monkeypatch):- envs = _record(monkeypatch, [- _result(2, {"ok": False, "error": DETACHED}),- _result(2, {"ok": False, "error": DETACHED}),- ])- with pytest.raises(SceneRenderError, match="detached Frame"):- run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)- assert len(envs) == 2, "exactly one retry — a box out of memory stays out of memory"---def test_a_driver_that_exits_0_with_no_summary_is_retried(monkeypatch):- """Every scene driver ends with a JSON summary line, so a run that produced none had- its stdout tail dropped (`proc._ABANDONED`) — transient, and worth one more attempt.- Without the retry the empty summary reached `probes.probe_report`, which rendered it- as "[?] scene did not boot"; desert_canyon then spent all three repair attempts on a- defect that was never there, while its own artifacts recorded `boot.ok: true`."""- envs = _record(monkeypatch, [- _result(0, None),- _result(0, {"ok": True, "boot": {"ok": True, "stage": "ready"}}),- ])- r = run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)- assert r.summary["boot"]["ok"] is True- assert len(envs) == 2 and envs[1]["C3D_BROWSER_REUSE"] == "off"---def test_a_driver_that_answered_is_not_retried_for_a_failing_verdict(monkeypatch):- """Exit 1 WITH a summary is a scene that failed — console errors, a scene that did not- boot — a verdict, and complete, not a driver failure. Re-rendering it would only- spend the time again."""- envs = _record(monkeypatch, [_result(1, {"ok": False, "boot": {"ok": False, "stage": "createScene",- "error": "TypeError: x is not a function"}})])- r = run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)- assert r.rc == 1 and r.summary["boot"]["stage"] == "createScene" and len(envs) == 1---def test_a_transient_host_failure_is_retried_on_the_same_browser(monkeypatch):- """`node.TRANSIENT_MARKERS` is one vocabulary for both render paths (2026-09-07): a host- that timed out waiting for the page under contention is the box, not the scene, and it- keeps the shared browser — only a browser LOSS takes an owned one."""- envs = _record(monkeypatch, [- _result(2, {"ok": False, "error": "host failed: Waiting failed: 60000ms exceeded"}),- _result(0, {"ok": True, "n_views": 8}),- ])- r = run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)- assert r.summary["n_views"] == 8 and len(envs) == 2- assert envs[1].get("C3D_BROWSER_REUSE") is None, "a timeout is not a browser loss"diff --git a/harness/tests/scene_runtime/test_shader_report.py b/harness/tests/scene_runtime/test_shader_report.pyindex b0930926..a9188c28 100644--- a/harness/tests/scene_runtime/test_shader_report.py+++ b/harness/tests/scene_runtime/test_shader_report.py@@ -42,21 +42,3 @@ def test_successful_evaluated_shader_retains_static_advice_without_false_failureassert result["errors"] == []assert result["warnings"][0]["kind"] == "include_not_alone"assert result["warnings"][0]["validation"] == "runtime_compile_passed"---def test_runtime_compile_failure_is_still_a_hard_error():- result = compile_report(- shader_errors=[dict(stage="fragment", message="syntax error", source_line="bad")]- )- assert {e["kind"] for e in result["errors"]} == {"include_not_alone", "compile"}- assert not result["warnings"]---def test_no_compiled_programs_and_boot_failure_cannot_override_source_errors():- for result in (compile_report(programs=0), compile_report(boot_ok=False)):- assert "include_not_alone" in {e["kind"] for e in result["errors"]}---def test_compile_success_does_not_clear_missing_uniform_binding():- result = compile_report(uniform_error=True)- assert [e["kind"] for e in result["errors"]] == ["unbound_uniform"]diff --git a/harness/tests/scene_runtime/test_shadow_filter.py b/harness/tests/scene_runtime/test_shadow_filter.pyindex 3bd25e9a..f566c905 100644--- a/harness/tests/scene_runtime/test_shadow_filter.py+++ b/harness/tests/scene_runtime/test_shadow_filter.py@@ -1,9 +1,4 @@-"""The shared renderer must compile filtered shadows on the installed Three.--Checking the enum alone missed r182's removal of PCFSoftShadowMap from the-WebGLProgram mapping: that old enum compiled BASIC without a runtime error.-Inspect the actual linked fragment shader of a shadow-receiving material.-"""+"""The shared renderer must compile filtered shadows on the installed Three."""import jsonimport subprocessdiff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.pyindex b52c7ff2..42d675b2 100644--- a/harness/tests/scene_runtime/test_skeleton.py+++ b/harness/tests/scene_runtime/test_skeleton.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom codeverse3d.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan-from codeverse3d.languages.scene_threejs import lint, write_example, write_skeleton+from codeverse3d.languages.scene_threejs import lint, write_skeletonfrom codeverse3d.workspace import Workspacefrom tests.scene_runtime.conftest import needs_node@@ -27,11 +27,7 @@ def make_plan() -> ScenePlan:@needs_nodedef test_plan_skeleton_writes_interface_stubs_and_lints(ws):- """The skeleton is the interface plus the plan's data: no landform, no positions, no example- files. It used to be a finished landscape (a level disc of the bounds' radius with hills- and a ridge beyond, kept byte for byte by 29 of 30 iteration-0 scenes), zone contents tiled- on a grid inside each bbox under "keep everything inside the plan bbox", and a pine tree, a- windmill and a pond shader copied in whatever the brief (owner, 2026-10-15)."""+ """The skeleton is the interface plus the plan's data: no landform, no positions, no example files (owner, 2026-10-15)."""plan = make_plan()paths = write_skeleton(ws, plan)rel = {p.relative_to(ws.src).as_posix() for p in paths}@@ -46,8 +42,7 @@ def test_plan_skeleton_writes_interface_stubs_and_lints(ws):pier = (ws.src / "zones" / "pier.js").read_text()assert "zone.name = 'Pier'" in pier and "import { buildCrate } from '../assets/crate.js';" in pier and "ctx.assets.crane" in pier# a TODO naming the plan's contents, no positions, no bbox wall- assert "TODO" in pier and "- Crate:" in pier and "- Crane:" in pier and "place(" not in pier and "position.set" not in pier- assert "inside the plan bbox" not in pier and "continue past the bbox" in pier and "scene_placement" in pier+ assert "- Crate:" in pier and "place(" not in pier and "position.set" not in piercrate = (ws.src / "assets" / "crate.js").read_text()assert "export function buildCrate" in crate and "PLACEHOLDER" in crate and "pine_tree" not in crate and "windmill" not in crateenv = (ws.src / "env.js").read_text()@@ -56,10 +51,8 @@ def test_plan_skeleton_writes_interface_stubs_and_lints(ws):for landform in ("CONTENT_RADIUS", "worldShell(", "makeOutskirts(", "roomShell(", "FLAT_RADIUS", "flat:","sunRig(", "MOOD", "scene.fog =", "scene.environment ="): # no light, sky or fog decided eitherassert landform not in code, landform- for mandate in ("TUNE these", "do not replace"):- assert mandate not in env, mandateassert "export function heightAt" in env and "export function buildEnv" in env and "export const SUN_AZIMUTH_DEG" in env- assert "ENV PLAN: calm sea" in env and "not the edge of the world" in env and "PLACEHOLDER" in env and "fog_short" in env+ assert "ENV PLAN: calm sea" in envassert "export const INTERIOR = null;" in envassert (ws.public / "assets").is_dir()rep = lint(ws)@@ -77,10 +70,7 @@ def test_plan_skeleton_writes_interface_stubs_and_lints(ws):def test_both_skeleton_paths_ship_the_effect_library(tmp_path):- """The library is only usable if it is IN the workspace, and plan mode is the- PRODUCTION path. It once shipped the example's pattern files only, so a planned run- carried the effects catalog in its prompt with no `src/lib/` to import from —- every `from './lib/grass.js'` an agent wrote would have been a build error."""+ """The library is only usable if it is IN the workspace, and plan mode is the PRODUCTION path."""from codeverse3d.languages.scene_threejs import lib_filesnames = {p.name for p in lib_files()}@@ -96,68 +86,8 @@ def test_both_skeleton_paths_ship_the_effect_library(tmp_path):assert ws.src / "zones" / "meadow.js" in written and (ws.src / "scene.js").is_file()-def test_the_library_is_harness_owned_so_an_agent_cannot_rewrite_it():- """`src/lib/` is starter code the agent CALLS. Registering it in- HARNESS_OWNED_SRC is what makes `_enforce_scope` revert a session's write to- it — the protection a seeded glsl file got on 2026-08-26, when a seeded file the agent- COULD rewrite was measured gone by the end of the run."""- from codeverse3d.contracts.common import HARNESS_OWNED_SRC, Language, is_harness_owned-- owned = HARNESS_OWNED_SRC[Language.SCENE_THREEJS]- assert owned == ("src/lib/",)- assert is_harness_owned("src/lib/grass.js", owned)- assert is_harness_owned("src/lib/nested/x.js", owned)- # the agent's OWN files stay writable- for rel in ("src/scene.js", "src/env.js", "src/zones/meadow.js", "src/libx.js"):- assert not is_harness_owned(rel, owned), rel- # a plain entry is still an exact match, not a prefix- assert is_harness_owned("src/owned.glsl", ("src/owned.glsl",))- assert not is_harness_owned("src/owned.glsl.bak", ("src/owned.glsl",))- assert Language.GLSL_SHADER not in HARNESS_OWNED_SRC, "the seeded recipes.glsl went with D107"---def test_the_lint_does_not_judge_the_library_as_agent_code(tmp_path):- """The workspace gate polices what the AGENT writes. Once the library shipped- inside `src/`, linting it as agent code was 3 hard ERRORs (signage.js's- node-only font fallback imports `node:module` / `node:fs/promises` / `node:url`,- which the browser half never reaches) plus 12 "large file" WARNs telling the- agent to split files it does not own — a red gate on every scene run."""- from codeverse3d.contracts.artifacts import Severity-- ws = Workspace(tmp_path / "ws")- write_example(ws)- report = lint(ws)- assert report.gate == "lint:scene_threejs"- assert report.passed, [f.message for f in report.findings if f.severity == Severity.ERROR]- assert not [f for f in report.findings if f.target.startswith("src/lib/")], \- [f.target for f in report.findings if f.target.startswith("src/lib/")]---def test_the_effects_catalog_reaches_the_scene_prompts_and_only_those():- """A catalog the prompt never carries teaches nothing (the same failure the- inlined cookbook chapters exist for). It is keyed on LANGUAGE: a blender- asset session inside a scene run must not be told to import three.js modules."""- from codeverse3d.contracts.common import Language- from codeverse3d.prompts import PROMPTS_DIR- from codeverse3d.prompts.catalog import language_text-- text = language_text(Language.SCENE_THREEJS, "effects_catalog.md")- assert "makeGrass" in text and "makeCanopy" in text and "lib/shader.js" in text- assert language_text(Language.BLENDER, "effects_catalog.md") == ""- assert language_text(Language.GLSL_SHADER, "effects_catalog.md") == ""-- tpl = PROMPTS_DIR / "tracks"- for name in ("scene_env.j2", "scene_zone.j2"):- assert "effects_catalog" in (tpl / name).read_text(), name- # the asset session authors BLENDER bpy, so it must NOT carry the table; a refine session edits- # one file with src/lib in its workspace and the skills routed, so it carries none either (2026-10-15)- for name in ("scene_asset.j2", "scene_refine.j2"):- assert "effects_catalog" not in (tpl / name).read_text(), name--def test_the_catalog_names_every_library_module_and_no_other():- """The catalog is the agent's only index of the library. That every call- it names is a real export is checked at runtime in lib/test_library.py."""+ """The catalog is the agent's only index of the library."""import refrom codeverse3d.languages.scene_threejs import lib_files@@ -167,20 +97,3 @@ 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/scene_runtime/test_update_hooks.py b/harness/tests/scene_runtime/test_update_hooks.pyindex 0945fc3b..b4b77f55 100644--- a/harness/tests/scene_runtime/test_update_hooks.py+++ b/harness/tests/scene_runtime/test_update_hooks.py@@ -58,26 +58,3 @@ export function createScene() {if not forward:assert findings[0].severity == Severity.WARN and findings[0].target == "CentralPad"assert "parent zone" in findings[0].fix_hint---@needs_node-def test_cached_hooks_shader_ticks_and_empty_stubs_are_not_reported():- """The zone that places an asset may cache its hook (prompts/tracks/scene_asset.j2), one tickShaders()- may drive every uTime, and a library stub `() => {}` has nothing to forward: none is 'unobserved'."""- result = run_node_json("""-import * as T from 'three';-import { observeUpdateHooks } from './lib/update_hooks.mjs';-const scene=new T.Scene(), zone=new T.Group(); zone.name='Farm'; scene.add(zone);-const mill=new T.Group(); mill.name='Windmill'; zone.add(mill);-mill.userData.update=t=>{mill.rotation.z=t;}; const hook=mill.userData.update;-const mat=new T.ShaderMaterial({uniforms:{uTime:{value:0}}});-const rain=new T.Mesh(new T.BoxGeometry(),mat); rain.name='Rain'; zone.add(rain);-rain.userData.update=t=>{mat.uniforms.uTime.value=t;};-const ice=new T.Group(); ice.name='Ice'; zone.add(ice); ice.userData.update=()=>{};-const still=new T.Group(); still.name='Still'; zone.add(still); still.userData.update=t=>{still.position.x=t;};-const report=observeUpdateHooks(scene,()=>{for(let i=1;i<=3;i++){hook(i/30);- scene.traverse(o=>{if(o.material?.uniforms?.uTime)o.material.uniforms.uTime.value=i/30;});}});-console.log(JSON.stringify(report.unobserved.map(r=>r.path)));-""")- assert result == ["Farm/Still"]diff --git a/harness/tests/scene_runtime/test_zone_roots.py b/harness/tests/scene_runtime/test_zone_roots.pyindex e7924204..67e62c90 100644--- a/harness/tests/scene_runtime/test_zone_roots.py+++ b/harness/tests/scene_runtime/test_zone_roots.py@@ -1,14 +1,4 @@-"""D111: placed-asset rows come from the plan's ZONE roots only — the roots the harness marks itself.--Argon loop iteration 4 (scene_threejs, 2026-10-15): every top-level scene child was a "zone", so an env-wall merged per material (body + piers in one mesh, the flashing strip in another) became rows that-overlap by construction, a two-mesh bollard was a cap "interpenetrating" its post, and in two runs-(r1_02, r1_10) every final placement ERROR sat on such scenery. The assembler now marks each zone root with-``userData[ZONE_ROOT_KEY]`` (the census GLB's zone-node extras for scene_blender); every other root is-scenery: no rows, never paired with other scenery, not in the free share — still a support, something-to sink into, something a zone asset is mounted on (``attached``, and the boot settle leaves it) and-something a zone asset can clip (a zone-vs-scenery interpenetration names the zone asset).-"""+"""D111: placement rows come from the zone roots the assembler marks; other roots are scenery (no rows)."""from __future__ import annotations@@ -26,49 +16,11 @@ from tests.scene_runtime.conftest import needs_node, run_node_jsonSCENE_JS = """import * as THREE from 'three';import fs from 'node:fs';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';import { sceneCensus } from './lib/host_census.mjs';import { settleScene } from './lib/host_placement.mjs';const brick = new THREE.MeshStandardMaterial({ name: 'Brick' }), metal = new THREE.MeshStandardMaterial({ name: 'Metal' });const geo = (sx, sy, sz, x, y, z) => new THREE.BoxGeometry(sx, sy, sz).translate(x, y + sy / 2, z);const box = (name, sx, sy, sz, x, y, z, m = brick) => { const o = new THREE.Mesh(geo(sx, sy, sz, 0, 0, 0), m); o.name = name; o.position.set(x, y, z); return o; };-function build(mark, withScenery) {- const scene = new THREE.Scene();- const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200, 8, 8), brick); ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2;- scene.add(ground);- const yard = new THREE.Group(); yard.name = 'Yard';- if (mark) yard.userData[mark] = 'Yard';- yard.add(box('Crate', 1, 1, 1, 0, 0, 0));- yard.add(box('Anvil', 1, 1, 1, -5, -0.5, 0)); // sunken 0.5 m into Ground: a real finding- yard.add(box('CrateA', 1, 1, 1, 10, 0, 0)); yard.add(box('CrateB', 1, 1, 1, 10.5, 0, 0)); // a real pair- // the assembler's probe nests the marked root in a wrapper: still found- const wrap = new THREE.Group(); wrap.name = '__zone__yard'; wrap.add(yard); scene.add(wrap);- if (withScenery) {- // an env parapet built and MERGED BY MATERIAL: wall body + piers in one brick mesh, the flashing- // strip in a metal one, flush on the wall and pierced by the piers (iteration 4, r1_02)- const parapet = new THREE.Group(); parapet.name = 'ParapetWall_North';- const body = [geo(25, 1.1, 0.5, 0, 0, -30)];- for (let i = -3; i <= 3; i++) body.push(geo(0.6, 1.3, 0.6, i * 4, 0, -30));- parapet.add(new THREE.Mesh(mergeGeometries(body), brick));- parapet.add(new THREE.Mesh(geo(25, 0.14, 0.5, 0, 1.0, -30), metal));- scene.add(parapet);- // harbour bollards: a cap and a post as two unnamed sibling meshes (iteration 4, r1_10)- const harbor = new THREE.Group(); harbor.name = 'HarborSurroundings';- for (const z of [-16, -6, 4]) {- harbor.add(box('', 0.4, 0.72, 0.4, 20, 0, z, metal));- harbor.add(box('', 0.36, 0.3, 0.36, 20, 0.6, z, metal)); // its foot inside the post's top- }- scene.add(harbor);- // a room shell (the RoomShell name exemption this replaces): a lintel running into the lid- const shell = new THREE.Group(); shell.name = 'RoomShell';- 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.add(shell);- // a free-tagged scenery root never enters the free share- const birds = box('Gull', 0.3, 0.2, 0.3, 0, 8, 0); birds.userData.placement = 'free'; scene.add(birds);- }- scene.updateMatrixWorld(true);- return sceneCensus(scene, THREE, { placement: true }).placement;-}// a marked street zone whose things hang on, and push into, an env facade (the scenery)function street(mark) {const scene = new THREE.Scene();@@ -89,7 +41,7 @@ const KEY = process.argv[2];const words = JSON.parse(fs.readFileSync('./lib/placement_words.json', 'utf8'));const settled = street(KEY);const settle = settleScene(settled, THREE, { groundY: 0, words });-console.log(JSON.stringify({ zoneOnly: build(KEY, false), marked: build(KEY, true), unmarked: build('', true),+console.log(JSON.stringify({street: sceneCensus(street(KEY), THREE, { placement: true }).placement, settle }));"""@@ -116,30 +68,10 @@ def test_the_assembled_scene_marks_every_zone_root():assert f"g.userData['{ZONE_ROOT_KEY}'] = name;" in text-@needs_node-def test_env_scenery_yields_no_rows_while_the_zone_findings_are_unchanged(tables):- marked, zone_only = tables["marked"], tables["zoneOnly"]- assert {r["zone"] for r in marked["assets"]} == {"Yard"}- assert marked["scenery"]["n"] == 5 and {"ParapetWall_North", "HarborSurroundings", "RoomShell", "Ground"} <= set(marked["scenery"]["names"])- assert not marked["exempt"].get("free"), "a free-tagged scenery root is not in the free share"- # the room shell (walls, lid, lintels abutting by construction): no row, no pair — the 2026-10-15- # `RoomShell…` name exemption this replaces (24 of 41 Blender ERRORs in loop iteration 0)- assert not [r for r in marked["assets"] if r["name"] in ("Ceiling", "RoomShellWallBack_0Lintel")]- found = _findings(marked)- assert found == _findings(zone_only), "scenery changes nothing about the zone's own findings"- kinds = {(k, t) for _, k, t in found}- assert ("sunken", "Yard/Anvil") in kinds and any(k == "interpenetration" for k, _ in kinds), found- assert all(t.startswith("Yard/") or t == "scene" for _, _, t in found), found--@needs_node@pytest.mark.nodedef test_a_zone_asset_mounted_on_scenery_is_attached_and_one_pushed_into_it_clips(tables):- """A sconce flush on an env facade is mounted on it — the gate leaves it, and so does the boot- settle (it used to drop a sign hung on scenery to the ground: the "touching a neighbour" test- looked at zone assets only) — while a kiosk pushed into the facade is still an interpenetration,- reported on the zone asset whichever box is smaller."""+ """A sconce flush on an env facade is mounted on it — the gate leaves it, and so does the boot settle (it used to drop a sign hung on scenery to the g..."""t = tables["street"]rows = {r["name"]: r for r in t["assets"]}assert rows["WallSconce"]["attached"] == ["FacadeWall"] and rows["ShopSign"]["attached"] == ["FacadeWall"]@@ -149,14 +81,3 @@ def test_a_zone_asset_mounted_on_scenery_is_attached_and_one_pushed_into_it_clipassert [t for _, k, t in found if k == "interpenetration"] == ["Street/Kiosk"], found(pair,) = t["interpenetrations"]assert (pair["a"], pair["zone_a"], pair["b"], pair["zone_b"]) == ("Kiosk", "Street", "FacadeWall", "StreetFacades")---@needs_node-def test_without_the_mark_the_scenery_is_measured_as_before(tables):- """The control: the same scene unmarked (a scene the harness did not assemble) still measures- every top-level child — which is exactly the artefact the mark removes."""- pairs = tables["unmarked"]["interpenetrations"]- zones = {p["zone_a"] for p in pairs} | {p["zone_b"] for p in pairs}- assert {"ParapetWall_North", "HarborSurroundings"} <= zones, pairs- assert tables["unmarked"]["scenery"]["n"] == 0diff --git a/harness/tests/skills/conftest.py b/harness/tests/skills/conftest.pyindex 78f6c68a..bcabb886 100644--- a/harness/tests/skills/conftest.py+++ b/harness/tests/skills/conftest.py@@ -27,7 +27,6 @@ metadata:{body}"""-def write_bundle(root: Path, name: str, *, description: str = "", evidence: str = "measured",body: str = "Rule one: prove it with `measure`.", references: dict[str, str] | None = None) -> Path:d = root / name@@ -41,7 +40,6 @@ def write_bundle(root: Path, name: str, *, description: str = "", evidence: str(d / "references" / rel).write_text(text)return d-@pytest.fixturedef library_dir(tmp_path: Path) -> Path:"""A library holding every skill the route table can name, all `measured`."""@@ -51,7 +49,6 @@ def library_dir(tmp_path: Path) -> Path:write_bundle(root, name)return root-@pytest.fixturedef library(library_dir: Path) -> dict:from codeverse3d.skills import all_skillsdiff --git a/harness/tests/skills/test_config.py b/harness/tests/skills/test_config.pydeleted file mode 100644index ca6ff1cc..00000000--- a/harness/tests/skills/test_config.py+++ /dev/null@@ -1,38 +0,0 @@-"""The skill switches are ``Settings`` fields: ON by default, tolerant of garbage, live (never a dead A/B switch)."""--from __future__ import annotations--import pytest--from codeverse3d.config import Settings, get_settings---def _settings(monkeypatch, **env: str) -> Settings:- for name in ("C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED"):- monkeypatch.delenv(name, raising=False)- for name, raw in env.items():- monkeypatch.setenv(name, raw)- return Settings()--[email protected]("name, raw, want", [- ("C3D_SKILLS", "off", (False, True, 5)), ("C3D_SKILLS", "", (True, True, 5)), ("C3D_SKILLS", "maybe", (True, True, 5)),- ("C3D_SKILLS_MAX", "3", (True, True, 3)), ("C3D_SKILLS_MAX", "-1", (True, True, 5)), ("C3D_SKILLS_MAX", "nope", (True, True, 5)),-])-def test_on_by_default_and_garbage_keeps_the_default(monkeypatch, name, raw, want):- """Default ON (owner 2026-09-22); garbage warns and keeps the default, never a crash (D44 c)."""- s = _settings(monkeypatch, **{name: raw})- assert (s.skills, s.skills_unverified, s.skills_max) == want---def test_doctor_reports_the_default_and_the_skill_tool(monkeypatch):- """ON is healthy, and claude-code's Skill tool must be allowed."""- from codeverse3d.doctor import check_skills-- monkeypatch.delenv("C3D_SKILLS", raising=False)- rows = {name: status for name, status, _ in check_skills()}- assert rows["skills switch"] == "OK"- assert rows["claude-code Skill tool"] == "OK"- monkeypatch.setenv("C3D_SKILLS", "0")- get_settings.cache_clear()- assert {name: status for name, status, _ in check_skills()}["skills switch"] == "WARN"diff --git a/harness/tests/skills/test_contract_agreement.py b/harness/tests/skills/test_contract_agreement.pydeleted file mode 100644index fe0c0aba..00000000--- a/harness/tests/skills/test_contract_agreement.py+++ /dev/null@@ -1,154 +0,0 @@-"""Keep skill advice, language contracts and live gate tolerances consistent."""--from __future__ import annotations--import re-from pathlib import Path--import pytest--from codeverse3d.conventions import CONTACT_GAP_M-from codeverse3d.prompts.catalog import PROMPT_DIRS-from codeverse3d.skills import bundle_dirs, iter_skills, skills_dir-from codeverse3d.skills.registry import ROUTES-from codeverse3d.spatial.connectivity import PENETRATION_WARN_M--HARNESS = Path(__file__).resolve().parents[2]-PROMPTS = HARNESS / "codeverse3d" / "prompts"-CONTRACTS = sorted(PROMPTS.glob("*/contract.md"))-BUNDLES = bundle_dirs()-SKILLS = list(iter_skills()) if BUNDLES else []--#: prompts/<dir> per language id — codeverse3d.prompts.catalog owns the mapping-#: (urdf_blender's docs live under prompts/urdf)-_DIR_FOR_LANG = {k.value: v for k, v in PROMPT_DIRS.items()}--WARN_MM = PENETRATION_WARN_M * 1000-GAP_MM = CONTACT_GAP_M * 1000--#: The sentence boundary must NOT be a decimal point: splitting "0.5-2 mm" on the dot-#: leaves "5-2 mm" and invents a 5 mm recommendation that nobody wrote.-_SENTENCE_SPLIT = re.compile(r"(?<!\d)\.(?!\d)|\n")-#: markdown wraps a sentence across lines, so a prohibition ("... , not `X`") often sits on-#: a different line from the name it prohibits. For prose claims the unit is the paragraph.-_PARAGRAPH_SPLIT = re.compile(r"\n\s*\n")-_WELD_WORD = re.compile(r"\b(?:weld|overlap|sunk|sink|reaches)\b", re.I)-#: a sentence that names a deep overlap while NOT recommending one: it states the limit,-#: quotes a gate message, or reports a measured statistic about defects we already have-_NOT_A_RECOMMENDATION = re.compile(- r"warn|error|interpenetrat|too (?:deep|far)|never|not\b|above|beyond|>|\bfired\b|\bat pose\b"- r"|median|mean\b|average|\bmax\b|\bmin\b|p50|p90|worst|observed|measured|corpus"- r"|\bruns?\b", re.I)-_MM = re.compile(r"(\d+(?:\.\d+)?)\s*(?:[-–—]\s*(\d+(?:\.\d+)?)\s*)?mm\b")---def _weld_sentences(text: str) -> list[str]:- return [s for s in _SENTENCE_SPLIT.split(text) if _WELD_WORD.search(s)]---def _mm_values(sentence: str) -> list[float]:- """Every millimetre figure in one sentence, ranges expanded to their endpoints."""- out: list[float] = []- for lo, hi in _MM.findall(sentence):- out.append(float(lo))- if hi:- out.append(float(hi))- return out---def test_contract_tolerances_match_the_live_gates():- for contract in CONTRACTS:- text = contract.read_text()- label = f"{contract.parent.name}/{contract.name}"- for sentence in _weld_sentences(text):- for mm in _mm_values(sentence):- assert mm <= WARN_MM, (- f"{label} asks for {mm} mm; the gate warns above {WARN_MM:.0f} mm:\n"- f" {sentence.strip()}"- )- for sentence in (part for part in _SENTENCE_SPLIT.split(text)- if re.search(r"\bgap\b", part, re.I)):- if not re.search(r"[<≤]=?\s*\d|within|at most|no more than", sentence, re.I):- continue- for mm in _mm_values(sentence):- assert mm <= GAP_MM, (- f"{label} allows a {mm} mm gap; the gate joins only within "- f"{GAP_MM:.0f} mm:\n {sentence.strip()}"- )---def _forbidden_apis(contract: Path) -> set[str]:- """Backticked names inside the contract's Forbidden block."""- text = contract.read_text()- out: set[str] = set()- for line in text.splitlines():- # ONLY the prohibitive bullets. A "Forbidden" block also carries the- # allowed alternatives ("use MeshStandardMaterial only"), and treating those as- # forbidden would fail every skill that recommends the right thing.- if not re.match(r"\s*\*?\s*(?:No|Never|Forbidden)\b", line):- continue- for token in re.findall(r"`([^`\n]+)`", line):- token = token.strip()- if len(token) > 3 and not token.startswith(("<", "//")):- out.add(token)- return out---def _languages_of(skill_name: str) -> set[str]:- return {lang for r in ROUTES if r.skill == skill_name for lang in r.languages}--[email protected](not SKILLS, reason=f"no bundles in {skills_dir()} yet")-def test_skill_advice_respects_gates_and_language_contracts():- for skill in SKILLS:- text = "\n".join(- [skill.body] + [p.read_text() for p in sorted(skill.dir.rglob("references/*.md"))]- )- for sentence in _weld_sentences(text):- if _NOT_A_RECOMMENDATION.search(sentence):- continue- for mm in _mm_values(sentence):- assert mm <= WARN_MM, f"{skill.name} recommends {mm} mm:\n {sentence.strip()}"-- for language in sorted(_languages_of(skill.name)):- contract = PROMPTS / _DIR_FOR_LANG.get(language, language) / "contract.md"- if not contract.is_file():- continue- for api in sorted(_forbidden_apis(contract)):- stem = api.rstrip("*").rstrip(".")- if len(stem) < 5:- continue- quoted = re.compile(- rf"`[^`\n]*(?<![A-Za-z0-9_]){re.escape(stem)}(?![A-Za-z0-9_])[^`\n]*`"- )- for paragraph in _PARAGRAPH_SPLIT.split(text):- if not quoted.search(paragraph):- continue- refusal = re.search(- r"never|not\b|forbidden|do not|don't|avoid|refuse|reject|instead of"- r"|banned|lint|fails|error|no DOM|headless",- paragraph,- re.I,- )- assert refusal, (- f"{skill.name} recommends {api!r}, forbidden by {language}/contract.md:\n"- f" {' '.join(paragraph.split())[:160]}"- )---#: a node name built from a loop index with nothing between the stem and the index-#: (``f"Leg{i + 1}"``, `` `Leg${i}` ``): `conventions.split_instance` does not split it-_GLUED_INDEX = re.compile(r"[A-Za-z]\$?\{i\b")-_OBJECT_TEXTS = [p for d in ("blender", "cadquery", "threejs", "urdf") for p in sorted((PROMPTS / d).glob("*.md"))] \- + sorted((PROMPTS / "tracks").glob("generate_*.j2")) + sorted(skills_dir().rglob("*.md"))---def test_object_texts_name_instances_the_way_the_gate_splits_them():- """Audit 2026-09-24 N1: the contracts' own examples named copies ``Leg1``..``Leg4``, which- the contract gate does not count as instances of plan part ``Leg`` (missing-part ERROR)."""- from codeverse3d.conventions import split_instance, to_snake-- assert split_instance(to_snake("Leg1")) == ("leg1", "") and split_instance(to_snake("Leg_1")) == ("leg", "1")- glued = [f"{p.relative_to(HARNESS)}:{n}: {line.strip()}" for p in _OBJECT_TEXTS- for n, line in enumerate(p.read_text().splitlines(), 1) if _GLUED_INDEX.search(line)]- assert not glued, "name instances Name_{i}:\n" + "\n".join(glued)diff --git a/harness/tests/skills/test_delivery.py b/harness/tests/skills/test_delivery.pydeleted file mode 100644index 3d867ad7..00000000--- a/harness/tests/skills/test_delivery.py+++ /dev/null@@ -1,12 +0,0 @@-"""Each backend's skill discovery root is one row in skills/prompting.py."""--from __future__ import annotations--from codeverse3d.skills.prompting import AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT, skill_path---def test_claude_code_reads_its_own_root_and_nobody_else_does():- """claude-code 2.1 has no `.agents` root, the others no `.claude` one; a model suffix never matters."""- assert skill_path("c3d-x", agent_kind="claude-code:opus") == f"{CLAUDE_SKILL_ROOT}/c3d-x/SKILL.md"- for kind in ("codex:gpt-6.1-sol", "gemini-cli", "agy", "some-future-cli", ""):- assert skill_path("c3d-x", agent_kind=kind) == f"{AGENTS_SKILL_ROOT}/c3d-x/SKILL.md", kinddiff --git a/harness/tests/skills/test_end_to_end.py b/harness/tests/skills/test_end_to_end.pyindex 2f43e187..9ea9e025 100644--- a/harness/tests/skills/test_end_to_end.py+++ b/harness/tests/skills/test_end_to_end.py@@ -10,6 +10,7 @@ from codeverse3d.config import Settingsfrom codeverse3d.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse3d.contracts.common import Languagefrom codeverse3d.contracts.run import RunStatus+from codeverse3d.conventions import to_snakefrom codeverse3d.skills.materialize import MARK_BEGINfrom codeverse3d.skills.registry import ROUTED_SKILLSfrom codeverse3d.tracks.static_object import StaticObjectTrack@@ -23,7 +24,6 @@ from tests.orchestrator_tracks.fakes import (FakeRuntime,FakeServices,)-from tests.orchestrator_tracks.test_tracks import _agent_writerfrom tests.skills.conftest import write_bundle@@ -39,7 +39,6 @@ class RealMessageServices(FakeServices):for p in parts]return GateReport(gate="contract", passed=not findings, findings=findings)-class RepairOnceRuntime(FakeRuntime):"""A real lint-shaped failure that the baseline's repair session must consume."""@@ -53,30 +52,31 @@ class RepairOnceRuntime(FakeRuntime):return GateReport(gate="lint:threejs", passed=False, findings=[finding])return super().lint(ws)-def _repairing_writer(job, ws):- files = _agent_writer(job, ws)+ """Every round edits something (identical output reads as a plateau); part files come from the prompt table."""+ files = {}+ for line in job.prompt.splitlines():+ if line.startswith("| ") and not line.startswith(("| part", "|---")) and line.split("|")[1].strip():+ name = line.split("|")[1].strip()+ files[f"src/parts/{to_snake(name)}.js"] = f"export function build{name}(THREE) {{ return new THREE.Group(); }}\n"+ files["src/object.js"] = f"// {job.label} r{job.round}\nexport function build(THREE) {{ return new THREE.Group(); }}\n"if job.kind == "baseline":files["src/object.js"] += "// SHADER_LINT_ERROR\n"return files-@pytest.fixture(autouse=True)def _no_brief(monkeypatch):"""The fake planner answers one canned plan; the optional brief call would eat it."""monkeypatch.setenv("C3D_PLAN_BRIEF", "off")-@pytest.fixturedef chair_plan():return _chair_plan.__wrapped__()-@pytest.fixturedef settings(tmp_path: Path) -> Settings:return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")-@pytest.fixturedef run(tmp_path: Path, chair_plan, settings, monkeypatch):lib = tmp_path / "library"@@ -94,7 +94,6 @@ def run(tmp_path: Path, chair_plan, settings, monkeypatch):assert rec.status is RunStatus.MAX_ROUNDSreturn rec, ws, agent-def test_enabled_run_delivers_routes_repairs_and_records_skills(run):rec, ws, agent = runfor root in (".agents/skills", ".claude/skills"):diff --git a/harness/tests/skills/test_freshness.py b/harness/tests/skills/test_freshness.pydeleted file mode 100644index 6f5d440c..00000000--- a/harness/tests/skills/test_freshness.py+++ /dev/null@@ -1,219 +0,0 @@-"""Keep every harness name, callable, gate, constant and skill cited by a bundle live.--Foreign APIs and example names are explicit allowlists, so deleting or renaming harness-vocabulary fails with the document that still cites it.-"""--from __future__ import annotations--import re-from pathlib import Path--import pytest--from codeverse3d.skills import bundle_dirs, iter_skills, skills_dir-from codeverse3d.skills.registry import ROUTED_SKILLS-from codeverse3d.spatial.registry import list_tools--BUNDLES = bundle_dirs()-SKILLS = list(iter_skills()) if BUNDLES else []-pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet")--HARNESS = Path(__file__).resolve().parents[2]-EVAL_BENCH = HARNESS.parent / "eval" / "bench" # absent on a harness-only checkout (D77)--#: every markdown file a bundle ships — SKILL.md and its references are equally quotable-DOCS: list[Path] = sorted(p for d in BUNDLES for p in d.rglob("*.md"))--_FENCE = re.compile(r"^```.*?^```", re.S | re.M)-_INLINE_CODE = re.compile(r"`([^`\n]+)`")-_CONST = re.compile(r"\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b")-_GATE_SLUG = re.compile(- r"\b(?:connectivity|contract|joint_sweep|motion_direction|scene_frames|gl_frames|lint"- r"|shader|render_console|shader_preflight)/[a-z_]+\b")-#: a snake_case token in backticks is CLAIMED to be a name in this harness. Which live-#: vocabulary it belongs to does not matter — that it belongs to one of them does.-_HARNESS_SHAPED = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$")--#: ALL_CAPS tokens that are NOT ours, with the namespace that owns them. Extend-#: deliberately: an author who adds a name here is asserting it is somebody else's.-FOREIGN: dict[str, str] = {- "SIMPLE_DEFORM": "bpy modifier type enum",- "DEPTH_TEST": "OpenGL capability (GL_DEPTH_TEST)",- "GL_QUADS": "legacy OpenGL primitive enum",- "USE_LOGDEPTHBUF": "three.js shader define",- "USE_FOG": "three.js shader define",- # variables inside a bundle's own worked examples- "SEAT_T": "example constant", "SEAT_Z": "example constant",- "X_0": "example part name", "X_3": "example part name",- "C3D_SKILLS_UNVERIFIED": "our own switch, named in prose as an env var",-}--LIVE_TOOLS = {t.name for t in list_tools()}---def _module_constants() -> set[str]:- out: set[str] = set()- for p in (HARNESS / "codeverse3d").rglob("*.py"):- for m in re.finditer(r"^([A-Z][A-Z0-9_]*)\s*[:=]", p.read_text(errors="ignore"), re.M):- out.add(m.group(1))- return out---LIVE_CONSTANTS = _module_constants()---def _live_gate_kinds() -> set[str]:- from codeverse3d.skills import registry-- return {v for k, v in vars(registry).items()- if k.isupper() and isinstance(v, str) and "/" in v}---LIVE_KINDS = _live_gate_kinds()---def _live_vocabulary() -> set[str]:- """Every word that appears anywhere in this harness's own source and prompts.-- Deliberately the WHOLE corpus rather than a curated list of tools: a skill quotes- tool names, gate ids, rubric criteria, ``fix_hint`` field names, uniform names the- glsl contract defines, lint rule ids and battery names, and every one of those is a- checkable claim about something that exists. Curating them by hand would mean the- author of the next vocabulary has to remember to extend the test; asking "does this- word occur anywhere in what we ship" needs no maintenance and still fails loudly the- day a name is renamed out of the codebase.- """- words: set[str] = set()- for root, exts in ((HARNESS / "codeverse3d", {".py", ".md", ".j2", ".yaml", ".yml", ".toml"}),- (EVAL_BENCH, {".py", ".yaml", ".yml"}), # battery + prompt ids a bundle cites- (HARNESS / "runtime_js", {".js", ".mjs", ".glsl", ".json"})):- if not root.is_dir():- continue- for p in root.rglob("*"):- if (not p.is_file() or p.suffix not in exts or "out" in p.parts- or "node_modules" in p.parts or "__pycache__" in p.parts- or p.parent.name.startswith("c3d-") or "_claims" in p.parts- or p.parent.parent.name.startswith("c3d-")):- continue- words |= set(re.findall(r"[A-Za-z_][A-Za-z0-9_]*", p.read_text(errors="ignore")))- out = EVAL_BENCH / "out"- if out.is_dir():- words |= {d.name for d in out.iterdir() if d.is_dir()}- return words---LIVE_VOCABULARY = _live_vocabulary()--#: snake_case names that are NOT ours, with who owns them. Extend deliberately.-FOREIGN_CALLS = {- # GLSL / three.js / bpy builtins a bundle quotes while teaching that language- "texture", "smoothstep", "fract", "mix", "clamp", "dot", "cross", "normalize", "length",- "abs", "max", "min", "mod", "pow", "sin", "cos", "step", "reflect", "refract",- "transform_apply", "primitive_cube_add", "ensure_lookup_table", "hide_set", "update",- "len", "setup", "range", "print", "float", "int",- "clean", # cadquery/trimesh mesh op quoted while teaching welding- # bpy API names (bmesh.ops.remove_doubles, ScrewModifier.screw_offset, Curve.bevel_object,- # ArrayModifier.use_object_offset, MirrorModifier.use_clip) — the vocabulary scan found them in- # the blender cookbook until D107 deleted it; they are Blender's- "remove_doubles", "screw_offset", "bevel_object", "use_object_offset", "use_clip",- # illustrative names inside a bundle's own worked example- "left_wheel", "right_wheel",- # batteries whose results are cited as evidence but whose output dir is gitignored- "graphics_v1_flash", "graphics_v2_flash", "scenes_v1_flash",-}---def _prose(text: str) -> str:- """The body with fenced code removed — a define inside a shader is not our vocabulary."""- return _FENCE.sub("", text)---_DEF_RE = re.compile(r"^\s*(?:def|function)\s+([a-z_][a-z0-9_]*)\s*\(", re.M)---def _defined_callables() -> set[str]:- """Every function the harness itself defines in python source. Prompt markdown is not a- source: no language ships a library of helpers to call by name any more (D107), so a bundle- that tells the agent to call a function the harness does not define points at nothing."""- out: set[str] = set()- for p in (HARNESS / "codeverse3d").rglob("*.py"):- if "__pycache__" not in p.parts:- out |= set(_DEF_RE.findall(p.read_text(errors="ignore")))- return out---LIVE_CALLABLES = _defined_callables()---def test_every_bundle_document_only_cites_live_vocabulary():- """Validate all bundle prose in one corpus pass, with path-specific diagnostics."""- have = {d.name for d in BUNDLES} | set(ROUTED_SKILLS)- fences = {- d: "\n".join(_FENCE.findall("\n".join(p.read_text() for p in d.rglob("*.md"))))- for d in BUNDLES- }- unverifiable: dict[str, list[str]] = {} # without eval/bench a battery id reads as stale- for doc in DOCS:- label = doc.relative_to(skills_dir())- raw = doc.read_text()- prose = _prose(raw)- named = {t.strip("`").split("(")[0].strip() for t in _INLINE_CODE.findall(prose)}- unknown = sorted(- {t for t in named if _HARNESS_SHAPED.match(t)} - LIVE_VOCABULARY - FOREIGN_CALLS- )- if unknown and not EVAL_BENCH.is_dir():- unverifiable[str(label)] = unknown- else:- assert not unknown, f"{label} quotes names absent from the harness: {unknown}"-- called = {- match.group(1)- for token in _INLINE_CODE.findall(prose)- if (match := re.match(r"^([a-z][a-z0-9_]*)\(", token.strip()))- }- bundle = next(d for d in BUNDLES if d == doc.parent or d in doc.parents)- unknown = sorted(- name- for name in called- if name not in LIVE_TOOLS- and name not in FOREIGN_CALLS- and name not in LIVE_CALLABLES- and f"{name}(" not in fences[bundle]- )- assert not unknown, f"{label} instructs calling unknown functions: {unknown}"-- unknown = sorted(set(_GATE_SLUG.findall(prose)) - LIVE_KINDS)- assert not unknown, f"{label} names undefined gate kinds: {unknown}"-- unknown = sorted(set(_CONST.findall(prose)) - LIVE_CONSTANTS - FOREIGN.keys())- assert not unknown, f"{label} names unknown constants: {unknown}"-- siblings = set(re.findall(r"\bc3d-[a-z0-9-]+\b", raw))- assert siblings <= have, f"{label} points at missing skills: {sorted(siblings - have)}"- if unverifiable:- pytest.skip(f"no eval/bench beside the harness to tell battery ids from stale names: {unverifiable}")---def test_no_bundle_points_at_a_cookbook():- """No language ships a cookbook (D106 for the scene track, D107 for the rest, owner 2026-10-15):- a bundle that still sends the agent to a cookbook chapter — or to ``.3dcode/cookbook.md`` —- points at nothing. Every bundle, every reference."""- for s in SKILLS:- for doc in [s.dir / "SKILL.md", *sorted(s.dir.rglob("references/*.md"))]:- hit = re.search(r"[^\n]{0,60}\bcookbook\b[^\n]{0,60}", doc.read_text(), re.I)- assert not hit, f"{doc.relative_to(skills_dir())} still mentions a cookbook: {hit.group(0)!r}"---def test_every_live_constant_named_by_a_skill_has_a_claim():- from codeverse3d.addons.skill_targets import load_claims-- for s in SKILLS:- pinned = {- str(row["python"]).rsplit(":", 1)[-1]- for row in load_claims(s.name)- if row.get("python")- }- named = set(_CONST.findall(_prose(s.body))) & LIVE_CONSTANTS- unpinned = sorted(named - pinned)- assert not unpinned, f"{s.name} names live constants without claims: {unpinned}"diff --git a/harness/tests/skills/test_hook.py b/harness/tests/skills/test_hook.pyindex 631adf30..86abcf83 100644--- a/harness/tests/skills/test_hook.py+++ b/harness/tests/skills/test_hook.py@@ -16,7 +16,6 @@ class Events(list):def emit(self, name, **kw):self.append((name, kw))-@pytest.fixturedef ctx(tmp_path: Path, library_dir: Path, monkeypatch):root = tmp_path / "ws"@@ -31,7 +30,6 @@ def ctx(tmp_path: Path, library_dir: Path, monkeypatch):single_shot=False, extra={}, events=Events(), prompt_hashes=hashes,record_prompt=lambda name, text: hashes.__setitem__(name, str(len(text))))-def test_the_switch_off_means_no_files_no_events_no_record(ctx, monkeypatch):monkeypatch.setenv("C3D_SKILLS", "0") # ON is the default since 2026-09-22; off must be saidassert H.attach_for_round(ctx, index=0, kind="baseline") is None@@ -40,7 +38,6 @@ def test_the_switch_off_means_no_files_no_events_no_record(ctx, monkeypatch):assert H.record_usage(ctx, index=0, kind="baseline") is Noneassert H.repair_pointers(ctx, BuildResult(ok=True, language="blender"), GateReport(gate="lint:blender", passed=True)) == ""-def test_no_skill_failure_costs_the_round(ctx, monkeypatch):monkeypatch.setenv("C3D_SKILLS", "on")assert H.attach_for_round(ctx, index=0, kind="baseline")@@ -60,12 +57,10 @@ def test_no_skill_failure_costs_the_round(ctx, monkeypatch):got = H.attach_for_round(ctx, index=2, kind="refine")assert got is not None and got.listed == []-def _report(gate: str, kind: str) -> GateReport:return GateReport(gate=gate, passed=False, findings=[GateFinding(gate=gate, severity=Severity.ERROR, message="m",data={"kind": kind})])-@pytest.mark.parametrize(("track", "language", "lint", "build_gates", "sheet"), [# the lint is found after the round attached its set: R9 points at the sheet("static_object", "blender", _report("lint:blender", "part_not_imported"), [], "c3d-blender-forms"),diff --git a/harness/tests/skills/test_library.py b/harness/tests/skills/test_library.pyindex e6d81b5b..8b62fcef 100644--- a/harness/tests/skills/test_library.py+++ b/harness/tests/skills/test_library.py@@ -2,45 +2,20 @@from __future__ import annotations-import datetime as dtimport json-import re-from collections import defaultdictimport pytestfrom codeverse3d.addons.skill_targets import (check_claims,check_prompt_claims,- claim_bases,- load_claims,)from codeverse3d.skills import bundle_dirs, iter_skills, skills_dir, validate_bundle-from codeverse3d.skills.registry import ROUTESBUNDLES = bundle_dirs()SKILLS = list(iter_skills()) if BUNDLES else []pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet (the Author phase writes them)")-#: the owner's rule (D107, 2026-10-15): a skill's practice may show the API names in use, never a-#: recipe to paste — no fence over ~12 lines, in SKILL.md or in a reference-MAX_FENCE_LINES = 12-#: law 2 of the contract: `conventions.py` is the only place a frame/unit rule is stated.-#: A skill that restates one gives the agent two truths to choose between.-CONTRACT_RESTATEMENTS = (- r"\bZ is UP\b", r"\bY is UP\b", r"-Y is the FRONT", r"\+Z is the FRONT",- r"units are meters", r"\bY-up\b.*\bframe\b",-)-MEASURED_PERCENTAGE = re.compile(- r"\d{1,3}(?:\.\d)?\s?%[^.\n]{0,40}\b(?:of runs|runs|corpus|battery|of the corpus)\b"- r"|\b(?:runs|corpus|battery|fired|deviates)\b[^.\n]{0,40}\d{1,3}(?:\.\d)?\s?%"-)-PROVENANCE = re.compile(- r"bench/out|battery|batteries|\bn\s?=\s?\d+|20\d\d-\d\d-\d\d|\bof\s+\d+\s+runs\b"- r"|\b\d+\s+(?:graded|run|runs|records?)\b"-)--def test_every_bundle_is_valid_and_its_claims_are_current():"""One corpus pass keeps structure, brevity, evidence and pinned values honest."""for bundle in BUNDLES:@@ -48,45 +23,17 @@ def test_every_bundle_is_valid_and_its_claims_are_current():assert not errors, f"{bundle.name}: {errors}"for skill in SKILLS:- for doc, text in [("SKILL.md", skill.body), *((str(p.relative_to(skill.dir)), p.read_text())- for p in sorted(skill.dir.rglob("references/*.md")))]:- for fence in re.findall(r"^```.*?^```", text, re.S | re.M):- lines = len(fence.splitlines()) - 2- assert lines <= MAX_FENCE_LINES, (- f"{skill.name}/{doc}: a {lines}-line code fence is a recipe, not a practice (D107)"- )- for pattern in CONTRACT_RESTATEMENTS:- assert not re.search(pattern, skill.body, re.I), (- f"{skill.name}: {pattern!r} belongs in conventions.py only"- )errors = check_claims(skill)assert not errors, f"{skill.name}: {errors}"- if skill.evidence != "measured":- assert skill.metadata.get("evidence_note"), (- f"{skill.name}: non-measured evidence needs a note"- )- verified = dt.date.fromisoformat(str(skill.metadata.get("verified", "")))- assert verified <= dt.date.today(), f"{skill.name}: verified {verified} is in the future"- for match in MEASURED_PERCENTAGE.finditer(skill.body):- window = skill.body[max(0, match.start() - 300): match.end() + 300]- assert PROVENANCE.search(window), (- f"{skill.name} gives {match.group(0)!r} without nearby provenance"- )assert not check_prompt_claims(), check_prompt_claims() # prompts/_claims.toml, the same check-_JS = "export const SPAN_M = 40;\n"-@pytest.mark.parametrize("row,doc,js", [({"text": "0.5 m", "python": "codeverse3d.spatial.frame_metrics:NEAR_HIT_M", "format": "{:.1f} m"},"stay 10.5 m back", _JS), # inside a longer number- ({"text": "0.5 m", "python": "codeverse3d.spatial.frame_metrics:NEAR_HIT_M", "format": "{:.1f} m",- "context": "near-hit"}, "near-hit: see below\nkeep 0.5 m", _JS), # not on the line that says what it is({"text": "40 m", "js": "{js}:SPAN_M", "format": "{:.0f} m"}, "over 40 m", _JS.replace("40", "45")), # JS moved- ({"text": "0, 1, 2.5, 4", "python": "codeverse3d.languages._gl_common:JUDGE_TIMES", "sep": ", "},- "t = 0, 1, 2.5, 4, 6 s", _JS), # a sequence renders whole-], ids=["token", "context", "js", "sequence"])+], ids=["token", "js"])def test_a_claim_fails_when_its_text_or_its_constant_moves(tmp_path, row, doc, js):"""N48: prompts/**, a bundle's references/ and JS constants are pinned like a SKILL body — and ashort number only counts where it stands as its own token, on the line its ``context`` names."""@@ -98,49 +45,3 @@ def test_a_claim_fails_when_its_text_or_its_constant_moves(tmp_path, row, doc, j(tmp_path / "_claims.toml").write_text("[[claim]]\n" + "".join(f"{k} = {json.dumps(v)}\n" for k, v in cells.items()))assert check_prompt_claims(tmp_path), row--def test_no_two_skills_anywhere_point_one_claim_key_at_different_numbers():- """Compare pre-scale values so equivalent units do not look contradictory."""- by_key: dict[str, dict[str, tuple[str, object]]] = defaultdict(dict)- for s in SKILLS:- for key, base in claim_bases(s.name).items():- by_key[key][s.name] = base- for key, owners in sorted(by_key.items()):- targets = {t for t, _ in owners.values()}- values = {repr(v) for _, v in owners.values()}- assert len(targets) == 1, f"{key} is pinned to {sorted(targets)} by {sorted(owners)}"- assert len(values) == 1, f"{key} resolves to {sorted(values)} across {sorted(owners)}"---def test_co_routing_skills_render_a_shared_number_the_same_way():- """A weaker but still useful rule for skills that can land in ONE session together:- if they chose the same units for a shared key, the sentence must read the same."""- rows = {s.name: {r["key"]: r for r in load_claims(s.name) if r.get("key")} for s in SKILLS}- for a in sorted(rows):- for b in sorted(rows):- if a >= b or not _can_co_route(a, b):- continue- for key in sorted(set(rows[a]) & set(rows[b])):- ra, rb = rows[a][key], rows[b][key]- if any(ra.get(k) != rb.get(k) for k in ("scale", "format", "sep", "last_sep")):- continue- assert ra.get("text") == rb.get("text"), f"{a} and {b} disagree about {key}"---def _can_co_route(a: str, b: str) -> bool:- """Two skills can co-route when some (track, language) can name both."""- def reach(name: str) -> set[tuple[str, str]]:- return {- (track, language)- for route in ROUTES- if route.skill == name- for track in route.tracks or ("*",)- for language in route.languages or ("*",)- }-- ra, rb = reach(a), reach(b)- return any(- (t1 == t2 or "*" in (t1, t2)) and (l1 == l2 or "*" in (l1, l2))- for t1, l1 in ra- for t2, l2 in rb- )diff --git a/harness/tests/skills/test_live_discovery.py b/harness/tests/skills/test_live_discovery.pydeleted file mode 100644index 48ba23bc..00000000--- a/harness/tests/skills/test_live_discovery.py+++ /dev/null@@ -1,75 +0,0 @@-"""T7 — the smoke test that a CLI upgrade cannot pass by accident (`pytest -m live`).--Everything else in this package proves we WROTE the bundles correctly. Only a real CLI-can prove it FINDS them, and that is the failure mode with no symptom: a moved discovery-root ships an empty index, the run still passes, and the read rate reads 0% as if the-model had ignored the skill. The design's discovery table was read out of the shipped-binaries; this test is what keeps it true after the next `npm -g update`.--The assertion is the read probe itself, so one test covers both halves: if the CLI found-and opened the bundle, ``atime > mtime`` on its ``references/`` file.-"""--from __future__ import annotations--from pathlib import Path--import pytest--from codeverse3d.agents.registry import get_coding_agent-from codeverse3d.contracts.agent import AgentJob-from codeverse3d.skills.materialize import materialize_skills-from codeverse3d.skills.telemetry import probe_reads-from tests.skills.conftest import write_bundle--pytestmark = pytest.mark.live--PROMPT = ("Your workspace has a skill installed whose description matches this task. "- "Activate it, read the whole skill INCLUDING every file under its references/ "- "directory, then reply with the single magic word the reference file contains. "- "Do not write any file.")-MAGIC = "ORTHOGONAL-KUMQUAT"-#: the model each CLI is driven with here. ``codex`` must name a model the local login-#: is entitled to — a 400 "not supported when using Codex with a ChatGPT account" is an-#: auth problem, not a discovery problem, and would read as a discovery failure.-BACKENDS = [("codex", "gpt-6-luna"), ("claude-code", "claude-opus-5-5"), ("agy", "gemini-4-argon")]--[email protected]("kind, model", BACKENDS, ids=[k for k, _ in BACKENDS])-def test_the_cli_discovers_and_opens_a_materialised_skill(tmp_path: Path, kind: str, model: str):- # the binary is NOT named after the agent kind (`gemini-cli` runs `gemini`,- # `claude-code` runs `claude`), so ask the adapter, which owns that mapping- agent = get_coding_agent(f"{kind}:{model}")- ok, why = agent.available()- if not ok:- pytest.skip(f"{kind} unavailable: {why}")- ws = tmp_path / "ws"- (ws / "src").mkdir(parents=True)- for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):- (ws / name).write_text("# 3dcode workspace\n\nRead this file before acting.\n")-- lib = tmp_path / "library"- write_bundle(lib, "c3d-live-probe",- description="Answer the magic-word question. Use when a task asks for the magic word.",- body="Read `references/magic.md` and reply with the word it contains.",- references={"magic.md": f"The magic word is {MAGIC}.\n"})- from codeverse3d.skills import load_skill- from codeverse3d.skills.materialize import write_index- from codeverse3d.skills.prompting import index_block-- skill = load_skill("c3d-live-probe", lib)- materialize_skills(ws, [skill])- write_index(ws, index_block([skill]))-- res = agent.run(AgentJob(workspace=str(ws), prompt=PROMPT, spatial_tools=False,- max_turns=8, timeout_s=300, label="skills_live"))-- from codeverse3d.skills.model import Selection, SkillsMaterialized-- got = SkillsMaterialized(- listed=[skill.name],- selections=[Selection(skill=skill, priority=99, rules=("live",), reason="live smoke")])- usage = probe_reads(ws, got)- assert usage.surfaced == [skill.name], f"{kind} never opened SKILL.md — discovery root drift? ({res.exit_reason})"- assert usage.deep == [skill.name], f"{kind} opened SKILL.md but not references/ ({res.text[:300]})"- assert MAGIC in (res.text or ""), f"{kind} read the skill but did not follow it: {res.text[:300]}"diff --git a/harness/tests/skills/test_loader.py b/harness/tests/skills/test_loader.pyindex dd90a2fd..a4e21313 100644--- a/harness/tests/skills/test_loader.py+++ b/harness/tests/skills/test_loader.py@@ -6,7 +6,7 @@ from pathlib import Pathimport pytest-from codeverse3d.skills import iter_skills, load_skill+from codeverse3d.skills import iter_skillsfrom codeverse3d.skills.model import (BODY_MAX_LINES,SkillError,@@ -36,7 +36,6 @@ def test_malformed_frontmatter_is_rejected_with_a_reason(tmp_path: Path, text: swith pytest.raises(SkillError, match=expect):parse_skill(d)-def test_validate_reports_budget_evidence_layout_symlinks_and_the_verified_date(tmp_path: Path):d = write_bundle(tmp_path, "c3d-big", evidence="guesswork", body="x\n" * (BODY_MAX_LINES + 5))(d / "references" / "deeper").mkdir()@@ -50,7 +49,6 @@ def test_validate_reports_budget_evidence_layout_symlinks_and_the_verified_date((d / "SKILL.md").write_text("---\nname: c3d-demo\ndescription: d\nmetadata:\n evidence: measured\n---\nbody\n")assert any("verified" in i for i in validate_bundle(d))-def test_a_broken_bundle_is_skipped_not_fatal_but_strict_raises(tmp_path: Path, caplog):write_bundle(tmp_path, "c3d-good")bad = tmp_path / "c3d-bad"@@ -62,9 +60,3 @@ def test_a_broken_bundle_is_skipped_not_fatal_but_strict_raises(tmp_path: Path,with pytest.raises(SkillError):list(iter_skills(tmp_path, strict=True))--def test_load_skill_by_name(tmp_path: Path):- write_bundle(tmp_path, "c3d-demo")- assert load_skill("c3d-demo", tmp_path).name == "c3d-demo"- with pytest.raises(SkillError, match="no skill"):- load_skill("c3d-missing", tmp_path)diff --git a/harness/tests/skills/test_materialize_prompting.py b/harness/tests/skills/test_materialize_prompting.pyindex 5dac2f6d..06e1d33b 100644--- a/harness/tests/skills/test_materialize_prompting.py+++ b/harness/tests/skills/test_materialize_prompting.py@@ -9,17 +9,12 @@ import pytestfrom codeverse3d.skills.materialize import (BODY_FILES,- MARK_BEGIN,- MARK_END,SKILL_ROOTS,attach_skills,materialize_skills,- write_index,)from codeverse3d.skills.prompting import (- MANDATE,index_block,- index_tokens,inline_body,repair_pointers,)@@ -34,7 +29,6 @@ def ws(tmp_path: Path) -> Path:(root / name).write_text("# 3dcode workspace\n\n## Hard rules\n\n1. …\n")return root-# --------------------------------------------------------------------------- filesdef test_bundles_and_the_read_control_land_in_both_roots_and_an_empty_route_sweeps_them(ws, library):"""codex refuses symlinks; the never-routed control falsifies the read probe (git diff opens files too)."""@@ -60,15 +54,7 @@ def test_bundles_and_the_read_control_land_in_both_roots_and_an_empty_route_sweefor root in SKILL_ROOTS:assert not (ws / root / "c3d-part-contact").exists(), f"stale bundle survived in {root}"-# --------------------------------------------------------------------------- prompt text-def test_native_loader_backends_get_one_sentence_and_no_second_index(library):- skills = [library["c3d-part-contact"], library["c3d-bbox-contract"]]- text = index_block(skills)- assert MANDATE in text- assert "c3d-part-contact" not in text, "the native loaders would double-index it"- assert index_tokens(skills) < 60-def test_repair_pointers_and_the_inlined_body_come_from_the_gate_fired_skill(library):sel = select("static_object", "blender", "repair", signals={"multi_part": True},@@ -82,16 +68,4 @@ def test_repair_pointers_and_the_inlined_body_come_from_the_gate_fired_skill(libassert name == "c3d-part-contact" and "c3d-part-contact" in textassert inline_body(sel, max_tokens=0) == ("", "")-# --------------------------------------------------------------------------- the section-def test_the_index_is_written_into_every_body_file_and_is_replaceable(ws, library):- write_index(ws, "## Skills\n\nc3d-part-contact")- for name in BODY_FILES:- body = (ws / name).read_text()- assert MARK_BEGIN in body and MARK_END in body and "c3d-part-contact" in body- assert body.startswith("# 3dcode workspace")- write_index(ws, "## Skills\n\nc3d-bbox-contract")- body = (ws / "AGENTS.md").read_text()- assert body.count(MARK_BEGIN) == 1 and "c3d-part-contact" not in body and "c3d-bbox-contract" in body- write_index(ws, "")- assert MARK_BEGIN not in (ws / "AGENTS.md").read_text()diff --git a/harness/tests/skills/test_only_switch.py b/harness/tests/skills/test_only_switch.pydeleted file mode 100644index 6cab037a..00000000--- a/harness/tests/skills/test_only_switch.py+++ /dev/null@@ -1,42 +0,0 @@-"""``C3D_SKILLS_ONLY``: route exactly one bundle, so an effect A/B can attribute its delta."""--from __future__ import annotations--import pytest--from codeverse3d.config import get_settings-from codeverse3d.skills.materialize import attach_skills---class _Part:- def __init__(self, instances=1, symmetry="none"):- self.instances, self.symmetry, self.children = instances, symmetry, None---class _Plan:- parts = (_Part(instances=4), _Part(symmetry="mirror_x"))- joints = effects = passes = ()- summary = style_notes = ""---def ws(tmp_path):- (tmp_path / "AGENTS.md").write_text("# agents\n")- return tmp_path---def _listed(ws, **kw):- return attach_skills(ws, track="static_object", language="blender", kind="baseline",- plan=_Plan(), **kw).listed---def test_only_restricts_the_library_and_reaches_the_router(ws, monkeypatch):- """It restricts the library, not the selection: a max of 1 over the full routing picks another bundle."""- assert _listed(ws, max_skills=1)[0] != "c3d-bbox-contract"- assert _listed(ws, only=frozenset({"c3d-bbox-contract"}), max_skills=1) == ["c3d-bbox-contract"]- # a typo makes the variant visibly identical to its control, never the full set- assert _listed(ws, only=frozenset({"c3d-typo"})) == []- # ``only=`` omitted, attach_skills reads ``C3D_SKILLS_ONLY`` (a comma list, blanks ignored)- monkeypatch.setenv("C3D_SKILLS_ONLY", " c3d-bbox-contract , ")- get_settings.cache_clear()- assert _listed(ws) == ["c3d-bbox-contract"], "attach_skills must consult the switch when only= is omitted"diff --git a/harness/tests/skills/test_packaging.py b/harness/tests/skills/test_packaging.pydeleted file mode 100644index 3879a26a..00000000--- a/harness/tests/skills/test_packaging.py+++ /dev/null@@ -1,60 +0,0 @@-"""A wheel that ships no SKILL.md routes nothing, silently — as the starter tree once went missing."""--from __future__ import annotations--import shutil-import subprocess-import sys-import zipfile-from pathlib import Path--import pytest--HARNESS = Path(__file__).resolve().parents[2]-PROBE = "c3d-packaging-probe"---def test_a_built_wheel_actually_contains_the_bundles(tmp_path: Path):- """Builds a real wheel. A probe bundle is added when the library is still empty, so- the guarantee is proven now rather than the first time a bundle lands."""- probe = HARNESS / "codeverse3d" / "skills" / PROBE- existing = [p.name for p in (HARNESS / "codeverse3d" / "skills").iterdir()- if p.is_dir() and (p / "SKILL.md").is_file()]- made_probe = False- try:- if not existing:- (probe / "references").mkdir(parents=True)- (probe / "SKILL.md").write_text(f"---\nname: {PROBE}\ndescription: probe\n---\nbody\n")- (probe / "references" / "depth.md").write_text("depth\n")- made_probe = True- out = tmp_path / "wheel"- r = subprocess.run([sys.executable, "-c",- f"from setuptools import build_meta as b; print(b.build_wheel({str(out)!r}))"],- cwd=HARNESS, capture_output=True, text=True, check=False)- assert r.returncode == 0, r.stdout + r.stderr- whl = next(out.glob("*.whl"))- names = set(zipfile.ZipFile(whl).namelist())- want = [PROBE] if made_probe else sorted(existing)- for name in want:- assert f"codeverse3d/skills/{name}/SKILL.md" in names, (- f"{name} is in the source tree and NOT in the wheel: "- f"{sorted(n for n in names if 'skills' in n)[:20]}")- # references/ is optional (c3d-glsl-craft has none since D107: telemetry then reports its- # depth as unmeasurable), but every reference file the source tree has must ship — it is- # the depth probe- src_refs = (HARNESS / "codeverse3d" / "skills" / name / "references")- want_refs = ([f"codeverse3d/skills/{name}/references/{f.name}" for f in sorted(src_refs.glob("*.md"))]- if src_refs.is_dir() else [])- missing = [r for r in want_refs if r not in names]- assert not missing, f"{name}: references/ must ship too — it is the depth probe: {missing}"- if not made_probe:- # every claims file too: `3dcode skills validate` runs against an installed wheel- claims = sorted((HARNESS / "codeverse3d" / "skills" / "_claims").glob("*.toml"))- for c in claims:- assert f"codeverse3d/skills/_claims/{c.name}" in names, f"{c.name} missing from the wheel"- assert not any(n.endswith(".pyc") for n in names if "skills" in n)- finally:- if made_probe:- shutil.rmtree(probe, ignore_errors=True)- shutil.rmtree(HARNESS / "build", ignore_errors=True)diff --git a/harness/tests/skills/test_registry.py b/harness/tests/skills/test_registry.pyindex ce92fb3f..2e3447f8 100644--- a/harness/tests/skills/test_registry.py+++ b/harness/tests/skills/test_registry.py@@ -5,15 +5,13 @@ from __future__ import annotationsimport pytestfrom codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity-from codeverse3d.skills.registry import ROUTES, finding_kind, finding_kinds, select+from codeverse3d.skills.registry import ROUTES, finding_kind, selectE, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741-def _f(gate, sev, message="", **data):return GateFinding(gate=gate, severity=sev, message=message, data=data)-@pytest.mark.parametrize(("finding", "kind"), [# the gate's own kind, whatever the message says (N52: the regex read "interpenetrate")(_f("connectivity", W, "part 'X' contains 3 tiny disconnected island(s)", kind="penetration"),@@ -28,19 +26,9 @@ def _f(gate, sev, message="", **data):def test_a_finding_is_named_by_its_gate_and_typed_kind(finding, kind):assert finding_kind(finding) == kind--def test_finding_kinds_accepts_reports_and_findings_distinct_in_order():- a = _f("connectivity", E, kind="penetration")- b = _f("contract", W, kind="part_bbox")- assert finding_kinds([a, b]) == finding_kinds([GateReport(gate="x", passed=False, findings=[a, b])]) \- == finding_kinds([a, b, a]) == ["connectivity/penetration", "contract/part_bbox"]- assert finding_kinds([]) == [] and finding_kinds(None) == []--_LEG = "import bpy\n\n\ndef build_leg():\n bpy.ops.mesh.primitive_cube_add(size=1)\n obj = bpy.context.object\n obj.name = 'Leg'\n return obj\n"_JOIN = "bpy.ops.object.join()\n"-@pytest.mark.parametrize(("model", "r9"), [("import bpy\n", True), # parts/leg.py never imported("import bpy\nfrom parts.leg import build_leg\n\nbuild_leg()\n" + _JOIN, False), # a bpy trap is not R9's@@ -57,18 +45,6 @@ def test_r9_answers_a_part_file_never_imported_and_no_other_lint(tmp_ws, librarygot = select("static_object", "blender", "repair", findings=[lint], library=library)assert ("R9" in next(s for s in got if s.name == "c3d-blender-forms").rules) is r9--def test_r13_answers_a_joint_moving_against_the_plan_not_a_skipped_check(library):- from codeverse3d.tracks.articulated_object import MOTION_GATE, MOTION_SKIPPED, MOTION_WRONG-- def rules(kind):- rep = GateReport(gate=MOTION_GATE, passed=False, findings=[_f(MOTION_GATE, E, "m", kind=kind)])- got = select("articulated_object", "urdf_blender", "repair", findings=[rep], library=library)- return next(s for s in got if s.name == "c3d-urdf-joints").rules-- assert "R13" in rules(MOTION_WRONG) and "R13" not in rules(MOTION_SKIPPED)--def test_r19_answers_a_scene_with_nothing_moving(library):"""N52: R19 keyed on a gl_frames-only regex, so a scene's no_motion ERROR routed nothing."""nothing_moves = _f("scene_frames", E, "nothing moves: …", kind="no_motion")@@ -77,12 +53,10 @@ def test_r19_answers_a_scene_with_nothing_moving(library):motion = next(s for s in got if s.name == "c3d-scene-motion")assert "R19" in motion.rules and motion.gate_fired-# --------------------------------------------------------------------------- the table#: Retired ids remain reserved because run records refer to routing decisions by id.RETIRED_RULES = {"R5": "c3d-form-manifest, cut 2026-08-25 (read 2/19); docs/SKILLS_LEDGER.md"}-def test_rule_ids_are_unique_and_the_design_numbers_are_all_present():ids = [r.rule for r in ROUTES]assert len(ids) == len(set(ids))@@ -94,10 +68,3 @@ def test_rule_ids_are_unique_and_the_design_numbers_are_all_present():assert any(r.rule == f"R{n}" for r in ROUTES), f"R{n} is missing from the table"assert [r for r in ROUTES if r.rule.startswith("R24")], "R24 (the graphics gate row) is missing"--def test_gate_fired_rows_always_outrank_standing_rows():- """Law 2: a repair round must spend its budget on what actually broke."""- fired = [r for r in ROUTES if r.gate_fired]- standing = [r for r in ROUTES if not r.gate_fired]- assert min(r.priority for r in fired) > max(r.priority for r in standing)- assert all(r.priority >= 90 for r in fired)diff --git a/harness/tests/skills/test_router.py b/harness/tests/skills/test_router.pyindex c0efa469..1162d989 100644--- a/harness/tests/skills/test_router.py+++ b/harness/tests/skills/test_router.py@@ -4,23 +4,18 @@ from __future__ import annotationsfrom types import SimpleNamespace as NS-from codeverse3d.skills.model import EVIDENCE_INHERITEDfrom codeverse3d.skills.registry import QUIET_KINDS, plan_signals, select-from tests.skills.conftest import write_bundledef part(name="Leg", instances=1, symmetry="none", children=()):return NS(name=name, instances=instances, symmetry=symmetry, children=list(children))-def static_plan(n=3, **kw):return NS(parts=[part(f"P{i}", **kw) for i in range(n)], summary="a chair", style_notes="")-def skills_for(track, language, kind, *, plan=None, **kw):return [s.skill for s in select(track, language, kind, signals=plan_signals(plan), **kw)]-def test_a_repair_round_spends_its_budget_on_what_broke(library):got = select("static_object", "blender", "repair",signals=plan_signals(static_plan()),@@ -30,7 +25,6 @@ def test_a_repair_round_spends_its_budget_on_what_broke(library):assert all(s.gate_fired for s in got)assert "R2" in got[0].rules and "connectivity/penetration" in got[0].reason-def test_quiet_kinds_attach_nothing_unless_a_gate_fired(library):"""Law 4: quiet sessions get only kind-agnostic gate-fired rows (R15/R17/R19, not R2/R4)."""for kind in QUIET_KINDS:@@ -43,21 +37,3 @@ def test_quiet_kinds_attach_nothing_unless_a_gate_fired(library):assert select("static_object", "blender", kind, signals=plan_signals(static_plan()),findings=["connectivity/floating"], library=library) == []--def test_inherited_unverified_bundles_are_off_until_the_switch_says_otherwise(library_dir):- from codeverse3d.skills import all_skills-- write_bundle(library_dir, "c3d-cadquery-forms", evidence=EVIDENCE_INHERITED)- lib = all_skills(library_dir, strict=True)- off = skills_for("static_object", "cadquery", "baseline", plan=static_plan(), library=lib)- on = skills_for("static_object", "cadquery", "baseline", plan=static_plan(), library=lib, allow_unverified=True)- assert "c3d-cadquery-forms" not in [s.name for s in off]- assert "c3d-cadquery-forms" in [s.name for s in on]---def test_scene_gate_findings_route_the_matching_scene_skill(library):- for finding, want in (("scene_frames/dark_frame", "c3d-scene-lighting"),- ("scene_frames/camera_below_high_ground", "c3d-scene-composition"),- ("scene_frames/no_motion", "c3d-scene-motion")):- got = select("scene", "scene_threejs", "repair", findings=[finding], library=library, max_skills=1)- assert got and got[0].name == want, findingdiff --git a/harness/tests/skills/test_routing_property.py b/harness/tests/skills/test_routing_property.pydeleted file mode 100644index 28c16573..00000000--- a/harness/tests/skills/test_routing_property.py+++ /dev/null@@ -1,59 +0,0 @@-"""Routing invariants over the shipped library's complete input space."""--from __future__ import annotations--import pytest--from codeverse3d.skills import all_skills, bundle_dirs, select, skills_dir-from codeverse3d.skills.registry import ROUTES, plan_signals--pytestmark = pytest.mark.skipif(not bundle_dirs(), reason=f"no bundles in {skills_dir()} yet")--LIBRARY = all_skills()--TRACKS = ("static_object", "articulated_object", "scene", "graphics")-LANGUAGES = ("blender", "cadquery", "threejs", "urdf_blender", "scene_threejs",- "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-SIGNAL_KEYS = tuple(plan_signals(None))--LIVE_KINDS = sorted({k for row in ROUTES for k in row.findings if not k.endswith("*")} |- {"connectivity/penetration", "connectivity/floating", "connectivity/untyped",- "contract/part_bbox", "contract/orientation", "joint_sweep/penetration",- "connectivity/stray_islands", "scene_frames/camera_low", "scene_frames/hero_unseen",- "gl_frames/static", "shader_preflight/no_fog"})---BASE_INPUTS = [(t, lang, kind) for t in TRACKS for lang in LANGUAGES for kind in KINDS]---def test_every_signal_a_route_requires_is_in_the_input_space():- """R26/R27 test wants_water / wants_night, which SIGNAL_KEYS once lacked: a route that- requires a signal plan_signals() never sets is dead."""- for row in ROUTES:- assert set(row.requires_all) | set(row.requires_any) <= set(SIGNAL_KEYS), row.rule---def test_every_corpus_finding_kind_routes_sanely_from_every_session():- """A gate finding must never crash the router, never blow the cap, and never- silently outrank nothing — where a row answers it, it must come back at >= 90."""- for finding in LIVE_KINDS:- answered_somewhere = False- for track, language, kind in BASE_INPUTS:- got = select(track, language, kind, findings=[finding], library=LIBRARY, max_skills=5)- assert len(got) <= 5, f"{finding}: {track}/{language}/{kind}"- fired = [skill for skill in got if skill.gate_fired]- for skill in fired:- assert skill.priority >= 90, (- f"{skill.name} answered {finding} at priority {skill.priority}"- )- assert finding in skill.reason or any(- finding.startswith(pattern.rstrip("*"))- for route in ROUTES- if route.rule in skill.rules- for pattern in route.findings- ), f"{skill.name} cannot explain why it answered {finding}"- answered_somewhere = answered_somewhere or bool(fired)- assert answered_somewhere, f"{finding} is classified but no route answers it"diff --git a/harness/tests/skills/test_spec_compliance.py b/harness/tests/skills/test_spec_compliance.pydeleted file mode 100644index 67ff81c9..00000000--- a/harness/tests/skills/test_spec_compliance.py+++ /dev/null@@ -1,93 +0,0 @@-"""Validate raw bundles independently of our loader and, when installed, with skills-ref."""--from __future__ import annotations--import json-import re-import shutil-import subprocess-from pathlib import Path--import pytest-import yaml--from codeverse3d.skills import bundle_dirs, skills_dir--BUNDLES = bundle_dirs()-pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet")--DESCRIPTION_MAX = 1024-OPTIONAL_DIRS = {"scripts", "references", "assets"}--#: `skills-ref` on PyPI installs its CLI as `agentskills`; accept either spelling-REF_VALIDATOR = shutil.which("agentskills") or shutil.which("skills-ref")---def _raw(d: Path) -> tuple[dict, str]:- text = (d / "SKILL.md").read_text(encoding="utf-8")- m = re.match(r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*\r?\n?", text, re.S)- assert m, f"{d.name}: SKILL.md must open with a '---' frontmatter block"- return yaml.safe_load(m.group(1)) or {}, text[m.end():]---def test_every_bundle_conforms_to_the_raw_spec():- for bundle in BUNDLES:- frontmatter, body = _raw(bundle)- description = frontmatter.get("description")- assert isinstance(description, str) and 1 <= len(description) <= DESCRIPTION_MAX, (- f"{bundle.name}: description must contain 1..{DESCRIPTION_MAX} characters"- )- assert re.search(r"\b(use|read|reach for)\b", description, re.I), (- f"{bundle.name}: description must say when the CLI should match it"- )-- for path in bundle.iterdir():- if path.is_file():- assert path.name == "SKILL.md", f"{bundle.name}: stray file {path.name}"- continue- assert path.name in OPTIONAL_DIRS, (- f"{bundle.name}: {path.name}/ is not one of {sorted(OPTIONAL_DIRS)}"- )- for child in path.rglob("*"):- assert child.is_file(), (- f"{bundle.name}: {child.relative_to(bundle)} is nested too deeply"- )-- for target in re.findall(r"\]\((?!https?:|#)([^)]+)\)", body):- relative = target.split("#", 1)[0].strip()- if not relative:- continue- assert not relative.startswith("/") and ".." not in Path(relative).parts, (- f"{bundle.name}: link {relative} escapes the bundle"- )- assert (bundle / relative).exists(), (- f"{bundle.name}: link {relative} does not exist"- )--[email protected](REF_VALIDATOR is None,- reason="the reference validator is not installed (pip install skills-ref)")-def test_reference_implementation_validates_and_agrees_with_our_loader():- from codeverse3d.skills.model import parse_skill-- for bundle in BUNDLES:- result = subprocess.run(- [REF_VALIDATOR, "validate", str(bundle)],- capture_output=True,- text=True,- check=False,- )- assert result.returncode == 0, f"{bundle.name}: {result.stdout}{result.stderr}"-- result = subprocess.run(- [REF_VALIDATOR, "read-properties", str(bundle)],- capture_output=True,- text=True,- check=False,- )- assert result.returncode == 0, f"{bundle.name}: {result.stdout}{result.stderr}"- theirs = json.loads(result.stdout)- ours = parse_skill(bundle)- assert theirs["name"] == ours.name, bundle.name- assert theirs["description"] == ours.description, bundle.name- assert dict(theirs.get("metadata") or {}) == dict(ours.metadata), bundle.namediff --git a/harness/tests/skills/test_targets.py b/harness/tests/skills/test_targets.pyindex 90183946..ffaffd5f 100644--- a/harness/tests/skills/test_targets.py+++ b/harness/tests/skills/test_targets.py@@ -2,22 +2,12 @@from __future__ import annotations-import re-from pathlib import Path-import pytest-import yamlfrom codeverse3d.addons.skill_targets import (BY_SKILL,- DIRECTIONS,- METRICS,- SOURCES,- SRC_GATE,TARGETS,Target,- gate_kinds_claimed,- target_for,)from codeverse3d.skills import bundle_dirs, skills_dirfrom codeverse3d.skills.registry import ROUTED_SKILLS@@ -25,21 +15,12 @@ from codeverse3d.skills.registry import ROUTED_SKILLSBUNDLES = bundle_dirs()pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet")-def _live_kinds() -> set[str]:from codeverse3d.skills import registryreturn {v for k, v in vars(registry).items()if k.isupper() and isinstance(v, str) and "/" in v}--def _frontmatter(d: Path) -> dict:- text = (d / "SKILL.md").read_text(encoding="utf-8")- m = re.match(r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*\r?\n", text, re.S)- assert m, f"{d.name}: no frontmatter"- return (yaml.safe_load(m.group(1)) or {}).get("metadata") or {}--# --------------------------------------------------------------------------- the tabledef test_target_table_exactly_covers_the_shipped_and_routed_bundles():"""No orphan rows, unmeasured routes, duplicate rows or bundles maintained by taste."""@@ -47,43 +28,9 @@ def test_target_table_exactly_covers_the_shipped_and_routed_bundles():assert len(BY_SKILL) == len(TARGETS), "a bundle has more than one target row"assert set(BY_SKILL) == have == set(ROUTED_SKILLS)--def test_every_gate_kind_a_target_counts_is_a_live_kind():- unknown = sorted(gate_kinds_claimed() - _live_kinds())- assert unknown == [], (- f"targets.py counts gate kind(s) registry.py no longer defines: {unknown} — the "- f"readout would report a silent zero")---def test_target_rows_and_bundle_metadata_are_complete():- for target in TARGETS:- assert target.direction in DIRECTIONS, target.skill- assert target.source in SOURCES, target.skill- assert target.unit and target.why, f"{target.skill}: target needs a unit and rationale"- if target.source == SRC_GATE:- assert target.kinds, f"{target.skill}: a gate target needs finding kinds"- if not target.measurable:- assert target.caveat, f"{target.skill}: an unmeasurable target needs a caveat"-- for bundle in BUNDLES:- metadata, target = _frontmatter(bundle), target_for(bundle.name)- assert target is not None, bundle.name- assert metadata.get("target_metric") == target.metric, bundle.name- assert metadata.get("target_direction") == target.direction, bundle.name- assert metadata.get("target_unit") == target.unit, bundle.name- assert metadata.get("target_measurable") == ("true" if target.measurable else "false"), (- bundle.name- )- baseline = str(metadata.get("target_baseline") or "").strip()- assert baseline, f"{bundle.name}: target_baseline is missing"- assert re.search(r"\bn\s*=\s*\d+", baseline), (- f"{bundle.name}: target_baseline must state n=<runs>"- )--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)+ assert len({t.metric for t in TARGETS}) == len(TARGETS)seen: dict[str, list[Target]] = {}for t in TARGETS:for k in t.kinds:@@ -94,7 +41,6 @@ def test_no_two_bundles_claim_the_same_quantity():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():"""The ledger has to be visible from the CLI, or it is a document nobody opens."""from typer.testing import CliRunnerdiff --git a/harness/tests/skills/test_telemetry.py b/harness/tests/skills/test_telemetry.pyindex 4e668c49..4bfc7013 100644--- a/harness/tests/skills/test_telemetry.py+++ b/harness/tests/skills/test_telemetry.py@@ -14,7 +14,6 @@ from codeverse3d.skills.telemetry import (TELEMETRY_DIR,probe_reads,)-from tests.skills.conftest import write_bundle@pytest.fixture@@ -24,25 +23,21 @@ def ws(tmp_path: Path) -> Path:(root / "AGENTS.md").write_text("# body\n")return root-def _plan(n=3):from types import SimpleNamespace as NSreturn NS(parts=[NS(name=f"P{i}", instances=1, symmetry="none", children=[]) for i in range(n)], summary="")-def _attach(ws, library, **kw):return attach_skills(ws, track="static_object", language="blender", kind="baseline",plan=_plan(), library=library,max_skills=5, allow_unverified=False, **kw)-def _touch_read(path: Path) -> None:"""Simulate a reader on a filesystem whose atime we cannot rely on in a test."""st = os.stat(path)os.utime(path, (st.st_mtime + 30, st.st_mtime))-def test_skill_md_is_surfaced_a_reference_is_deep_and_the_claude_copy_counts(ws, library):got = _attach(ws, library)a, b = got.listed[:2]@@ -53,54 +48,6 @@ def test_skill_md_is_surfaced_a_reference_is_deep_and_the_claude_copy_counts(ws,assert usage.body_tokens_read == next(r.body_tokens for r in usage.reads if r.name == a)assert usage.deep_read_rate == 1 / len(got.listed)--def test_a_bundle_with_no_references_says_depth_is_unmeasurable(tmp_path, ws):- from codeverse3d.skills import all_skills-- lib_dir = tmp_path / "lib"- write_bundle(lib_dir, "c3d-part-contact", references={})- got = _attach(ws, all_skills(lib_dir, strict=True))- read = probe_reads(ws, got).reads[0]- assert read.deep_measurable is False and read.deep is False----def test_git_diff_alone_trips_the_control(tmp_path, library): # noqa: PLR0915- """``Workspace.changed_files``' `git add -A -N` + `git diff` reads every untracked bundle file."""- import subprocess-- from codeverse3d.skills.materialize import materialize_skills-- ws = tmp_path / "ws"- (ws / "src").mkdir(parents=True)- subprocess.run(["git", "init", "-q"], cwd=ws, check=True)- subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q",- "--allow-empty", "-m", "init"], cwd=ws, check=True)- for f in materialize_skills(ws, [library["c3d-part-contact"]]):- # back-date by more than ATIME_EPSILON_S: a real session lasts minutes, and the- # probe deliberately ignores an access within a second of the write- st = os.stat(f)- os.utime(f, (st.st_mtime - 10, st.st_mtime - 10))-- before = probe_reads(ws, _materialized(library, "c3d-part-contact"))- assert not before.control_read, "materialisation alone must leave the control unread"-- subprocess.run(["git", "add", "-A", "-N"], cwd=ws, check=True)- subprocess.run(["git", "diff", "--numstat", "HEAD"], cwd=ws, check=True, capture_output=True)-- after = probe_reads(ws, _materialized(library, "c3d-part-contact"))- assert after.control_read, "git read every untracked file; the control must have caught it"- assert after.deep_read_rate is None---def _materialized(library, *names):- from codeverse3d.skills.model import Selection, SkillsMaterialized-- sels = [Selection(skill=library[n], priority=50, rules=("R1",), reason="test") for n in names]- return SkillsMaterialized(listed=list(names), selections=sels)---# ===================================================================== transcript evidence# Since 2026-09-22 every CLI backend folds its session's tool calls into# trajectories/<label>/transcript.jsonl (agents/cli_common.record_tool_calls), and the probe@@ -117,14 +64,6 @@ def _session(ws: Path, label: str, calls: list[dict], *, t: float, traced: boolwith (d / "transcript.jsonl").open("a") as fh:fh.writelines(json.dumps(r) + "\n" for r in rows)--def _git_read_everything(ws: Path) -> None:- """What `git add -A -N` + `git diff` does to the atime of every bundle file."""- for f in ws.rglob("*.md"):- if "/skills/" in str(f):- _touch_read(f)--def test_the_cli_transcript_is_the_evidence_when_every_session_left_one(ws, library):import time@@ -135,14 +74,15 @@ def test_the_cli_transcript_is_the_evidence_when_every_session_left_one(ws, libr{"tool": "command_execution", "args": {"command": f"sed -n '1,280p' .agents/skills/{b}/SKILL.md"}},{"tool": "view_file", "args": {"AbsolutePath": f"{ws}/.agents/skills/{b}/references/worked_example.md"}},], t=time.time() + 1)- _git_read_everything(ws) # the atime probe would now call every bundle, and the control, read+ for f in ws.rglob("*.md"): # git reading every bundle file must not fool the transcript evidence+ if "/skills/" in str(f):+ _touch_read(f)usage = probe_reads(ws, got)assert usage.evidence == "transcript"assert usage.surfaced == [a, b] and usage.deep == [b]assert not usage.control_readassert usage.deep_read_rate == 1 / len(got.listed)-def test_a_shell_read_the_trace_cannot_parse_counts_while_the_control_is_untouched(ws, library):"""claude-code 2.1.317 (live, 2026-11-03) read the references with `cd <bundle> && for f in$(find references -type f); do cat "$f"; done`: no path to match, but the file's atime moved."""@@ -167,7 +107,6 @@ def test_a_shell_read_the_trace_cannot_parse_counts_while_the_control_is_untouchusage = probe_reads(ws, got)assert usage.deep == [] and usage.surfaced == [a] and not usage.control_read-def test_only_traced_sessions_after_the_attach_are_credited(ws, library):import time@@ -184,34 +123,6 @@ def test_only_traced_sessions_after_the_attach_are_credited(ws, library):usage = probe_reads(ws, got)assert usage.evidence == "atime" and usage.surfaced == []--def test_a_call_the_cli_marked_failed_read_nothing(ws, library):- """codex 0.155.1, 2026-09-22: its first `sed` expanded the skill-root alias wrongly and exited 2."""- import time-- got = _attach(ws, library)- name = got.listed[0]- _session(ws, "baseline", [{"tool": "command_execution", "failed": True,- "args": {"command": f"sed -n 1,240p /home/u/.codex/skills/.system/{name}/SKILL.md"}}],- t=time.time() + 1)- assert probe_reads(ws, got).surfaced == []---def test_the_path_match_is_exact_about_names_and_about_reading():- from codeverse3d.skills.telemetry import _called-- def called(*args: dict) -> tuple[bool, bool]:- return _called("c3d-scene", [{"args": a} for a in args])-- assert called({"file_path": "/ws/.claude/skills/c3d-scene/SKILL.md"}) == (True, False)- assert called({"command": "cat r1/c3d-scene/SKILL.md"}) == (True, False) # codex's root alias- assert called({"AbsolutePath": "/ws/.agents/skills/c3d-scene/references/a.md"}) == (True, True)- assert called({"DirectoryPath": "/ws/.agents/skills/c3d-scene/references"}) == (False, False) # a listing- assert called({"file_path": ".agents/skills/c3d-scene-water/SKILL.md"}) == (False, False) # a longer name- assert called({"file_path": ".agents/skills/xc3d-scene/SKILL.md"}) == (False, False)- assert called({"pattern": "src/**"}) == (False, False)--def test_the_report_counts_exact_sessions_and_drops_only_blind_ones(tmp_path):from typer.testing import CliRunnerdiff --git a/harness/tests/skills/test_variants.py b/harness/tests/skills/test_variants.pyindex e749c53f..4973b4fa 100644--- a/harness/tests/skills/test_variants.py+++ b/harness/tests/skills/test_variants.py@@ -13,8 +13,6 @@ from codeverse3d.config import get_settingsfrom codeverse3d.prompts import variants as Vfrom codeverse3d.prompts.variants import activatefrom codeverse3d.skills import (- RouteBoost,- VariantRoutes,all_skills,bundle_dirs,library_roots,@@ -27,7 +25,6 @@ from codeverse3d.skills.registry import (GATE_FIRED_PRIORITY,ROUTED_SKILLS,ROUTES,- Route,effective_priority,select,)@@ -50,11 +47,9 @@ 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="")-@pytest.fixturedef variant(tmp_path: Path, monkeypatch) -> Path:"""A tmp library (every routed bundle, measured) with the overlay ``variants/tv/``: a shadowing@@ -84,7 +79,6 @@ def variant(tmp_path: Path, monkeypatch) -> Path:yield libget_settings.cache_clear()-# --------------------------------------------------------------------------- the overlay librarydef test_an_overlay_bundle_shadows_the_base_and_a_new_name_is_added(variant):assert library_roots() == [variant]@@ -103,19 +97,6 @@ def test_an_overlay_bundle_shadows_the_base_and_a_new_name_is_added(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 routerdef 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@@ -143,66 +124,19 @@ def test_boosts_move_the_ranking_but_never_cross_the_gate_fired_floor(library, cboosts={"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-@pytest.mark.parametrize("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):@@ -211,11 +145,9 @@ def test_routes_toml_typing_errors_are_refused(variant, text, problem):with pytest.raises(ValueError, match=problem):variants_table("tv")-# --------------------------------------------------------------------------- the CLIs walk the overlaysBROKEN_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 perline: an xdist worker runs under ``COLUMNS=80``, which rich pins on the console when it is built, so@@ -230,7 +162,6 @@ def _cli(*args: str, width: int = 300):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 thevariant is active — so ``skills validate`` must see them, labelled by their variant, and a malformed@@ -261,19 +192,6 @@ def test_skills_validate_walks_every_shipped_overlay_and_a_broken_overlay_bundleassert r.exit_code == 0 and "tv/routes.toml" in r.output and "V1 -> c3d-nowhere" in r.outputassert _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@pytest.fixturedef ws(tmp_path: Path) -> Path:@@ -282,7 +200,6 @@ def ws(tmp_path: Path) -> Path:(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@@ -301,25 +218,10 @@ def test_attach_skills_routes_through_the_variant_table_and_stamps_the_variant(vassert "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_lenientfrom codeverse3d.tracks import skills_hook as Hdiff --git a/harness/tests/spatial_tools/test_complexity.py b/harness/tests/spatial_tools/test_complexity.pyindex d0f389d2..5cfba6eb 100644--- a/harness/tests/spatial_tools/test_complexity.py+++ b/harness/tests/spatial_tools/test_complexity.py@@ -6,20 +6,17 @@ from __future__ import annotationsfrom pathlib import Pathimport pytest-import trimeshfrom codeverse3d.spatial.complexity import (COMPLEXITY_WEIGHTS,band_of,complexity_of_glb,- complexity_of_parts,)-from codeverse3d.spatial.measure import part_meshesdef test_vector_shape_and_weights(stool_glb: Path) -> None:vec = complexity_of_glb(stool_glb)- assert set(COMPLEXITY_WEIGHTS) == set(vec.components) == set(vec.axes)+ assert set(COMPLEXITY_WEIGHTS) == set(vec.components)assert sum(COMPLEXITY_WEIGHTS.values()) == pytest.approx(1.0)assert vec.part_count == 5 and vec.tri_count > 0assert 0.0 < vec.index < 1.0@@ -30,18 +27,3 @@ def test_vector_shape_and_weights(stool_glb: Path) -> None:)labels = [band_of(x) for x in (0.0, 0.3, 0.45, 0.6, 0.9, 1.0)]assert labels == ["trivial", "simple", "moderate", "complex", "intricate", "intricate"]---def test_degenerate_input_never_raises() -> None:- empty = complexity_of_parts({})- assert empty.index == 0.0 and empty.extra["error"] == "no geometry"- none_only = complexity_of_parts({"Ghost": None})- assert none_only.part_count == 0---def test_symmetry_groups_count_geometric_families(solid_stool_glb: Path) -> None:- parts = part_meshes(trimesh.load(str(solid_stool_glb), force="scene", process=False))- vec = complexity_of_parts(parts)- assert vec.symmetry_groups == 1 # the four legs are one family; the seat is alone- assert vec.extra["repeated_parts"] == 4-diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.pyindex 05cdbb42..3eb788cb 100644--- a/harness/tests/spatial_tools/test_connectivity.py+++ b/harness/tests/spatial_tools/test_connectivity.py@@ -12,99 +12,11 @@ from codeverse3d.spatial.connectivity import (PENETRATION_MIN_FRACTION,THROUGH_FAR_SIDE_RATIO,check_connectivity,- pair_distance,penetration_depth,)from tests.spatial_tools.conftest import FLOAT_GAP_M-def test_hints_use_the_authoring_frame(stool_glb: Path) -> None:- """The 5 mm gap is along GLB +y (up). A Blender/CadQuery/URDF agent codes in Z-up, so- the pasted hint must say +z (a literal '+y' would move the leg towards the back)."""- err = check_connectivity(stool_glb, language="blender").errors[0]- assert "translate 'Leg_3' by (+0.0000, +0.0000, +0.0050) m (blender frame: Z-up, -Y front)" in err.fix_hint- assert np.allclose(err.data["gap_vector_m"], (0.0, 0.0, FLOAT_GAP_M), atol=1e-4)- assert np.allclose(err.data["gap_vector_glb_m"], (0.0, FLOAT_GAP_M, 0.0), atol=1e-4)- assert err.data["frame"] == "z_up_neg_y_front"- err = check_connectivity(stool_glb, language="threejs").errors[0]- assert "(+0.0000, +0.0050, +0.0000) m (threejs frame: Y-up, +Z front)" in err.fix_hint- # nothing grounded: the ground hint names the language's up axis- s = trimesh.Scene()- for i, x in enumerate((0.0, 0.3)):- m = trimesh.creation.box((0.1, 0.1, 0.1))- m.apply_translation((x, 0.5, 0))- s.add_geometry(m, node_name=f"P{i}", geom_name=f"P{i}")- p = stool_glb.parent / "floating_pair.glb"- p.write_bytes(s.export(file_type="glb"))- ground = [f for f in check_connectivity(p, language="cadquery").findings if "touches the ground" in f.message]- assert ground and "(z=0)" in ground[0].message and "z=0, cadquery frame" in ground[0].fix_hint---def test_tiny_island_warns(tmp_path: Path) -> None:- body = trimesh.creation.box(extents=(0.3, 0.3, 0.3))- body.apply_translation((0, 0.15, 0))- crumb = trimesh.creation.box(extents=(0.004, 0.004, 0.004))- crumb.apply_translation((0.5, 0.5, 0.5))- part = trimesh.util.concatenate([body, crumb])- sc = trimesh.Scene()- sc.add_geometry(part, node_name="Body", geom_name="Body")- p = tmp_path / "crumb.glb"- sc.export(str(p))- r = check_connectivity(p)- warns = [f for f in r.findings if f.severity == Severity.WARN]- assert warns and "tiny disconnected island" in warns[0].message and warns[0].data["kind"] == "stray_islands"---def test_missing_glb_is_error(tmp_path: Path) -> None:- r = check_connectivity(tmp_path / "none.glb")- assert not r.passed and r.errors---def test_pair_distance_sampled_fallback(monkeypatch: pytest.MonkeyPatch) -> None:- import codeverse3d.spatial.joints_collide as collide-- monkeypatch.setattr(collide, "_fcl", None)- a = trimesh.creation.box(extents=(1, 1, 1))- b = trimesh.creation.box(extents=(1, 1, 1))- b.apply_translation((1.02, 0, 0))- pd = pair_distance("a", a, "b", b)- assert pd.distance == pytest.approx(0.02, abs=1e-6)- assert pd.gap_vector[0] == pytest.approx(0.02, abs=1e-6)---def _open_bottom_box(extents, translation) -> trimesh.Trimesh:- """A box with its bottom face dropped — an open shell, what agents actually export."""- m = trimesh.creation.box(extents=extents)- m.apply_translation(translation)- low = m.vertices[m.faces].mean(axis=1)[:, 1]- shell = trimesh.Trimesh(vertices=m.vertices, faces=m.faces[low > low.min() + 1e-9], process=False)- assert not shell.is_watertight- return shell---def test_interpenetration_is_found_between_two_non_watertight_parts(tmp_path: Path) -> None:- """Open shells (not watertight) are measured too — they once read as "no overlap"."""- base_ext, post_ext = (0.4, 0.2, 0.4), (0.2, 0.2, 0.2)- base_at, post_at = (0, 0.1, 0), (0, 0.25, 0) # post bottom 50 mm below the base's top face- closed = (trimesh.creation.box(extents=base_ext), trimesh.creation.box(extents=post_ext))- closed[0].apply_translation(base_at)- closed[1].apply_translation(post_at)- shells = (_open_bottom_box(base_ext, base_at), _open_bottom_box(post_ext, post_at))-- for tag, (a, b) in (("closed", closed), ("open shells", shells)):- depth, frac = penetration_depth(a, b)- assert depth == pytest.approx(0.05, abs=1e-3), f"{tag}: 50 mm of interpenetration must be measured"- assert frac > 0.05, tag-- scene = trimesh.Scene()- scene.add_geometry(shells[0], node_name="Base", geom_name="Base")- scene.add_geometry(shells[1], node_name="Post", geom_name="Post")- glb = tmp_path / "open_shells.glb"- scene.export(str(glb))- r = check_connectivity(glb)- assert not r.passed and any("interpenetrate" in f.message for f in r.errors)--def _stool_with_a_leg_short_at_the_top(path: Path, gap_m: float = FLOAT_GAP_M) -> Path:"""The stool, but Leg_3 is shortened by ``gap_m`` at the TOP only: on the floor, shy of the seat."""from tests.spatial_tools.conftest import LEG_XZ@@ -117,7 +29,7 @@ def _stool_with_a_leg_short_at_the_top(path: Path, gap_m: float = FLOAT_GAP_M) -h = 0.41 - gap_m if i == 3 else 0.41leg = trimesh.creation.cylinder(radius=0.02, height=h, sections=24)leg.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, (1, 0, 0)))- leg.apply_translation((x, h / 2, z)) # bottom stays on the ground+ leg.apply_translation((x, h / 2, z))sc.add_geometry(leg, node_name=f"Leg_{i}", geom_name=f"Leg_{i}")sc.export(str(path))return path@@ -125,10 +37,7 @@ def _stool_with_a_leg_short_at_the_top(path: Path, gap_m: float = FLOAT_GAP_M) -def test_a_part_detached_at_the_top_is_floating_even_though_it_reaches_the_floor(tmp_path: Path) -> None:"""Reaching the floor is not being supported: a leg shy of the seat is floating."""- p = _stool_with_a_leg_short_at_the_top(tmp_path / "top_gap.glb")-- r = check_connectivity(p)-+ r = check_connectivity(_stool_with_a_leg_short_at_the_top(tmp_path / "top_gap.glb"))assert not r.passed, [f.message for f in r.findings]errs = r.errorsassert len(errs) == 1 and errs[0].target == "Leg_3"@@ -138,34 +47,6 @@ def test_a_part_detached_at_the_top_is_floating_even_though_it_reaches_the_floorassert not [f for f in r.findings if "parts are connected" in f.message]-def _hat_and_body(path: Path, dy: float) -> Path:- """'hat' floating 100 mm above 'body', the pair translated by ``dy``."""- sc = trimesh.Scene()- body = trimesh.creation.box(extents=(0.2, 0.2, 0.2))- body.apply_translation((0, 0.1 + dy, 0))- hat = trimesh.creation.box(extents=(0.1, 0.1, 0.1))- hat.apply_translation((0, 0.2 + 0.1 + 0.05 + dy, 0)) # 100 mm above the body's top- sc.add_geometry(body, node_name="body", geom_name="body")- sc.add_geometry(hat, node_name="hat", geom_name="hat")- path.write_bytes(sc.export(file_type="glb"))- return path---def test_a_model_authored_below_the_floor_still_reports_its_floating_part(tmp_path: Path) -> None:- """A model authored below the floor must not switch the floating check off."""- on_ground = check_connectivity(_hat_and_body(tmp_path / "f2_on_ground.glb", 0.0))- sunk = check_connectivity(_hat_and_body(tmp_path / "f2_sunk.glb", -1.0))-- assert not on_ground.passed- assert [(e.target, e.data["nearest"]) for e in on_ground.errors] == [("hat", "body")]-- # the identical model, 1 m lower, must reach the identical verdict- assert not sunk.passed, "a sunk model must not disable the floating check"- assert [(e.target, e.data["nearest"]) for e in sunk.errors] == [("hat", "body")]- # ... plus the ground warning, since nothing is on the floor any more- assert any("touches the ground" in f.message and f.data["kind"] == "no_ground" for f in sunk.findings)--def _scene(path: Path, **meshes: trimesh.Trimesh) -> Path:sc = trimesh.Scene()for name, m in meshes.items():@@ -185,12 +66,6 @@ def _penetrations(r) -> list:return [f for f in r.findings if f.data.get("kind") == "penetration"]-def _ledger(r):- led = [f for f in r.findings if f.message.startswith("contact ledger")]- assert len(led) == 1 and led[0].severity == Severity.INFO and led[0].target == ""- return led[0]--def test_thin_rod_through_a_plate_is_measured_and_named_but_severity_stays_on_depth(tmp_path: Path) -> None:"""An 8 mm rod through a 10 mm plate: found by the dense pass, through-ratio measured, still a WARN."""rod = _cylinder_y(0.004, 1.0, (0, 0.5, 0))@@ -210,25 +85,6 @@ def test_thin_rod_through_a_plate_is_measured_and_named_but_severity_stays_on_deassert d["entering"] == "Rod" and d["container"] == "Plate" and d["thickness_m"] == pytest.approx(0.01, abs=1e-6)assert "reaches 93% of the way to the mid-plane of 'Plate' (10 mm thick)" in pen[0].messageassert "middle of 'Plate'" in pen[0].fix_hint and "shorten it" in pen[0].fix_hint- # the ledger carries the same pair with the same numbers, rounded- over = _ledger(r).data["overlaps"]- assert len(over) == 1 and set(over[0][:2]) == {"Rod", "Plate"}- assert over[0][2:] == [pytest.approx(5.0, abs=0.5), pytest.approx(d["through_ratio"], abs=0.01)]---def test_planned_edges_are_measured_regardless_of_the_aabb_prefilter(solid_stool_glb: Path) -> None:- """Leg_0-Seat is a contact; Leg_0-Leg_1 are 260 mm apart, a pair the AABB prefilter- never measures — a planned join is measured anyway and reported open, not as an ERROR- (whether it should fail the gate is the owner's call); a name the GLB does not have is- listed unresolved."""- r = check_connectivity(solid_stool_glb, planned_edges=[("Leg_0", "Seat"), ("Leg_0", "Leg_1"), ("Leg_0", "Ghost")])-- assert r.passed- d = _ledger(r).data- assert d["planned"] == [["Leg_0", "Seat", 0.0, "contact"], ["Leg_0", "Leg_1", pytest.approx(260.0, abs=0.5), "open"]]- assert d["planned_unresolved"] == ["Ghost"]- assert sorted(d["parts"]) == ["Leg_0", "Leg_1", "Leg_2", "Leg_3", "Seat"]- assert len(d["contacts"]) == 4 and all(c[1] == "Seat" or c[0] == "Seat" for c in d["contacts"])def test_a_deep_overlap_only_the_dense_pass_can_see_is_a_warn_with_every_number(tmp_path: Path) -> None:@@ -254,3 +110,105 @@ def test_a_deep_overlap_only_the_dense_pass_can_see_is_a_warn_with_every_number(pen2 = _penetrations(r2)assert pen2 and pen2[0].severity == Severity.ERROR and not r2.passedassert pen2[0].data["fraction_inside"] >= PENETRATION_MIN_FRACTION+++def _open_bottom_box(extents, translation) -> trimesh.Trimesh:+ """A box with its bottom face dropped — an open shell, what agents actually export."""+ m = trimesh.creation.box(extents=extents)+ m.apply_translation(translation)+ low = m.vertices[m.faces].mean(axis=1)[:, 1]+ shell = trimesh.Trimesh(vertices=m.vertices, faces=m.faces[low > low.min() + 1e-9], process=False)+ assert not shell.is_watertight+ return shell+++def _hat_and_body(path: Path, dy: float) -> Path:+ """'hat' floating 100 mm above 'body', the pair translated by ``dy``."""+ sc = trimesh.Scene()+ body = trimesh.creation.box(extents=(0.2, 0.2, 0.2))+ body.apply_translation((0, 0.1 + dy, 0))+ hat = trimesh.creation.box(extents=(0.1, 0.1, 0.1))+ hat.apply_translation((0, 0.2 + 0.1 + 0.05 + dy, 0)) # 100 mm above the body's top+ sc.add_geometry(body, node_name="body", geom_name="body")+ sc.add_geometry(hat, node_name="hat", geom_name="hat")+ path.write_bytes(sc.export(file_type="glb"))+ return path+++def _ledger(r):+ led = [f for f in r.findings if f.message.startswith("contact ledger")]+ assert len(led) == 1 and led[0].severity == Severity.INFO and led[0].target == ""+ return led[0]+++def test_tiny_island_warns(tmp_path: Path) -> None:+ body = trimesh.creation.box(extents=(0.3, 0.3, 0.3))+ body.apply_translation((0, 0.15, 0))+ crumb = trimesh.creation.box(extents=(0.004, 0.004, 0.004))+ crumb.apply_translation((0.5, 0.5, 0.5))+ part = trimesh.util.concatenate([body, crumb])+ sc = trimesh.Scene()+ sc.add_geometry(part, node_name="Body", geom_name="Body")+ p = tmp_path / "crumb.glb"+ sc.export(str(p))+ r = check_connectivity(p)+ warns = [f for f in r.findings if f.severity == Severity.WARN]+ assert warns and "tiny disconnected island" in warns[0].message and warns[0].data["kind"] == "stray_islands"+++def test_missing_glb_is_error(tmp_path: Path) -> None:+ r = check_connectivity(tmp_path / "none.glb")+ assert not r.passed and r.errors+++def test_interpenetration_is_found_between_two_non_watertight_parts(tmp_path: Path) -> None:+ """Open shells (not watertight) are measured too — they once read as "no overlap"."""+ base_ext, post_ext = (0.4, 0.2, 0.4), (0.2, 0.2, 0.2)+ base_at, post_at = (0, 0.1, 0), (0, 0.25, 0) # post bottom 50 mm below the base's top face+ closed = (trimesh.creation.box(extents=base_ext), trimesh.creation.box(extents=post_ext))+ closed[0].apply_translation(base_at)+ closed[1].apply_translation(post_at)+ shells = (_open_bottom_box(base_ext, base_at), _open_bottom_box(post_ext, post_at))++ for tag, (a, b) in (("closed", closed), ("open shells", shells)):+ depth, frac = penetration_depth(a, b)+ assert depth == pytest.approx(0.05, abs=1e-3), f"{tag}: 50 mm of interpenetration must be measured"+ assert frac > 0.05, tag++ scene = trimesh.Scene()+ scene.add_geometry(shells[0], node_name="Base", geom_name="Base")+ scene.add_geometry(shells[1], node_name="Post", geom_name="Post")+ glb = tmp_path / "open_shells.glb"+ scene.export(str(glb))+ r = check_connectivity(glb)+ assert not r.passed and any("interpenetrate" in f.message for f in r.errors)+++def test_a_model_authored_below_the_floor_still_reports_its_floating_part(tmp_path: Path) -> None:+ """A model authored below the floor must not switch the floating check off."""+ on_ground = check_connectivity(_hat_and_body(tmp_path / "f2_on_ground.glb", 0.0))+ sunk = check_connectivity(_hat_and_body(tmp_path / "f2_sunk.glb", -1.0))++ assert not on_ground.passed+ assert [(e.target, e.data["nearest"]) for e in on_ground.errors] == [("hat", "body")]++ # the identical model, 1 m lower, must reach the identical verdict+ assert not sunk.passed, "a sunk model must not disable the floating check"+ assert [(e.target, e.data["nearest"]) for e in sunk.errors] == [("hat", "body")]+ # ... plus the ground warning, since nothing is on the floor any more+ assert any("touches the ground" in f.message and f.data["kind"] == "no_ground" for f in sunk.findings)+++def test_planned_edges_are_measured_regardless_of_the_aabb_prefilter(solid_stool_glb: Path) -> None:+ """Leg_0-Seat is a contact; Leg_0-Leg_1 are 260 mm apart, a pair the AABB prefilter+ never measures — a planned join is measured anyway and reported open, not as an ERROR+ (whether it should fail the gate is the owner's call); a name the GLB does not have is+ listed unresolved."""+ r = check_connectivity(solid_stool_glb, planned_edges=[("Leg_0", "Seat"), ("Leg_0", "Leg_1"), ("Leg_0", "Ghost")])++ assert r.passed+ d = _ledger(r).data+ assert d["planned"] == [["Leg_0", "Seat", 0.0, "contact"], ["Leg_0", "Leg_1", pytest.approx(260.0, abs=0.5), "open"]]+ assert d["planned_unresolved"] == ["Ghost"]+ assert sorted(d["parts"]) == ["Leg_0", "Leg_1", "Leg_2", "Leg_3", "Seat"]+ assert len(d["contacts"]) == 4 and all(c[1] == "Seat" or c[0] == "Seat" for c in d["contacts"])diff --git a/harness/tests/spatial_tools/test_contract.py b/harness/tests/spatial_tools/test_contract.pyindex 60baafe7..da36b032 100644--- a/harness/tests/spatial_tools/test_contract.py+++ b/harness/tests/spatial_tools/test_contract.py@@ -8,7 +8,6 @@ from codeverse3d.contracts.artifacts import GateFinding, Measurement, PartMeasurfrom codeverse3d.contracts.plan import BBox, PartPlan, StaticPlanfrom codeverse3d.spatial.contract import (check_contract,- match_parts,)from codeverse3d.spatial.measure import measure_glb@@ -37,73 +36,6 @@ def test_bbox_deviation_warn_then_error(solid_stool_glb: Path) -> None:assert seat and seat[0].severity == Severity.ERROR-def test_instance_count_and_extras(solid_stool_glb: Path) -> None:- m = measure_glb(solid_stool_glb)- plan = _stool_plan()- plan.parts[1].instances = 3- r = check_contract(m, plan, language="blender")- inst = [f for f in r.findings if f.target == "Leg" and "instance" in f.message]- assert inst and inst[0].severity == Severity.WARN- # extra part → INFO- plan2 = _stool_plan(parts=[_stool_plan().parts[0]])- r2 = check_contract(m, plan2, language="blender")- assert [f for f in r2.findings if f.severity == Severity.INFO and "not in the plan" in f.message]---def test_ground_and_footprint_warnings() -> None:- m = Measurement(bbox_min=(0.1, 0.02, 0.1), bbox_max=(0.5, 0.47, 0.5), extents=(0.4, 0.45, 0.4), center=(0.3, 0.245, 0.3),- tri_count=10, n_meshes=1, n_islands=1, ground_gap_m=0.02, footprint_offset_m=0.42,- parts=[PartMeasure(name="Seat", bbox_min=(0.1, 0.41, 0.1), bbox_max=(0.5, 0.45, 0.5)),- *[PartMeasure(name=f"Leg_{i}", bbox_min=(0.1, 0.02, 0.1), bbox_max=(0.14, 0.43, 0.14)) for i in range(4)]])- r = check_contract(m, _stool_plan(), language="blender")- msgs = " | ".join(f.message for f in r.findings)- assert "above the ground" in msgs and "footprint centre" in msgs- # every defect is typed: the caps and the skill router key on the kind, not the words (N52)- kinds = {f.data.get("kind") for f in r.findings if f.severity != Severity.INFO}- assert {"ground_gap", "footprint_offset", "part_bbox", "overall_bbox"} <= kinds and None not in kinds---def test_an_exact_name_wins_over_another_part_instance_pattern() -> None:- """An exact name wins over another part's instance pattern ('Slat1' is not an instance of Slat)."""- plan = [PartPlan(name=n, role="r", description="d", bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)))- for n in ("Slat", "Slat1")]- rows = [PartMeasure(name=n, bbox_min=(0, 0, 0), bbox_max=(1, 1, 1))- for n in ("Slat_0", "Slat1", "Slat", "Slat_1")]-- matched, extra = match_parts(plan, rows)-- assert {m.name for m in matched["Slat"]} == {"Slat", "Slat_0", "Slat_1"}- assert [m.name for m in matched["Slat1"]] == ["Slat1"]- assert extra == []---def test_hints_are_written_in_the_authoring_frame() -> None:- """Sizes, deltas and centres in the hint are in the language's frame (Blender: Z-up)."""- plan = StaticPlan(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.5, 0.5, 0.45)),- parts=[PartPlan(name="Seat", role="seat", description="d", bbox=BBox(center=(0, 0, 0.425), extents=(0.5, 0.5, 0.05))),- PartPlan(name="Leg", role="leg", description="d", bbox=BBox(center=(0.2, -0.2, 0.2), extents=(0.05, 0.05, 0.40)))])- m = Measurement(bbox_min=(-0.25, 0, -0.25), bbox_max=(0.25, 0.45, 0.25), extents=(0.5, 0.45, 0.5), center=(0.1, 0.225, -0.05),- tri_count=24, n_meshes=2, n_islands=2, footprint_offset_m=0.3,- parts=[PartMeasure(name="Seat", bbox_min=(-0.25, 0.40, -0.25), bbox_max=(0.25, 0.45, 0.25)),- PartMeasure(name="Leg", bbox_min=(0.175, 0.0, 0.075), bbox_max=(0.225, 0.40, 0.325))])- r = check_contract(m, plan, language="blender")- leg = [f for f in r.findings if f.target == "Leg"][0]- assert "size 5.0×25.0×40.0 vs planned 5.0×5.0×40.0 cm (Δ x+0.0cm, y+20.0cm, z+0.0cm)" in leg.fix_hint- assert "centre off by (x+0.0cm, y+0.0cm, z+0.0cm)" not in leg.fix_hint- assert "planned centre (0.200, -0.200, 0.200) m (blender frame: Z-up, -Y front)" in leg.fix_hint- assert leg.data["delta_extents_m"] == pytest.approx([0.0, 0.2, 0.0], abs=1e-9) and leg.data["frame"] == "z_up_neg_y_front"- foot = [f for f in r.findings if "footprint" in f.message][0]- # GLB offset (+0.1, ·, -0.05) → move by (-0.1, 0, +0.05) GLB = (-0.1, -0.05, 0) in Blender's Z-up frame- assert "translate everything by (-0.100, -0.050, +0.000) m (blender frame: Z-up, -Y front)" in foot.fix_hint- # Y-up languages keep the GLB numbers verbatim- plan_tjs = plan.model_copy(deep=True)- plan_tjs.parts[1].bbox = BBox(center=(0.2, 0.2, 0.2), extents=(0.05, 0.40, 0.05))- leg = [f for f in check_contract(m, plan_tjs, language="threejs").findings if f.target == "Leg"][0]- assert "size 5.0×40.0×25.0 vs planned 5.0×40.0×5.0 cm (Δ x+0.0cm, y+0.0cm, z+20.0cm)" in leg.fix_hint- assert "(threejs frame: Y-up, +Z front)" in leg.fix_hint---# --------------------------------------------------------------------------- orientationdef _one_part_plan(extents_plan: tuple[float, float, float], *, up: int) -> StaticPlan:"""A plan whose single part IS the overall box, standing on the ground of a frame withup axis ``up`` (2 for Z-up languages, 1 for Y-up)."""@@ -134,22 +66,11 @@ def test_a_box_rotated_90_about_x_is_lying_down() -> None:o = _orientation(r.findings)assert len(o) == 1 and o[0].severity == Severity.ERROR and not r.passedassert o[0].data["best_axis"] == "y" and o[0].data["pose"] == "lying"- assert o[0].data["planned_up_m"] == pytest.approx(1.2) and o[0].data["measured_up_m"] == pytest.approx(0.2)assert "lying down relative to the planned box: planned 120.0 cm tall (z), measured 20.0 cm tall" in o[0].messageassert "rotate the whole object 90° about x so its height runs along z (blender frame: Z-up, -Y front)" in o[0].fix_hint- # the same in the threejs frame: Y-up plan (0.4, 1.2, 0.2) built with the height along z+ # the same in the threejs framer = check_contract(_measurement_glb((0.4, 0.2, 1.2)), _one_part_plan((0.4, 1.2, 0.2), up=1), language="threejs")- o = _orientation(r.findings)- assert len(o) == 1 and o[0].severity == Severity.ERROR and o[0].data["best_axis"] == "z"- assert "planned 120.0 cm tall (y)" in o[0].message and "about x so its height runs along y (threejs frame" in o[0].fix_hint---def test_a_yaw_of_90_is_a_turned_warning() -> None:- # Blender plan (0.4, 0.2, 1.2) turned about z: plan-frame (0.2, 0.4, 1.2) → GLB (0.2, 1.2, 0.4)- r = check_contract(_measurement_glb((0.2, 1.2, 0.4)), _one_part_plan((0.4, 0.2, 1.2), up=2), language="blender")- o = _orientation(r.findings)- assert len(o) == 1 and o[0].severity == Severity.WARN and o[0].data["pose"] == "turned"- assert "turned 90° about z" in o[0].message and o[0].data["best_axis"] == "x"+ assert [f.data["best_axis"] for f in _orientation(r.findings)] == ["z"]@pytest.mark.parametrize("glb, plan", [@@ -160,21 +81,3 @@ def test_a_yaw_of_90_is_a_turned_warning() -> None:def test_a_sizing_error_is_a_contract_violation_not_an_orientation(glb, plan) -> None:r = check_contract(_measurement_glb(glb), _one_part_plan(plan, up=2), language="blender")assert not r.passed and not _orientation(r.findings)---def test_stood_on_end_needs_a_2x_change_in_height() -> None:- """An under-sized tall plan built 1.46× taller is not 'stood on end'; a bench on its end is."""- orrery = _one_part_plan((0.48, 0.32, 0.48), up=1)- assert not _orientation(check_contract(_measurement_glb((0.374, 0.468, 0.351)), orrery, language="threejs").findings)- bench = _one_part_plan((1.5, 0.5, 0.45), up=2)- o = _orientation(check_contract(_measurement_glb((0.45, 1.5, 0.5)), bench, language="blender").findings)- assert len(o) == 1 and o[0].severity == Severity.ERROR and o[0].data["pose"] == "stood" and o[0].data["best_axis"] == "x"---def test_the_brilliana_c_clamp_is_caught_with_the_real_planner_box() -> None:- """A C-clamp lying flat against the real planner box: only the long axis must reappear."""- plan = _one_part_plan((0.125, 0.096, 0.22), up=2)- r = check_contract(_measurement_glb((0.137, 0.024, 0.183)), plan, language="cadquery")- o = _orientation(r.findings)- assert len(o) == 1 and o[0].severity == Severity.ERROR and o[0].data["best_axis"] == "y"- assert o[0].data["measured_up_m"] == pytest.approx(0.024)diff --git a/harness/tests/spatial_tools/test_mcp_server.py b/harness/tests/spatial_tools/test_mcp_server.pyindex 52b27c5f..99f40aa8 100644--- a/harness/tests/spatial_tools/test_mcp_server.py+++ b/harness/tests/spatial_tools/test_mcp_server.py@@ -9,14 +9,12 @@ from pathlib import Pathimport pytestfrom PIL import Image-from pydantic import ValidationErrorfrom codeverse3d.spatial.mcp_server import encode_image, main, observation_contentfrom codeverse3d.spatial.registry import Observation, ToolContextdef test_observation_content_blocks(tmp_path: Path) -> None:- from PIL import Imagebig = tmp_path / "big.png"Image.new("RGB", (2048, 1024), (10, 20, 30)).save(big)@@ -32,106 +30,23 @@ def test_observation_content_blocks(tmp_path: Path) -> None:assert encode_image(str(tmp_path / "missing.png")) is None-def test_result_payload_is_bounded_by_outcome(tmp_path: Path) -> None:- """Text is capped and the image budget shrinks with the outcome (gemini-cli re-sends an error as text, docs/COST.md §30)."""- from PIL import Image-- from codeverse3d.spatial.mcp_server import MAX_TEXT_CHARS, max_images_for-- pngs = []- for i in range(5):- p = tmp_path / f"v{i}.png"- Image.new("RGB", (32, 32), (10 * i, 0, 0)).save(p)- pngs.append(str(p))- huge = "x" * 200_000- cases = ((Observation(ok=True, text=huge, images=pngs), 4),- (Observation(ok=False, text=huge, images=pngs), 1), # a FAIL verdict- (Observation(ok=False, failed=True, text=huge, images=pngs), 0)) # the tool could not run- for obs, n_images in cases:- assert max_images_for(obs) == n_images- blocks = observation_content(obs)- assert len(blocks[0].text) <= MAX_TEXT_CHARS- assert sum(1 for b in blocks if b.type == "image") == n_images--def test_the_byte_bound_keeps_the_sheet_drops_the_rest_and_says_so(tmp_path: Path) -> None:"""The byte budget stops at the first image that does not fit (images[0] is the sheet) and says what did not come."""- from PIL import Image-- from codeverse3d.spatial.mcp_server import MAX_IMAGE_BYTES, encode_image+ from codeverse3d.spatial.mcp_server import MAX_IMAGE_BYTESdef noise(name: str, side: int) -> str:- img = Image.frombytes("RGB", (side, side), __import__("random").Random(len(name)).randbytes(side * side * 3))p = tmp_path / name- img.save(p)+ Image.frombytes("RGB", (side, side), __import__("random").Random(len(name)).randbytes(side * side * 3)).save(p)return str(p)small, heavy = noise("small.png", 64), noise("heavy.png", 1024)- assert len(encode_image(small) or "") < MAX_IMAGE_BYTES / 4 < len(encode_image(heavy) or "")-- # an in-budget sheet is KEPT (the bug this pins: it used to be skipped for the views)- blocks = observation_content(Observation(ok=True, text="t", images=[small, small, small, small]))- assert sum(1 for b in blocks if b.type == "image") == 4 and "not attached" not in blocks[0].text-- # the budget stops at the first image that does not fit, and the text says how many+ blocks = observation_content(Observation(ok=True, text="t", images=[small, small]))+ assert sum(1 for b in blocks if b.type == "image") == 2 and "not attached" not in blocks[0].textblocks = observation_content(Observation(ok=True, text="t", images=[small, heavy, small, small]))images = [b for b in blocks if b.type == "image"]assert len(images) == 1 and sum(len(b.data) for b in images) <= MAX_IMAGE_BYTESassert "3 image(s) not attached" in blocks[0].text- # a FAIL verdict ships one image; if that one is over budget it ships none WITH a note- blocks = observation_content(Observation(ok=False, text="t", images=[heavy, small]))- assert not [b for b in blocks if b.type == "image"]- assert "1 image(s) not attached" in blocks[0].text---def test_an_oversized_sheet_is_downscaled_and_every_bound_holds_including_the_note(tmp_path: Path) -> None:- """The sheet is re-encoded smaller until it fits (never dropped), and the note stays under the text cap."""- from codeverse3d.spatial.mcp_server import MAX_IMAGE_BYTES, MAX_TEXT_CHARS-- heavy = tmp_path / "heavy.png"- Image.effect_noise((1600, 4200), 90).convert("RGB").save(heavy)- blocks = observation_content(Observation(ok=True, text="x" * 20_000,- images=[str(heavy), str(heavy)]))- assert len(encode_image(str(heavy))) > MAX_IMAGE_BYTES- images = [b for b in blocks if b.type == "image"]- assert len(images) == 1 and len(images[0].data) <= MAX_IMAGE_BYTES- assert len(blocks[0].text) <= MAX_TEXT_CHARS and "re-encoded at" in blocks[0].text---def test_is_error_is_failed_not_the_verdict(stool_ctx: ToolContext) -> None:- """A FAIL verdict is an ordinary result (its images go as images); only a tool that could not run is is_error."""- from mcp import types-- from codeverse3d.spatial import mcp_server- from codeverse3d.spatial.registry import NoArgs, ToolDef-- fakes = [- ToolDef(name="verdict", args_model=NoArgs, description="a gate that answers FAIL",- fn=lambda ctx, args: Observation(ok=False, failed=False, text="GATE: FAIL — one error")),- ToolDef(name="broken", args_model=NoArgs, description="a tool that cannot run",- fn=lambda ctx, args: Observation.error("no readable GLB")),- ]- defs = {t.name: t for t in fakes}-- async def call(name: str) -> types.CallToolResult:- return await mcp_server.call_tool(stool_ctx, defs,- types.CallToolRequestParams(name=name, arguments={}))-- verdict = asyncio.run(call("verdict"))- broken = asyncio.run(call("broken"))- assert verdict.is_error is False, "a FAIL verdict is a result, not a protocol error"- assert "FAIL" in verdict.content[0].text- assert broken.is_error is True, "a tool that could not run IS a protocol error"---def test_a_failure_cannot_also_be_a_pass() -> None:- """``failed`` implies ``not ok``."""- with pytest.raises(ValidationError, match="has no verdict"):- Observation(ok=True, failed=True, text="both")- assert Observation(ok=False, failed=True, text="could not run").failed- assert not Observation(ok=False, failed=False, text="FAIL: the gate ran").failed-def test_cli_list(stool_ctx: ToolContext, capsys: pytest.CaptureFixture[str]) -> None:assert main(["--workspace", str(stool_ctx.workspace.root), "--list"]) == 0@@ -145,9 +60,7 @@ def test_stdio_roundtrip(stool_ctx: ToolContext, tmp_path: Path) -> None:from mcp import ClientSessionfrom mcp.client.stdio import StdioServerParameters, stdio_client- # `errlog` is handed straight to loop.subprocess_exec, which needs a real- # fileno(); pytest's captured sys.stderr (stdio_client's default) has none- # from anyio 4.14 on. A file also keeps the server's stderr readable here.+ # stdio_client's default errlog (pytest's captured stderr) has no fileno(): hand it a real fileerrlog = (tmp_path / "server.err").open("w")async def run():@@ -159,9 +72,7 @@ def test_stdio_roundtrip(stool_ctx: ToolContext, tmp_path: Path) -> None:assert "measure" in by_name and "check_connectivity" in by_nameassert by_name["render_views"].input_schema["properties"]["views"]["type"] == "array"conn = await s.call_tool("check_connectivity", {})- assert conn.content and conn.content[0].type == "text"- # the gate ran and answered FAIL: a RESULT, not a protocol error the model retries- assert not conn.is_error+ assert not conn.is_error # the gate answered FAIL: a RESULT, not a protocol errorassert conn.content[0].text.startswith("connectivity: FAIL") # the verdict leadsassert "Leg_3" in conn.content[0].text # the fixture's floating legmeas = await s.call_tool("measure", {})@@ -173,10 +84,44 @@ def test_stdio_roundtrip(stool_ctx: ToolContext, tmp_path: Path) -> None:assert bad.is_error and "invalid arguments" in bad.content[0].textunusable = await s.call_tool("isolate", {"part": "Nope"})assert unusable.is_error and "unknown part" in unusable.content[0].text- unknown = await s.call_tool("nope", {})- assert unknown.is_errortry:asyncio.run(asyncio.wait_for(run(), timeout=120))finally:errlog.close()+++def test_result_payload_is_bounded_by_outcome(tmp_path: Path) -> None:+ """Text is capped and the image budget shrinks with the outcome (gemini-cli re-sends an error as text, docs/COST.md §30)."""+ from PIL import Image++ from codeverse3d.spatial.mcp_server import MAX_TEXT_CHARS, max_images_for++ pngs = []+ for i in range(5):+ p = tmp_path / f"v{i}.png"+ Image.new("RGB", (32, 32), (10 * i, 0, 0)).save(p)+ pngs.append(str(p))+ huge = "x" * 200_000+ cases = ((Observation(ok=True, text=huge, images=pngs), 4),+ (Observation(ok=False, text=huge, images=pngs), 1), # a FAIL verdict+ (Observation(ok=False, failed=True, text=huge, images=pngs), 0)) # the tool could not run+ for obs, n_images in cases:+ assert max_images_for(obs) == n_images+ blocks = observation_content(obs)+ assert len(blocks[0].text) <= MAX_TEXT_CHARS+ assert sum(1 for b in blocks if b.type == "image") == n_images+++def test_an_oversized_sheet_is_downscaled_and_every_bound_holds_including_the_note(tmp_path: Path) -> None:+ """The sheet is re-encoded smaller until it fits (never dropped), and the note stays under the text cap."""+ from codeverse3d.spatial.mcp_server import MAX_IMAGE_BYTES, MAX_TEXT_CHARS++ heavy = tmp_path / "heavy.png"+ Image.effect_noise((1600, 4200), 90).convert("RGB").save(heavy)+ blocks = observation_content(Observation(ok=True, text="x" * 20_000,+ images=[str(heavy), str(heavy)]))+ assert len(encode_image(str(heavy))) > MAX_IMAGE_BYTES+ images = [b for b in blocks if b.type == "image"]+ assert len(images) == 1 and len(images[0].data) <= MAX_IMAGE_BYTES+ assert len(blocks[0].text) <= MAX_TEXT_CHARS and "re-encoded at" in blocks[0].textdiff --git a/harness/tests/spatial_tools/test_measure.py b/harness/tests/spatial_tools/test_measure.pyindex 7f8dc529..58ea22f8 100644--- a/harness/tests/spatial_tools/test_measure.py+++ b/harness/tests/spatial_tools/test_measure.py@@ -6,74 +6,10 @@ import numpy as npimport pytestimport trimesh-from codeverse3d.spatial.measure import (- GlbLoadError,- instance_groups,- measure_glb,-)+from codeverse3d.spatial.measure import measure_glb-def test_instance_groups() -> None:- g = instance_groups(["Leg_3", "Leg_0", "Seat", "Bolt.1", "Bolt.2", "Rail_1"])- assert g["Leg"] == ["Leg_0", "Leg_3"]- assert g["Bolt"] == ["Bolt.1", "Bolt.2"]- assert g["Seat"] == ["Seat"]- assert g["Rail_1"] == ["Rail_1"] # singleton keeps its full name- # a bare base beside indexed siblings joins their group (it once crashed the judge input)- assert instance_groups(["lens", "lens_2", "lens_1"])["lens"] == ["lens", "lens_1", "lens_2"]---def test_missing_file_raises(tmp_path: Path) -> None:- with pytest.raises(GlbLoadError):- measure_glb(tmp_path / "nope.glb")---def test_degenerate_mesh_is_a_finding(tmp_path: Path) -> None:- sc = trimesh.Scene()- flat = trimesh.Trimesh(vertices=[[0, 0, 0], [1, 0, 0], [1, 0, 1]], faces=[[0, 1, 2]]) # zero height, open- sc.add_geometry(flat, node_name="Sheet", geom_name="Sheet")- p = tmp_path / "flat.glb"- sc.export(str(p))- m = measure_glb(p)- assert m.tri_count == 1- assert m.parts[0].watertight is False and m.parts[0].volume_m3 is None- assert m.extents[1] == 0.0---def test_cyclic_scene_graph_does_not_hang(tmp_path: Path) -> None:- """A GLB node named like the loader's base frame ('world') closes a cycle in the- scene graph; measuring must terminate (with the geometry still counted once)."""- from codeverse3d.spatial.measure import _subtree_nodes, part_meshes-- box = trimesh.creation.box((0.2, 0.2, 0.2))- scene = trimesh.Scene(base_frame="root")- scene.graph.update(frame_to="wrapper", frame_from="root")- scene.add_geometry(box, node_name="world", geom_name="world", parent_node_name="wrapper")- scene.graph.update(frame_to="root", frame_from="world") # cycle: root → wrapper → world → root- assert "world" in _subtree_nodes(scene, "root") and len(_subtree_nodes(scene, "root")) == 3- assert [k for k, v in part_meshes(scene).items() if v is not None]---def test_caches_share_meshes_invalidate_on_stat_and_never_leak_edits(stool_glb: Path) -> None:- from codeverse3d.spatial.measure import cached_parts-- p1 = cached_parts(stool_glb)- p2 = cached_parts(stool_glb)- assert p1 is not p2 # fresh dict per call- assert all(p1[k] is p2[k] for k in p1) # same stat → shared meshes- # rewriting the file (new mtime_ns/size) invalidates the entry- import os- os.utime(stool_glb, ns=(1, 1))- p3 = cached_parts(stool_glb)- assert set(p3) == set(p1) and all(p3[k] is not p1[k] for k in p3)- m1 = measure_glb(stool_glb)- m2 = measure_glb(stool_glb)- assert m1 is not m2 and m1 == m2- m1.extra["findings"].append("mutated") # a caller's edit never leaks back- assert measure_glb(stool_glb).extra["findings"] == []---def _root_pivot_scene(dup_names: bool = False) -> trimesh.Scene:+def _root_pivot_scene() -> trimesh.Scene:"""Two 0.1 x 0.1 x 0.4 posts authored Z-up under a root 'pivot' carrying the Z-up→Y-uprotation — what THREE.GLTFExporter writes for a Z-up scene."""rot = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], float)@@ -95,33 +31,3 @@ def test_a_root_pivot_glb_measures_upright(tmp_path: Path) -> None:assert m.bbox_min[1] == pytest.approx(0.0, abs=1e-6) and m.bbox_max[1] == pytest.approx(0.4, abs=1e-6)assert m.ground_gap_m == pytest.approx(0.0, abs=1e-6)assert not [f for f in m.extra.get("findings", []) if "node" in f]---def test_duplicate_or_unnamed_glTF_nodes_are_named_in_the_findings(tmp_path: Path) -> None:- """Duplicate or unnamed nodes mis-pose under trimesh: the reader is told the numbers are approximate."""- import json- import struct-- from codeverse3d.spatial.measure import gltf_node_names, node_name_findings-- raw = _root_pivot_scene().export(file_type="glb")- (n,) = struct.unpack("<I", raw[12:16])- js = json.loads(raw[20:20 + n])- for node in js["nodes"]:- if node.get("name", "").startswith("Post_"):- node["name"] = "Post" # a duplicate- js["nodes"][0].pop("name", None) # and an unnamed one- body = json.dumps(js, separators=(",", ":")).encode()- body += b" " * ((4 - len(body) % 4) % 4)- glb = struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(body) + len(raw[20 + n:])) + struct.pack("<I", len(body)) + b"JSON" + body + raw[20 + n:]- p = tmp_path / "dups.glb"- p.write_bytes(glb)-- assert gltf_node_names(p).count("Post") == 2- found = node_name_findings(p)- assert any("duplicate glTF node names ('Post' x2)" in f for f in found)- assert any(f"1 of {len(gltf_node_names(p))} glTF nodes are unnamed" in f for f in found)- assert found == [f for f in measure_glb(p).extra["findings"] if "glTF node" in f]- clean = tmp_path / "clean.glb"- clean.write_bytes(raw)- assert node_name_findings(clean) == []diff --git a/harness/tests/spatial_tools/test_observe.py b/harness/tests/spatial_tools/test_observe.pyindex dc4ee6e4..4fa0639c 100644--- a/harness/tests/spatial_tools/test_observe.py+++ b/harness/tests/spatial_tools/test_observe.py@@ -2,46 +2,8 @@ from __future__ import annotationsfrom pathlib import Path-from codeverse3d.contracts.artifacts import (- BuildResult,- GateFinding,- GateReport,- RenderSet,- RenderView,- Severity,-)-from codeverse3d.spatial.observe import (- build_failure_lines,- fmt_numbers,- gate_observation,- image_budget,- render_observation,-)---def test_fmt_numbers_compact() -> None:- s = fmt_numbers({"a": 1.23456789, "b": [0.1, 0.2], "c": True, "d": {"x": 1, "y": {"z": {"deep": 1}}}, "e": "x" * 100})- assert "a=1.2346" in s and "b=[0.1, 0.2]" in s and "c=yes" in s and "{1 keys}" in s and "…" in s---def test_image_budget_keeps_sheet_first() -> None:- imgs = [f"/x/{i}.png" for i in range(10)]- out = image_budget(imgs, max_n=3)- assert out == imgs[:3]---def test_gate_observation_errors_first() -> None:- rep = GateReport(gate="g", passed=False, findings=[- GateFinding(gate="g", severity=Severity.INFO, message="fyi"),- GateFinding(gate="g", severity=Severity.WARN, target="A", message="warnish", fix_hint="do x"),- GateFinding(gate="g", severity=Severity.ERROR, target="B", message="bad", fix_hint="do y", data={"gap_m": 0.01}),- ])- obs = gate_observation(rep)- assert not obs.ok- lines = obs.text.splitlines()- assert "FAIL" in lines[0] and "1 error(s), 1 warning(s)" in lines[0]- assert lines[1].startswith("- ERROR [B]") and "fix: do y" in lines[2]- assert obs.numbers["errors"] == 1 and obs.numbers["error_data"]["B"]["gap_m"] == 0.01+from codeverse3d.contracts.artifacts import RenderSet, RenderView+from codeverse3d.spatial.observe import render_observationdef test_render_with_no_views_is_a_failure_console_errors_are_a_verdict(tmp_path: Path) -> None:@@ -57,22 +19,3 @@ def test_render_with_no_views_is_a_failure_console_errors_are_a_verdict(tmp_pathassert not obs.ok and not obs.failedassert obs.text.startswith("RENDER: FAIL — 1 console error(s); the views below rendered anyway")assert "scene views" in obs.text and "TypeError" in obs.text-- booted = render_observation(RenderSet(views=[], renderer="fake", console_errors=["SyntaxError: scene.js:12"]),- tmp_path)- assert not booted.ok and not booted.failed # the scene told the agent what to fix- assert booted.text.startswith("RENDER: FAIL — 1 console error(s) and no view rendered")- assert "SyntaxError" in booted.text---def test_build_failure_lines_relative_file_and_tail_dedupe(tmp_path: Path) -> None:- # (ii) an already-relative error_file is shown as-is from any cwd (rel_path would give the bare name)- # (iii) a stderr tail that is already part of the message is not repeated- log = "0:4: 'nope' undeclared"- br = BuildResult(ok=False, language="glsl_shader", error_type="GlslCompileError", error_file="src/shader.frag",- error_line=4, error_message="GLSL compile error:\n" + log, stderr_tail=log)- lines = build_failure_lines(br, tmp_path, ["- WARN: w"], tail_n=25)- assert lines == ["BUILD FAILED: GlslCompileError: GLSL compile error: at src/shader.frag:4", log, "lint hints:\n- WARN: w"]- br2 = br.model_copy(update={"error_file": str(tmp_path / "src" / "a.py"), "error_message": "boom", "stderr_tail": "l1\nl2"})- lines = build_failure_lines(br2, tmp_path, [], tail_n=1)- assert lines == ["BUILD FAILED: GlslCompileError: boom at src/a.py:4", "stderr (tail):\nl2"]diff --git a/harness/tests/spatial_tools/test_placeholder_gate.py b/harness/tests/spatial_tools/test_placeholder_gate.pyindex 1f2520fb..24d79753 100644--- a/harness/tests/spatial_tools/test_placeholder_gate.py+++ b/harness/tests/spatial_tools/test_placeholder_gate.py@@ -18,7 +18,6 @@ from codeverse3d.contracts.artifacts import (PartMeasure,Severity,)-from codeverse3d.contracts.common import Languagefrom codeverse3d.contracts.plan import BBox, PartPlan, StaticPlanfrom codeverse3d.orchestrator import build_refine_instructionsfrom codeverse3d.spatial.contract import (@@ -73,15 +72,6 @@ def test_rule_is_triangles_and_the_plan_box_to_a_millimetre():assert not is_placeholder(copies[:3] + [_row("Leg_3", leg, 200)], leg) # one real leg: being built-def test_a_bare_box_built_exactly_to_the_plan_is_taken_for_the_placeholder():- """The known limit, pinned: measurement alone cannot tell a real bare 12-triangle box at the- plan's millimetre from the skeleton's box, so it fires. Over the loop_argon iter_00/01 corpus- (942 part rows) no such real part existed — every hit was a byte-unchanged skeleton file."""- box = plan_bbox_to_glb(_plan().parts[0].bbox, "threejs")- assert is_placeholder([_row("TableTop", box, 12)], box)- assert not is_placeholder([_row("TableTop", box, 20)], box) # the same box, segmented once--def test_gate_finding_is_typed_and_routes_first():plan = _plan()rows = [_row("TableTop", plan_bbox_to_glb(plan.parts[0].bbox, "blender"), 400),@@ -100,7 +90,6 @@ def test_gate_finding_is_typed_and_routes_first():assert [t.target for t in tasks[:2]] == ["Leg", "Shelf"] and tasks[2].target == "TableTop"-# ----------------------------------------------------------------------------- each real skeletondef _placeholders(glb: str, language: str) -> set[str]:from codeverse3d.spatial.measure import measure_glb@@ -108,14 +97,8 @@ def _placeholders(glb: str, language: str) -> set[str]:return {f.target for f in report.findings if f.data.get("kind") == PLACEHOLDER_PART}-def _edit(path, old: str, new: str) -> None:- text = path.read_text()- assert old in text, f"{old!r} not in {path}"- path.write_text(text.replace(old, new))--@pytest.mark.blender-def test_blender_skeleton_fires_and_a_built_part_does_not(tmp_path):+def test_blender_skeleton_fires(tmp_path):b = get_settings().resolve_blender()if not b or (not shutil.which(b) and not b.startswith("/")):pytest.skip("no Blender binary")@@ -126,63 +109,3 @@ def test_blender_skeleton_fires_and_a_built_part_does_not(tmp_path):r = rt.build(ws, timeout_s=120)assert r.ok, (r.error_type, r.error_message)assert _placeholders(r.glb_path, "blender") == {"TableTop", "Leg", "Shelf"}- _edit(ws.src / "parts" / "shelf.py", 'return add_box("Shelf", SHELF_CENTER, SHELF_EXTENTS, mat)',- 'bpy.ops.mesh.primitive_cylinder_add(vertices=32, radius=0.21, depth=0.02, location=SHELF_CENTER)\n'- ' obj = bpy.context.object\n obj.name = "Shelf"\n obj.data.materials.append(mat)\n return obj')- r = rt.build(ws, timeout_s=120)- assert r.ok, (r.error_type, r.error_message)- assert _placeholders(r.glb_path, "blender") == {"TableTop", "Leg"}---def test_cadquery_skeleton_fires_and_a_built_part_does_not(tmp_path):- pytest.importorskip("cadquery")- from codeverse3d.languages.cadquery import CadQueryRuntime-- ws, rt = Workspace(tmp_path / "c").create(), CadQueryRuntime()- rt.skeleton(ws, _plan())- r = rt.build(ws, timeout_s=120)- assert r.ok, (r.error_type, r.error_message)- assert _placeholders(r.glb_path, "cadquery") == {"TableTop", "Leg", "Shelf"}- _edit(ws.src / "model.py", 'cq.Workplane("XY").box(0.420, 0.420, 0.020)',- 'cq.Workplane("XY").box(0.420, 0.420, 0.020).edges("|Z").fillet(0.02)')- r = rt.build(ws, timeout_s=120)- assert r.ok, (r.error_type, r.error_message)- assert _placeholders(r.glb_path, "cadquery") == {"TableTop", "Leg"}---def test_cadquery_tapered_extrude_at_its_plan_box_does_not_fire(tmp_path):- """A real tapered part (a fretboard: trapezoid outline extruded) is 12 triangles and sits- exactly on its plan box, yet does not fill it — it was built, not left as the skeleton."""- pytest.importorskip("cadquery")- from codeverse3d.languages.cadquery import CadQueryRuntime-- ws, rt = Workspace(tmp_path / "f").create(), CadQueryRuntime()- rt.skeleton(ws, _plan())- _edit(ws.src / "model.py", 'cq.Workplane("XY").box(0.420, 0.420, 0.020)',- 'cq.Workplane("XY").polyline([(-0.21, -0.21), (0.21, -0.21), (0.15, 0.21), (-0.15, 0.21)])'- '.close().extrude(0.020).translate((0, 0, -0.010))')- r = rt.build(ws, timeout_s=120)- assert r.ok, (r.error_type, r.error_message)- from codeverse3d.spatial.measure import measure_glb-- shelf = [p for p in measure_glb(r.glb_path).parts if p.name.lower() == "shelf"]- assert shelf and shelf[0].tri_count <= PLACEHOLDER_MAX_TRIS # the case the fill rule exists for- assert _placeholders(r.glb_path, "cadquery") == {"TableTop", "Leg"}---def test_threejs_skeleton_fires_and_a_built_part_does_not(tmp_path):- if shutil.which("node") is None:- pytest.skip("node not available")- from codeverse3d.languages.threejs import ThreeJsRuntime-- ws, rt = Workspace(tmp_path / "t").create(), ThreeJsRuntime()- rt.skeleton(ws, _plan())- r = rt.build(ws)- assert r.ok, (r.error_type, r.error_message)- assert _placeholders(r.glb_path, Language.THREEJS.value) == {"TableTop", "Leg", "Shelf"}- _edit(ws.src / "parts" / "shelf.js", "new THREE.BoxGeometry(size[0], size[1], size[2])",- "new THREE.BoxGeometry(size[0], size[1], size[2], 4, 1, 4)")- r = rt.build(ws)- assert r.ok, (r.error_type, r.error_message)- assert _placeholders(r.glb_path, Language.THREEJS.value) == {"TableTop", "Leg"}diff --git a/harness/tests/spatial_tools/test_render_common.py b/harness/tests/spatial_tools/test_render_common.pydeleted file mode 100644index e3f26455..00000000--- a/harness/tests/spatial_tools/test_render_common.py+++ /dev/null@@ -1,102 +0,0 @@-"""Render caching: one cache authority, keyed by content, safe under concurrent writers."""--from __future__ import annotations--from pathlib import Path--import pytest--from codeverse3d.conventions import OBJECT_VIEWS-from codeverse3d.spatial.registry import ToolContext-from codeverse3d.workspace import Workspace---def test_cached_render_glb_leaves_the_cache_to_render_glb(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:- """``render.render_glb`` (content hash) is the one cache authority: a same-size, same-mtime rebuild re-renders."""- import codeverse3d.spatial.tool_common as tc- from codeverse3d.contracts.artifacts import RenderSet, RenderView-- calls: list[Path] = []-- def fake_render_glb(glb, out_dir, *, views, mode, width, height, isolate, explode, sheet):- calls.append(Path(out_dir))- png = Path(out_dir) / f"{views[0].name}.png"- png.write_bytes(b"png")- return RenderSet(views=[RenderView(name=views[0].name, path=str(png))], contact_sheet=None)-- monkeypatch.setattr("codeverse3d.spatial.render.render_glb", fake_render_glb)- glb = stool_ctx.workspace.artifacts / "object.glb"- preset = OBJECT_VIEWS[0]- first = tc.cached_render_glb(stool_ctx, glb, views=[preset])- stamp = glb.stat()- glb.write_bytes(glb.read_bytes()[::-1]) # new content, same size- import os-- os.utime(glb, ns=(stamp.st_atime_ns, stamp.st_mtime_ns)) # ...and the same mtime- second = tc.cached_render_glb(stool_ctx, glb, views=[preset])- assert len(calls) == 2 and calls[0] == calls[1], calls # re-rendered into the same dir- assert first.views[0].path == second.views[0].path- assert not list(calls[0].glob("renderset.json")) # no second marker on disk---def test_store_in_cache_survives_a_concurrent_identical_writer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """Two writers of one cache entry (a judge fan-out): no exception, and the cache ends up complete."""- import shutil- import threading- import time-- from codeverse3d.spatial import render as R-- out = tmp_path / "out"- out.mkdir()- record = {"views": [{"name": f"v{i}"} for i in range(6)]}- for i in range(6):- (out / f"view_v{i}.png").write_bytes(b"x" * 1000)- cache_dir = tmp_path / "cache" / "deadbeefdeadbeefdeadbeef"- cache_dir.parent.mkdir(parents=True)-- orig = shutil.copy2- monkeypatch.setattr(R.shutil, "copy2", lambda src, dst, **kw: (time.sleep(0.03), orig(src, dst, **kw))[1])-- errs: list[str] = []-- def store(delay: float) -> None:- time.sleep(delay)- try:- R._store_in_cache(cache_dir, out, record)- except Exception as e: # noqa: BLE001 — the failure mode under test- errs.append(f"{type(e).__name__}: {e}")-- threads = [threading.Thread(target=store, args=(d,)) for d in (0.0, 0.08)]- for t in threads:- t.start()- for t in threads:- t.join()- assert errs == []- assert (cache_dir / "views.json").is_file()- assert sorted(p.name for p in cache_dir.glob("view_*.png")) == [f"view_v{i}.png" for i in range(6)]- assert not list(cache_dir.parent.glob("*.tmp")), "no tmp dirs left behind"---def test_gl_metrics_summary_is_the_one_frame_stats_formatter(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity- from codeverse3d.spatial.frame_stats import FrameStat, SequenceStats- from codeverse3d.spatial.tool_common import gl_metrics_summary-- stats = SequenceStats(frames=[FrameStat(time=0.0, path="f0.png", mean_lum=0.4, std_lum=0.2, pct_black=0.0,- pct_blown=0.0, colourfulness=0.3, edge_density=0.05)], mean_diff=0.0)- gate = GateReport(gate="gl_frames", passed=False, findings=[- GateFinding(gate="gl_frames", severity=Severity.ERROR, message=f"static image in {tmp_ws.root}/src",- fix_hint="animate with u_time", data={"kind": "static"}),- GateFinding(gate="gl_frames", severity=Severity.INFO, message="ignored"),- ])- monkeypatch.setattr("codeverse3d.languages._gl_common.read_metrics", lambda ws: (stats, gate))- lines, numbers, ok = gl_metrics_summary(tmp_ws, hints=True, root=tmp_ws.root)- body = "\n".join(lines)- assert not ok and "frames=1" in body and "[static]" in body and "fix: animate with u_time" in body- assert "ignored" not in body and str(tmp_ws.root) not in body # INFO dropped, paths sanitised- assert numbers["gate_errors"] == 1 and numbers["n_frames"] == 1 and numbers["gate_passed"] is False- no_hints, _, _ = gl_metrics_summary(tmp_ws, hints=False)- assert "fix:" not in "\n".join(no_hints)- monkeypatch.setattr("codeverse3d.languages._gl_common.read_metrics", lambda ws: None)- assert gl_metrics_summary(tmp_ws) == (["(no frame metrics)"], {}, True)diff --git a/harness/tests/spatial_tools/test_sections.py b/harness/tests/spatial_tools/test_sections.pyindex a45433e6..045c7f61 100644--- a/harness/tests/spatial_tools/test_sections.py+++ b/harness/tests/spatial_tools/test_sections.py@@ -8,7 +8,7 @@ import pytestimport trimeshfrom PIL import Image-from codeverse3d.spatial.sections import SliceManifest, cross_section, judge_slices+from codeverse3d.spatial.sections import cross_section, judge_slicesdef test_cross_section_position_is_a_fraction_of_the_selected_parts(stool_glb: Path, tmp_path: Path) -> None:@@ -18,76 +18,7 @@ def test_cross_section_position_is_a_fraction_of_the_selected_parts(stool_glb: Passert "Plane axes: x horizontal, z vertical" in o.text-def test_cross_section_that_cuts_nothing_answers_without_an_image(tmp_path: Path) -> None:- glb = _two_boxes(tmp_path / "apart.glb", overlap_x=-0.1) # a 10 cm gap at the bbox middle- o = cross_section(glb, "x", 0.5, tmp_path / "gap.png")- assert o.ok and o.numbers["n_loops"] == 0 and o.images == [] and "nothing" in o.text- assert not (tmp_path / "gap.png").exists()---def test_bad_inputs(stool_glb: Path, tmp_path: Path) -> None:- assert not cross_section(stool_glb, "w", 0.5, tmp_path / "x.png").ok- o = cross_section(stool_glb, "y", 0.5, tmp_path / "x.png", parts=["Nope"])- assert not o.ok and "Nope" in o.text and "Seat" in o.text- assert not cross_section(tmp_path / "missing.glb", "y", 0.5, tmp_path / "x.png").ok--# ===================================================================== judge slices (D48)-def _two_boxes(path: Path, *, overlap_x: float = 0.05, dy: float = 0.0) -> Path:- """Box A (0.3³ at origin, resting on y=0) + box B shifted so they overlap by- ``overlap_x`` along x (and optionally offset ``dy`` up)."""- sc = trimesh.Scene()- a = trimesh.creation.box(extents=(0.3, 0.3, 0.3))- a.apply_translation((0, 0.15, 0))- b = trimesh.creation.box(extents=(0.3, 0.3, 0.3))- b.apply_translation((0.3 - overlap_x, 0.15 + dy, 0))- sc.add_geometry(a, node_name="A", geom_name="A")- sc.add_geometry(b, node_name="B", geom_name="B")- sc.export(str(path))- return path---def test_judge_slices_ignores_hairline_contact_slivers(tmp_path: Path) -> None:- # 1 mm of in-plane overlap (a weld) is under the ~2·erode thickness: not drawn at all- glb = _two_boxes(tmp_path / "weld.glb", overlap_x=0.3, dy=0.299) # stacked, 1 mm y-overlap- m = judge_slices(glb, [("A", "B")], tmp_path / "out")- assert m.rendered()- for s in m.rendered():- assert s.hatched_pairs == [] and s.plain_pairs == []---def test_judge_slices_drops_a_degenerate_slice(tmp_path: Path) -> None:- """A portal frame whose centre-x plane cuts only the thin top beam (4 % of the- part's projected silhouette): F4 drops front_back, keeps left_right."""- cols = []- for x in (-0.45, 0.45):- c = trimesh.creation.box(extents=(0.1, 1.0, 0.1))- c.apply_translation((x, 0.5, 0))- cols.append(c)- beam = trimesh.creation.box(extents=(1.0, 0.04, 0.1))- beam.apply_translation((0, 0.98, 0))- sc = trimesh.Scene()- sc.add_geometry(trimesh.util.concatenate([*cols, beam]), node_name="Frame", geom_name="Frame")- glb = tmp_path / "portal.glb"- sc.export(str(glb))-- m = judge_slices(glb, [], tmp_path / "out")- by_name = {s.name: s for s in m.slices}- assert not by_name["front_back"].rendered and "degenerate" in by_name["front_back"].reason- assert by_name["left_right"].rendered- assert not (tmp_path / "out" / "slice_front_back.png").is_file()---def test_judge_slices_manifest_round_trips_and_bad_glb_degrades(tmp_path: Path) -> None:- glb = _two_boxes(tmp_path / "boxes.glb")- out = tmp_path / "out"- m = judge_slices(glb, [("B", "A"), ("A", "A")], out, planes=("front_back",)) # self-pair ignored- assert m.error_pairs == [("A", "B")] and [s.name for s in m.slices] == ["front_back"]- stored = SliceManifest.model_validate_json((out / "manifest.json").read_text())- assert stored == m-- bad = judge_slices(tmp_path / "missing.glb", [], tmp_path / "bad")- assert bad.slices == [] and bad.errors and (tmp_path / "bad" / "manifest.json").is_file()# ===================================================================== D48 pixels, pinneddiff --git a/harness/tests/spatial_tools/test_silhouette.py b/harness/tests/spatial_tools/test_silhouette.pyindex c8f0a6ea..577e6f90 100644--- a/harness/tests/spatial_tools/test_silhouette.py+++ b/harness/tests/spatial_tools/test_silhouette.py@@ -2,7 +2,6 @@ from __future__ import annotationsfrom pathlib import Path-import pytestfrom PIL import Image, ImageDrawfrom codeverse3d.spatial.silhouette import compare_silhouette, foreground_mask@@ -26,33 +25,6 @@ def test_iou_ignores_framing_but_not_aspect(tmp_path: Path) -> None:assert r["aspect_ratio_err"] > 1.0 and r["iou"] < 0.8-def test_alpha_mask_and_enclosed_pockets(tmp_path: Path) -> None:- im = Image.new("RGBA", (200, 200), (0, 0, 0, 0))- d = ImageDraw.Draw(im)- d.rectangle([20, 20, 180, 180], fill=(200, 200, 200, 255))- d.rectangle([80, 80, 120, 120], fill=(0, 0, 0, 0)) # a hole- p = tmp_path / "alpha.png"- im.save(p)- m = foreground_mask(p)- assert m.sum() == pytest.approx(161 * 161 - 41 * 41, rel=0.01)- # opaque version: the pocket is enclosed → counted as foreground- im2 = Image.new("RGB", (200, 200), (255, 255, 255))- d2 = ImageDraw.Draw(im2)- d2.rectangle([20, 20, 180, 180], fill=(40, 40, 40))- d2.rectangle([80, 80, 120, 120], fill=(255, 255, 255))- p2 = tmp_path / "opaque.png"- im2.save(p2)- assert foreground_mask(p2).sum() == pytest.approx(161 * 161, rel=0.01)---def test_unreliable_when_empty(tmp_path: Path) -> None:- blank = tmp_path / "blank.png"- Image.new("RGB", (100, 100), (250, 250, 250)).save(blank)- a = _disc(tmp_path / "a.png", (100, 100), (20, 20, 80, 80))- r = compare_silhouette(blank, a)- assert r["iou"] == 0.0 and not r["reliable"]--def test_a_mask_that_fills_its_frame_is_failed_segmentation_but_a_tight_render_is_not(tmp_path: Path) -> None:"""Bbox cover > 0.98 is failed background segmentation; a tightly cropped render (~0.9) still passes."""import numpy as npdiff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.pyindex 41072e62..ebb15975 100644--- a/harness/tests/spatial_tools/test_tools.py+++ b/harness/tests/spatial_tools/test_tools.py@@ -2,20 +2,16 @@from __future__ import annotations-import jsonfrom pathlib import Pathfrom types import SimpleNamespaceimport pytest-from PIL import Image, ImageDrawimport codeverse3d.spatial.tools # noqa: F401 (registers all tools)from codeverse3d.contracts.artifacts import (BuildResult,GateFinding,GateReport,- RenderSet,- RenderView,Severity,)from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan@@ -32,14 +28,6 @@ def test_measure_tool(stool_ctx: ToolContext) -> None:assert not obs.ok and "Seat" in obs.text # didactic: lists available parts-def test_tools_without_glb(tmp_ws: Workspace) -> None:- ctx = ToolContext(workspace=tmp_ws, language="blender")- for name in ("measure", "check_connectivity", "cross_section", "render_views", "isolate"):- obs = get_tool(name).call(ctx, {"part": "x"} if name == "isolate" else {})- # a missing artefact IS a failure: the tool could not run at all- assert not obs.ok and obs.failed and "run `build` first" in obs.text, name--def test_connectivity_and_section_tools(stool_ctx: ToolContext) -> None:obs = get_tool("check_connectivity").call(stool_ctx, {})# the 5 mm gap is along GLB +y (up) → written in the Blender frame as +z, labelled@@ -53,7 +41,6 @@ def test_connectivity_and_section_tools(stool_ctx: ToolContext) -> None:assert not obs.ok and "x|y|z" in obs.text-# --------------------------------------------------------------------------- build with a fake runtimeclass _FakeRuntime:def __init__(self, *, lint_errors: bool = False, build_ok: bool = True, glb: Path | None = None, root: Path | None = None):self.lint_errors, self.build_ok, self.glb, self.root = lint_errors, build_ok, glb, root@@ -83,9 +70,10 @@ def _patch_runtime(monkeypatch: pytest.MonkeyPatch, rt: object) -> None:def test_a_negative_verdict_is_not_a_tool_failure(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:"""``ok`` is the verdict, ``failed`` is 'the tool could not run' (only that is an MCP error); FAIL leads the text."""- import codeverse3d.spatial.tools as ts-ws = stool_ctx.workspace+ _patch_runtime(monkeypatch, _FakeRuntime(glb=ws.artifacts / "object.glb")) # a build that works leads BUILD OK+ obs = get_tool("build").call(stool_ctx, {})+ assert obs.ok and obs.text.startswith("BUILD OK") and "Leg ×4" in obs.text and str(ws.root) not in obs.textws.write_json(ws.plan_path, _stool_plan_with_missing_backrest())for name, head in (("check_connectivity", "connectivity: FAIL"), ("check_contract", "contract: FAIL")):obs = get_tool(name).call(stool_ctx, {})@@ -95,133 +83,23 @@ def test_a_negative_verdict_is_not_a_tool_failure(stool_ctx: ToolContext, monkey# the other direction: a tool that could not run stays an errorobs = get_tool("measure").call(stool_ctx, {"parts": ["Nope"]}) # ToolUsageErrorassert not obs.ok and obs.failed and "Seat" in obs.text- def boom(*_a, **_k):- raise RuntimeError("boom")-- monkeypatch.setattr(ts, "measure_glb", boom)- obs = get_tool("measure").call(stool_ctx, {})- assert not obs.ok and obs.failed and "measure failed: RuntimeError: boom" in obs.text- monkeypatch.undo()-_patch_runtime(monkeypatch, _FakeRuntime(build_ok=False)) # code that will not runobs = get_tool("build").call(stool_ctx, {})assert not obs.ok and not obs.failed and obs.text.startswith("BUILD FAILED")- # the error leads, at a workspace-relative path, with a ≤ 30-line stderr tailassert obs.text.splitlines()[0].startswith("BUILD FAILED: NameError: name 'bpyx' is not defined at src/model.py:7")assert "l59" in obs.text and "l10" not in obs.textassert str(stool_ctx.workspace.root) not in obs.text and obs.numbers["error_line"] == 7- _patch_runtime(monkeypatch, _FakeRuntime(lint_errors=True))- obs = get_tool("build").call(stool_ctx, {})- assert not obs.ok and not obs.failed and obs.text.startswith("LINT FAILED")---def test_build_that_leaves_no_readable_glb_is_a_failure(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:- """Success with nothing measurable is a tool failure, and the headline must not read BUILD OK."""- _patch_runtime(monkeypatch, _FakeRuntime(glb=stool_ctx.workspace.artifacts / "gone.glb"))- obs = get_tool("build").call(stool_ctx, {})- assert not obs.ok and obs.failed- assert obs.text.startswith("BUILD PRODUCED NO USABLE GLB") and "GLB unreadable" in obs.text---def test_build_lint_fail_refuses_stale_glb(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:- """A lint refusal is the latest build status: the previous GLB is no longer readable as current."""- _patch_runtime(monkeypatch, _FakeRuntime(glb=stool_ctx.workspace.artifacts / "object.glb"))- obs = get_tool("build").call(stool_ctx, {})- assert obs.ok and obs.text.startswith("BUILD OK") and "Leg ×4" in obs.text- assert "lint warnings" in obs.text and "uses bpy.ops.render" in obs.text and "build warnings" in obs.text- assert str(stool_ctx.workspace.root) not in obs.text- assert (stool_ctx.workspace.artifacts / "measurement.json").is_file()- _patch_runtime(monkeypatch, _FakeRuntime(lint_errors=True))- obs = get_tool("build").call(stool_ctx, {})- assert not obs.ok and obs.text.startswith("LINT FAILED")- last = json.loads((stool_ctx.workspace.artifacts / "build.json").read_text())- assert last["ok"] is False and last["error_type"] == "LintError"- obs = get_tool("measure").call(stool_ctx, {})- assert not obs.ok and "build FAILED" in obs.text---def _fake_render_glb(glb, out_dir, *, views=None, mode="shaded", width=768, height=768, isolate=None, explode=0.0, sheet=True, background="studio", **_):- out_dir = Path(out_dir)- out_dir.mkdir(parents=True, exist_ok=True)- rviews = []- for v in views or []:- p = out_dir / f"view_{v.name}.png"- im = Image.new("RGB", (width, height), (255, 255, 255))- ImageDraw.Draw(im).rectangle([width // 4, height // 4, 3 * width // 4, 3 * height // 4], fill=(0, 0, 0))- im.save(p)- rviews.append(RenderView(name=v.name, path=str(p), mode=mode, width=width, height=height, camera_position=(1.0, 1.0, 1.0), fov=35))- sheet_p = None- if sheet:- sheet_p = out_dir / "sheet.png"- Image.new("RGB", (64, 64), (200, 200, 200)).save(sheet_p)- _fake_render_glb.calls += 1- return RenderSet(views=rviews, contact_sheet=str(sheet_p) if sheet_p else None, renderer="fake")---_fake_render_glb.calls = 0---def fake_renderer(monkeypatch: pytest.MonkeyPatch):- import codeverse3d.spatial.render as render-- _fake_render_glb.calls = 0- monkeypatch.setattr(render, "render_glb", _fake_render_glb)- return _fake_render_glb---def test_render_views_cached(stool_ctx: ToolContext, fake_renderer) -> None:- obs = get_tool("render_views").call(stool_ctx, {})- assert obs.ok and obs.images[0].endswith("sheet.png") and len(obs.images) == 5 # sheet + 4 views- assert obs.numbers["views"] == ["front_right_high", "back_left_high", "front", "top"]- assert "artifacts/tool_renders/r00_" in obs.text and str(stool_ctx.workspace.root) not in obs.text- again = get_tool("render_views").call(stool_ctx, {})- # same args → the same out_dir, where render_glb's own cache decides (this fake has none: two calls)- assert again.images == obs.images and fake_renderer.calls == 2- obs = get_tool("render_views").call(stool_ctx, {"views": ["front", "back", "left", "right", "top"]})- assert obs.ok and len(obs.images) == 1 # > 4 views → sheet only- obs = get_tool("render_views").call(stool_ctx, {"views": ["frontal"]})- assert not obs.ok and "front_right_high" in obs.text- obs = get_tool("render_views").call(stool_ctx, {"mode": "xray"})- assert not obs.ok and "shaded" in obs.text- # an unknown mode is a usage error with the mode list, not a RenderError from inside the rig- obs = get_tool("render_views").call(stool_ctx, {"mode": "depth"})- assert not obs.ok and "shaded" in obs.text and "failed" not in obs.text---def test_render_tool_with_no_view_is_a_tool_failure(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:- """A renderer that returns nothing is ``failed`` (an MCP error), not a result saying '0 view(s)'."""- import codeverse3d.spatial.render as render-- monkeypatch.setattr(render, "render_glb", lambda *a, **k: RenderSet(views=[], renderer="fake"))- for name, args in (("render_views", {}), ("render_sheet", {}), ("isolate", {"part": "Leg_3"})):- obs = get_tool(name).call(stool_ctx, args)- assert not obs.ok and obs.failed, name- assert obs.text.startswith("RENDER PRODUCED NO VIEWS"), namedef test_render_modes_match_the_js_rig() -> None:- """One mode tuple: contracts.RENDER_MODES ↔ runtime_js/render_glb.mjs MODES ↔ the arg schema."""+ """contracts.RENDER_MODES == runtime_js/render_glb.mjs MODES."""import refrom codeverse3d.config import get_settingsfrom codeverse3d.contracts.artifacts import RENDER_MODES- src = (get_settings().runtime_js_dir() / "render_glb.mjs").read_text()- m = re.search(r"const MODES = \[([^\]]*)\]", src)+ m = re.search(r"const MODES = \[([^\]]*)\]", (get_settings().runtime_js_dir() / "render_glb.mjs").read_text())assert m and tuple(re.findall(r"'([a-z]+)'", m.group(1))) == RENDER_MODES- assert "depth" not in RENDER_MODES- for name in ("render_views", "render_sheet"):- assert get_tool(name).schema()["properties"]["mode"]["description"] == " | ".join(RENDER_MODES)---def test_render_sheet_and_isolate(stool_ctx: ToolContext, fake_renderer) -> None:- obs = get_tool("render_sheet").call(stool_ctx, {"mode": "wire"})- assert obs.ok and len(obs.images) == 1 and obs.numbers["n_views"] == 14- obs = get_tool("isolate").call(stool_ctx, {"part": "Leg_3"})- assert obs.ok and obs.numbers["part"] == "Leg_3" and "| Leg_3 |" in obs.text- obs = get_tool("isolate").call(stool_ctx, {"part": "Nope"})- assert not obs.ok and "Leg_3" in obs.textdef test_scene_tools_with_fake_siblings(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:@@ -237,67 +115,26 @@ def test_scene_tools_with_fake_siblings(stool_ctx: ToolContext, monkeypatch: pytdef fake_probe_scene(ws, **kw):return SceneProbeResult(gate=failed, census={"meshes": 12, "lights": 2}, ok=True, findings=["[error] src/scene.js: console: boom"])- # shader_probe reports the BUILD's probe + preflight (one boot), never a driver of its ownmonkeypatch.setattr(ts, "run_probe", lambda ws, **kw: (GateReport.of("scene_probe"), shaders, {}))obs = get_tool("shader_probe").call(stool_ctx, {})- assert not obs.ok and not obs.failed and "vUv" in obs.text and "declare varying" in obs.text- assert obs.text.startswith("shader probe: FAIL") # a shader that will not compile is a verdict- # a scene that never booted has no preflight: the probe's report says why- skipped = GateReport(gate="shader_preflight", passed=False)- boot = GateReport.of("scene_probe", [GateFinding(gate="scene_probe", severity=Severity.ERROR, target="src/scene.js",- message="[import] SyntaxError: Unexpected token")])- monkeypatch.setattr(ts, "run_probe", lambda ws, **kw: (boot, skipped, {}))- obs = get_tool("shader_probe").call(stool_ctx, {})- assert not obs.ok and not obs.failed and "SyntaxError" in obs.text- # the driver died: the tool could not run- died = GateReport.of("scene_probe", [GateFinding(gate="scene_probe", severity=Severity.ERROR, target="src/scene.js",- message="scene probe could not run: timeout", data={"harness_failure": True})])- monkeypatch.setattr(ts, "run_probe", lambda ws, **kw: (died, skipped, {}))- obs = get_tool("shader_probe").call(stool_ctx, {})- assert obs.failed and "could not run" in obs.text- # scene_probe probes through the workspace language's SceneRuntime (D101)+ assert not obs.ok and not obs.failed and obs.text.startswith("shader probe: FAIL") and "declare varying" in obs.textscene_ctx = ToolContext(workspace=stool_ctx.workspace, language="scene_threejs", track="scene")- _patch_runtime(monkeypatch, SimpleNamespace(probe=fake_probe_scene))+ _patch_runtime(monkeypatch, SimpleNamespace(probe=fake_probe_scene)) # D101: via the language's SceneRuntimeobs = get_tool("scene_probe").call(scene_ctx, {})- # ok = the gate verdict; failed = the probe TOOL could not run. The gate fails on- # agent-fixable findings here, so the observation is a FAIL, not a tool error- assert not obs.ok and not obs.failed- assert obs.text.startswith("scene probe: FAIL")- assert "meshes=12" in obs.text and "boom" in obs.text and obs.numbers["census"]["meshes"] == 12- _patch_runtime(monkeypatch, SimpleNamespace(probe=lambda ws, **kw: SceneProbeResult(gate=failed, errors=["driver died"], ok=False)))- obs = get_tool("scene_probe").call(scene_ctx, {})- assert not obs.ok and obs.failed and "driver died" in obs.text+ assert not obs.ok and not obs.failed and obs.text.startswith("scene probe: FAIL")+ assert "meshes=12" in obs.text and obs.numbers["census"]["meshes"] == 12obs = get_tool("joint_sweep").call(stool_ctx, {})assert not obs.ok and obs.failed and "run `build`" in obs.text # no robot.urdf in a static workspace-# --------------------------------------------------------------------------- build without a GLB (scene / graphics)-class _NoGlbRuntime(_FakeRuntime):- """Build succeeds with glb_path=None (scene_threejs / graphics runtimes)."""+class _GlRuntime:+ """A graphics build: ok, no GLB (the gl tools pass times / preview / size kwargs)."""- def __init__(self, language: str, census: dict, extra_paths: dict | None = None):- super().__init__()- self.language, self.census, self.extra_paths = language, census, extra_paths or {}+ def __init__(self, language: str, census: dict, extra_paths: dict):+ self.language, self.census, self.extra_paths = language, census, extra_paths- def build(self, ws, *, timeout_s=None):- return BuildResult(ok=True, language=self.language, glb_path=None, duration_ms=9,- census=self.census, extra_paths=self.extra_paths)---def test_build_tool_scene_reports_probe_census(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:- ctx = ToolContext(workspace=tmp_ws, language="scene_threejs", track="scene")- rt = _NoGlbRuntime("scene_threejs", {"meshes": 12, "lights": 2, "fps": 58.0},- {"scene_probe": str(tmp_ws.artifacts / "scene_probe.json")})- _patch_runtime(monkeypatch, rt)- obs = get_tool("build").call(ctx, {})- assert obs.ok, obs.text- assert "no GLB path" not in obs.text- assert "scene probe census" in obs.text and "meshes=12" in obs.text- assert obs.numbers["census"]["fps"] == 58.0---class _GlRuntime(_NoGlbRuntime):- """Graphics runtime whose build takes the gl tools' kwargs (times / preview / size)."""+ def lint(self, ws):+ return GateReport(gate="lint", passed=True, findings=[])def build(self, ws, **_kw):return BuildResult(ok=True, language=self.language, glb_path=None, duration_ms=9,@@ -318,21 +155,12 @@ def test_gl_tools_lead_with_the_frame_gate_verdict(tmp_ws: Workspace, monkeypatcreturn FrameStat(time=t, path=path, mean_lum=0.4, std_lum=0.2, pct_black=0.01, pct_blown=0.01,colourfulness=0.3, edge_density=0.05)- # a passing gate: a graphics build (no GLB) reports its frames and sheet- two = SequenceStats(frames=[_frame(0.0, "f0.png"), _frame(1.0, "f1.png")], mean_diff=0.1)- monkeypatch.setattr(gl_build, "read_metrics", lambda ws: (two, GateReport(gate="gl_frames", passed=True)))- obs = get_tool("build").call(ctx, {})- assert obs.ok, obs.text- assert "no GLB path" not in obs.text and "frames=2" in obs.text and "sheet:" in obs.text- assert obs.numbers["n_frames"] == 2 and obs.numbers["gate_errors"] == 0-stats = SequenceStats(frames=[_frame(0.0, "f0.png")], mean_diff=0.0)bad = GateReport(gate="gl_frames", passed=False, findings=[GateFinding(gate="gl_frames", severity=Severity.ERROR, message="static image", data={"kind": "static"},fix_hint="animate with u_time")])monkeypatch.setattr(gl_build, "read_metrics", lambda ws: (stats, bad))- for name, args, ok_headline in (("build", {}, "BUILD OK"), ("gl_probe", {}, "PROBE OK"),- ("gl_frames", {"times": [0.0, 1.0]}, "FRAMES OK")):+ for name, args, ok_headline in (("build", {}, "BUILD OK"), ("gl_frames", {"times": [0.0, 1.0]}, "FRAMES OK")):obs = get_tool(name).call(ctx, args)assert not obs.ok and not obs.failed, nameassert obs.text.splitlines()[0].startswith("FRAME GATE: FAIL — 1 error(s)"), (name, obs.text)@@ -364,7 +192,6 @@ def test_gl_frames_renders_the_judged_times_by_default(tmp_ws: Workspace, monkeyassert seen == [[0.0, 0.5, 1.0, 1.5, 2.0]], obs.text-# --------------------------------------------------------------------------- the gate tools on a stooldef _stool_plan_with_missing_backrest() -> StaticPlan:return StaticPlan(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.4, 0.4, 0.45)),parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),@@ -390,14 +217,9 @@ class _SceneRuntime:return res[email protected]("language", ["scene_blender", "scene_threejs"])-def test_a_session_build_reports_an_unlit_env_above_build_ok(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,- language: str) -> None:- """D112 review: ``unlit`` is an ERROR so the ROUND's build fails and its repair gets the env — but an- asset or zone session building while the env is still the placeholder cannot write the env module, and- a BUILD FAILED it cannot clear would spend its window. Its own ``build`` states the error above BUILD- OK; any other ERROR beside it is still a BUILD FAILED."""- ctx = ToolContext(workspace=Workspace(tmp_path / "ws").create(), language=language, track="scene")+def test_a_session_build_reports_an_unlit_env_above_build_ok(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """D112: a session build whose only ERROR is the unlit env leads with SCENE UNLIT above BUILD OK; any other ERROR is BUILD FAILED."""+ ctx = ToolContext(workspace=Workspace(tmp_path / "ws").create(), language="scene_blender", track="scene")unlit = GateFinding(gate="scene_probe", severity=Severity.ERROR, target="src/env.py", data={"kind": "unlit"},message="scene has no lamps and no world: it renders black")_patch_runtime(monkeypatch, _SceneRuntime([unlit]))diff --git a/harness/tests/spatial_tools/test_tools_cli.py b/harness/tests/spatial_tools/test_tools_cli.pyindex b998b147..49ef6800 100644--- a/harness/tests/spatial_tools/test_tools_cli.py+++ b/harness/tests/spatial_tools/test_tools_cli.py@@ -2,30 +2,9 @@from __future__ import annotations-import json-from typer.testing import CliRunner-from codeverse3d.cli._common import console, print_observation-from codeverse3d.spatial.registry import Observation, ToolContext---def _panel_title(obs: Observation) -> str:- with console.capture() as cap:- print_observation(obs, as_json=False)- return cap.get().splitlines()[0]---def test_print_observation_shows_three_states() -> None:- """ok / FAIL / error in the panel title — the split the MCP server reports as ``is_error``."""- assert "ok" in _panel_title(Observation(ok=True, text="fine"))- assert "FAIL" in _panel_title(Observation(ok=False, text="connectivity: FAIL — 1 error(s)"))- assert "error" in _panel_title(Observation(ok=False, failed=True, text="measure: no GLB"))- # --json-out carries both flags, so a script does not have to parse the panel- with console.capture() as cap:- print_observation(Observation(ok=False, text="connectivity: FAIL"), as_json=True)- data = json.loads(cap.get())- assert data["ok"] is False and data["failed"] is False+from codeverse3d.spatial.registry import ToolContextdef test_cli_exit_code_follows_the_verdict_not_the_failure(stool_ctx: ToolContext) -> None:diff --git a/harness/tests/texturing/__init__.py b/harness/tests/texturing/__init__.pydeleted file mode 100644index e69de29b..00000000diff --git a/harness/tests/threejs_render/conftest.py b/harness/tests/threejs_render/conftest.pyindex 7c0803c0..d8c68b27 100644--- a/harness/tests/threejs_render/conftest.py+++ b/harness/tests/threejs_render/conftest.py@@ -14,11 +14,8 @@ import * as THREE from 'three';import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';export function buildSeat(THREE_) {const g = new THREE.Group(); g.name = 'Seat';- const mesh = new THREE.Mesh(new RoundedBoxGeometry(0.34, 0.04, 0.34, 3, 0.01),- new THREE.MeshStandardMaterial({ color: 0x8b5a2b, roughness: 0.6 }));- mesh.name = 'SeatTop';- mesh.position.set(0, 0.43, 0);- g.add(mesh);+ const mesh = new THREE.Mesh(new RoundedBoxGeometry(0.34, 0.04, 0.34, 3, 0.01), new THREE.MeshStandardMaterial({ color: 0x8b5a2b }));+ mesh.name = 'SeatTop'; mesh.position.set(0, 0.43, 0); g.add(mesh);return g;}"""@@ -27,7 +24,7 @@ LEGS_JS = """\import * as THREE from 'three';export function buildLegs(THREE_) {const g = new THREE.Group(); g.name = 'Legs';- const mat = new THREE.MeshStandardMaterial({ color: 0x333333, roughness: 0.4, metalness: 0.6 });+ const mat = new THREE.MeshStandardMaterial({ color: 0x333333 });const geo = new THREE.CylinderGeometry(0.015, 0.018, 0.41, 16);const off = 0.13;for (const [x, z] of [[-off, -off], [off, -off], [-off, off], [off, off]]) {@@ -40,32 +37,13 @@ export function buildLegs(THREE_) {}"""-STRETCHERS_JS = """\-import * as THREE from 'three';-export function buildStretchers(THREE_) {- const g = new THREE.Group(); g.name = 'Stretchers';- const mat = new THREE.MeshStandardMaterial({ color: 0x333333, roughness: 0.4, metalness: 0.6 });- const geo = new THREE.CylinderGeometry(0.008, 0.008, 0.26, 12);- for (let i = 0; i < 4; i++) {- const m = new THREE.Mesh(geo, mat);- m.name = `Stretcher_${i}`;- const a = (i * Math.PI) / 2;- m.position.set(0.13 * Math.cos(a), 0.15, 0.13 * Math.sin(a));- m.rotateY(-a); m.rotateX(Math.PI / 2);- g.add(m);- }- return g;-}-"""-OBJECT_JS = """\import * as THREE from 'three';import { buildSeat } from './parts/seat.js';import { buildLegs } from './parts/legs.js';-import { buildStretchers } from './parts/stretchers.js';export function build(THREE_) {const root = new THREE.Group(); root.name = 'Stool';- root.add(buildSeat(THREE), buildLegs(THREE), buildStretchers(THREE));+ root.add(buildSeat(THREE), buildLegs(THREE));root.userData.tick = (t, dt) => { root.rotation.y = t * 0.2; };return root;}@@ -75,7 +53,6 @@ STOOL_FILES = {"src/object.js": OBJECT_JS,"src/parts/seat.js": SEAT_JS,"src/parts/legs.js": LEGS_JS,- "src/parts/stretchers.js": STRETCHERS_JS,}@@ -95,7 +72,7 @@ def stool_ws(tmp_path: Path) -> Workspace:@pytest.fixture(scope="session")def stool_build(tmp_path_factory: pytest.TempPathFactory):- """Build the stool once per session (needs node); skipped when node is missing."""+ """Build the stool once per session (needs node)."""if shutil.which("node") is None:pytest.skip("node not available")from codeverse3d.languages.threejs import ThreeJsRuntimediff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.pyindex 573c3338..f8cd29ba 100644--- a/harness/tests/threejs_render/test_build.py+++ b/harness/tests/threejs_render/test_build.py@@ -23,27 +23,19 @@ def _glb_json(glb: str) -> dict:def test_build_stool_glb_and_census(stool_build, stool_ws: Workspace):res = stool_build # the session's one stool build- assert Path(res.glb_path).is_file() and Path(res.glb_path).stat().st_size > 1000- assert (Path(res.glb_path).parent / "build.json").is_file()+ assert Path(res.glb_path).is_file() and (Path(res.glb_path).parent / "build.json").is_file()c = res.census # what only the export knows; the object itself is measured off the GLBassert set(c) == {"placement_offset", "instanced_meshes_baked", "selfcheck_ran", "tick_present","unnamed_meshes", "warnings", "glb_bytes", "three_revision"}- assert c["three_revision"] == "182"- assert c["tick_present"] is True- assert c["placement_offset"] is None- assert c["instanced_meshes_baked"] == 0 and c["selfcheck_ran"] is False- assert c["unnamed_meshes"] == 0+ assert c["three_revision"] == "182" and c["tick_present"] is True and c["placement_offset"] is None+ assert c["instanced_meshes_baked"] == 0 and c["selfcheck_ran"] is False and c["unnamed_meshes"] == 0m = measure_glb(res.glb_path)- assert sorted(p.name for p in m.parts) == ["Legs", "Seat", "Stretchers"] and m.tri_count > 500- assert len(_glb_json(res.glb_path)["materials"]) == 3 # seat + legs + stretchers (distinct objects)- # the GLB carries named nodes per part and the bbox matches the authored sizes- scene = trimesh.load(res.glb_path, force="scene")- names = set(scene.graph.nodes)- assert {"Stool", "Seat", "Legs", "Stretchers", "Leg_LB", "Leg_RF"} <= names- assert len(scene.graph.nodes_geometry) == 9- lo, hi = scene.bounds- assert np.allclose(lo, [-0.17, 0.0, -0.17], atol=2e-3)- assert np.allclose(hi, [0.17, 0.45, 0.17], atol=2e-3)+ assert sorted(p.name for p in m.parts) == ["Legs", "Seat"] and m.tri_count > 500+ assert len(_glb_json(res.glb_path)["materials"]) == 2+ scene = trimesh.load(res.glb_path, force="scene") # named nodes per part; bbox matches the authored sizes+ assert {"Stool", "Seat", "Legs", "Leg_LB", "Leg_RF"} <= set(scene.graph.nodes)+ assert len(scene.graph.nodes_geometry) == 5+ assert np.allclose(scene.bounds, [[-0.17, 0.0, -0.17], [0.17, 0.45, 0.17]], atol=2e-3)# no entry module: the shared typed failure, before any node boot, and the GLB is wiped(stool_ws.src / "object.js").unlink()res = ThreeJsRuntime().build(stool_ws)@@ -52,7 +44,7 @@ def test_build_stool_glb_and_census(stool_build, stool_ws: Workspace):@pytest.mark.parametrize("path, find, repl, etype, line", [("parts/legs.js", "const off = 0.13;", "const off = undefinedThing();", "ReferenceError", 6),- ("parts/seat.js", None, "\nlet = 1;\n", "SyntaxError", 13),+ ("parts/seat.js", None, "\nlet = 1;\n", "SyntaxError", 10),])def test_build_error_maps_to_file_line(stool_ws: Workspace, path, find, repl, etype, line):p = stool_ws.src / path@@ -60,25 +52,17 @@ def test_build_error_maps_to_file_line(stool_ws: Workspace, path, find, repl, etres = ThreeJsRuntime().build(stool_ws)assert not res.ok and res.error_type == etypeassert res.error_file == f"src/{path}" and res.error_line == line- assert not (stool_ws.artifacts / "object.glb").exists()- assert (stool_ws.artifacts / "export_error.json").is_file()- assert json.loads((stool_ws.artifacts / "build.json").read_text())["ok"] is False+ assert not (stool_ws.artifacts / "object.glb").exists() and (stool_ws.artifacts / "export_error.json").is_file()[email protected]("source, message", [- ("import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name='Empty'; return g; }\n",- "no meshes"),- ("export const x = 1;\n", "export function build"),-])-def test_build_contract_errors(stool_ws: Workspace, source, message):- (stool_ws.src / "object.js").write_text(source)+def test_build_contract_errors(stool_ws: Workspace):+ (stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name='Empty'; return g; }\n")res = ThreeJsRuntime().build(stool_ws)- assert not res.ok and res.error_type == "ContractError" and message in res.error_message+ assert not res.ok and res.error_type == "ContractError" and "no meshes" in res.error_messagedef test_build_keeps_source_placement_and_warns(stool_ws: Workspace):- """Law 7: an off-ground / off-centre object is exported as authored, with a warning.- (Same build: an exported selfcheck that passes is run and recorded.)"""+ """Law 7: an off-ground / off-centre object is exported as authored, with a warning; a passing selfcheck is recorded."""p = stool_ws.src / "object.js"p.write_text(p.read_text().replace("return root;", "root.position.set(0.5, 0.2, 0); return root;")+ "export function selfcheck(THREE_, root) { return true; }\n")@@ -92,62 +76,33 @@ def test_build_keeps_source_placement_and_warns(stool_ws: Workspace):assert abs(lo[1] - 0.2) < 2e-3 and abs(lo[0] - 0.33) < 2e-3-def test_build_seeds_math_random(stool_ws: Workspace):- """Audit 2026-09-24 N23: export_glb neither seeded nor warned on `Math.random`, so the round's- re-build measured a different object than the agent's build. Seeded like the Python wrappers."""- p = stool_ws.src / "object.js"- p.write_text(p.read_text().replace("return root;", "root.position.x = Math.random() * 0.1; return root;"))- offsets = [ThreeJsRuntime().build(stool_ws).census["placement_offset"][0] for _ in range(2)]- assert offsets[0] == offsets[1] and offsets[0] < 0--[email protected]("bare_root", [False, True])-def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace, bare_root: bool):- """InstancedMesh is baked (trimesh ignores EXT_mesh_gpu_instancing) into SIBLING meshes- ``Posts_0..9``, so the contract gate counts them as the plan's ×10 instances (audit- 2026-09-24 N2: a wrapper Group ``Posts`` was one part, "found 1 instance(s)" + a bbox ERROR)."""+def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace):+ """InstancedMesh is baked (trimesh ignores EXT_mesh_gpu_instancing) into SIBLING meshes ``Posts_0..9``,+ so the contract gate counts them as the plan's x10 instances (a wrapper Group was one part)."""from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan- from codeverse3d.spatial.connectivity import check_connectivityfrom codeverse3d.spatial.contract import check_contract- posts = (" const mat = new THREE.MeshStandardMaterial({ color: 0x885533 });\n"- " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05, 1, 2, 1), mat, 10); posts.name = 'Posts';\n"- " const m = new THREE.Matrix4();\n"- " for (let i = 0; i < 10; i++) { m.makeTranslation(-2.25 + i * 0.5, 0.5, 0); posts.setMatrixAt(i, m); posts.setColorAt(i, new THREE.Color(i % 2 ? 0xff0000 : 0x00ff00)); }\n"- " posts.instanceMatrix.needsUpdate = true;\n")- if bare_root:- body = posts + " return posts; }\n"- else:- body = (" const g = new THREE.Group(); g.name = 'Fence';\n" + posts + " g.add(posts);\n"- " const rail = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.05, 0.03, 2, 1, 1), mat); rail.name = 'Rail'; rail.position.set(0, 1.025, 0); g.add(rail);\n"- " return g; }\n")+ body = (" const mat = new THREE.MeshStandardMaterial({ color: 0x885533 });\n"+ " const g = new THREE.Group(); g.name = 'Fence';\n"+ " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05, 1, 2, 1), mat, 10); posts.name = 'Posts';\n"+ " const m = new THREE.Matrix4();\n"+ " for (let i = 0; i < 10; i++) { m.makeTranslation(-2.25 + i * 0.5, 0.5, 0); posts.setMatrixAt(i, m); posts.setColorAt(i, new THREE.Color(i % 2 ? 0xff0000 : 0x00ff00)); }\n"+ " g.add(posts);\n"+ " return g; }\n")(stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function build(T) {\n" + body)res = ThreeJsRuntime().build(stool_ws)assert res.ok, res.error_messageassert res.census["instanced_meshes_baked"] == 1header = _glb_json(res.glb_path)assert "EXT_mesh_gpu_instancing" not in (header.get("extensionsUsed") or [])- assert len(header["materials"]) == (2 if bare_root else 3) # (base +) two instance colours- names = [f"Posts_{i}" for i in range(10)] + ([] if bare_root else ["Rail"])m = measure_glb(res.glb_path)- assert sorted(p.name for p in m.parts) == sorted(names)- assert m.tri_count == 20 * len(names) and abs(m.ground_gap_m) < 1e-3 # 2-segment boxes: 20 triangles each+ assert sorted(p.name for p in m.parts) == sorted(f"Posts_{i}" for i in range(10))+ assert m.tri_count == 200 and abs(m.ground_gap_m) < 1e-3 # 2-segment boxes: 20 triangles eachp9 = next(p for p in m.parts if p.name == "Posts_9")- assert np.allclose(p9.bbox_min, [2.225, 0.0, -0.025], atol=1e-3)- assert np.allclose(p9.bbox_max, [2.275, 1.0, 0.025], atol=1e-3)- parts = [PartPlan(name="Posts", role="r", description="d", instances=10,- bbox=BBox(center=(0, 0.5, 0), extents=(0.05, 1.0, 0.05)))]- if not bare_root:- parts.append(PartPlan(name="Rail", role="r", description="d",- bbox=BBox(center=(0, 1.025, 0), extents=(4.6, 0.05, 0.03))))- plan = StaticPlan(object_name="Fence", summary="s", overall_bbox=BBox(center=(0, 0.525, 0), extents=(4.6, 1.05, 0.05)),- parts=parts)- # the boxes are segmented (20 triangles), so they are not the skeleton's 12-triangle placeholder- # (D110; a bare box exactly at its plan box is pinned in test_placeholder_gate)- assert [f.message for f in check_contract(m, plan, language="threejs").findings- if f.severity.value != "info"] == []- if not bare_root:- assert check_connectivity(res.glb_path).passed+ assert np.allclose(p9.bbox_min, [2.225, 0.0, -0.025], atol=1e-3) and np.allclose(p9.bbox_max, [2.275, 1.0, 0.025], atol=1e-3)+ parts = [PartPlan(name="Posts", role="r", description="d", instances=10, bbox=BBox(center=(0, 0.5, 0), extents=(0.05, 1.0, 0.05)))]+ plan = StaticPlan(object_name="Fence", summary="s", overall_bbox=BBox(center=(0, 0.5, 0), extents=(4.6, 1.0, 0.05)), parts=parts)+ assert [f.message for f in check_contract(m, plan, language="threejs").findings if f.severity.value != "info"] == []def test_build_nan_geometry_names_mesh_part_and_file(stool_ws: Workspace):@@ -164,6 +119,15 @@ def test_build_nan_geometry_names_mesh_part_and_file(stool_ws: Workspace):assert rec["error"]["part"] == "Legs"+def test_build_seeds_math_random(stool_ws: Workspace):+ """Audit 2026-09-24 N23: export_glb neither seeded nor warned on `Math.random`, so the round's+ re-build measured a different object than the agent's build. Seeded like the Python wrappers."""+ p = stool_ws.src / "object.js"+ p.write_text(p.read_text().replace("return root;", "root.position.x = Math.random() * 0.1; return root;"))+ offsets = [ThreeJsRuntime().build(stool_ws).census["placement_offset"][0] for _ in range(2)]+ assert offsets[0] == offsets[1] and offsets[0] < 0++def test_build_failing_selfcheck_is_a_typed_error(stool_ws: Workspace):p = stool_ws.src / "object.js"src = p.read_text()@@ -172,4 +136,4 @@ def test_build_failing_selfcheck_is_a_typed_error(stool_ws: Workspace):res = ThreeJsRuntime().build(stool_ws)assert not res.ok and res.error_type == "SelfCheckError"assert res.error_message.startswith("selfcheck(THREE, root) threw: too short: 0.45")- assert res.error_file == "src/object.js" and res.error_line == 13+ assert res.error_file == "src/object.js" and res.error_line == src.count("\n") + 3 # the `throw` linediff --git a/harness/tests/threejs_render/test_camera_fit.py b/harness/tests/threejs_render/test_camera_fit.pydeleted file mode 100644index 333e6a0e..00000000--- a/harness/tests/threejs_render/test_camera_fit.py+++ /dev/null@@ -1,63 +0,0 @@-"""The object rig's camera fit fills exactly `fill` of the frame for every canonical view."""--from __future__ import annotations--import json--import pytest--from codeverse3d.conventions import OBJECT_VIEWS-from codeverse3d.spatial.node import run_node, runtime_js_dir--pytestmark = pytest.mark.node--VIEWS = [{"name": v.name, "azimuth": v.azimuth_deg, "elevation": v.elevation_deg} for v in OBJECT_VIEWS]-BOXES = [- [[-0.17, 0.0, -0.17], [0.17, 0.47, 0.17]], # stool: tall-ish, centred- [[-1.2, 0.0, -0.3], [1.2, 0.9, 0.3]], # bench: wide and shallow- [[0.4, 0.4, 0.4], [0.6, 3.0, 0.5]], # tall, thin and OFF-CENTRE (the old loop diverged here)-]---def _fit_report(tmp_path) -> list[dict]:- script = tmp_path / "fit.mjs"- script.write_text(f"""-import * as THREE from 'three';-import {{ fitCameraToBox, viewDirection }} from {json.dumps(str(runtime_js_dir() / 'lib/browser/camera_fit.js'))};-const views = {json.dumps(VIEWS)}, boxes = {json.dumps(BOXES)};-const rows = [];-for (const [bi, [mn, mx]] of boxes.entries()) {{- const box = new THREE.Box3(new THREE.Vector3(...mn), new THREE.Vector3(...mx));- for (const v of views) {{- for (const aspect of [1, 16 / 9]) {{- const cam = new THREE.PerspectiveCamera(35, aspect, 0.01, 100);- const fit = fitCameraToBox(cam, box, v.azimuth, v.elevation, {{ fill: 0.85 }});- let maxExt = 0;- for (const x of [mn[0], mx[0]]) for (const y of [mn[1], mx[1]]) for (const z of [mn[2], mx[2]]) {{- const n = new THREE.Vector3(x, y, z).project(cam);- maxExt = Math.max(maxExt, Math.abs(n.x), Math.abs(n.y));- }}- const centre = box.getCenter(new THREE.Vector3());- rows.push({{ box: bi, name: v.name, aspect, distance: fit.distance, max_ndc: maxExt,- inside: box.containsPoint(cam.position), near: cam.near, far: cam.far,- look_at: fit.lookAt, centre: centre.toArray() }});- }}- }}-}}-const dir = viewDirection(0, 0).toArray();-console.log(JSON.stringify({{ rows, front_dir: dir }}));-""")- return run_node(script, [], three_hook=True, timeout_s=60).last_json---def test_every_canonical_view_frames_the_box_exactly(tmp_path):- report = _fit_report(tmp_path)- # azimuth 0 = +Z (conventions.py) — the shared orbitDirection, not a second copy- assert report["front_dir"] == pytest.approx([0.0, 0.0, 1.0], abs=1e-12)- assert len(report["rows"]) == len(OBJECT_VIEWS) * len(BOXES) * 2- for r in report["rows"]:- where = f"{r['name']} box={r['box']} aspect={r['aspect']:.2f}"- assert r["max_ndc"] == pytest.approx(0.85, abs=1e-6), where # exact frustum fit- assert r["distance"] > 0 and not r["inside"], where # never lands inside the object- assert 0 < r["near"] < r["far"], where- assert r["look_at"] == pytest.approx(r["centre"], abs=1e-9), wherediff --git a/harness/tests/threejs_render/test_cli_flush.py b/harness/tests/threejs_render/test_cli_flush.pydeleted file mode 100644index 3d94e165..00000000--- a/harness/tests/threejs_render/test_cli_flush.py+++ /dev/null@@ -1,33 +0,0 @@-"""A driver's summary survives a pipe larger than the 8 KiB buffer (finish() used to exit before flushing)."""--from __future__ import annotations--import json--import pytest--from codeverse3d.spatial.node import run_node, runtime_js_dir-from tests.scene_runtime.conftest import needs_node--pytestmark = [pytest.mark.node, needs_node]--#: comfortably past the 8 KiB pipe buffer that used to truncate-PAYLOAD_BYTES = 64 * 1024---def _driver(tmp_path, n: int, code: int):- p = tmp_path / "d.mjs"- p.write_text(f"""-import {{ finish }} from {json.dumps(str(runtime_js_dir() / 'lib' / 'cli.mjs'))};-finish({{ ok: true, blob: 'x'.repeat({n}), tail: 'LAST' }}, {code});-""")- return p--[email protected]("code", [0, 1])-def test_a_large_summary_survives_the_pipe(tmp_path, code: int):- res = run_node(_driver(tmp_path, PAYLOAD_BYTES, code), [], timeout_s=60, check=False)- assert res.rc == code- assert res.last_json is not None, "the summary was truncated mid-JSON"- assert res.last_json["tail"] == "LAST" and len(res.last_json["blob"]) == PAYLOAD_BYTES-diff --git a/harness/tests/threejs_render/test_lint.py b/harness/tests/threejs_render/test_lint.pyindex eeb65d60..4527313c 100644--- a/harness/tests/threejs_render/test_lint.py+++ b/harness/tests/threejs_render/test_lint.py@@ -23,14 +23,6 @@ def _msgs(rep, sev=None):return [f.message for f in rep.findings if sev is None or f.severity == sev]-def test_missing_object_js(tmp_path: Path, no_node_syntax):- ws = Workspace(tmp_path)- (ws.src / "parts").mkdir(parents=True)- rep = lint_workspace(ws)- assert not rep.passed- assert any("object.js is missing" in m for m in _msgs(rep, Severity.ERROR))--def test_forbidden_apis_and_imports(stool_ws: Workspace, no_node_syntax):(stool_ws.src / "parts" / "legs.js").write_text("import * as THREE from 'three';\nimport x from 'https://cdn.example.com/x.js';\nimport y from 'lodash';\n"@@ -44,31 +36,37 @@ def test_forbidden_apis_and_imports(stool_ws: Workspace, no_node_syntax):assert any("URL 'https://cdn.example.com/x.js'" in m for m in errs)assert any("package 'lodash'" in m for m in errs)assert any("does not exist: './nope.js'" in m for m in errs)- assert any("fetch" in m and "legs.js:7" in m for m in errs)- assert any("document" in m and "legs.js:7" in m for m in errs)- assert any("renderers" in m and "legs.js:8" in m for m in errs)- assert any("cameras" in m for m in _msgs(rep, Severity.WARN))- # comment/string mentions must not trigger- assert not any("legs.js:5" in m or "legs.js:6" in m for m in errs)+ assert any("fetch" in m and "legs.js:7" in m for m in errs) and any("renderers" in m and "legs.js:8" in m for m in errs)+ assert not any("legs.js:5" in m or "legs.js:6" in m for m in errs) # comment/string mentions do not triggerdef test_part_export_name_dead_file_and_build_export(stool_ws: Workspace, no_node_syntax):(stool_ws.src / "parts" / "extra.js").write_text("import * as THREE from 'three';\nexport function buildWrong(THREE_) { return new THREE.Group(); }\n")- # the plan's ``TVStand`` lives in tv_stand.js and exports buildTVStand (to_pascal keeps- # it); the lint must not ask for the snake-rebuilt ``buildTvStand`` instead- (stool_ws.src / "parts" / "tv_stand.js").write_text(- "import * as THREE from 'three';\nexport function buildTVStand(THREE_) { return new THREE.Group(); }\n")rep = lint_workspace(stool_ws)- warns = _msgs(rep, Severity.WARN)- assert any("expected `export function buildExtra(THREE)`" in m for m in warns)+ assert any("expected `export function buildExtra(THREE)`" in m for m in _msgs(rep, Severity.WARN))assert any("not imported by any module" in f.message and f.data["kind"] == "part_not_imported" for f in rep.findings)- assert not any("tv_stand.js: expected" in m for m in _msgs(rep))- (stool_ws.src / "parts" / "extra.js").write_text("export const nothing = 1;\n")- rep = lint_workspace(stool_ws)- assert any("buildExtra" in m for m in _msgs(rep, Severity.ERROR))(stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function make() {}\n")+ assert any("must `export function build(THREE)`" in m for m in _msgs(lint_workspace(stool_ws), 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 any("must `export function build(THREE)`" in m for m in _msgs(rep, Severity.ERROR))+ 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+++def test_missing_object_js(tmp_path: Path, no_node_syntax):+ ws = Workspace(tmp_path)+ (ws.src / "parts").mkdir(parents=True)+ rep = lint_workspace(ws)+ assert not rep.passed+ assert any("object.js is missing" in m for m in _msgs(rep, Severity.ERROR))def test_plan_parts_missing_are_warned(stool_ws: Workspace, no_node_syntax):@@ -84,19 +82,9 @@ def test_plan_parts_missing_are_warned(stool_ws: Workspace, no_node_syntax):@pytest.mark.nodedef test_syntax_error_reported_with_line(stool_ws: Workspace):p = stool_ws.src / "parts" / "seat.js"- p.write_text(p.read_text() + "\nconst = 5;\n")+ text = p.read_text()+ p.write_text(text + "\nconst = 5;\n")+ line = text.count("\n") + 2 # the appended statement's line, whatever the skeleton's lengthrep = 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+ assert any(f"seat.js:{line}" in m and "SyntaxError" in m for m in _msgs(rep, Severity.ERROR))diff --git a/harness/tests/threejs_render/test_node.py b/harness/tests/threejs_render/test_node.pyindex ad99f701..7cf90e37 100644--- a/harness/tests/threejs_render/test_node.py+++ b/harness/tests/threejs_render/test_node.py@@ -6,19 +6,7 @@ from pathlib import Pathimport pytest-from codeverse3d.spatial.node import NodeError, parse_last_json, run_node---def test_parse_last_json_picks_last_object():- out = 'noise\n{"a": 1}\nmore noise\n{"ok": true, "n": 2}\n[1,2]\n'- assert parse_last_json(out) == {"ok": True, "n": 2}- assert parse_last_json("nothing here") is None- assert parse_last_json('{"broken": \n') is None---def test_missing_script_raises(tmp_path: Path):- with pytest.raises(NodeError):- run_node(tmp_path / "nope.mjs", [], timeout_s=5)+from codeverse3d.spatial.node import run_node@pytest.mark.nodediff --git a/harness/tests/threejs_render/test_render.py b/harness/tests/threejs_render/test_render.pyindex 3f5f94d1..2a169ded 100644--- a/harness/tests/threejs_render/test_render.py+++ b/harness/tests/threejs_render/test_render.py@@ -9,20 +9,7 @@ import pytestfrom PIL import Imagefrom codeverse3d.conventions import OBJECT_VIEWS_QUICK, ViewPreset-from codeverse3d.spatial.render import RenderError, render_glb---def test_render_glb_offline_validation(tmp_path: Path):- with pytest.raises(RenderError):- render_glb(tmp_path / "missing.glb", tmp_path / "out")- fake = tmp_path / "x.glb"- fake.write_bytes(b"glTF" + b"\0" * 16)- with pytest.raises(RenderError, match="mode"):- render_glb(fake, tmp_path / "out", mode="xray")- with pytest.raises(RenderError, match="background"):- render_glb(fake, tmp_path / "out", background="blue")- with pytest.raises(RenderError, match="no views"):- render_glb(fake, tmp_path / "out", views=[])+from codeverse3d.spatial.render import render_glb@pytest.mark.node@@ -33,12 +20,8 @@ def test_render_views_modes_isolate_and_cache(stool_glb: Path, tmp_path: Path):assert rs.renderer and rs.contact_sheet and Path(rs.contact_sheet).is_file()for v in rs.views:assert Path(v.path).is_file() and v.mode == "shaded" and v.camera_position is not None and v.fov == 35- with Image.open(v.path) as im:- assert im.size == (256, 256)- meta = json.loads((out / "views.json").read_text())- assert meta["ok"] and len(meta["views"]) == 4- # the front view: camera on +Z, looking at the bbox centre- front = next(v for v in rs.views if v.name == "front")+ assert json.loads((out / "views.json").read_text())["ok"]+ front = next(v for v in rs.views if v.name == "front") # camera on +Zassert front.camera_position[2] > 0.5 and abs(front.camera_position[0]) < 1e-6# cached re-render lands in a new directory without calling nodeout2 = tmp_path / "shaded2"@@ -56,11 +39,3 @@ def test_render_views_modes_isolate_and_cache(stool_glb: Path, tmp_path: Path):assert dark > 300 and light > 3000assert mid < 0.08 * len(px), f"silhouette is not separable: {mid} mid-tone px of {len(px)}"assert sil.contact_sheet is None-- iso = render_glb(stool_glb, tmp_path / "iso", views=[ViewPreset("front", 0, 8)], isolate=["Legs"], width=128, height=128, sheet=False)- assert Path(iso.views[0].path).is_file()- with pytest.raises(RenderError, match="isolate hid everything|nothing visible"):- render_glb(stool_glb, tmp_path / "iso_bad", views=[ViewPreset("front", 0, 8)], isolate=["NotAPart"], width=64, height=64, sheet=False)-- ex = render_glb(stool_glb, tmp_path / "explode", views=[ViewPreset("front", 0, 8)], explode=0.5, mode="clay", width=128, height=128, sheet=False)- assert Path(ex.views[0].path).is_file()diff --git a/harness/tests/threejs_render/test_render_retry.py b/harness/tests/threejs_render/test_render_retry.pyindex d6c8e8d8..6ec15edc 100644--- a/harness/tests/threejs_render/test_render_retry.py+++ b/harness/tests/threejs_render/test_render_retry.py@@ -2,8 +2,6 @@from __future__ import annotations-from pathlib import Path-import pytestimport codeverse3d.spatial.render as R@@ -21,12 +19,6 @@ def _isolated_cache(tmp_path, monkeypatch):get_settings.cache_clear()-def _glb(tmp_path: Path) -> Path:- p = tmp_path / "x.glb"- p.write_bytes(b"glTF")- return p--# verbatim from a real run where Chrome reaped the render tabDETACHED = "render_glb failed: Attempted to use detached Frame '10276B428E350BFA074A02AF37D52E6C'."@@ -37,24 +29,17 @@ def test_retry_policy(tmp_path, monkeypatch):def fake(glb, out_dir, params, *, gpu, timeout_s, own_browser=False):calls.append((timeout_s, own_browser))- if len(calls) == 1 or fail_with[0].startswith("render_glb failed: Cannot"):+ if len(calls) == 1:raise RenderError(fail_with[0])return {"views": [], "renderer": "fake", "duration_ms": 1}monkeypatch.setattr(R, "_run_render", fake)- glb = _glb(tmp_path)- # a transient failure is retried once with twice the time on the shared browser:- # a slow box is not a reason to give up browser reuse+ glb = tmp_path / "x.glb"+ glb.write_bytes(b"glTF")+ # a transient failure is retried once with twice the time on the shared browserfail_with[:] = ["render_glb failed: node script render_glb.mjs exited 1: Waiting failed: 30000 ms exceeded"]rs = render_glb(glb, tmp_path / "out", use_cache=False, timeout_s=100)assert rs.renderer == "fake" and calls == [(100, False), (200, False)]- # a real failure is not retried- calls.clear()- fail_with[:] = ["render_glb failed: Cannot find module 'puppeteer'"]- with pytest.raises(RenderError):- render_glb(glb, tmp_path / "out", use_cache=False, timeout_s=100)- assert calls == [(100, False)]- # a lost browser is retried on a browser of our owncalls.clear()fail_with[:] = [DETACHED]rs = render_glb(glb, tmp_path / "out", use_cache=False, timeout_s=100)diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.pyindex 7a20c791..7c352914 100644--- a/harness/tests/threejs_render/test_runtime_js.py+++ b/harness/tests/threejs_render/test_runtime_js.py@@ -3,12 +3,11 @@from __future__ import annotationsimport json-import shutilfrom pathlib import Pathimport pytest-from codeverse3d.spatial.node import NodeError, run_node, runtime_js_dir+from codeverse3d.spatial.node import run_node, runtime_js_dirfrom codeverse3d.workspace import Workspacepytestmark = pytest.mark.node@@ -21,8 +20,6 @@ def test_serve_and_importmap(tmp_path: Path):root = tmp_path / "root"root.mkdir()(root / "a.glb").write_bytes(b"glTF1234")- (root / "sub").mkdir()- (root / "sub" / "b.json").write_text("{}")(root / "ok.txt").write_text("fine")(tmp_path / "secret.txt").write_text("s3cr3t")(root / "inside.txt").symlink_to(root / "ok.txt")@@ -31,12 +28,11 @@ def test_serve_and_importmap(tmp_path: Path):script.write_text(f"""const {{ serveDirs, importMapHtml }} = require({json.dumps(str(runtime_js_dir() / 'serve.cjs'))});(async () => {{- const srv = await serveDirs({{ root: {json.dumps(str(root))}, routes: {{ '/__p.html': {{ body: '<html>hi</html>' }} }} }});+ const srv = await serveDirs({{ root: {json.dumps(str(root))}, routes: {{}} }});const get = async (p) => {{ const r = await fetch(srv.url(p)); return {{ status: r.status, type: r.headers.get('content-type'), len: (await r.arrayBuffer()).byteLength }}; }};const out = {{- glb: await get('/a.glb'), json: await get('/sub/b.json'), page: await get('/__p.html'),- three: await get('/__runtime/node_modules/three/build/three.module.js'),- escape: await get('/../s.cjs'), missing: await get('/nope.png'), fav: await get('/favicon.ico'),+ glb: await get('/a.glb'), three: await get('/__runtime/node_modules/three/build/three.module.js'),+ escape: await get('/../s.cjs'), missing: await get('/nope.png'),malformed: await get('/100%.png'), after: await get('/a.glb'), // decodeURIComponent throws on '%.p'importmap: importMapHtml(),links: {{ ok: (await get('/ok.txt')).status, inside: (await get('/inside.txt')).status,@@ -48,46 +44,14 @@ const {{ serveDirs, importMapHtml }} = require({json.dumps(str(runtime_js_dir()""")out = run_node(script, [], timeout_s=60).last_jsonassert out["glb"] == {"status": 200, "type": "model/gltf-binary", "len": 8}- assert out["json"]["type"] == "application/json"- assert out["page"]["status"] == 200 and "text/html" in out["page"]["type"]- assert out["three"]["status"] == 200 and out["three"]["len"] > 100000 and out["three"]["type"] == "text/javascript"- assert out["escape"]["status"] == 404 and out["missing"]["status"] == 404 and out["fav"]["status"] == 204+ assert out["three"]["status"] == 200 and out["three"]["type"] == "text/javascript"+ assert out["escape"]["status"] == 404 and out["missing"]["status"] == 404assert out["malformed"]["status"] == 404 and out["after"]["status"] == 200 # the server survived itim = json.loads(out["importmap"].split(">", 1)[1].rsplit("<", 1)[0])["imports"]- assert im["three"].startswith("/__runtime/") and im["three/addons/"].endswith("/examples/jsm/")- assert "http" not in json.dumps(im)+ assert im["three"].startswith("/__runtime/") and "http" not in json.dumps(im)assert out["links"] == {"ok": 200, "inside": 200, "leak": 404, "dirleak": 404}-def test_two_runtime_trees_never_share_one_browser_endpoint(tmp_path: Path):- """The browser endpoint name carries the runtime_js tree, so two trees share one cache dir safely."""- cache = tmp_path / "cache"- paths = []- for tree in ("worktree", "checkout"):- d = tmp_path / tree- d.mkdir()- shutil.copy(runtime_js_dir() / "gpu_launch.cjs", d / "gpu_launch.cjs")- script = tmp_path / f"{tree}.cjs"- script.write_text(f"""-const {{ _internal }} = require({json.dumps(str(d / 'gpu_launch.cjs'))});-console.log(JSON.stringify({{- endpoint: _internal.endpointPath('cpu'),- lock: _internal.spawnLockPath('cpu'),- failed: _internal.daemonFailPath('cpu'),-}}));-""")- paths.append(run_node(script, [], timeout_s=60, env_extra={"C3D_CACHE_DIR": str(cache)}).last_json)-- a, b = paths- for key in ("endpoint", "lock", "failed"):- assert a[key] != b[key], f"both trees would advertise into the same {key}"- # the separation must be the NAME: one cache dir is still one cache dir- assert Path(a[key]).parent == Path(b[key]) .parent == cache- # the reaper and the daemon-failure skip both key off these shapes- assert Path(a["endpoint"]).name.startswith("browser_cpu_")- assert a["failed"].endswith(".failed.json")--def _reap_daemons(cache_dir: Path) -> None:"""Kill any shared browser advertised under an ephemeral test cache dir."""import contextlib@@ -95,13 +59,11 @@ def _reap_daemons(cache_dir: Path) -> None:import signalfor ep in cache_dir.glob("browser_*.json"):- if ep.name.endswith(".failed.json"):- continue- info = json.loads(ep.read_text())for key in ("pid", "daemon_pid"):- if info.get(key):+ pid = json.loads(ep.read_text()).get(key) if not ep.name.endswith(".failed.json") else None+ if pid:with contextlib.suppress(OSError):- os.kill(int(info[key]), signal.SIGTERM)+ os.kill(int(pid), signal.SIGTERM)def test_gpu_launch_probe_and_browser_reuse(tmp_path: Path):@@ -135,50 +97,11 @@ const {{ launchBrowser, rendererInfo }} = require({json.dumps(str(runtime_js_dirassert off["gpu"] is False and "swiftshader" in off["probe"].lower()assert off["a_shared"] is True and off["b_shared"] is True and off["alive"]assert off["reconnect_ms"] < 1000 # connect, not a fresh ~550ms+ launch- # the endpoint is keyed by the runtime_js that spawned the daemon, so a worktree- # and the main checkout sharing one cache dir cannot advertise over each other- endpoints = list((tmp_path / "cache").glob("browser_cpu_*.json"))- assert len(endpoints) == 1 and not endpoints[0].name.endswith(".failed.json")own = run_node(script, [], timeout_s=120, env_extra={**env, "T_GPU": "off", "C3D_BROWSER_REUSE": "off"}).last_jsonassert own["a_shared"] is False and own["b_shared"] is False- with pytest.raises(NodeError):- run_node(script, [], timeout_s=60, env_extra={**env, "T_GPU": "bogus"})_reap_daemons(tmp_path / "cache")-def test_a_rejected_shared_browser_is_never_superseded(tmp_path: Path):- """A caller whose canary rejects the shared browser launches its own and leaves- the advertised one alone. It used to spawn a second daemon, whose advertisement- superseded the first; the superseded daemon then closed its browser under its- clients' pages — "Target closed" across a loaded test suite (2026-09-23)."""- script = tmp_path / "r.cjs"- script.write_text(f"""-const fs = require('fs');-const {{ launchBrowser, _internal }} = require({json.dumps(str(runtime_js_dir() / 'gpu_launch.cjs'))});-(async () => {{- const a = await launchBrowser({{ gpu: 'off' }});- const before = _internal.readJson(_internal.endpointPath('cpu')).ws;- const pages = [];- for (let i = 0; i < 13; i++) pages.push(await a.browser.newPage()); // over the canary's page budget- const b = await launchBrowser({{ gpu: 'off' }});- await new Promise((r) => setTimeout(r, 1500)); // a spawned daemon would have advertised by now- const after = _internal.readJson(_internal.endpointPath('cpu'));- const out = {{ a_shared: a.shared, b_shared: b.shared, same: !!after && after.ws === before }};- await b.release();- for (const p of pages) await p.close();- await a.release();- console.log(JSON.stringify(out));-}})().catch((e) => {{ console.error(e); process.exit(1); }});-""")- cache = tmp_path / "cache"- try:- out = run_node(script, [], timeout_s=120, env_extra={"C3D_CACHE_DIR": str(cache)}).last_json- finally:- _reap_daemons(cache)- assert out["a_shared"] is True and out["b_shared"] is False- assert out["same"], "the rejecting caller replaced the advertised browser"--def test_scene_server_only_mounts_src_public_assets(tmp_path: Path):"""Scene code must not read the run's spec, state, git or judge output."""ws = Workspace(tmp_path / "run").create()@@ -204,17 +127,3 @@ console.log(JSON.stringify(out));out = run_node(script, [], timeout_s=60).last_jsonassert [out[p] for p in serve] == [200] * len(serve), outassert [out[p] for p in denied] == [404] * len(denied), out---def test_cli_safe_name_rejects_path_tricks(tmp_path: Path):- """lib/cli.mjs safeName guards every filename composed from a camera/view name."""- script = tmp_path / "n.mjs"- cli = (runtime_js_dir() / "lib" / "cli.mjs").as_uri()- script.write_text(f"""-const {{ safeName }} = await import({json.dumps(cli)});-const rejects = (v) => {{ try {{ safeName(v); return false; }} catch {{ return true; }} }};-const bad = ['x/../y', '/abs', 'a\\\\b', 'a b', 'a.png', '', 'x'.repeat(200)];-console.log(JSON.stringify({{ ok: true, good: safeName('cam_a-1'), all_rejected: bad.every(rejects) }}));-""")- out = run_node(script, [], timeout_s=30).last_json- assert out == {"ok": True, "good": "cam_a-1", "all_rejected": True}diff --git a/harness/tests/threejs_render/test_sheet.py b/harness/tests/threejs_render/test_sheet.pydeleted file mode 100644index 94e7ecf7..00000000--- a/harness/tests/threejs_render/test_sheet.py+++ /dev/null@@ -1,32 +0,0 @@-"""contact_sheet: layout, labels, missing tiles, determinism."""--from __future__ import annotations--from pathlib import Path--import pytest-from PIL import Image--from codeverse3d.spatial.sheet import LABEL_H, PAD, contact_sheet---def _png(path: Path, color, size=(120, 80)):- Image.new("RGB", size, color).save(path)- return path---def test_sheet_layout_labels_missing_tile_and_empty(tmp_path: Path):- imgs = [(f"v{i}", _png(tmp_path / f"{i}.png", (i * 40, 100, 200))) for i in range(5)]- out = contact_sheet(imgs, tmp_path / "sheet.png", cols=3, tile=100)- with Image.open(out) as im:- assert im.size == (3 * (100 + PAD) + PAD, 2 * (100 + LABEL_H + PAD) + PAD)- # label strip under the first tile is dark- assert im.getpixel((PAD + 2, PAD + 100 + 2))[0] < 60- # the first tile centre carries the first image colour (letterboxed)- assert im.getpixel((PAD + 50, PAD + 50)) == (0, 100, 200)- # a missing image is a grey tile, not a crash- out = contact_sheet([("ok", _png(tmp_path / "a.png", (10, 200, 10))), ("gone", tmp_path / "missing.png")], tmp_path / "s.png", cols=2, tile=64)- with Image.open(out) as im:- assert im.getpixel((PAD + 64 + PAD + 40, PAD + 40)) == (200, 200, 200)- with pytest.raises(ValueError):- contact_sheet([], tmp_path / "s.png")diff --git a/harness/tests/threejs_render/test_skeleton.py b/harness/tests/threejs_render/test_skeleton.pydeleted file mode 100644index a4a5ace4..00000000--- a/harness/tests/threejs_render/test_skeleton.py+++ /dev/null@@ -1,52 +0,0 @@-"""Skeleton generation from a StaticPlan."""--from __future__ import annotations--from pathlib import Path--import pytest--from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan-from codeverse3d.languages.threejs import write_skeleton-from codeverse3d.workspace import Workspace---def _plan() -> StaticPlan:- return StaticPlan(- object_name="bar stool", summary="s", overall_bbox=BBox(center=(0, 0.35, 0), extents=(0.4, 0.7, 0.4)),- parts=[- PartPlan(name="Seat Cushion", role="seat", description="round seat", bbox=BBox(center=(0, 0.68, 0), extents=(0.36, 0.04, 0.36)), material="leather"),- PartPlan(name="LegFrame", role="legs", description="four legs", bbox=BBox(center=(0, 0.33, 0), extents=(0.34, 0.66, 0.34)), attach_to="Seat Cushion"),- ],- )---def test_skeleton_files_and_contents(tmp_path: Path):- ws = Workspace(tmp_path / "ws")- written = write_skeleton(ws, _plan())- rel = sorted(str(p.relative_to(ws.root)) for p in written)- assert rel == ["src/object.js", "src/package.json", "src/parts/leg_frame.js", "src/parts/seat_cushion.js"]- obj = (ws.src / "object.js").read_text()- assert "export function build(THREE_)" in obj- assert "import { buildSeatCushion } from './parts/seat_cushion.js';" in obj- assert "root.name = 'BarStool';" in obj- seat = (ws.src / "parts" / "seat_cushion.js").read_text()- assert "export function buildSeatCushion(THREE_)" in seat- assert "group.name = 'SeatCushion';" in seat- # the stub is a plain box at the plan bbox plus the measured requirements — no recipe to copy- # (D106's rule for every track, 2026-10-15): nothing in it says what the part should be made of- assert "new THREE.BoxGeometry(size[0], size[1], size[2])" in seat- assert "mesh.position.set(0, 0.68, 0);" in seat- for recipe in ("RoundedBoxGeometry", "ExtrudeGeometry", "LatheGeometry", "Copyable", "roughness", "tick"):- assert recipe not in seat, recipe- assert "max(10 mm, 10 % of the plan extent)" in seat and "gap <= 2 mm" in seat- assert "Material: leather" in seat- assert "userData.tick is recorded by the census but never called" in obj- assert '"type": "module"' in (ws.src / "package.json").read_text()- # never overwrites- (ws.src / "parts" / "seat_cushion.js").write_text("// mine\n")- again = write_skeleton(ws, _plan())- assert again == []- assert (ws.src / "parts" / "seat_cushion.js").read_text() == "// mine\n"- with pytest.raises(TypeError):- write_skeleton(Workspace(tmp_path), object()) # type: ignore[arg-type]diff --git a/harness/tests/threejs_render/test_stale_outputs.py b/harness/tests/threejs_render/test_stale_outputs.pyindex 2d82730a..7566b99d 100644--- a/harness/tests/threejs_render/test_stale_outputs.py+++ b/harness/tests/threejs_render/test_stale_outputs.py@@ -2,28 +2,19 @@from __future__ import annotations-import json-import pytestimport codeverse3d.languages.threejs as rt_modfrom codeverse3d.languages.threejs import ThreeJsRuntime-from codeverse3d.spatial.node import NodeError, NodeResult+from codeverse3d.spatial.node import NodeErrorfrom codeverse3d.workspace import Workspace-def _ws_with_stale(tmp_path) -> Workspace:+def test_no_stale_outputs_survive_a_node_failure(tmp_path, monkeypatch):ws = Workspace(tmp_path / "run").create()(ws.src / "object.js").write_text("export function build() {}\n")- (ws.artifacts / "object.glb").write_bytes(b"stale glb")- ws.write_json(ws.artifacts / "build.json", {"ok": True})- ws.write_json(ws.artifacts / "census.json", {"tri_count": 3})- (ws.artifacts / "export_error.json").write_text("{}")- return ws---def test_no_stale_outputs_survive_a_node_failure(tmp_path, monkeypatch):- ws = _ws_with_stale(tmp_path / "missing")+ for name in ("build.json", "object.glb", "census.json", "export_error.json"):+ (ws.artifacts / name).write_text("{}")def no_node(*a, **k):raise NodeError("node binary not found", None) # harness problem → re-raised@@ -33,16 +24,3 @@ def test_no_stale_outputs_survive_a_node_failure(tmp_path, monkeypatch):ThreeJsRuntime().build(ws)for name in ("build.json", "object.glb", "census.json", "export_error.json"):assert not (ws.artifacts / name).exists(), name-- # a node failure WITH a result writes a failed build.json- ws = _ws_with_stale(tmp_path / "timeout")-- def timeout(*a, **k):- raise NodeError("timed out", NodeResult(rc=-9, stdout="", stderr="killed",- last_json=None, duration_ms=5, timed_out=True))-- monkeypatch.setattr(rt_mod, "run_node", timeout)- res = ThreeJsRuntime().build(ws)- assert not res.ok and res.error_type == "BuildTimeout"- assert not (ws.artifacts / "object.glb").exists()- assert json.loads((ws.artifacts / "build.json").read_text())["ok"] is Falsediff --git a/harness/tests/threejs_render/test_studio_rig.py b/harness/tests/threejs_render/test_studio_rig.pyindex 71ee4d4d..39ab5589 100644--- a/harness/tests/threejs_render/test_studio_rig.py+++ b/harness/tests/threejs_render/test_studio_rig.py@@ -1,5 +1,4 @@-"""The object studio rig: every look-changing file is in the cache signature, and renders are reproducible."""-+"""The object studio rig: renders are reproducible and the backdrop is a sweep, not a flat fill."""from __future__ import annotationsimport json@@ -10,47 +9,8 @@ import pytestfrom PIL import Imagefrom codeverse3d.conventions import OBJECT_VIEWS_QUICK-from codeverse3d.spatial import render as render_mod-from codeverse3d.spatial.node import runtime_js_dirfrom codeverse3d.spatial.render import render_glb-#: the page-side modules that decide what a frame LOOKS like (host plumbing —-#: lib/cli.mjs, lib/host_env.mjs, lib/host_page.mjs — deliberately stays out: it-#: cannot change a pixel, and hashing it would drop the cache on unrelated edits)-PAGE_RIG = ("lib/browser/render_rig.js", "lib/browser/studio.js", "lib/browser/studio_env.js",- "lib/browser/renderer.js", "lib/browser/camera_fit.js", "lib/orbit.mjs")---def test_rig_signature_covers_every_file_that_can_change_the_look():- rt = runtime_js_dir().resolve()- entry = "lib/browser/render_rig.js"- reachable = {entry}- frontier = [entry]- while frontier:- rel = frontier.pop()- here = (rt / rel).parent- for token in (rt / rel).read_text().split("'"):- if not token.endswith((".js", ".mjs")) or token.startswith(("http", "three")):- continue- if token.startswith("."):- target = (here / token).resolve()- elif "/__runtime/" in token:- target = (rt / token.split("/__runtime/", 1)[1]).resolve()- else:- continue- if not target.is_file() or rt not in target.parents:- continue- found = target.relative_to(rt).as_posix()- if found not in reachable:- reachable.add(found)- frontier.append(found)- signed = set(render_mod.RIG_FILES)- missing = sorted(reachable - signed)- assert not missing, f"add these to spatial/render.py::RIG_FILES: {missing}"- assert set(PAGE_RIG) <= signed and "render_glb.mjs" in signed- sig = render_mod._rig_signature()- assert len(sig) == 12 and sig != "d41d8cd98f00"-@pytest.mark.nodedef test_studio_render_is_reproducible_and_stamps_the_rig_version(stool_glb: Path, tmp_path: Path):@@ -75,29 +35,3 @@ def test_studio_render_is_reproducible_and_stamps_the_rig_version(stool_glb: Patpytest.skip(f"different GL backends between runs ({a.renderer} vs {b.renderer})")for va, vb in zip(a.views, b.views, strict=True):assert Path(va.path).read_bytes() == Path(vb.path).read_bytes(), f"{va.name} is not reproducible"--[email protected] # renders through the node studio rig-def test_orbit_views_share_one_camera_distance(stool_glb: Path, tmp_path: Path):- """D47: one camera distance per elevation ring; the 10 % pullback cap bounds the spread."""- from codeverse3d.conventions import OBJECT_VIEWS-- render_glb(stool_glb, tmp_path / "o", views=OBJECT_VIEWS, width=192, height=192,- sheet=False, use_cache=False)- meta = json.loads((tmp_path / "o" / "views.json").read_text())- band, steep = [], []- rings: dict[float, list[float]] = {}- for v in meta["views"]:- d = float(np.linalg.norm(np.array(v["camera_position"]) - np.array(v["look_at"])))- if abs(v["elevation"]) > 60:- steep.append(d)- else:- band.append(d)- rings.setdefault(abs(float(v["elevation"])), []).append(d)- assert len(band) >= 4 and len(rings) >= 2- for el, ds in rings.items():- assert max(ds) / min(ds) <= 1.0 + 1e-6, f"ring |el|={el} not uniform: {sorted(ds)}"- # the pullback cap bounds how far rings can drift apart; 1.25 is slack over the- # stool's measured 1.14 (eye ring vs the ±30° rings), a real regression is far larger- assert max(band) / min(band) <= 1.25 + 1e-6, f"orbit distances spread too far: {sorted(band)}"- assert steep, "OBJECT_VIEWS should still contain a plan view that fits itself"diff --git a/harness/tests/urdf_joints/conftest.py b/harness/tests/urdf_joints/conftest.pyindex 0dd08844..67b4c74c 100644--- a/harness/tests/urdf_joints/conftest.py+++ b/harness/tests/urdf_joints/conftest.py@@ -4,7 +4,6 @@ from __future__ import annotationsfrom pathlib import Path-import numpy as npimport pytestimport trimesh@@ -71,64 +70,3 @@ def cabinet_plan() -> ArticulatedPlan:JointPlan(name="handle_mount", type="fixed", parent="Door", child="Handle", axis=(0, 0, 1), pivot=(0.2, -0.24, 0.4)),],)---def drawer_plan() -> ArticulatedPlan:- return ArticulatedPlan(- object_name="Nightstand", summary="nightstand with a drawer",- overall_bbox=BBox(center=(0, 0, 0.3), extents=(0.5, 0.5, 0.6)), root_link="Carcass",- parts=[- PartPlan(name="Carcass", role="body", description="box", bbox=BBox(center=(0, 0.025, 0.3), extents=(0.5, 0.45, 0.6))),- PartPlan(name="Drawer", role="drawer", description="front panel (placeholder)", bbox=BBox(center=(0, -0.21, 0.45), extents=(0.44, 0.02, 0.2))),- ],- joints=[JointPlan(name="slide", type="prismatic", parent="Carcass", child="Drawer", axis=(0, -1, 0),- pivot=(0, -0.21, 0.45), lower=0.0, upper=0.3, motion="slides out the front")],- )---def _panel(lo, hi) -> trimesh.Trimesh:- lo, hi = np.asarray(lo, dtype=float), np.asarray(hi, dtype=float)- m = trimesh.creation.box(hi - lo)- m.apply_translation((lo + hi) / 2)- return m---def agent_style_mesh(panels: list[tuple[tuple[float, float, float], tuple[float, float, float]]]) -> trimesh.Trimesh:- """What agent-built links look like after the wrapper join: touching panels that- share vertices (→ the merged mesh is NOT watertight) with inverted winding."""- m = trimesh.util.concatenate([_panel(lo, hi) for lo, hi in panels])- m.invert()- m.merge_vertices()- return m---def write_carcass_drawer_robot(root: Path, *, drawer_shift_x: float = 0.0) -> tuple[Path, Path]:- """Cabinet carcass (5 panels, 30 mm sides) + open-top drawer, both agent-style meshes- (world coordinates, like the wrapper writes). ``drawer_shift_x`` slides the drawer- sideways: +0.032 drives it 30 mm through the right side panel."""- meshes = root / "meshes"- meshes.mkdir(parents=True, exist_ok=True)- carcass = agent_style_mesh([- ((-0.23, -0.18, 0.08), (-0.2, 0.21, 0.58)), ((0.2, -0.18, 0.08), (0.23, 0.21, 0.58)),- ((-0.23, -0.21, 0.58), (0.23, 0.21, 0.6)), ((-0.2, -0.18, 0.08), (0.2, 0.2, 0.092)),- ((-0.2, 0.2, 0.08), (0.2, 0.21, 0.58)),- ])- drawer = agent_style_mesh([- ((-0.198, -0.19, 0.445), (0.198, -0.172, 0.565)), ((-0.18, -0.17, 0.445), (0.18, 0.15, 0.455)),- ((-0.18, -0.17, 0.455), (-0.17, 0.15, 0.555)), ((0.17, -0.17, 0.455), (0.18, 0.15, 0.555)),- ((-0.17, 0.14, 0.455), (0.17, 0.15, 0.555)),- ])- assert not carcass.is_watertight and carcass.volume < 0 and not drawer.is_watertight and drawer.volume < 0- (meshes / "Carcass.glb").write_bytes(carcass.export(file_type="glb"))- (meshes / "Drawer.glb").write_bytes(drawer.export(file_type="glb"))- # drawer link frame at its front-bottom centre (world 0 -0.19 0.445); visual origin = -frame (+ shift)- urdf = root / "robot.urdf"- urdf.write_text(f"""<robot name="cabinet">-<link name="Carcass"><visual><origin xyz="0 0 0"/><geometry><mesh filename="meshes/Carcass.glb"/></geometry></visual></link>-<link name="Drawer"><visual><origin xyz="{drawer_shift_x} 0.19 -0.445"/><geometry><mesh filename="meshes/Drawer.glb"/></geometry></visual></link>-<joint name="slide" type="prismatic"><parent link="Carcass"/><child link="Drawer"/>- <origin xyz="0 -0.19 0.445"/><axis xyz="0 -1 0"/><limit lower="0" upper="0.3" effort="10" velocity="1"/></joint>-</robot>-""")- return urdf, meshesdiff --git a/harness/tests/urdf_joints/test_axis_repair.py b/harness/tests/urdf_joints/test_axis_repair.pyindex 847fdd05..e0cc7396 100644--- a/harness/tests/urdf_joints/test_axis_repair.py+++ b/harness/tests/urdf_joints/test_axis_repair.py@@ -3,8 +3,6 @@ from __future__ import annotationsimport xml.etree.ElementTree as ET-import pytest-from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse3d.tracks.articulated_object import MOTION_GATE, repair_motion_axesfrom codeverse3d.workspace import Workspace@@ -68,52 +66,3 @@ def test_repair_skips_what_it_cannot_trust_then_fixes_both_kinds(tmp_path):# the artifacts copy is kept in stepassert (ws.artifacts / "robot.urdf").read_text() == (ws.src / "robot.urdf").read_text()-[email protected]("raw", ["0", "off", "false"])-def test_kill_switch_disables(tmp_path, switch, raw):- """Every off spelling disables it (only "0" used to be read)."""- switch("C3D_AXIS_REPAIR", raw)- ws = _ws(tmp_path)- assert repair_motion_axes(ws, _report(_finding("Hinge", cos=-1.0))) == []- assert _axis_of(ws, "Hinge") == (0.0, 0.0, -1.0)---def test_a_paired_axis_tag_keeps_the_joints_limit():- """The splice of a paired <axis></axis> used to eat the joint's <limit/>."""- from codeverse3d.tracks.articulated_object import _set_axis_in_urdf_text-- for axis_form in ('<axis xyz="1 0 0"></axis>', '<axis xyz="1 0 0"/>'):- urdf = ('<robot name="r"><joint name="h" type="revolute">\n'- '<parent link="a"/><child link="b"/>\n' + axis_form + '\n'- '<limit lower="0" upper="1.57" effort="10" velocity="1"/>\n</joint></robot>')- out = _set_axis_in_urdf_text(urdf, "h", (0.0, 0.0, 1.0))- assert out is not None and '<axis xyz="0 0 1"/>' in out- assert "<limit" in out, f"the splice ate the limit for {axis_form!r}"---def test_suggested_axis_is_expressed_in_the_joint_frame(tmp_path):- """A rotated joint origin: installing the suggestion must actually fix the motion."""- import numpy as np-- from codeverse3d.spatial.joints_model import load_urdf- from codeverse3d.spatial.joints_sweep import motion_direction_check-- urdf = tmp_path / "r.urdf"- urdf.write_text(- '<robot name="r">\n'- ' <link name="base"><visual><geometry><box size="0.2 0.2 0.2"/></geometry></visual>\n'- ' <collision><geometry><box size="0.2 0.2 0.2"/></geometry></collision></link>\n'- ' <link name="door"><visual><origin xyz="0.3 0 0"/><geometry><box size="0.6 0.05 0.4"/></geometry></visual>\n'- ' <collision><origin xyz="0.3 0 0"/><geometry><box size="0.6 0.05 0.4"/></geometry></collision></link>\n'- ' <joint name="hinge" type="revolute">\n'- ' <parent link="base"/><child link="door"/>\n'- ' <origin xyz="0.1 0 0" rpy="0 0 1.5708"/>\n'- ' <axis xyz="1 0 0"/>\n'- ' <limit lower="0" upper="1.57" effort="10" velocity="1"/>\n'- ' </joint>\n</robot>')- robot = load_urdf(urdf, load_meshes=True)- chk = motion_direction_check(robot, "hinge", "up")- assert not chk.ok and chk.suggested_axis is not None- robot.joints["hinge"].axis = np.asarray(chk.suggested_axis, dtype=float)- after = motion_direction_check(robot, "hinge", "up")- assert after.ok and after.cos > 0.9, "installing the suggestion must actually fix the motion"diff --git a/harness/tests/urdf_joints/test_export.py b/harness/tests/urdf_joints/test_export.pyindex a03f2ec9..d8c59d40 100644--- a/harness/tests/urdf_joints/test_export.py+++ b/harness/tests/urdf_joints/test_export.py@@ -29,35 +29,36 @@ def test_urdf_to_glb_hierarchy_and_extras(tmp_path):names = {n["name"]: n for n in js["nodes"]}assert {"cab", "body", "door", "handle"} <= set(names)assert "joint" in names["door"]["extras"] and names["door"]["extras"]["joint"]["type"] == "revolute"- assert "extras" not in names["body"] or "joint" not in names["body"].get("extras", {})- scene_extras = js["scenes"][0]["extras"]- assert [j["name"] for j in scene_extras["joints"]] == ["hinge", "handle_mount"]- assert scene_extras["links"] == ["body", "door", "handle"]- # hierarchy: cab → body → door → handle+ assert js["scenes"][0]["extras"]["links"] == ["body", "door", "handle"]idx = {n["name"]: i for i, n in enumerate(js["nodes"])}assert idx["door"] in names["body"]["children"] and idx["handle"] in names["door"]["children"]- # canonical frame: Y-up (ground at y=0), door at +z front- s = trimesh.load(glb)- assert abs(s.bounds[0][1]) < 1e-6 and s.bounds[1][1] > 0.79- assert s.bounds[1][2] > 0.2# posed export moves the doorglb2 = urdf_to_glb(r, tmp_path / "open.glb", {"hinge": 1.57})s2 = trimesh.load(glb2)assert s2.bounds[1][2] > 0.7 # door swung out to +z (front)assert _gltf_json(glb2)["scenes"][0]["extras"]["pose"] == {"hinge": 1.57}- # a multi-material link keeps its materials: one node per submesh under the link- a = trimesh.creation.box((0.1, 0.1, 0.1))- a.visual = trimesh.visual.TextureVisuals(material=trimesh.visual.material.PBRMaterial(name="wood", baseColorFactor=[200, 150, 100, 255]))- b = trimesh.creation.box((0.05, 0.05, 0.3))- b.apply_translation((0, 0, 0.3))- b.visual = trimesh.visual.TextureVisuals(material=trimesh.visual.material.PBRMaterial(name="metal", baseColorFactor=[200, 200, 210, 255]))- (meshes / "body.glb").write_bytes(trimesh.Scene([a, b]).export(file_type="glb"))- r = load_urdf(urdf, meshes)- assert len(r.links["body"].submeshes) == 2 and len(r.links["body"].mesh.split(only_watertight=False)) == 2- s = trimesh.load(urdf_to_glb(r, tmp_path / "mm.glb"))- names = {k: getattr(getattr(g.visual, "material", None), "name", None) for k, g in s.geometry.items()}- assert {names["body__0"], names["body__1"]} == {"wood", "metal"}- assert sorted(n for n in [e[1] for e in s.graph.to_edgelist()] if n.startswith("body")) == ["body", "body__0", "body__1"]+++def test_joint_sweep_penetration_is_a_verdict_not_an_mcp_error(tmp_path, monkeypatch):+ """A sweep that finds a penetration RAN: ``failed`` stays False (each MCP error bought a retry at ~117k prompt tokens)+ and the FAIL verdict leads the text; the tool and ``sweep_gate`` say the same thing."""+ import codeverse3d.spatial.tools as ts+ from codeverse3d.spatial.joints_sweep import sweep_gate+ from codeverse3d.spatial.registry import ToolContext, get_tool+ from codeverse3d.workspace import Workspace+ from tests.urdf_joints.conftest import write_prims_robot++ ws = Workspace(tmp_path / "ws").create()+ write_prims_robot(ws.artifacts / "robot.urdf", axis_z=+1) # the door swings into the body+ monkeypatch.setattr(ts, "render_poses", lambda robot, out_dir, poses=None, **kw: [+ Image.new("RGB", (8, 8), "gray").save(out_dir / ARTICULATION_SHEET_NAME)])+ ctx = ToolContext(workspace=ws, language="urdf_blender", track="articulated_object")+ obs = get_tool("joint_sweep").call(ctx, {})+ assert not obs.ok and not obs.failed+ assert obs.text.startswith("joint_sweep: FAIL — 1 error(s)")+ assert "links 'body|door' overlap in 2 of the sampled poses" in obs.text and "fix:" in obs.text+ gate, _ = sweep_gate(ws)+ assert not gate.passed and [f.message for f in gate.errors][0] in obs.textdef test_render_poses_with_fake_renderer_builds_sheet(tmp_path, monkeypatch):@@ -87,37 +88,6 @@ def test_render_poses_with_fake_renderer_builds_sheet(tmp_path, monkeypatch):assert sheet.is_file() and Image.open(sheet).size[0] > 32-def test_joint_sweep_penetration_is_a_verdict_not_an_mcp_error(tmp_path, monkeypatch):- """A sweep that finds a penetration RAN: ``failed`` stays False (63% of 1404 recorded- joint_sweep calls answered FAIL, and each one reported as an MCP error bought a retry- at ~117k prompt tokens), and the FAIL verdict leads the text. The verdict is the- round's: the tool and ``sweep_gate`` say the same thing about the same robot."""- import codeverse3d.spatial.tools as ts- from codeverse3d.spatial.joints_sweep import sweep_gate- from codeverse3d.spatial.registry import ToolContext, get_tool- from codeverse3d.workspace import Workspace- from tests.urdf_joints.conftest import write_prims_robot-- ws = Workspace(tmp_path / "ws").create()- write_prims_robot(ws.artifacts / "robot.urdf", axis_z=+1) # the door swings into the body- monkeypatch.setattr(ts, "render_poses", lambda robot, out_dir, poses=None, **kw: [- Image.new("RGB", (8, 8), "gray").save(out_dir / ARTICULATION_SHEET_NAME)])- ctx = ToolContext(workspace=ws, language="urdf_blender", track="articulated_object")- obs = get_tool("joint_sweep").call(ctx, {})- assert not obs.ok and not obs.failed- assert obs.text.startswith("joint_sweep: FAIL — 1 error(s)")- assert "links 'body|door' overlap in 2 of the sampled poses" in obs.text and "fix:" in obs.text- gate, _ = sweep_gate(ws)- assert not gate.passed and [f.message for f in gate.errors][0] in obs.text- # the tool and the gate share ONE urdf rule, the built copy: an authored src/robot.urdf with no- # build behind it is "run build first" for both, never a sweep against the last build's meshes- bare = Workspace(tmp_path / "bare").create()- write_prims_robot(bare.src / "robot.urdf", axis_z=+1)- obs = get_tool("joint_sweep").call(ToolContext(workspace=bare, language="urdf_blender", track="articulated_object"), {})- gate, robot = sweep_gate(bare)- assert "run `build` first" in obs.text and robot is None and [f.message for f in gate.errors] == ["no robot.urdf found after build"]--def test_robot_named_like_a_link_keeps_frame_and_placement(tmp_path):"""``<robot name="body">`` with a root link ``body``: scene-graph node names must beunique, so the root node gets a ``__root`` suffix instead of aliasing the link nodediff --git a/harness/tests/urdf_joints/test_joints_model.py b/harness/tests/urdf_joints/test_joints_model.pyindex c20dd9aa..fcbc83a8 100644--- a/harness/tests/urdf_joints/test_joints_model.py+++ b/harness/tests/urdf_joints/test_joints_model.py@@ -44,18 +44,3 @@ def test_load_prims_fk_and_pose_samples(tmp_path):if "s" in q:assert -0.1 - 1e-9 <= q["s"] <= 0.2 + 1e-9--def test_load_errors(tmp_path):- p = tmp_path / "bad.urdf"- p.write_text("<robot name='x'><link name='a'/><link name='b'/></robot>")- with pytest.raises(UrdfError, match="exactly one root"):- load_urdf(p)- p.write_text("<robot name='x'><link name='a'/><link name='b'/><joint name='j' type='revolute'><parent link='a'/><child link='b'/></joint></robot>")- with pytest.raises(UrdfError, match="limit"):- load_urdf(p)- p.write_text("<robot name='x'><link name='a'/><link name='b'/><joint name='j' type='fixed'><parent link='a'/><child link='zz'/></joint></robot>")- with pytest.raises(UrdfError, match="unknown"):- load_urdf(p)- p.write_text("<robot name='x'><link name='a'><visual><geometry><mesh filename='meshes/nope.glb'/></geometry></visual></link></robot>")- with pytest.raises(UrdfError, match="not found"):- load_urdf(p)diff --git a/harness/tests/urdf_joints/test_lint.py b/harness/tests/urdf_joints/test_lint.pyindex 66da4d19..6d8769be 100644--- a/harness/tests/urdf_joints/test_lint.py+++ b/harness/tests/urdf_joints/test_lint.py@@ -5,9 +5,8 @@ from __future__ import annotationsimport pytestfrom codeverse3d.contracts.artifacts import Severity-from codeverse3d.languages.urdf import lint_model_text, lint_urdf_text, lint_workspace+from codeverse3d.languages.urdf import lint_urdf_textfrom codeverse3d.spatial.joints_model import UrdfError, load_urdf-from codeverse3d.workspace import WorkspaceGOOD = """<?xml version="1.0"?><robot name="cab">@@ -33,142 +32,41 @@ def _msgs(findings, sev=None):return [f.message for f in findings if sev is None or f.severity == sev]-def test_xml_and_structure_errors():+def _door(old: str, new: str) -> str:+ return GOOD.replace(old, new)+++# (mutation of GOOD, severity, a fragment of the finding's message): one row per lint rule+RULES = [+ (_door('<joint name="hinge"', '<link name="x"/><joint name="hinge"'), Severity.ERROR, "exactly one root"),+ (_door("</robot>", '<joint name="j2" type="fixed"><parent link="body"/><child link="door"/></joint></robot>'), Severity.ERROR, "child of two joints"),+ (_door('lower="0" upper="1.57"', 'lower="1" upper="0"'), Severity.ERROR, "upper 0.0 < lower 1.0"),+ (_door('filename="meshes/door.glb"', 'filename="door.glb"'), Severity.ERROR, "mesh filename"),+ (_door('name="door"', 'name="DoorOpen"').replace('link="door"', 'link="DoorOpen"').replace("meshes/door.glb", "meshes/DoorOpen.glb"),+ Severity.WARN, "state word"),+ (_door('name="body"', 'name="world"').replace('link="body"', 'link="world"').replace("meshes/body.glb", "meshes/world.glb"),+ Severity.ERROR, "reserved"),+]++[email protected](("text", "severity", "fragment"), RULES, ids=[r[2] for r in RULES])+def test_lint_rules(text, severity, fragment):+ f, _ = lint_urdf_text(text)+ assert any(fragment in x.message and x.severity == severity for x in f), _msgs(f)+++def test_xml_errors_and_pascal_case_part_names_are_clean():f, _ = lint_urdf_text("<robot name='x'><link name='a'>")assert f[0].severity == Severity.ERROR and "well-formed" in f[0].message and f[0].data.get("line") == 1- f, _ = lint_urdf_text("<model/>")- assert "must be <robot>" in f[0].message- f, links = lint_urdf_text("<robot name='x'></robot>")- assert "no <link>" in f[0].message and links == []---def test_tree_rules():- two_roots = GOOD.replace('<joint name="hinge"', '<link name="x"/><joint name="hinge"')- f, _ = lint_urdf_text(two_roots)- assert any("exactly one root" in m for m in _msgs(f, Severity.ERROR))- dup = GOOD.replace("</robot>", '<joint name="j2" type="fixed"><parent link="body"/><child link="door"/></joint></robot>')- f, _ = lint_urdf_text(dup)- assert any("child of two joints" in m for m in _msgs(f, Severity.ERROR))- cyc = GOOD.replace("</robot>", '<link name="c"><visual><geometry><mesh filename="meshes/c.glb"/></geometry></visual></link>'- '<link name="d"><visual><geometry><mesh filename="meshes/d.glb"/></geometry></visual></link>'- '<joint name="j3" type="fixed"><parent link="c"/><child link="d"/></joint>'- '<joint name="j4" type="fixed"><parent link="d"/><child link="c"/></joint></robot>')- f, _ = lint_urdf_text(cyc)- assert any("does not reach the root" in m for m in _msgs(f, Severity.ERROR))- unknown = GOOD.replace('<child link="door"/>', '<child link="dor"/>')- f, _ = lint_urdf_text(unknown)- assert any("does not exist" in m for m in _msgs(f, Severity.ERROR))- same = GOOD.replace('<parent link="body"/>', '<parent link="door"/>')- f, _ = lint_urdf_text(same)- assert any("parent == child" in m for m in _msgs(f, Severity.ERROR))---def test_joint_rules():- f, _ = lint_urdf_text(GOOD.replace('<limit lower="0" upper="1.57" effort="10" velocity="1"/>', ""))- assert any("need <limit" in m for m in _msgs(f, Severity.ERROR))- f, _ = lint_urdf_text(GOOD.replace('lower="0" upper="1.57"', 'lower="1" upper="0"'))- assert any("upper 0.0 < lower 1.0" in m for m in _msgs(f, Severity.ERROR))- f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 0"/>'))- assert any("zero axis" in m for m in _msgs(f, Severity.ERROR))- f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 -2"/>'))- w = [x for x in f if "not unit" in x.message]- assert w and w[0].severity == Severity.WARN and 'xyz="0 0 -1"' in w[0].fix_hint- f, _ = lint_urdf_text(GOOD.replace('type="revolute"', 'type="continuous"'))- assert any("continuous joints have no lower/upper" in m for m in _msgs(f, Severity.WARN))- f, _ = lint_urdf_text(GOOD.replace('type="revolute"', 'type="hinge"'))- assert any("must be one of" in m for m in _msgs(f, Severity.ERROR))- f, _ = lint_urdf_text(GOOD.replace('<origin xyz="-0.29 -0.2 0" rpy="0 0 0"/>', '<origin xyz="-0.29 -0.2" rpy="0 0 0"/>'))- assert any("origin xyz: expected 3 numbers" in m for m in _msgs(f, Severity.ERROR))- f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', ""))- assert any("no <axis>" in m for m in _msgs(f, Severity.WARN))---def test_link_rules():- f, _ = lint_urdf_text(GOOD.replace('filename="meshes/door.glb"', 'filename="door.glb"'))- e = [x for x in f if "mesh filename" in x.message]- assert e and e[0].severity == Severity.ERROR and "meshes/door.glb" in e[0].fix_hint- f, _ = lint_urdf_text(GOOD.replace('<mesh filename="meshes/door.glb"/>', '<box size="1 1 1"/>'))- assert any("must be a <mesh>" in m for m in _msgs(f, Severity.ERROR))- f, _ = lint_urdf_text(GOOD.replace('<collision><origin xyz="0.29 0.2 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision>', ""))- assert any("no <collision>" in m for m in _msgs(f, Severity.WARN))- f, _ = lint_urdf_text(GOOD.replace('<collision><origin xyz="0.29 0.2 0"', '<collision><origin xyz="0.3 0.2 0"'))- assert any("differs from <visual>" in m for m in _msgs(f, Severity.WARN))- f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="DoorOpen"').replace('link="door"', 'link="DoorOpen"').replace("meshes/door.glb", "meshes/DoorOpen.glb"))- msgs = _msgs(f, Severity.WARN)- assert any("state word" in m for m in msgs)- # the plan's PascalCase part names are accepted silently (check_contract normalises names) …- f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="FrontDoor"').replace('link="door"', 'link="FrontDoor"').replace("meshes/door.glb", "meshes/FrontDoor.glb"))+ # the plan's PascalCase part names are accepted silently (check_contract normalises names)+ f, _ = lint_urdf_text(_door('name="door"', 'name="FrontDoor"').replace('link="door"', 'link="FrontDoor"').replace("meshes/door.glb", "meshes/FrontDoor.glb"))assert f == []- # … but Blender auto-suffixes / spaces are not plain identifiers- f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="door.001"').replace('link="door"', 'link="door.001"').replace("meshes/door.glb", "meshes/door.001.glb"))- assert any("plain identifier" in m for m in _msgs(f, Severity.WARN))- f, _ = lint_urdf_text(GOOD.replace('<link name="door">', '<link name="door"><visual><geometry><mesh filename="meshes/door.glb"/></geometry></visual>'))- assert any("2 <visual>" in m for m in _msgs(f, Severity.ERROR))---def test_model_lint():- f = lint_model_text(MODEL, ["body", "door", "lid"])- assert [x.severity for x in f] == [Severity.WARN] and "lid" in f[0].message- f = lint_model_text("import bpy, subprocess\nbpy.ops.wm.save_mainfile()\nbpy.ops.render.render()\nsys.exit()\nbpy.ops.object.camera_add()\n", [])- msgs = _msgs(f, Severity.ERROR)- assert any("subprocess" in m for m in msgs) and any("bpy.ops.wm.save_mainfile" in m for m in msgs)- assert any("render" in m for m in msgs)- assert any("camera" in m for m in _msgs(f, Severity.WARN)) and any("sys.exit" in m for m in _msgs(f, Severity.WARN))- assert any("quit()" in m for m in _msgs(lint_model_text("import bpy\nquit()\n", []), Severity.ERROR))- f = lint_model_text("x = (1,\n", [])- assert f[0].severity == Severity.ERROR and "SyntaxError" in f[0].message and f[0].data["line"] == 1- f = lint_model_text("import math\n", [])- assert any("never imports bpy" in m for m in _msgs(f, Severity.ERROR))- f = lint_model_text("import bpy\nfrom codeverse3d.x import y\n", [])- assert any("codeverse3d" in m for m in _msgs(f, Severity.WARN))---def test_model_py_is_linted_by_the_blender_rules():- """Regression (audit 2026-09-24 N19): model.py runs in the blender language's interpreter and- gets that lint; the URDF copy caught 2 WARNs where blender found 7 ERRORs on this source."""- from codeverse3d.languages.blender import lint_blender_source-- src = ("import bpy\nimport pathlib\nimport os\ncfg = open('/etc/passwd').read()\nos.makedirs('/tmp/x')\n"- "bpy.data.libraries.load('/tmp/a.blend')\nbpy.ops.image.save_as()\n"- "bsdf = bpy.data.materials.new('m').node_tree.nodes['Principled BSDF']\n"- "bsdf.inputs['Specular'].default_value = 0.5\nbpy.ops.object.join({'object': None})\n"- "o = bpy.context.active_object\no.name = 'base'\n")- blender = _msgs(lint_blender_source(src).findings, Severity.ERROR)- assert len(blender) == 7 and _msgs(lint_model_text(src, ["base"]), Severity.ERROR) == blender---def test_lint_workspace(tmp_path):- ws = Workspace(tmp_path / "ws").create()- rep = lint_workspace(ws)- assert not rep.passed and rep.gate == "lint:urdf" and len(rep.errors) == 2- (ws.src / "robot.urdf").write_text(GOOD)- (ws.src / "model.py").write_text(MODEL)- rep = lint_workspace(ws)- assert rep.passed and rep.findings == []---def test_reserved_link_name_world():- # glTF readers use 'world' as the scene-graph base frame: a link of that name cannot become a GLB node- f, _ = lint_urdf_text(GOOD.replace('name="body"', 'name="world"').replace('link="body"', 'link="world"').replace("meshes/body.glb", "meshes/world.glb"))- assert any("reserved" in m for m in _msgs(f, Severity.ERROR))--[email protected]("old,new", [- ('lower="0" upper="1.57"', 'lower="0 1" upper="1.57"'), # raised a bare ValueError in the build- ('effort="10"', 'effort="ten"'), # ditto- ('lower="0" upper="1.57"', 'lower="0" upper="inf"'),- ('<axis xyz="0 0 -1"/>', '<axis xyz="0 0"/>'),- ('type="revolute"', 'type="fixed"'), # the loader checks a FIXED joint's axis too- ('<limit lower="0" upper="1.57" effort="10" velocity="1"/>', '<mimic/>'),-])-def test_lint_clean_means_the_loader_parses(tmp_path, old, new):- """Regression (audit 2026-09-24 N18): the lint and the build parse joints through one- ``parse_joint``, so a URDF the lint passes never fails (or raises) in ``load_urdf``."""- text = GOOD.replace(old, new)- if new == 'type="fixed"':- text = text.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 0"/>')+++def test_lint_clean_means_the_loader_parses(tmp_path):+ """Regression (audit N18): lint and build parse joints through one ``parse_joint``; a bad limit once raised a bare ValueError."""+ text = GOOD.replace('lower="0" upper="1.57"', 'lower="0 1" upper="1.57"')(tmp_path / "robot.urdf").write_text(text)with pytest.raises(UrdfError) as e:load_urdf(tmp_path / "robot.urdf", load_meshes=False)- f, _ = lint_urdf_text(text)- assert str(e.value) in _msgs(f, Severity.ERROR)+ assert str(e.value) in _msgs(lint_urdf_text(text)[0], Severity.ERROR)diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.pyindex 2969450c..5d45293b 100644--- a/harness/tests/urdf_joints/test_live_blender.py+++ b/harness/tests/urdf_joints/test_live_blender.py@@ -1,21 +1,20 @@-"""Real Blender builds (marked ``blender``): cabinet+door with yourdfpy FK, a rest-shifted drawer, typed wrapper failures, sys.exit(0)."""+"""Real Blender builds (marked ``blender``): the cabinet end to end, and the links wrapper's typed failures."""from __future__ import annotations-import numpy as np+import json+import subprocess+from pathlib import Path+import pytestfrom codeverse3d.config import get_settingsfrom codeverse3d.languages.urdf import UrdfBlenderRuntime-from codeverse3d.spatial.joints_model import fk, link_world_meshes, load_urdf+from codeverse3d.spatial.joints_model import link_world_meshes, load_urdffrom codeverse3d.spatial.joints_sweep import motion_direction_check, sweep_gatefrom codeverse3d.workspace import Workspacepytestmark = pytest.mark.blender-try:- import yourdfpy-except ImportError: # the [urdf] extra; the rest of the end-to-end test still runs- yourdfpy = Noneneeds_blender = pytest.mark.skipif(not get_settings().resolve_blender(), reason="no Blender binary")@@ -27,20 +26,13 @@ def test_cabinet_door_end_to_end_then_broken(tmp_path, cabinet_plan):assert rt.lint(ws).passedres = rt.build(ws)assert res.ok, res.error_message- assert res.duration_ms < 30_000r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")assert r.link_order() == ["body", "door", "handle"]- # door + handle swing to the front-left at the upper limitwm = link_world_meshes(r, {"hinge": 1.57})assert wm["door"].centroid[1] < -0.4 and wm["handle"].centroid[1] < -0.4assert motion_direction_check(r, "hinge", "front").okgate, _ = sweep_gate(ws) # the round's joint_sweep gate on this buildassert gate.passed and not gate.findings, [f.message for f in gate.findings]- # loads in yourdfpy with the same FK- if yourdfpy is not None:- u = yourdfpy.URDF.load(str(ws.artifacts / "robot.urdf"), load_meshes=True)- u.update_cfg({"hinge": 1.0})- assert np.allclose(u.get_transform("door", "body"), fk(r, {"hinge": 1.0})["door"], atol=1e-6)# the same workspace, broken: typed wrapper failuresm = ws.src / "model.py"@@ -52,111 +44,38 @@ def test_cabinet_door_end_to_end_then_broken(tmp_path, cabinet_plan):assert not res.ok and res.error_type == "MissingLinkObjects" and "Handle" in res.error_message-@needs_blender-def test_rest_shifted_skeleton_builds_clean(tmp_path, drawer_plan):- """Plan with rest ≠ 0 and the bbox authored AT that rest (drawer 0.1 m out): the- skeleton's shifted limits (-0.1 .. 0.2) put q=0 at the authored pose and @lower at the- closed position — no penetration anywhere in the sweep."""- plan = drawer_plan.model_copy(deep=True)- plan.parts[1].bbox.center = (0, -0.31, 0.45) # front panel 0.1 m out of the carcass- plan.joints[0].pivot = (0, -0.31, 0.45)- plan.joints[0].rest = 0.1- ws = Workspace(tmp_path / "drawer_rest").create()- rt = UrdfBlenderRuntime()- rt.skeleton(ws, plan)- assert 'lower="-0.1" upper="0.2"' in (ws.src / "robot.urdf").read_text()- res = rt.build(ws)- assert res.ok, res.error_message- r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")- closed = link_world_meshes(r, {"slide": -0.1})["drawer"].bounds- assert np.isclose(closed[1][1], -0.20, atol=1e-6) # back face of the panel flush with the carcass front- assert not [f for f in sweep_gate(ws)[0].findings if f.data.get("kind") == "penetration"]---@needs_blender-def test_links_script_that_calls_sys_exit_0_still_builds(tmp_path):- """``sys.exit(0)`` ends the script, not the build: the objects it made are the links- (the blender language's rule; this wrapper used to report it as a SystemExit error).- The run is seeded like the blender language's, so ``random`` draws the same numbers."""- import json as _json- import subprocess-+def _wrapper_build(tmp_path, model: str) -> tuple[dict, Path]:+ """Run the links wrapper on a one-link robot whose model.py is ``model``; return build.json and the out dir."""from codeverse3d.languages.urdf import WRAPPER(tmp_path / "robot.urdf").write_text('<robot name="r"><link name="base"/></robot>')- (tmp_path / "model.py").write_text(- "import random, sys\nimport bpy\n"- "bpy.ops.mesh.primitive_cube_add(size=0.2 + random.random())\n"- "bpy.context.active_object.name = 'base'\n"- "sys.exit(0)\n"- "raise RuntimeError('never reached')\n")+ (tmp_path / "model.py").write_text(model)out = tmp_path / "art"- subprocess.run(- [get_settings().resolve_blender(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",- "--script", str(tmp_path / "model.py"), "--urdf", str(tmp_path / "robot.urdf"), "--out", str(out)],- capture_output=True, text=True, timeout=180, check=False)- build = _json.loads((out / "build.json").read_text())- assert build["ok"] and build["error_type"] == "", build- census = _json.loads((out / "census.json").read_text())- import random+ subprocess.run([get_settings().resolve_blender(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",+ "--script", str(tmp_path / "model.py"), "--urdf", str(tmp_path / "robot.urdf"), "--out", str(out)],+ capture_output=True, text=True, timeout=180, check=False)+ return json.loads((out / "build.json").read_text()), out- random.seed(0)- assert census["links"]["base"]["bbox_max"][0] == pytest.approx((0.2 + random.random()) / 2, abs=1e-5)- assert (out / "meshes" / "base.glb").is_file()- assert any("has no material" in w for w in census["warnings"]) # the blender language's census+BASE = "bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5)); base = bpy.context.active_object; base.name = 'base'\n"-@needs_blender[email protected]("parented", [True, False])-def test_a_hidden_boolean_cutter_is_not_link_geometry(tmp_path, parented):- """Regression (audit 2026-09-24 N7): the link exporter skips hidden objects by the blender- language's own predicate (``_census.is_hidden``). It used to export a parented hidden cutter- as a solid rod inside the link (z 0..2) and fail an unparented one as UnmatchedObjects."""- import json as _json- import subprocess- from codeverse3d.languages.urdf import WRAPPER-- (tmp_path / "robot.urdf").write_text('<robot name="r"><link name="base"/></robot>')- (tmp_path / "model.py").write_text(- "import bpy\n"- "bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5)); base = bpy.context.active_object; base.name = 'base'\n"+@needs_blender+def test_a_hidden_boolean_cutter_is_not_link_geometry(tmp_path):+ """Regression (audit 2026-09-24 N7): a parented hidden cutter was exported as a solid rod inside the link."""+ build, out = _wrapper_build(tmp_path, "import bpy\n" + BASE +"bpy.ops.mesh.primitive_cylinder_add(radius=0.2, depth=2, location=(0, 0, 0.5)); cut = bpy.context.active_object\n"- "cut.name = 'HoleCutter'\n"- "m = base.modifiers.new('hole', 'BOOLEAN'); m.object = cut; m.operation = 'DIFFERENCE'\n"- + ("cut.parent = base\n" if parented else "")- + "cut.hide_set(True); cut.hide_render = True\n")- out = tmp_path / "art"- subprocess.run(- [get_settings().resolve_blender(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",- "--script", str(tmp_path / "model.py"), "--urdf", str(tmp_path / "robot.urdf"), "--out", str(out)],- capture_output=True, text=True, timeout=180, check=False)- build = _json.loads((out / "build.json").read_text())+ "cut.name = 'HoleCutter'\nm = base.modifiers.new('hole', 'BOOLEAN'); m.object = cut; m.operation = 'DIFFERENCE'\n"+ "cut.parent = base\ncut.hide_set(True); cut.hide_render = True\n")assert build["ok"], build- link = _json.loads((out / "census.json").read_text())["links"]["base"]+ link = json.loads((out / "census.json").read_text())["links"]["base"]assert link["objects"] == ["base"] and link["bbox_max"][2] == pytest.approx(1.0, abs=1e-4)@needs_blenderdef test_a_nan_in_a_link_is_the_scripts_error(tmp_path):- """D114: a NaN world matrix is never baked into ``meshes/<link>.glb``: the build fails naming the- object and the channel (the glTF exporter would drop the NaN translation and ship it at the origin)."""- import json as _json- import subprocess-- from codeverse3d.languages.urdf import WRAPPER-- (tmp_path / "robot.urdf").write_text('<robot name="r"><link name="base"/></robot>')- (tmp_path / "model.py").write_text(- "import bpy\n"- "bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5)); base = bpy.context.active_object; base.name = 'base'\n"- "base.scale.x = float('nan')\n")- out = tmp_path / "art"- subprocess.run(- [get_settings().resolve_blender(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",- "--script", str(tmp_path / "model.py"), "--urdf", str(tmp_path / "robot.urdf"), "--out", str(out)],- capture_output=True, text=True, timeout=180, check=False)- build = _json.loads((out / "build.json").read_text())+ """D114: a NaN world matrix is never baked into ``meshes/<link>.glb``: the build fails naming the object and channel."""+ build, out = _wrapper_build(tmp_path, "import bpy\n" + BASE + "base.scale.x = float('nan')\n")assert not build["ok"] and build["error_type"] == "NonFiniteTransform", buildassert build["error_message"].startswith("link base: 1 object(s)") and "'base': scale=(nan, 1, 1)" in build["error_message"]assert not (out / "meshes" / "base.glb").exists()diff --git a/harness/tests/urdf_joints/test_mimic.py b/harness/tests/urdf_joints/test_mimic.pyindex 729cbad8..8c6ce49c 100644--- a/harness/tests/urdf_joints/test_mimic.py+++ b/harness/tests/urdf_joints/test_mimic.py@@ -7,7 +7,7 @@ from pathlib import Pathimport pytestfrom codeverse3d.contracts.plan import ArticulatedPlan-from codeverse3d.languages.urdf import lint_workspace, render_urdf+from codeverse3d.languages.urdf import lint_workspacefrom codeverse3d.spatial.joints_model import UrdfError, fk, load_urdf, resolve_qfrom codeverse3d.spatial.joints_poses import pose_samplesfrom codeverse3d.spatial.joints_sweep import motion_direction_check, sweep_collisions@@ -40,15 +40,6 @@ RIB = """<?xml version="1.0"?>"""-EXTRA_RUNNER = """ <link name="runner2"><visual><geometry><mesh filename="meshes/rib_b.glb"/></geometry></visual></link>- <joint name="runner_slide_2" type="prismatic">- <parent link="shaft"/><child link="runner2"/>- <origin xyz="0 0 0.6" rpy="0 0 0"/><axis xyz="0 0 1"/>- <limit lower="0" upper="0.3" effort="10" velocity="1"/>- </joint>-</robot>"""--def _robot(tmp_path: Path, urdf_text: str = RIB):meshes = tmp_path / "meshes"box_glb(meshes / "shaft.glb", (0, 0, 0.6), (0.04, 0.04, 1.2))@@ -61,64 +52,49 @@ def _robot(tmp_path: Path, urdf_text: str = RIB):def test_a_driven_joint_follows_its_driver_everywhere(tmp_path):- import numpy as np- import trimesh-- from codeverse3d.spatial.joints_export import ZUP_TO_YUP, urdf_to_glb-r = _robot(tmp_path)assert [j.name for j in r.independent_joints()] == ["runner_slide"]- assert r.joints["rib_a_hinge"].driven and r.joints["rib_b_hinge"].driven+ assert r.joints["rib_a_hinge"].mimic and r.joints["rib_b_hinge"].mimicq = resolve_q(r, {"runner_slide": 0.2})assert q["rib_a_hinge"] == pytest.approx(0.8) # multiplier 4assert q["rib_b_hinge"] == pytest.approx(0.8) # follows rib_a_hinge, multiplier 1# a value handed in for a driven joint is ignored: the mechanism has one inputassert resolve_q(r, {"runner_slide": 0.1, "rib_a_hinge": 99.0})["rib_a_hinge"] == pytest.approx(0.4)- # the rib hinges about its own frame origin, so the coupling shows in the rotation- assert fk(r, {"runner_slide": 0.1})["rib_a"][:3, :3].tolist() != fk(r, {})["rib_a"][:3, :3].tolist()- assert fk(r, {"runner_slide": 0.1})["runner"][2, 3] == pytest.approx(fk(r, {})["runner"][2, 3] + 0.1)-- # the sweep poses the mechanism the way it moves: one input, not three- rep = sweep_collisions(r, pose_samples(r))- assert {p.label for p in rep.per_pose} == {"rest", "runner_slide@upper", "runner_slide@mid"}- assert rep.summary.n_poses == 3-- # a driven joint is probed through its driver- chk = motion_direction_check(r, "rib_a_hinge", "up")- assert "driven by runner_slide" in chk.message- assert chk.observed_dir != (0.0, 0.0, 0.0)-- # urdf_to_glb poses followers through fk, like the sweep (it used to leave them at rest)- q = {"runner_slide": 0.3}-- def rib_a_world(glb):- scene = trimesh.load(glb, force="scene")- node = next(n for n in scene.graph.nodes_geometry if scene.graph[n][1] == "rib_a")- T, _ = scene.graph[node]- return trimesh.transform_points([scene.geometry["rib_a"].centroid], T)[0]-- rest = rib_a_world(urdf_to_glb(r, tmp_path / "rest.glb", {}))- posed = rib_a_world(urdf_to_glb(r, tmp_path / "posed.glb", q))- assert not np.allclose(rest, posed), "rib_a did not follow runner_slide in the exported scene"- # and it lands exactly where fk puts that point: undo the export's Y-up, move the rest- # centroid by fk's rib_a motion for the same q, re-apply Y-up- T0, T1 = fk(r, {})["rib_a"], fk(r, q)["rib_a"]- rest_zup = trimesh.transform_points([rest], np.linalg.inv(ZUP_TO_YUP))[0]- moved_zup = trimesh.transform_points([rest_zup], T1 @ np.linalg.inv(T0))[0]- expected = trimesh.transform_points([moved_zup], ZUP_TO_YUP)[0]- assert np.allclose(posed, expected, atol=1e-6), (posed, expected)--[email protected]("bad,msg", [- ('<mimic joint="nope"/>', "names no joint"),- ('<mimic joint="rib_a_hinge" multiplier="0"/>', "cannot move"),- ('<mimic joint="rib_b_hinge"/>', "cycle"),- ('<mimic joint="rib_a_hinge" multiplier="1" offset="0"/>', "names itself"),-])+ assert fk(r, {"runner_slide": 0.1})["rib_a"][:3, :3].tolist() != fk(r, {})["rib_a"][:3, :3].tolist() # the coupling shows in the rotation+ assert {p.label for p in sweep_collisions(r, pose_samples(r)).per_pose} == {"rest", "runner_slide@upper", "runner_slide@mid"} # one input, not three+ assert "driven by runner_slide" in motion_direction_check(r, "rib_a_hinge", "up").message++[email protected]("bad,msg", [('<mimic joint="rib_a_hinge" multiplier="0"/>', "cannot move"), ('<mimic joint="rib_b_hinge"/>', "cycle")])def test_a_broken_coupling_is_refused_at_load(tmp_path, bad, msg):- text = RIB.replace('<mimic joint="runner_slide" multiplier="4" offset="0"/>', bad)with pytest.raises(UrdfError, match=msg):- _robot(tmp_path, text)+ _robot(tmp_path, RIB.replace('<mimic joint="runner_slide" multiplier="4" offset="0"/>', bad))+++EXTRA_RUNNER = """ <link name="runner2"><visual><geometry><mesh filename="meshes/rib_b.glb"/></geometry></visual></link>+ <joint name="runner_slide_2" type="prismatic">+ <parent link="shaft"/><child link="runner2"/>+ <origin xyz="0 0 0.6" rpy="0 0 0"/><axis xyz="0 0 1"/>+ <limit lower="0" upper="0.3" effort="10" velocity="1"/>+ </joint>+</robot>"""+++def _plan(**joint_overrides):+ """The worked articulated example with a second joint that can carry a coupling."""+ import copy++ from codeverse3d.contracts.common import Track+ from codeverse3d.tracks.planner import plan_example++ d = copy.deepcopy(plan_example(Track.ARTICULATED_OBJECT))+ d["parts"].append({"name": "Lid", "role": "top lid", "description": "a flat lid", "attach_to": "Cabinet",+ "bbox": {"center": [0, 0, 0.61], "extents": [0.4, 0.5, 0.02]}, "material": "oak"})+ d["joints"].append({"name": "LidHinge", "type": "revolute", "parent": "Cabinet", "child": "Lid",+ "axis": [1, 0, 0], "pivot": [0, 0.21, 0.6], "lower": 0.0, "upper": 1.2, "rest": 0.0,+ "motion": "the lid tilts up"})+ d["joints"][1].update(joint_overrides)+ return ddef test_the_lint_on_couplings(tmp_path):@@ -158,24 +134,6 @@ def test_the_lint_on_couplings(tmp_path):assert not [f for f in findings if "mimic" in f.message and f.severity.value == "error"]-# ------------------------------------------------------------------ the plan's own rules-def _plan(**joint_overrides):- """The worked articulated example with a second joint that can carry a coupling."""- import copy-- from codeverse3d.contracts.common import Track- from codeverse3d.tracks.planner import plan_example-- d = copy.deepcopy(plan_example(Track.ARTICULATED_OBJECT))- d["parts"].append({"name": "Lid", "role": "top lid", "description": "a flat lid", "attach_to": "Cabinet",- "bbox": {"center": [0, 0, 0.61], "extents": [0.4, 0.5, 0.02]}, "material": "oak"})- d["joints"].append({"name": "LidHinge", "type": "revolute", "parent": "Cabinet", "child": "Lid",- "axis": [1, 0, 0], "pivot": [0, 0.21, 0.6], "lower": 0.0, "upper": 1.2, "rest": 0.0,- "motion": "the lid tilts up"})- d["joints"][1].update(joint_overrides)- return d--def test_a_broken_coupling_is_refused_by_the_plan():for mimic, msg in (({"joint": "NoSuchJoint"}, "is not a joint in this plan"), ({"joint": "LidHinge"}, "mimics itself")):with pytest.raises(Exception, match=msg):@@ -195,7 +153,6 @@ def test_a_broken_coupling_is_refused_by_the_plan():ArticulatedPlan.model_validate(d)-# ------------------------------------------------------------------ one rule set, three layersdef test_the_three_layers_reject_the_same_near_zero_multiplier(tmp_path):"""Plan validator, loader and lint share one MIMIC_MIN_MULTIPLIER floor."""from codeverse3d.contracts.common import MIMIC_MIN_MULTIPLIER@@ -214,32 +171,3 @@ def test_the_three_layers_reject_the_same_near_zero_multiplier(tmp_path):(ws.src / "robot.urdf").write_text(text)(ws.src / "model.py").write_text("import bpy\n")assert [f for f in lint_workspace(ws).findings if "cannot move" in f.message]---def test_the_skeleton_says_when_only_the_first_instance_of_a_driver_is_followed():- """An instanced driver exists only as <name>_1.._n: the skeleton follows _1 and says so."""- from codeverse3d.languages.urdf import compute_urdf_frames-- d = _plan()- d["parts"][1]["instances"] = 2- d["joints"][1]["mimic"] = {"joint": "DrawerSlide", "multiplier": 0.5}- urdf = render_urdf(compute_urdf_frames(ArticulatedPlan.model_validate(d)))- assert '<mimic joint="drawer_slide_1" multiplier="0.5" offset="0"/>' in urdf- names = {ln.split('"')[1] for ln in urdf.splitlines() if "<joint name=" in ln}- refs = {ln.split('"')[1] for ln in urdf.splitlines() if "<mimic joint=" in ln}- assert refs <= names, f"dangling mimic reference: {refs - names}"- line = next(ln for ln in urdf.splitlines() if "<mimic joint=" in ln)- assert "follows drawer_slide_1 only; drawer_slide_2 stay independent inputs" in line---def test_a_self_joint_says_which_links_collided():- """parent == child names both sides (pydantic truncated the value; models re-asked blind)."""- from codeverse3d.contracts.plan import JointPlan-- common = {"type": "revolute", "axis": [0, 0, 1], "pivot": [0, 0, 0],- "lower": 0.0, "upper": 1.0, "rest": 0.0}- with pytest.raises(Exception, match="parent and child are both 'Sash'"):- JointPlan.model_validate({"name": "SashHinge", "parent": "Sash", "child": "Sash", **common})- with pytest.raises(Exception, match="same name once normalised"):- JointPlan.model_validate({"name": "SashHinge", "parent": "SashFrame", "child": "sash_frame",- **common})diff --git a/harness/tests/urdf_joints/test_runtime_offline.py b/harness/tests/urdf_joints/test_runtime_offline.pyindex 15cc2d8b..9c484b79 100644--- a/harness/tests/urdf_joints/test_runtime_offline.py+++ b/harness/tests/urdf_joints/test_runtime_offline.py@@ -57,19 +57,6 @@ def _two_link(plan):return plan.model_copy(update={"parts": plan.parts[:2], "joints": plan.joints[:1]})-def test_build_script_error_maps_line_and_a_timeout_is_typed(tmp_path, cabinet_plan, fake_blender, monkeypatch):- fake_blender["error"] = {"error_type": "NameError", "error_message": "name 'bpyy' is not defined", "error_file": "src/model.py",- "error_line": 7, "stderr_tail": "Traceback..."}- ws = _ws(tmp_path, cabinet_plan)- res = UrdfBlenderRuntime().build(ws)- assert not res.ok and res.error_type == "NameError" and res.error_line == 7 and res.error_file == "src/model.py"- assert "hint: did you mean" in res.error_message- monkeypatch.setattr(rt_mod, "_run_blender",- lambda *a, **k: ProcResult(returncode=-9, stdout="", stderr="", timed_out=True, duration_ms=0))- res = UrdfBlenderRuntime().build(ws, timeout_s=1)- assert not res.ok and res.error_type == "BuildTimeout"--def test_build_rest_penetration_fails_and_publishes_nothing(tmp_path, cabinet_plan, fake_blender):fake_blender["door"] = ((0, -0.19, 0.4), (0.58, 0.02, 0.78)) # authored 10 mm inside the bodyws = _ws(tmp_path, cabinet_plan)@@ -83,48 +70,3 @@ def test_build_rest_penetration_fails_and_publishes_nothing(tmp_path, cabinet_plassert not (ws.artifacts / "meshes").exists()assert json.loads((ws.artifacts / "build.json").read_text())["ok"] is False--def test_post_wrapper_failure_never_leaves_ok_true_build_json(tmp_path, cabinet_plan, fake_blender):- """The wrapper reports ok:true, then FkInconsistent fails the build — the- published build.json must say what the returned BuildResult says (the old code- left the wrapper's ok:true on disk while the run failed)."""- ws = _ws(tmp_path, cabinet_plan)- u = ws.src / "robot.urdf"- u.write_text(u.read_text().replace('xyz="0.29 0.2 0"', 'xyz="-0.29 -0.2 0"'))- res = UrdfBlenderRuntime().build(ws)- assert not res.ok and res.error_type == "FkInconsistent"- assert 'xyz="0.29 0.2 0"' in res.error_message and res.census["fk_check"][0]["target"] == "door"- disk = json.loads((ws.artifacts / "build.json").read_text())- assert disk["ok"] is False and disk["error_type"] == "FkInconsistent"- assert not (ws.artifacts / "object.glb").exists() and not (ws.artifacts / "meshes").exists()---def test_lint_fail_invalidates_stale_artifacts(tmp_path, cabinet_plan, fake_blender):- ws = _ws(tmp_path, cabinet_plan)- rt = UrdfBlenderRuntime()- assert rt.build(ws).ok- (ws.src / "robot.urdf").write_text("<robot name='x'><link name='a'>")- res = rt.build(ws)- assert not res.ok and res.error_type == "LintError" and "well-formed" in res.error_message- assert not (ws.artifacts / "object.glb").exists() and not (ws.artifacts / "meshes").exists()- assert json.loads((ws.artifacts / "build.json").read_text())["error_type"] == "LintError"---def test_wrapper_rejects_unsafe_link_names_offline():- """run_bpy_links refuses link names that are not plain identifiers — ``../evil``- must be a build error, never a ``meshes/<link>.glb`` write outside meshes/. The- wrapper needs bpy, so its pure name check is exec'd out of the source."""- import ast- import re as _re-- src = rt_mod.WRAPPER.read_text()- assert "UnsafeLinkName" in src and "_bad_links(links)" in src # main() wired to the check- tree = ast.parse(src)- picked = [n for n in tree.body- if (isinstance(n, ast.FunctionDef) and n.name == "_bad_links")- or (isinstance(n, ast.Assign) and getattr(n.targets[0], "id", "") == "_SAFE_LINK")]- assert len(picked) == 2- ns: dict = {"re": _re}- exec(compile(ast.Module(body=picked, type_ignores=[]), str(rt_mod.WRAPPER), "exec"), ns)- bad = ns["_bad_links"](["body", "door_2", "DoorHandle", "../evil", "a/b", "Door.001", "", "9lives"])- assert bad == ["../evil", "a/b", "Door.001", "", "9lives"]diff --git a/harness/tests/urdf_joints/test_skeleton.py b/harness/tests/urdf_joints/test_skeleton.pyindex da83c905..a5018f76 100644--- a/harness/tests/urdf_joints/test_skeleton.py+++ b/harness/tests/urdf_joints/test_skeleton.py@@ -5,9 +5,7 @@ from __future__ import annotationsimport astimport numpy as np-import pytest-from codeverse3d.contracts.plan import ArticulatedPlan, BBox, JointPlan, PartPlanfrom codeverse3d.languages.urdf import (compute_urdf_frames,lint_model_text,@@ -16,7 +14,6 @@ from codeverse3d.languages.urdf import (render_urdf,)from codeverse3d.spatial.joints_model import fk, load_urdf-from codeverse3d.workspace import Workspacedef test_frames_chain_and_rendered_files_lint_clean_and_load(tmp_path, cabinet_plan):@@ -26,10 +23,8 @@ def test_frames_chain_and_rendered_files_lint_clean_and_load(tmp_path, cabinet_passert fr.links["handle"].frame_xyz == (0.2, -0.24, 0.4)by = {j.name: j for j in fr.joints}assert by["hinge"].origin_xyz == (-0.29, -0.2, 0.0)- # handle joint origin is relative to the DOOR frame (accumulated)assert np.allclose(by["handle_mount"].origin_xyz, (0.49, -0.04, 0.4))assert by["handle_mount"].type == "fixed" and by["handle_mount"].lower is None- # the rendered files lint clean and loadurdf_text = render_urdf(fr)findings, links = lint_urdf_text(urdf_text)assert findings == [] and links == ["body", "door", "handle"]@@ -40,36 +35,20 @@ def test_frames_chain_and_rendered_files_lint_clean_and_load(tmp_path, cabinet_pp.write_text(urdf_text)r = load_urdf(p, load_meshes=False)T = fk(r, {})- # visual origin is the inverse of the link frame → meshes land where authoredfor name in fr.links:assert np.allclose(T[name] @ r.links[name].visual_origin, np.eye(4), atol=1e-9), name-def test_rest_shift():++def test_rest_shift_puts_q0_at_the_authored_pose():+ from codeverse3d.contracts.plan import ArticulatedPlan, BBox, JointPlan, PartPlan+plan = ArticulatedPlan(object_name="Box", summary="s", overall_bbox=BBox(center=(0, 0, 0.1), extents=(0.2, 0.2, 0.2)), root_link="Base",parts=[PartPlan(name="Base", role="r", description="d", bbox=BBox(center=(0, 0, 0.05), extents=(0.2, 0.2, 0.1))),PartPlan(name="Lid", role="r", description="d", bbox=BBox(center=(0, 0, 0.11), extents=(0.2, 0.2, 0.02)))],joints=[JointPlan(name="lid_hinge", type="revolute", parent="Base", child="Lid", axis=(1, 0, 0), pivot=(0, 0.1, 0.1),- lower=0.0, upper=1.5, rest=0.5)],- )+ lower=0.0, upper=1.5, rest=0.5)])fr = compute_urdf_frames(plan)- j = fr.joints[0]- assert (j.lower, j.upper) == (-0.5, 1.0) and j.rest == 0.5 # q=0 is the authored rest- # the rendered files SAY so, next to the shifted limit and the pivot, so the agent who- # reads the plan table (unshifted lower/upper/rest) and the skeleton sees one rule- urdf_text = render_urdf(fr)- assert '<limit lower="-0.5" upper="1" effort="10" velocity="1"/> <!-- plan lower=0 upper=1.5 rest=0.5' in urdf_text- assert "shifted by -rest" in urdf_text and "q=0 is the authored pose" in urdf_text- assert "(plan rest=0.5 → this pose is URDF q=0)" in render_model_py(plan, fr)- assert lint_urdf_text(urdf_text)[0] == []---def test_skeleton_rejects_static_plan(tmp_path):- from codeverse3d.contracts.plan import StaticPlan- from codeverse3d.languages.urdf import UrdfBlenderRuntime-- sp = StaticPlan(object_name="x", summary="s", overall_bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)),- parts=[PartPlan(name="A", role="r", description="d", bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)))])- with pytest.raises(TypeError):- UrdfBlenderRuntime().skeleton(Workspace(tmp_path / "ws").create(), sp)+ assert (fr.joints[0].lower, fr.joints[0].upper) == (-0.5, 1.0)+ assert lint_urdf_text(render_urdf(fr))[0] == []diff --git a/harness/tests/urdf_joints/test_sweep.py b/harness/tests/urdf_joints/test_sweep.pyindex 7b394ad2..5eb039ed 100644--- a/harness/tests/urdf_joints/test_sweep.py+++ b/harness/tests/urdf_joints/test_sweep.py@@ -2,19 +2,14 @@from __future__ import annotations-import pytest-from codeverse3d.contracts.artifacts import GateFinding, Severityfrom codeverse3d.spatial.joints_model import load_urdf-from codeverse3d.spatial.joints_poses import pose_samplesfrom codeverse3d.spatial.joints_sweep import (- MAX_PAIR_FINDINGS,aggregate_findings,sweep_collisions,sweep_findings,)from tests.urdf_joints.conftest import (- write_carcass_drawer_robot,write_mesh_robot,)@@ -37,86 +32,6 @@ def test_rest_penetration_and_floating(tmp_path):assert sev["body|door"] == Severity.ERROR and sev["handle"] == Severity.ERROR-def test_hinged_child_near_parent_is_only_a_warning(tmp_path):- # door hinged 6 mm in front of the body face: within 3x hinge clearance → WARN, not ERROR- urdf, meshes = write_mesh_robot(tmp_path, handle=False)- text = urdf.read_text().replace('<origin xyz="0.29 0.2 0" rpy="0 0 0"/>', '<origin xyz="0.29 0.194 0" rpy="0 0 0"/>')- urdf.write_text(text)- r = load_urdf(urdf, meshes)- rep = sweep_collisions(r, [{}], hinge_clearance_m=0.004)- assert rep.summary.floating_at_rest == ["door"]- fl = rep.per_pose[0].floating[0]- assert fl.nearest == "body" and fl.joint_type == "revolute" and 0.004 < fl.gap_m < 0.008- finds = sweep_findings(rep, hinge_clearance_m=0.004)- assert finds[-1].target == "door" and finds[-1].severity == Severity.WARN- # an inserted prismatic child (AABB overlap) is never reported as unattached- rep_ok = sweep_collisions(load_urdf(*write_mesh_robot(tmp_path / "ok")), [{}])- assert rep_ok.summary.floating_at_rest == []--[email protected]("fcl", [True, False], ids=["fcl", "trimesh-fallback"])-def test_agent_style_meshes_penetration_is_real_and_deterministic(tmp_path, monkeypatch, fcl):- """Non-watertight, inverted-winding links (the wrapper's usual output), both backends, deterministic."""- import codeverse3d.spatial.joints_collide as jc-- if not fcl:- monkeypatch.setattr(jc, "_fcl", None)- clean = load_urdf(*write_carcass_drawer_robot(tmp_path / "clean"))- assert not clean.links["Carcass"].mesh.is_watertight and clean.links["Carcass"].mesh.volume < 0- reps = [sweep_collisions(clean, pose_samples(clean, n_random=4, seed=0), volumes=False) for _ in range(3)]- assert all(r.summary.max_penetration_m == 0.0 and r.summary.overlapping_poses == [] for r in reps)- assert reps[0].summary.floating_links == [] and reps[0].summary.link_islands == {"Carcass": 5, "Drawer": 5}- assert reps[0].summary.backend == ("fcl" if fcl else "trimesh")-- bad = load_urdf(*write_carcass_drawer_robot(tmp_path / "bad", drawer_shift_x=0.032))- rests = [sweep_collisions(bad, [{}]).summary.rest_max_penetration_m for _ in range(3)]- assert len(set(rests)) == 1 and 0.008 < rests[0] < 0.02 # 30 mm through a 30 mm panel → ≥ 10 mm to its surface- rep = sweep_collisions(bad, [{}])- ov = rep.per_pose[0].overlaps- assert [(o.a, o.b, o.approx) for o in ov] == [("Carcass", "Drawer", False)] # islands are watertight → exact- assert ov[0].volume_m3 is not None and ov[0].volume_m3 > 1e-6- sev = {x.target: x.severity for x in sweep_findings(rep, rest_max_m=0.005)}- assert sev["Carcass|Drawer"] == Severity.ERROR---def test_welded_child_overlap_is_structural_not_motion(tmp_path):- """A weld overlap is one WARN under the rest policy, not an ERROR per swung pose."""- urdf, meshes = write_mesh_robot(tmp_path, handle=True)- urdf.write_text(urdf.read_text().replace('<origin xyz="-0.2 0.24 -0.4" rpy="0 0 0"/>', '<origin xyz="-0.2 0.243 -0.4" rpy="0 0 0"/>'))- r = load_urdf(urdf, meshes)- rep = sweep_collisions(r, pose_samples(r))- ovs = [(pr.label, o) for pr in rep.per_pose for o in pr.overlaps]- assert [(lbl, o.a, o.b, o.rigid) for lbl, o in ovs] == [("rest", "door", "handle", True)]- assert 0.0025 < rep.summary.rest_max_penetration_m < 0.0035 and rep.summary.overlapping_poses == ["rest"]- finds = sweep_findings(rep)- assert [(f.target, f.severity) for f in finds] == [("door|handle", Severity.WARN)]- # without a rest pose in the sweep the weld is still measured (once, first pose) and counts as rest penetration- rep2 = sweep_collisions(r, [{"hinge": 1.0}, {"hinge": 1.5}])- assert [len(pr.overlaps) for pr in rep2.per_pose] == [1, 0] and rep2.summary.rest_max_penetration_m > 0.0025- assert sweep_findings(rep2)[0].severity == Severity.WARN and "rigidly joined" in sweep_findings(rep2)[0].fix_hint---# ------------------------------------------------- joints= narrows the RENDER, not the sweep-def test_joints_argument_narrows_the_render_to_those_joints(monkeypatch, tmp_path):- from codeverse3d.spatial import tools as ts-- class _J:- def __init__(self, name, lo, hi, type="revolute"): self.name, self.lower, self.upper, self.type = name, lo, hi, type- class _Robot:- joints = {n: _J(n, -1.0, 1.0) for n in ("hinge", "slide", "knob")}- def movable_joints(self): return list(self.joints.values())- def independent_joints(self): return list(self.joints.values()) # no coupling in this fake-- full = ts._poses_for(_Robot(), None)- assert full is None, "no filter = the full articulation sheet, unchanged"- narrowed = ts._poses_for(_Robot(), ["hinge"])- labels = [lbl for lbl, _ in narrowed]- assert labels[0] == "rest" and all(x == "rest" or x.startswith("hinge@") for x in labels)- assert len(narrowed) == 3, "rest + hinge@lower + hinge@upper, nothing from slide or knob"- typo = ts._poses_for(_Robot(), ["hinge_typo"])- assert [lbl for lbl, _ in typo] == ["rest"], "an unknown joint yields a visibly wrong sheet, not the full one"--# ------------------------------------------------------------------ sweep aggregationdef _pen(a, b, depth, pose, sev=Severity.ERROR):return GateFinding(gate="articulation", severity=sev, target=f"{a}|{b}", message=f"{a}/{b} {depth}",@@ -135,10 +50,3 @@ def test_aggregate_merges_ranks_caps_and_summarises():assert "3 of the sampled poses" in dw.message and "31.0 mm" in dw.message and "hinge=1.50" in dw.messageassert "1 at rest" in dw.messageassert all(f.severity == Severity.ERROR for f in out)- # errors are capped; the rest is one summary WARN- fs = [_pen(f"p{i}", "base", 0.001 * (i + 1), {"j": 1.0}) for i in range(MAX_PAIR_FINDINGS + 3)]- out = aggregate_findings(fs)- errors = [f for f in out if f.severity == Severity.ERROR]- warns = [f for f in out if f.severity == Severity.WARN]- assert len(errors) == MAX_PAIR_FINDINGS and errors[0].target == f"p{MAX_PAIR_FINDINGS + 2}|base"- assert len(warns) == 1 and warns[0].data["kind"] == "penetration_summary" and "3 more" in warns[0].messagediff --git a/harness/tests/urdf_joints/test_sweep_degrade.py b/harness/tests/urdf_joints/test_sweep_degrade.pyindex 3c736cbc..0942bdcb 100644--- a/harness/tests/urdf_joints/test_sweep_degrade.py+++ b/harness/tests/urdf_joints/test_sweep_degrade.py@@ -9,9 +9,7 @@ from codeverse3d.spatial.render import RenderErrordef test_pose_render_failure_keeps_the_measured_sweep(tmp_path, monkeypatch):- """art_verify architect_lamp, 2026-08-26: render_glb.mjs timed out after 330 s inside- render_poses with three articulated runs sharing the browser; gates() raised and the run- was recorded failed before its first round."""+ """Regression: a render_glb timeout inside render_poses made gates() raise and failed the run before round 0."""import codeverse3d.tracks.articulated_object as artfrom codeverse3d.contracts.artifacts import GateReportfrom codeverse3d.spatial import joints_export, joints_sweep